import torch.nn as nn
import torch
import torch.nn.functional as F
#from profilehooks import profile
from model.utils import *
import numpy as np

class convolution_block(torch.nn.Module):
    def __init__(self,in_filters, out_filters, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding = (1,1,1)):
        super(convolution_block, self).__init__()
        self.convolution1 = nn.Conv3d(in_filters, out_filters, kernel_size = kernel_size, stride = stride, padding= padding)
        if out_filters % 16 == 0:
            self.normalization1 = nn.GroupNorm(16, out_filters)
        elif out_filters % 12 == 0:
            self.normalization1 = nn.GroupNorm(12, out_filters)
        else:
            self.normalization1 = nn.GroupNorm(out_filters, out_filters)

        self.activation1 = nn.LeakyReLU()

    def forward(self,x):
        out = self.convolution1(x)
        out = self.normalization1(out)
        out = self.activation1(out)
        return out

class localization_module(torch.nn.Module):
    def __init__(self,in_filters, out_filters, kernel_size=(3, 3, 3), stride=(1, 1, 1)):
        super(localization_module, self).__init__()
        self.convolution1 = convolution_block(in_filters, out_filters)
        self.convolution2 = convolution_block(out_filters, out_filters, kernel_size=(1,1,1) , padding =0) #

    def forward(self,x):
        out = self.convolution1(x)
        out = self.convolution2(out)
        return out

class up_sampling_module(torch.nn.Module):
    def __init__(self,in_filters, out_filters, size=(2, 2, 2)):
        super(up_sampling_module, self).__init__()
        self.upsample = nn.Upsample(scale_factor=2, mode='trilinear', align_corners=False)
        self.convolution1 = convolution_block(in_filters, out_filters, kernel_size=(1,1,1), padding =0)
    def forward(self,x):
        out = self.upsample(x)
        out = self.convolution1(out)
        return out

class context_module(torch.nn.Module):
    def __init__(self,in_filters, out_filters, dropout_rate=0.3):
        super(context_module, self).__init__()
        self.convolution1 = convolution_block(in_filters, out_filters)
        self.dropout =  nn.Dropout3d(p=dropout_rate)
        self.convolution2 = convolution_block(in_filters, out_filters)
    def forward(self,x):
        out = self.convolution1(x)
        out = self.dropout(out)
        out = self.convolution2(out)
        return out

class PyramidPool(nn.Module):
    def __init__(self, in_features, out_features, pool_factor):
        super(PyramidPool,self).__init__()
        self.net = nn.Sequential(
            nn.AvgPool3d(pool_factor, stride=pool_factor, padding=0),
            nn.Conv3d(in_features, out_features, 1, bias=False),
            nn.GroupNorm(out_features, out_features),
            nn.LeakyReLU(), nn.Dropout3d(p=0.3),
            nn.Upsample(scale_factor= pool_factor,  mode='trilinear', align_corners=False)
        )

    def forward(self, x):
        return self.net(x)

class MultiDataModel(nn.Module):
    def __init__(self, in_channels, n_classes, n_filter_per_level =( 4,16,64,128,256), dropout_rate =0.3):
        super(MultiDataModel, self).__init__()

        self.material = False
        self.n_classes= n_classes
        self.in_channels = in_channels
        self.n_filter_per_level = n_filter_per_level
        self.dropout_rate = dropout_rate
        self.base_n_filter = 8

        self.initial_downconvolution =nn.Conv3d(self.in_channels, self.base_n_filter, kernel_size = (7,7,7), stride = (2,2,2) , padding= (3,3,3))

        self.convolution_block1 = convolution_block(self.base_n_filter, n_filter_per_level[0])
        self.context_module1 = context_module(n_filter_per_level[0], n_filter_per_level[0], dropout_rate=self.dropout_rate)

        self.convolution_block2 = convolution_block(n_filter_per_level[0],n_filter_per_level[1], stride=(2, 2, 2))
        self.context_module2 = context_module(n_filter_per_level[1],n_filter_per_level[1], dropout_rate=self.dropout_rate)

        self.convolution_block3 = convolution_block(n_filter_per_level[1],n_filter_per_level[2], stride=(2, 2, 2))
        self.context_module3 = context_module(n_filter_per_level[2],n_filter_per_level[2], dropout_rate=self.dropout_rate)

        self.convolution_block4 = convolution_block(n_filter_per_level[2],n_filter_per_level[3], stride=(2, 2, 2))
        self.context_module4 = context_module(n_filter_per_level[3],n_filter_per_level[3], dropout_rate=self.dropout_rate)

        self.convolution_block5 = convolution_block(n_filter_per_level[3],n_filter_per_level[4], stride=(2, 2, 2))
        self.context_module5 = context_module(n_filter_per_level[4],n_filter_per_level[4], dropout_rate=self.dropout_rate)

        self.up_sampling_module4 = up_sampling_module(n_filter_per_level[4],n_filter_per_level[3])
        self.localization_module4 = localization_module( n_filter_per_level[4], n_filter_per_level[3])

        self.up_sampling_module3 = up_sampling_module(n_filter_per_level[3],n_filter_per_level[2])
        self.localization_module3 = localization_module(n_filter_per_level[2]*2, n_filter_per_level[2])

        self.up_sampling_module2 = up_sampling_module(n_filter_per_level[2],n_filter_per_level[1])
        self.localization_module2 = localization_module(n_filter_per_level[1]*2, n_filter_per_level[1])

        self.up_sampling_module1 = up_sampling_module(n_filter_per_level[1], n_filter_per_level[0])
        self.localization_module1 = localization_module(n_filter_per_level[0]*2,  n_filter_per_level[0])

        self.Up4 = nn.Upsample(scale_factor= 4,  mode='trilinear', align_corners=False)
        self.Up2 = nn.Upsample(scale_factor= 2,  mode='trilinear', align_corners=False)

        #self.final_layers = nn.ModuleList([nn.ConvTranspose3d(n_filter_per_level[0]*3,self.n_classes,  kernel_size = (7,7,7), stride=(2, 2, 1),  padding=(3, 3, 3), output_padding = (1,1,0)) for i in range(11)])
        #self.final_layers = nn.ModuleList([nn.Conv3d(n_filter_per_level[0],self.n_classes,  kernel_size = (3,3,3), stride=(1,1, 1), padding = (1,1,1)) for i in range(13)])
        self.final_layers = nn.ModuleList([nn.ConvTranspose3d(n_filter_per_level[0],self.n_classes,  kernel_size = (7,7,7), stride=(2, 2,2),  padding=(3, 3, 3), output_padding = (1,1,1)) for i in range(17)])

        self.final_activation = nn.Sigmoid()

        #self.PSPa = PyramidPool(n_filter_per_level[0], self.PSP_features, 2)
        #self.PSPb = PyramidPool(n_filter_per_level[0], self.PSP_features, 4)
        #self.PSPc = PyramidPool(n_filter_per_level[0], self.PSP_features, 8)
        #self.PSPd = PyramidPool(n_filter_per_level[0], self.PSP_features, 16)
        if self.material:
            self.final_layer_mat = nn.ConvTranspose3d(n_filter_per_level[0],6, kernel_size = (7,7,7), stride=(2, 2,2),  padding=(3, 3, 3), output_padding = (1,1,1))

        self.dropout =  nn.Dropout3d(p=0.3)

    def forward(self, x, task, alltasks):
        #print('task',task.shape)
        #tasfor layer in range()
        task = task.cpu().numpy()[0]
        #print('task number', task)
        out = self.initial_downconvolution(x)
        #import pdb; pdb.set_trace()
        out = self.convolution_block1(out)
        out_context = self.context_module1(out)
        out = out + out_context
        level1 = out

        out = self.convolution_block2(out)
        out_context = self.context_module2(out)
        out = out + out_context
        level2 = out

        out = self.convolution_block3(out)
        out_context = self.context_module3(out)
        out = out + out_context
        level3 = out

        out =self.convolution_block4(out)
        out_context = self.context_module4(out)
        out = out + out_context
        level4 = out

        out = self.convolution_block5(out)
        out_context = self.context_module5(out)
        out = out + out_context

        #up_sampling4
        out = self.up_sampling_module4(out) # 16
        out = torch.cat( (out,level4), dim =1) #
        out = self.localization_module4(out)

        #up_sampling3
        out = self.up_sampling_module3(out)
        out = torch.cat( (out,level3), dim =1)
        out = self.localization_module3(out)
        #segmentation3 = self.seg3(out)

        #up_sampling2
        out = self.up_sampling_module2(out)
        out = torch.cat( (out,level2), dim =1)
        out = self.localization_module2(out)
        #segmentation2 = self.seg2(out)

        #up_sampling1
        out = self.up_sampling_module1(out)
        out = torch.cat((out,level1), dim =1)
        #dense1 = out
        out = self.localization_module1(out)
        #out = torch.cat((out,dense1), dim =1)

        #PSP
        #out = torch.cat([
        #    self.dropout(out),
        #    self.PSPa(out)*0,
        #    self.PSPb(out)*0,
        #    self.PSPc(out)*0,
        #    self.PSPd(out)*0], dim=1)
        # generate multitask outptut
        #print(out.shape)
        with torch.no_grad():
            combined = x
            for i in alltasks:
                #print(i)
                #final_layer = self.final_layers[i]
                #final = final_layer(out)
                final = self.final_layers[i](out)
                final = self.final_activation(final)
                combined = torch.cat( (combined, final ), dim = 1)

        # select output
        output = dict()
        if self.material:
            mat = self.final_layer_mat(out)
            output['matmap'] = mat

        out = self.final_layers[task](out)
        seg_layer = self.final_activation(out)

        output['final_layerA'] = seg_layer
        output['complete'] = combined

        return output

CT Liver Segmentation Software/model/MultiData_big_lowfilter_stretch_old.py


import pickle
import pandas as pd
import numpy as np
import os
from tqdm import tqdm
import click

class FileTransformer:
    def __init__(self, labels_file):
        self.labels_file = labels_file
        name = self.labels_file.split(".")[0]
        self.output_file = name + ".pickle"

    def transform(self):
        success = self.load_labels()
        if success:
            self.save()

    def save(self):
        with open(self.output_file, "wb") as f:
            pickle.dump(
                (self.metadata, self.loaded_labels, self.animals, self.loaded_times), f
            )

    def load_labels(self, length=None):
        if self.labels_file is not None:
            try:
                with pd.HDFStore(self.labels_file) as store:
                    self.loaded_data = store["annotation"]
                    try:
                        self.metadata = store.get_storer("annotation").attrs.metadata
                    except:
                        self.metadata = {}
                self.loaded_labels = list(self.loaded_data.columns.unique("categories"))
                self.animals = list(self.loaded_data.columns.unique("individuals"))
                n_cat = len(self.loaded_data.columns.unique("categories"))
                self.loaded_data = self.loaded_data.to_numpy().T.reshape(
                    (self.n_ind, n_cat, -1)
                )
                times = [[] for i in range(self.n_ind)]
                from copy import copy

                for ind_i, ind_list in enumerate(self.loaded_data):
                    for i in range(ind_list.shape[0]):
                        l = copy(ind_list[i, :])
                        l = (l == 0.5).astype(int)
                        list_amb = [
                            [*x, True]
                            for x in np.flatnonzero(
                                np.diff(np.r_[0, l, 0]) != 0
                            ).reshape(-1, 2)
                        ]
                        l = copy(ind_list[i, :])
                        l = (l == 1).astype(int)
                        list_sure = [
                            [*x, False]
                            for x in np.flatnonzero(
                                np.diff(np.r_[0, l, 0]) != 0
                            ).reshape(-1, 2)
                        ]
                        times[ind_i].append(np.array(list_amb + list_sure))
                self.loaded_times = times
                del self.loaded_data
                return True
            except:
                try:
                    with open(self.labels_file, "rb") as f:
                        _ = pickle.load(f)
                    print(f"{self.labels_file} seems to be ok")
                except:
                    print(
                        f"something is wrong with {self.labels_file} (cannot be opened by pickle or hdf5)"
                    )
                return False

@click.command()
@click.option(
    "--directory", required=True, help="the directory where the files to transform are"
)
def main(directory):
    files = [file for file in os.listdir(directory) if file.split(".")[-1] == "h5"]
    for file in tqdm(files):
        fts = FileTransformer(os.path.join(directory, file))
        fts.transform()

if __name__ == "__main__":
    main()


"""
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Example:

Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true

Then 4 is the first bad version.
"""

# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):

class Solution:
    def firstBadVersion(self, n):
        if n == 1: return 1 if isBadVersion(1) else -1
        def helper(low, high):
            nonlocal n
            if abs(high - low) <= 1:
                if isBadVersion(low): return low
                elif isBadVersion(high): return high
                else: return high + 1 if high + 1 <= n else -1
            else:
                middle = low + int((high - low) / 2)
                if isBadVersion(middle):
                    if not isBadVersion(middle - 1): return middle
                    return helper(low, middle - 1)
                else:
                    if isBadVersion(middle + 1): return middle + 1
                    return helper(middle + 1, high)
        return helper(1,n)

Leetcode/May Leetcode Challenge/First Bad Version.py


import hmac
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt, get_jwt_identity
from flask_restful import Resource, reqparse
from models.user_models import UserModels
from flask_mail import Message
from mail import mail

import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

class UserLogin(Resource):
    user_parser = reqparse.RequestParser()
    user_parser.add_argument("email",
                              type=str,
                              required=True,
                              location='json',
                              help = "email is required!!")
    user_parser.add_argument("password",
                              type=str,
                              required=True,
                              location='json',
                              help = "password is required!!")

    @classmethod
    def post(cls):
        logger.info("Start*********************")
        data = cls.user_parser.parse_args()
        logger.info(f"data===========>   {data}")
        user = UserModels.find_by_email(data["email"])

        response_data = {}
        if user and hmac.compare_digest(user.password, data["password"]):
            access_token = create_access_token(identity=user.id, fresh=True)
            refresh_token = create_refresh_token(identity=user.id)
            response_data["data"] = {
                "access_token": access_token,
                "refresh_token": refresh_token
                }
            response_data["data"]["profile"] = user.json()
            del response_data["data"]["profile"]["id"]
            response_data["message"] = "User logged in Successfully"
            response_data["status"] = "success"
            return (
                response_data,
                200,
                {"Content-Type": "application/json"}
            )

        logger.info("access_token not genrated")

        response_data["message"] = "Invalid credentials"
        response_data["status"] = "Un-authorized"
        response_data["data"] = {}
        return (response_data,
                401,
                {"Content-Type": "application/json"})

class UserProfile(Resource):

    @jwt_required()
    def get(self):
        user_id = get_jwt_identity()
        user = UserModels.find_by_id(user_id)
        response_data = {}
        if user:
            response_data["data"] = user.json()
            del response_data["data"]["id"]
            response_data["status"] = "success"
            return (
                response_data,
                200,
                {"Content-Type": "application/json"})
        response_data["message"] = "Data not found!!"
        response_data["status"] = "Bad Request"
        response_data["data"] = {}
        return (
            response_data,
            400,
            {"Content-Type": "application/json"})

class UpdateUserProfile(Resource):
    user_parser = reqparse.RequestParser()
    user_parser.add_argument("email",
                             type=str,
                             required=True,
                             location='json',
                             help="email is required!!")
    user_parser.add_argument("first_name",
                             type=str,
                             required=True,
                             location='json',
                             help="first_name is required!!")
    user_parser.add_argument("last_name",
                             type=str,
                             required=True,
                             location='json',
                             help="last_name is required!!")

    @jwt_required()
    def put(self):
        user_id = get_jwt_identity()
        user_data = UserModels.find_by_id(user_id)
        response_data = {}
        if user_data:
            data = UpdateUserProfile.user_parser.parse_args()
            response_data["data"] = {}
            try:
                user_data.email = data["email"]
                user_data.first_name = data["first_name"]
                user_data.last_name = data["last_name"]
                user_data.save_to_db()
                response_data["message"] = "Update Successfully"
                response_data["status"] = "success"
            except:
                response_data["message"] = "An error occurred updating the item"
                response_data["status"] = "Server Error"
                return (response_data,
                        500,
                        {"Content-Type": "application/json"})
        return (response_data,
                200,
                {"Content-Type": "application/json"})

class ForgetPassword(Resource):

    def get(self, email):
        is_email_valid = UserModels.find_by_email(email)
        response_data = {}
        if is_email_valid:
            try:
                token = UserModels.get_reset_token(email=email)
                msg = Message()
                msg.subject = "Test Lims Dev"
                msg.sender = "abiliquest@gmail.com"
                msg.recipients = [email]
                msg.body = f'Link'
                mail.send(msg)
                response_data["data"] = {"token": token}
                response_data["message"] = "Email varification link sent"
                response_data["status"] = "success"
                return(response_data,
                        200, {"Content-Type": "application/json"})
            except:
                response_data["data"] = {}
                response_data["message"] = "Something went wrong!!"
                response_data["status"] = "Internal Server Error"
                return {response_data,
                        500, {"Content-Type": "application/json"}}

        response_data["data"] = {}
        response_data["message"] = "Invalid Email"
        response_data["status"] = "Un-authorized"
        return (response_data,
                401, {"Content-Type": "application/json"})


import enum
import logging
from typing import Any, Dict, Optional
import urllib.parse

from simple_ado.base_client import ADOBaseClient
from simple_ado.http_client import ADOHTTPClient, ADOResponse

class TaskAgentPoolActionFilter(enum.Enum):
    """Represents an agent pool action filter."""

    MANAGE = "manage"
    NONE = "none"
    USE = "use"

class ADOPoolsClient(ADOBaseClient):
    """Wrapper class around the undocumented ADO pools APIs.

    :param http_client: The HTTP client to use for the client
    :param log: The logger to use
    """

    def __init__(self, http_client: ADOHTTPClient, log: logging.Logger) -> None:
        super().__init__(http_client, log.getChild("pools"))

    def get_pools(
        self,
        *,
        pool_name: Optional[str] = None,
        action_filter: Optional[TaskAgentPoolActionFilter] = None,
    ) -> ADOResponse:
        """Gets the agent details.

        :param Optional[str] pool_name: The name of the pool to match on
        :param Optional[TaskAgentPoolActionFilter] action_filter: Set to filter on the type of pools

        :returns: The ADO response with the data in it
        """

        request_url = self.http_client.api_endpoint(is_default_collection=False)
        request_url += "/distributedtask/pools?"

        parameters = {"api-version": "5.1"}

        if pool_name:
            parameters["poolName"] = pool_name

        if action_filter:
            parameters["actionFilter"] = action_filter.value

        request_url += urllib.parse.urlencode(parameters)

        response = self.http_client.get(request_url)
        response_data = self.http_client.decode_response(response)
        return self.http_client.extract_value(response_data)

    def get_agents(
        self,
        *,
        pool_id: int,
        agent_name: Optional[str] = None,
        include_capabilities: bool = True,
        include_assigned_request: bool = True,
        include_last_completed_request: bool = True,
    ) -> ADOResponse:
        """Gets the agents details.

        :param int pool_id: The ID of the pool the agents are in
        :param Optional[str] agent_name: The name of the agent to match on
        :param bool include_capabilities: Set to False to not include capabilities
        :param bool include_assigned_request: Set to False to not include the current assigned request
        :param bool include_last_completed_request: Set to False to not include the last completed request

        :returns: The ADO response with the data in it
        """

        request_url = self.http_client.api_endpoint(is_default_collection=False)
        request_url += f"/distributedtask/pools/{pool_id}/agents?"

        parameters = {
            "includeCapabilities": include_capabilities,
            "includeAssignedRequest": include_assigned_request,
            "includeLastCompletedRequest": include_last_completed_request,
            "api-version": "5.1",
        }

        if agent_name:
            parameters["agentName"] = agent_name

        request_url += urllib.parse.urlencode(parameters)

        response = self.http_client.get(request_url)
        response_data = self.http_client.decode_response(response)
        return self.http_client.extract_value(response_data)

    def get_agent(self, *, pool_id: int, agent_id: int) -> ADOResponse:
        """Gets the agent details.

        :param int pool_id: The ID of the pool the agent is in
        :param int agent_id: The ID of the agent to get

        :returns: The ADO response with the data in it
        """

        request_url = self.http_client.api_endpoint(is_default_collection=False)
        request_url += f"/distributedtask/pools/{pool_id}/agents/{agent_id}?api-version=5.1"

        response = self.http_client.get(request_url)
        return self.http_client.decode_response(response)

    def update_agent(
        self, *, pool_id: int, agent_id: int, agent_data: Dict[str, Any]
    ) -> ADOResponse:
        """Adds required reviewers when opening PRs against a given branch.

        :param int pool_id: The ID of the pool the agent is in
        :param int agent_id: The ID of the agent to disable
        :param Dict[str,Any] agent_data: The data to set on the agent

        :returns: The ADO response with the data in it
        """

        request_url = self.http_client.api_endpoint(is_default_collection=False)
        request_url += f"/distributedtask/pools/{pool_id}/agents/{agent_id}?api-version=5.1"

        response = self.http_client.patch(request_url, json_data=agent_data)
        return self.http_client.decode_response(response)

    def set_agent_state(self, *, pool_id: int, agent_id: int, enabled: bool) -> ADOResponse:
        """Set the enabled/disabled state of an agent.

        :param int pool_id: The ID of the pool the agent is in
        :param int agent_id: The ID of the agent to disable
        :param bool enabled: Set to True to enable an agent, False to disable it

        :returns: The ADO response with the data in it
        """

        agent_details = self.get_agent(pool_id=pool_id, agent_id=agent_id)
        agent_details["enabled"] = enabled
        return self.update_agent(pool_id=pool_id, agent_id=agent_id, agent_data=agent_details)

    def update_agent_capabilities(
        self, *, pool_id: int, agent_id: int, capabilities: Dict[str, str]
    ) -> ADOResponse:
        """Set the enabled/disabled state of an agent.

        :param int pool_id: The ID of the pool the agent is in
        :param int agent_id: The ID of the agent to disable
        :param Dict[str,str] capabilities: The new capabilities to set

        :returns: The ADO response with the data in it
        """

        request_url = self.http_client.api_endpoint(is_default_collection=False)
        request_url += (
            f"/distributedtask/pools/{pool_id}/agents/{agent_id}/usercapabilities?api-version=5.1"
        )

        response = self.http_client.put(request_url, json_data=capabilities)
        return self.http_client.decode_response(response)


# Given the head of a singly linked list, return true if it is a palindrome.
# LeetCode 234

class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution(object):
    def isPalindrome(self, head):
        fast = head
        slow = head

        #Find middle(slow)
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next

        #Reverse second half
        prev = None
        while slow:
            tmp = slow.next
            slow.next = prev
            prev = slow
            slow = tmp

        #Chech palindrome
        left, right = head, prev
        while right:
            if left.val != right.val:
                return False
            left = left.next
            right = right.next

        return True

        #Array Solution
        # nums = []
        #
        # while head:
        #     nums.append(head.val)
        #     head = head.next
        #
        # l, r = 0, len(nums)-1
        # while l <= r:
        #     if nums[l] != nums[r]:
        #         return False
        #     l += 1
        #     r -= 1
        #
        # return True


# -*- coding: cp1252 -*-

# auswahl der zu bearbeitenden Datei
dateiname = raw_input("Bitte Dateinamen eingeben:   ")
file = open(dateiname,'r')

# definition der Variablen
dok=''
index = 0
newline = ''
buh = ''
# deklaration der Latex-befehlslisten und deren ersetzung in Dokuwiki Syntax
# Latex-befehl
befehl = ["\\verantwortlich{","\\ref{sec:",'\\URL{','\\url{','\\Url{','\\href{','\\isofuss{']
# eröffnender Befehl dokuwiki Syntax
befehlneu = ["**verantwortlich: //","[[",'[[','[[','[[','[[','Erstellt am ']
# Abschliessender Befehl dokuwiki Syntax
befehlneu2 = ["//**","]]",']]',']]',']]',']]',' ']

# öffnen der Datei und Auslesen jeder zeile
file = open(dateiname,'r')
for line in file:

    index=0
    while index<len(befehl):
        if befehl[index] in line:

            newline = line				# Die aktuelle zeile wird in die Variable Newline gespeichert
            print(line)
            newline = newline.replace((befehl[index]),(befehlneu[index])) 	# in Newline wird der Latex Befehl durch den eröffneden wiki Befehl ersetzt
            newline = newline.replace('}',(befehlneu2[index]))				# und die spitze Klammerzu wird durch den schliessenden wiki Befehl ersetzt
            print(newline)					# ausgabe der Zeile zur überprüfung
			# Nachfrage ob die Zeile in Ordnung ist oder nicht
            ok = raw_input('zeile OK? j zum bestätigen n um per hand zu korregieren  ')
            if ok == 'j':
                line = newline 		# newline wird wieder nach line Gespeichert  und line wird Überprüft
            if ok =='n':
                line = raw_input('Bitte Zeile korekt eingeben:   ')		# wenn nein wird die neu eingabe der Zeile Verlangt
            else:
                line = line
        index = index + 1 # Index um die Befehle weiterzuzählen wird um 1 erhöht

    dok = dok + line  # Die zeile wird an die variable Dok angehängt sodas sich das dokument langsam wieder zusammen setzt

print(dok) # Das gesamte Dokument wird zum Korrekturlesen nochmal angezeigt

# neue Datei unter dem Namen dateineu2.txt Absteichern
file=open("dateineu2.txt",'w')
file.write(dok)
file.close
file=open("dateineu2.txt",'w')
file.write(dok)
file.close


import pickle

def model_prediction(features):

    pickled_model = pickle.load(open('C:/Users/Sakshi Rohida/Desktop/deepak sir ML projects/California_housing_prices/model/california_housing_prices_LinearRegression.pkl', 'rb'))
    median_house_value = str(list(pickled_model.predict(features)))

    return str(f'The Price is {median_house_value}')

longitude = float(input("Enter longitude"))

latitude = float(input("Enter latitude"))

total_rooms = int(input("Enter total rooms"))

total_bedrooms = float(input("Enter total bedrooms"))

population = int(input("Enter population"))

households = int(input("Enter households"))

median_income = float(input("Enter median income"))

ocean_proximity = int(input("Enter Ocean proximity"))

print(model_prediction([[longitude,latitude,total_rooms,total_bedrooms,population,households,median_income,ocean_proximity]]))


def color_judge(n):
    if 1<=n<=399:
        return 'gray'
    elif n<=799:
        return 'brown'
    elif n<=1199:
        return 'green'
    elif n<=1599:
        return 'light blue'
    elif n<=1999:
        return 'blue'
    elif n<=2399:
        return 'yellow'
    elif n<=2799:
        return 'orange'
    elif n<=3199:
        return 'red'
    else:
        return 'choice'

n = int(input())
a = list(map(int, input().split()))
dic = {}
for i in a:
    if dic.get(color_judge(i)):
        dic[color_judge(i)] += 1
    else:
        dic[color_judge(i)] = 1
choice = 0
l = len(dic)
if dic.get('choice'):
    choice = dic['choice']
    l -= 1
print(max(1, l), l+choice)


#!/usr/bin/env python3
"""
operation wrapper class
"""
__author__ = "Michael Montuori [michael.montuori@gmail.com]"
__copyright__ = "Copyright 2017 Michael Montuori. All rights reserved."
__credits__ = ["Warren Crigger"]
__license__ = "GPLv3"
__version__ = "0.1"
__revision__ = "2"

from libsprinkle import clfile

class Operation(object):

    ADD = "add"
    UPDATE = "update"
    REMOVE = "remove"

    def __init__(self, operation, src, dst):
        if operation.lower() != 'add' and operation.lower() != 'update' and operation.lower() != 'remove':
            raise Exception('invalid operation: ' + operation)
        self.operation = operation
        self.src = src
        self.dst = dst


import sys
import traceback
from pathlib import Path
from time import perf_counter as timer

import numpy as np
import torch

from encoder import inference as encoder
from synthesizer.inference import Synthesizer
from toolbox.ui import UI
from toolbox.utterance import Utterance
from vocoder import inference as vocoder

# Use this directory structure for your datasets, or modify it to fit your needs
recognized_datasets = [
    "LibriSpeech/dev-clean",
    "LibriSpeech/dev-other",
    "LibriSpeech/test-clean",
    "LibriSpeech/test-other",
    "LibriSpeech/train-clean-100",
    "LibriSpeech/train-clean-360",
    "LibriSpeech/train-other-500",
    "LibriTTS/dev-clean",
    "LibriTTS/dev-other",
    "LibriTTS/test-clean",
    "LibriTTS/test-other",
    "LibriTTS/train-clean-100",
    "LibriTTS/train-clean-360",
    "LibriTTS/train-other-500",
    "LJSpeech-1.1",
    "VoxCeleb1/wav",
    "VoxCeleb1/test_wav",
    "VoxCeleb2/dev/aac",
    "VoxCeleb2/test/aac",
    "VCTK-Corpus/wav48",
]

# Maximum of generated wavs to keep on memory
MAX_WAVS = 15

class Toolbox:
    def __init__(self, datasets_root: Path, models_dir: Path, seed: int=None):
        sys.excepthook = self.excepthook
        self.datasets_root = datasets_root
        self.utterances = set()
        self.current_generated = (None, None, None, None) # speaker_name, spec, breaks, wav

        self.synthesizer = None # type: Synthesizer
        self.current_wav = None
        self.waves_list = []
        self.waves_count = 0
        self.waves_namelist = []

        # Check for webrtcvad (enables removal of silences in vocoder output)
        try:
            import webrtcvad
            self.trim_silences = True
        except:
            self.trim_silences = False

        # Initialize the events and the interface
        self.ui = UI()
        self.reset_ui(models_dir, seed)
        self.setup_events()
        self.ui.start()

    def excepthook(self, exc_type, exc_value, exc_tb):
        traceback.print_exception(exc_type, exc_value, exc_tb)
        self.ui.log("Exception: %s" % exc_value)

    def setup_events(self):
        # Dataset, speaker and utterance selection
        self.ui.browser_load_button.clicked.connect(lambda: self.load_from_browser())
        random_func = lambda level: lambda: self.ui.populate_browser(self.datasets_root,
                                                                     recognized_datasets,
                                                                     level)
        self.ui.random_dataset_button.clicked.connect(random_func(0))
        self.ui.random_speaker_button.clicked.connect(random_func(1))
        self.ui.random_utterance_button.clicked.connect(random_func(2))
        self.ui.dataset_box.currentIndexChanged.connect(random_func(1))
        self.ui.speaker_box.currentIndexChanged.connect(random_func(2))

        # Model selection
        self.ui.encoder_box.currentIndexChanged.connect(self.init_encoder)
        def func():
            self.synthesizer = None
        self.ui.synthesizer_box.currentIndexChanged.connect(func)
        self.ui.vocoder_box.currentIndexChanged.connect(self.init_vocoder)

        # Utterance selection
        func = lambda: self.load_from_browser(self.ui.browse_file())
        self.ui.browser_browse_button.clicked.connect(func)
        func = lambda: self.ui.draw_utterance(self.ui.selected_utterance, "current")
        self.ui.utterance_history.currentIndexChanged.connect(func)
        func = lambda: self.ui.play(self.ui.selected_utterance.wav, Synthesizer.sample_rate)
        self.ui.play_button.clicked.connect(func)
        self.ui.stop_button.clicked.connect(self.ui.stop)
        self.ui.record_button.clicked.connect(self.record)

        #Audio
        self.ui.setup_audio_devices(Synthesizer.sample_rate)

        #Wav playback & save
        func = lambda: self.replay_last_wav()
        self.ui.replay_wav_button.clicked.connect(func)
        func = lambda: self.export_current_wave()
        self.ui.export_wav_button.clicked.connect(func)
        self.ui.waves_cb.currentIndexChanged.connect(self.set_current_wav)

        # Generation
        func = lambda: self.synthesize() or self.vocode()
        self.ui.generate_button.clicked.connect(func)
        self.ui.synthesize_button.clicked.connect(self.synthesize)
        self.ui.vocode_button.clicked.connect(self.vocode)
        self.ui.random_seed_checkbox.clicked.connect(self.update_seed_textbox)

        # UMAP legend
        self.ui.clear_button.clicked.connect(self.clear_utterances)

    def set_current_wav(self, index):
        self.current_wav = self.waves_list[index]

    def export_current_wave(self):
        self.ui.save_audio_file(self.current_wav, Synthesizer.sample_rate)

    def replay_last_wav(self):
        self.ui.play(self.current_wav, Synthesizer.sample_rate)

    def reset_ui(self, models_dir: Path, seed: int=None):
        self.ui.populate_browser(self.datasets_root, recognized_datasets, 0, True)
        self.ui.populate_models(models_dir)
        self.ui.populate_gen_options(seed, self.trim_silences)

    def load_from_browser(self, fpath=None):
        if fpath is None:
            fpath = Path(self.datasets_root,
                         self.ui.current_dataset_name,
                         self.ui.current_speaker_name,
                         self.ui.current_utterance_name)
            name = str(fpath.relative_to(self.datasets_root))
            speaker_name = self.ui.current_dataset_name + '_' + self.ui.current_speaker_name

            # Select the next utterance
            if self.ui.auto_next_checkbox.isChecked():
                self.ui.browser_select_next()
        elif fpath == "":
            return
        else:
            name = fpath.name
            speaker_name = fpath.parent.name

        # Get the wav from the disk. We take the wav with the vocoder/synthesizer format for
        # playback, so as to have a fair comparison with the generated audio
        wav = Synthesizer.load_preprocess_wav(fpath)
        self.ui.log("Loaded %s" % name)

        self.add_real_utterance(wav, name, speaker_name)

    def record(self):
        wav = self.ui.record_one(encoder.sampling_rate, 5)
        if wav is None:
            return
        self.ui.play(wav, encoder.sampling_rate)

        speaker_name = "user01"
        name = speaker_name + "_rec_%05d" % np.random.randint(100000)
        self.add_real_utterance(wav, name, speaker_name)

    def add_real_utterance(self, wav, name, speaker_name):
        # Compute the mel spectrogram
        spec = Synthesizer.make_spectrogram(wav)
        self.ui.draw_spec(spec, "current")

        # Compute the embedding
        if not encoder.is_loaded():
            self.init_encoder()
        encoder_wav = encoder.preprocess_wav(wav)
        embed, partial_embeds, _ = encoder.embed_utterance(encoder_wav, return_partials=True)

        # Add the utterance
        utterance = Utterance(name, speaker_name, wav, spec, embed, partial_embeds, False)
        self.utterances.add(utterance)
        self.ui.register_utterance(utterance)

        # Plot it
        self.ui.draw_embed(embed, name, "current")
        self.ui.draw_umap_projections(self.utterances)

    def clear_utterances(self):
        self.utterances.clear()
        self.ui.draw_umap_projections(self.utterances)

    def synthesize(self):
        self.ui.log("Generating the mel spectrogram...")
        self.ui.set_loading(1)

        # Update the synthesizer random seed
        if self.ui.random_seed_checkbox.isChecked():
            seed = int(self.ui.seed_textbox.text())
            self.ui.populate_gen_options(seed, self.trim_silences)
        else:
            seed = None

        if seed is not None:
            torch.manual_seed(seed)

        # Synthesize the spectrogram
        if self.synthesizer is None or seed is not None:
            self.init_synthesizer()

        texts = self.ui.text_prompt.toPlainText().split("\n")
        embed = self.ui.selected_utterance.embed
        embeds = [embed] * len(texts)
        specs = self.synthesizer.synthesize_spectrograms(texts, embeds)
        breaks = [spec.shape[1] for spec in specs]
        spec = np.concatenate(specs, axis=1)

        self.ui.draw_spec(spec, "generated")
        self.current_generated = (self.ui.selected_utterance.speaker_name, spec, breaks, None)
        self.ui.set_loading(0)

    def vocode(self):
        speaker_name, spec, breaks, _ = self.current_generated
        assert spec is not None

        # Initialize the vocoder model and make it determinstic, if user provides a seed
        if self.ui.random_seed_checkbox.isChecked():
            seed = int(self.ui.seed_textbox.text())
            self.ui.populate_gen_options(seed, self.trim_silences)
        else:
            seed = None

        if seed is not None:
            torch.manual_seed(seed)

        # Synthesize the waveform
        if not vocoder.is_loaded() or seed is not None:
            self.init_vocoder()

        def vocoder_progress(i, seq_len, b_size, gen_rate):
            real_time_factor = (gen_rate / Synthesizer.sample_rate) * 1000
            line = "Waveform generation: %d/%d (batch size: %d, rate: %.1fkHz - %.2fx real time)" \
                   % (i * b_size, seq_len * b_size, b_size, gen_rate, real_time_factor)
            self.ui.log(line, "overwrite")
            self.ui.set_loading(i, seq_len)
        if self.ui.current_vocoder_fpath is not None:
            self.ui.log("")
            wav = vocoder.infer_waveform(spec, progress_callback=vocoder_progress)
        else:
            self.ui.log("Waveform generation with Griffin-Lim... ")
            wav = Synthesizer.griffin_lim(spec)
        self.ui.set_loading(0)
        self.ui.log(" Done!", "append")

        # Add breaks
        b_ends = np.cumsum(np.array(breaks) * Synthesizer.hparams.hop_size)
        b_starts = np.concatenate(([0], b_ends[:-1]))
        wavs = [wav[start:end] for start, end, in zip(b_starts, b_ends)]
        breaks = [np.zeros(int(0.15 * Synthesizer.sample_rate))] * len(breaks)
        wav = np.concatenate([i for w, b in zip(wavs, breaks) for i in (w, b)])

        # Trim excessive silences
        if self.ui.trim_silences_checkbox.isChecked():
            wav = encoder.preprocess_wav(wav)

        # Play it
        wav = wav / np.abs(wav).max() * 0.97
        self.ui.play(wav, Synthesizer.sample_rate)

        # Name it (history displayed in combobox)
        # TODO better naming for the combobox items?
        wav_name = str(self.waves_count + 1)

        #Update waves combobox
        self.waves_count += 1
        if self.waves_count > MAX_WAVS:
          self.waves_list.pop()
          self.waves_namelist.pop()
        self.waves_list.insert(0, wav)
        self.waves_namelist.insert(0, wav_name)

        self.ui.waves_cb.disconnect()
        self.ui.waves_cb_model.setStringList(self.waves_namelist)
        self.ui.waves_cb.setCurrentIndex(0)
        self.ui.waves_cb.currentIndexChanged.connect(self.set_current_wav)

        # Update current wav
        self.set_current_wav(0)

        #Enable replay and save buttons:
        self.ui.replay_wav_button.setDisabled(False)
        self.ui.export_wav_button.setDisabled(False)

        # Compute the embedding
        # TODO: this is problematic with different sampling rates, gotta fix it
        if not encoder.is_loaded():
            self.init_encoder()
        encoder_wav = encoder.preprocess_wav(wav)
        embed, partial_embeds, _ = encoder.embed_utterance(encoder_wav, return_partials=True)

        # Add the utterance
        name = speaker_name + "_gen_%05d" % np.random.randint(100000)
        utterance = Utterance(name, speaker_name, wav, spec, embed, partial_embeds, True)
        self.utterances.add(utterance)

        # Plot it
        self.ui.draw_embed(embed, name, "generated")
        self.ui.draw_umap_projections(self.utterances)

    def init_encoder(self):
        model_fpath = self.ui.current_encoder_fpath

        self.ui.log("Loading the encoder %s... " % model_fpath)
        self.ui.set_loading(1)
        start = timer()
        encoder.load_model(model_fpath)
        self.ui.log("Done (%dms)." % int(1000 * (timer() - start)), "append")
        self.ui.set_loading(0)

    def init_synthesizer(self):
        model_fpath = self.ui.current_synthesizer_fpath

        self.ui.log("Loading the synthesizer %s... " % model_fpath)
        self.ui.set_loading(1)
        start = timer()
        self.synthesizer = Synthesizer(model_fpath)
        self.ui.log("Done (%dms)." % int(1000 * (timer() - start)), "append")
        self.ui.set_loading(0)

    def init_vocoder(self):
        model_fpath = self.ui.current_vocoder_fpath
        # Case of Griffin-lim
        if model_fpath is None:
            return

        self.ui.log("Loading the vocoder %s... " % model_fpath)
        self.ui.set_loading(1)
        start = timer()
        vocoder.load_model(model_fpath)
        self.ui.log("Done (%dms)." % int(1000 * (timer() - start)), "append")
        self.ui.set_loading(0)

    def update_seed_textbox(self):
       self.ui.update_seed_textbox()


"""
Entrypoint module, in case you use `python -mdaily_income`.

Why does this file exist, and why __main__? For more info, read:

- https://www.python.org/dev/peps/pep-0338/
- https://docs.python.org/2/using/cmdline.html#cmdoption-m
- https://docs.python.org/3/using/cmdline.html#cmdoption-m
"""
import argparse
from pathlib import Path

from daily_income.cli import run

def parse_args():
    parser = argparse.ArgumentParser()

    parser.add_argument("month", type=int, help="month of income workbook")
    parser.add_argument("year", type=int, help="year of income workbook")
    parser.add_argument("--output", type=Path, default=".", help="Output path")

    return parser.parse_args()

def main():
    args = parse_args()

    run(args.month, args.year, args.output)

if __name__ == "__main__":
    main()


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Chrome History database plugin."""

import unittest

from plaso.formatters import chrome as _  # pylint: disable=unused-import
from plaso.lib import eventdata
from plaso.lib import timelib
from plaso.parsers import sqlite
from plaso.parsers.sqlite_plugins import chrome

from tests.parsers.sqlite_plugins import test_lib

class ChromeHistoryPluginTest(test_lib.SQLitePluginTestCase):
  """Tests for the Google Chrome History database plugin."""

  def setUp(self):
    """Makes preparations before running an individual test."""
    self._plugin = chrome.ChromeHistoryPlugin()

  def testProcess(self):
    """Tests the Process function on a Chrome History database file."""
    test_file = self._GetTestFilePath([u'History'])
    cache = sqlite.SQLiteCache()
    event_queue_consumer = self._ParseDatabaseFileWithPlugin(
        self._plugin, test_file, cache)
    event_objects = self._GetEventObjectsFromQueue(event_queue_consumer)

    # The History file contains 71 events (69 page visits, 1 file downloads).
    self.assertEqual(len(event_objects), 71)

    # Check the first page visited entry.
    event_object = event_objects[0]

    self.assertEqual(
        event_object.timestamp_desc, eventdata.EventTimestamp.PAGE_VISITED)

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2011-04-07 12:03:11')
    self.assertEqual(event_object.timestamp, expected_timestamp)

    expected_url = u'http://start.ubuntu.com/10.04/Google/'
    self.assertEqual(event_object.url, expected_url)

    expected_title = u'Ubuntu Start Page'
    self.assertEqual(event_object.title, expected_title)

    expected_msg = (
        u'{0:s} ({1:s}) [count: 0] Host: start.ubuntu.com '
        u'Visit Source: [SOURCE_FIREFOX_IMPORTED] Type: [LINK - User clicked '
        u'a link] (URL not typed directly - no typed count)').format(
            expected_url, expected_title)
    expected_short = u'{0:s} ({1:s})'.format(expected_url, expected_title)

    self._TestGetMessageStrings(event_object, expected_msg, expected_short)

    # Check the first file downloaded entry.
    event_object = event_objects[69]

    self.assertEqual(
        event_object.timestamp_desc, eventdata.EventTimestamp.FILE_DOWNLOADED)

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2011-05-23 08:35:30')
    self.assertEqual(event_object.timestamp, expected_timestamp)

    expected_url = (
        u'http://fatloss4idiotsx.com/download/funcats/'
        u'funcats_scr.exe')
    self.assertEqual(event_object.url, expected_url)

    expected_full_path = u'/home/john/Downloads/funcats_scr.exe'
    self.assertEqual(event_object.full_path, expected_full_path)

    expected_msg = (
        u'{0:s} ({1:s}). '
        u'Received: 1132155 bytes out of: '
        u'1132155 bytes.').format(expected_url, expected_full_path)
    expected_short = u'{0:s} downloaded (1132155 bytes)'.format(
        expected_full_path)
    self._TestGetMessageStrings(event_object, expected_msg, expected_short)

if __name__ == '__main__':
  unittest.main()


import requests
import re
from lxml import etree
import pymongo
from config import *
from multiprocessing import Pool

client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]

def get_one_page(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}
    response = requests.get(url, headers=headers)
    return response

def get_url_page(html):
    selector = etree.HTML(html.text)
    music_hrefs = selector.xpath('//a[@class="nbg"]/@href')
    return music_hrefs

def parse_url_page(html):
    selector = etree.HTML(html.text)
    name = selector.xpath('//*[@id="wrapper"]/h1/span/text()')[0]
    author = re.findall('表演者:.*?>(.*?)', html.text, re.S)[0]
    styles = re.findall('流派: (.*?)
', html.text, re.S)
    if len(styles) == 0:
        style = '未知'
    else:
        style = styles[0].strip()
    time = re.findall('发行时间: (.*?)
', html.text, re.S)[0].strip()
    number = re.findall('class="rating_people.*?"v:votes">(.*?)', html.text, re.S)
    if len(number) == 0:
        number = '未知'
    else:
        number = number[0].strip() + '人评论'
    source = selector.xpath('//*[@id="interest_sectl"]/div/div[2]/strong/text()')[0]
    return {
        'name': name,
        'author': author,
        'styles': style,
        'time': time,
        'number': number,
        'source': source
    }

def save_to_mongo(result):
    if db[MONGO_TABLE].insert(result):
        print('存储到MongoDB成功', result)
        return True
    return False

def main(offset):
    url = 'https://music.douban.com/top250?start=' + str(offset)
    html = get_one_page(url)
    for item in get_url_page(html):
        parse = get_one_page(item)
        result = parse_url_page(parse)
        print(result)
        save_to_mongo(result)

if __name__ == '__main__':
    groups = [i * 25 for i in range(GROUP_START, GROUP_END + 1)]
    pool = Pool(4)
    pool.map(main, groups)


from settings import *
from random import randint

class Enemy(pygame.Rect):
    def __init__(self, hp, speed, coin, image, x_view, y_view, x_matrix, y_matrix, template_count_step, spawn_count):
        super().__init__(x_view, y_view, STEP, STEP)
        # image = 1
        self.image = pygame.image.load(PATH + f'/images/enemies/zombie{image}-1.png')
        self.image = pygame.transform.scale(self.image, (STEP,STEP))
        self.image1 = pygame.image.load(PATH + f'/images/enemies/zombie{image}-2.png')
        self.image1 = pygame.transform.scale(self.image1, (STEP,STEP))
        self.image_right_1 = pygame.transform.flip(self.image,True, False)
        self.image_left_1 = self.image
        self.image_right_2 = pygame.transform.flip(self.image1,True, False)
        self.image_left_2 = self.image1
        self.skin = 0
        self.speed = STEP
        self.hp = hp
        self.max_hp = hp
        self.coin = coin
        self.x_matrix = x_matrix
        self.y_matrix = y_matrix
        self.template_count_step = template_count_step
        self.spawn_count = spawn_count
        self.count_step = template_count_step
        self.count_moving = 0
        self.template_count_moving = 25
        self.hp_bar = pygame.Rect(self.x + 5, self.y - 10, 40, 6)
        self.hp_rect = pygame.Rect(self.x + 5, self.y - 10, 40, 6)
        self.damage_to_pixel = 40 - (((hp - 1) * 40) /  hp )
        self.rotation_side = "left"
        self.invulnerability = True
        self.count_skin = 0
        self.coin_y = None
        self.dead_count = -1
    def move(self):
        if self.count_step == 0:
            if self.invulnerability:
                self.invulnerability = False
            direction = map[self.y_matrix][self.x_matrix]
            # u d r l
            if direction == 'u':
                if self.count_moving != self.template_count_moving:
                    self.y -= self.speed // self.template_count_moving
                    if self.skin == 0:
                        if self.rotation_side == "right":
                            self.image = self.image_right_1
                        elif self.rotation_side == "left":
                            self.image = self.image_left_1
                    elif self.skin == 1:
                        if self.rotation_side == "right":
                            self.image = self.image_right_2
                        elif self.rotation_side == "left":
                            self.image = self.image_left_2
                    self.count_moving += 1
                else:
                    self.y_matrix -= 1
                    self.count_moving = 0
            elif direction == 'd':
                if self.count_moving != self.template_count_moving:
                    self.y += self.speed // self.template_count_moving
                    if self.skin == 0:
                        if self.rotation_side == "right":
                            self.image = self.image_right_1
                        elif self.rotation_side == "left":
                            self.image = self.image_left_1
                    elif self.skin == 1:
                        if self.rotation_side == "right":
                            self.image = self.image_right_2
                        elif self.rotation_side == "left":
                            self.image = self.image_left_2
                    self.count_moving += 1
                else:
                    self.y_matrix += 1
                    self.count_moving = 0
            elif direction == 'l':
                if self.count_moving != self.template_count_moving:
                    if self.skin == 0:
                        self.image = self.image_left_1
                    else:
                        self.image = self.image_left_2
                    self.rotation_side = "left"
                    self.x -= self.speed // self.template_count_moving
                    self.count_moving += 1
                else:
                    self.x_matrix -= 1
                    self.count_moving = 0
            elif direction == 'r':
                if self.count_moving != self.template_count_moving:
                    if self.skin == 0:
                        self.image = self.image_right_1
                    else:
                        self.image = self.image_right_2
                    self.rotation_side = "right"
                    self.x += self.speed // self.template_count_moving
                    self.count_moving += 1
                else:
                    self.x_matrix += 1
                    self.count_moving = 0
            self.count_step = self.template_count_step
            self.hp_bar.x = self.x + 5
            self.hp_bar.y = self.y - 10
            self.hp_rect.x = self.x + 5
            self.hp_rect.y = self.y - 10
        else:
            self.count_step -= 1

    def draw(self):
        if self.spawn_count == 0:
            # self.attack()
            # print(self.x_matrix, self.y_matrix)
            if self.count_skin == 0:
                if self.skin == 0:
                    self.skin = 1
                else:
                    self.skin = 0
                self.count_skin = 50
            else:
                self.count_skin -= 1
            if self.dead_count == -1:
                self.move()
            else:
                window.blit(coin_image, (self.x + 10, self.coin_y))
            window.blit(self.image, (self.x, self.y))
            pygame.draw.rect(window, (0,0,0), self.hp_bar)
            pygame.draw.rect(window, (255,0,0), self.hp_rect)
        else:
            self.spawn_count -= 1

    # def attack(self):
    #     if randint(1,10) == 1:
    #         damage = randint(1,10)
    #         self.hp -= damage
    #         self.hp_rect.width -= damage * self.damage_to_pixel
# [  ]


#!/usr/bin/env python3

from cmath import exp
import os
import pymonetdb

conn = pymonetdb.connect(
    database=os.getenv("TSTDB"),
    port=int(os.getenv("MAPIPORT")))

conn.set_autocommit(False)

CONTENT = dict(
    invalid_utf8=b'"invali\x80\x80"',
    unterminated_object=b'{"foo": "bar',
    valid_json=b'{"foo":42}'
)

class MyUploader(pymonetdb.Uploader):
    def handle_upload(self, upload: pymonetdb.Upload, filename: str, text_mode: bool, skip_amount: int):
        assert text_mode == False
        assert skip_amount == 0
        json = CONTENT[filename]
        bw = upload.binary_writer()
        bw.write(json + b'\x00')

conn.set_uploader(MyUploader())

def run_test(content_name, expected_exception):
    c = conn.cursor()
    try:
        c.execute("DROP TABLE IF EXISTS foo")
        c.execute("CREATE TABLE foo(j JSON)")
        try:
            c.execute("COPY BINARY INTO foo FROM %s ON CLIENT", [content_name])
            if expected_exception:
                content = CONTENT[content_name]
                msg = f"Expected error involving '{expected_exception}' when loading {content!r}"
                raise Exception(msg)
        except pymonetdb.OperationalError as e:
            if expected_exception in str(e):
                conn.rollback()
                return
            raise e
    finally:
        c.close()

run_test('valid_json', None)
run_test('invalid_utf8', 'malformed utf')
run_test('unterminated_object', 'JSONfromString')


class Solution(object):
    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        ret = ""
        for i in range(0, len(s), 2*k):
            rev = s[i:i+k]
            rev = rev[::-1]
            ret += rev + s[i+k: i+2*k]
        return ret


from aocd.models import Puzzle
from argparse import ArgumentParser
import itertools

def load_data(mode: str):
    if mode == "test":
        data = Puzzle(2015, 13).example_data.splitlines()
    else:
        data = Puzzle(2015, 13).input_data.splitlines()

    happys = {}
    for line in data:
        splits = line.split()
        beneficiary, gain, target = splits[0], -1*int(splits[3]) if splits[2] == "lose" else int(splits[3]), splits[len(splits)-1].removesuffix('.')
        if beneficiary not in happys.keys():
            happys[beneficiary] = {target: gain}
        else:
            happys[beneficiary][target] = gain
    return happys

def find_happiest_table(happys: dict):
    people = list(set(happys.keys()))
    print(people)
    possibilities = list(itertools.permutations(people))
    max_happiness = 0
    for possibility in possibilities:
        table_happiness = 0
        for i in range(len(people)):
            if i < len(people)-1:
                j = i+1
            else:
                j = 0
            table_happiness += happys[possibility[i]][possibility[j]] + happys[possibility[j]][possibility[i]]
        max_happiness = max(max_happiness, table_happiness)
    return max_happiness

def add_self(happys: dict):
    for k in happys.keys():
        happys[k]['self'] = 0
    keys = happys.keys()
    happys['self'] = {k: 0 for k in keys}
    return happys

if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("mode", choices=['test', 'input'])
    args = parser.parse_args()

    happys = load_data(args.mode)
    total = find_happiest_table(happys)
    print(total)

    total = find_happiest_table(add_self(happys))
    print(total)


class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        carry = 0
        result = []
        i = len(a) - 1
        j = len(b) - 1

        while i >= 0 or j >= 0 or carry:
            # Convert characters to integers or use 0 if the index is out of range
            digit_a = int(a[i]) if i >= 0 else 0
            digit_b = int(b[j]) if j >= 0 else 0

            # Calculate sum and carry
            digit_sum = digit_a + digit_b + carry
            carry = digit_sum // 2
            result.append(str(digit_sum % 2))

            # Decrement indices
            i -= 1
            j -= 1

        # Reverse the result and return as a string
        return ''.join(result[::-1])

# Example usage:
solution = Solution()
binary_string1 = "101010"
binary_string2 = "11011"

sum_result = solution.addBinary(binary_string1, binary_string2)
print("Sum:", sum_result)


from . import conf, shortcuts, exceptions
import os
import subprocess
import sys
import json

class BowerAdapter(object):
    """Adapter for working with bower"""

    def __init__(self, bower_path, components_root):
        self._bower_path = bower_path
        self._components_root = components_root

    def is_bower_exists(self):
        """Check is bower exists"""
        if shortcuts.is_executable(self._bower_path)\
                or shortcuts.which(self._bower_path):
            return True
        else:
            return False

    def create_components_root(self):
        """Create components root if need"""
        if not os.path.exists(self._components_root):
            os.makedirs(self._components_root)

    def call_bower(self, args):
        """Call bower with a list of args"""
        proc = subprocess.Popen(
            [self._bower_path] + list(args),
            cwd=self._components_root)
        proc.wait()

    def install(self, packages, *options):
        """Install packages from bower"""
        self.call_bower(['install'] + list(options) + list(packages))

    def _accumulate_dependencies(self, data):
        """Accumulate dependencies"""
        for name, params in data['dependencies'].items():
            meta = params.get('pkgMeta', {})
            version = meta.get(
                'version', meta.get('_resolution', {}).get('commit', ''),
            )

            if version:
                full_name = '{0}#{1}'.format(name, version)
            else:
                full_name = name

            self._packages.append(full_name)
            self._accumulate_dependencies(params)

    def _parse_package_names(self, output):
        """Get package names in bower >= 1.0"""
        data = json.loads(output)
        self._packages = []
        self._accumulate_dependencies(data)
        return self._packages

    def freeze(self):
        """Yield packages with versions list"""
        proc = subprocess.Popen(
            [self._bower_path, 'list', '--json', '--offline', '--no-color'],
            cwd=conf.COMPONENTS_ROOT,
            stdout=subprocess.PIPE,
        )
        outs, errs = proc.communicate()
        output = outs.decode(sys.getfilesystemencoding())

        try:
            packages = self._parse_package_names(output)
        except ValueError:
            raise exceptions.LegacyBowerVersionNotSupported()

        return iter(set(packages))

bower_adapter = BowerAdapter(conf.BOWER_PATH, conf.COMPONENTS_ROOT)


class Entity():
  def __init__(self, isEntity):
    self.isEntity = isEntity

class LivingThing(Entity):
  def __init__(self, isLive, isEntity):
    self.isLive = isLive
    self.isEntity = isEntity

  def isLiving(self):
      if self.isLive == 1:
        print("I am living")
      elif self.isLive == 0:
        print("....")

class Animal(LivingThing):
  def __init__(self,isLive,isEntity, name, age, realm):
    self.name = name
    self.age = age
    self.realm = realm
    self.isLive = isLive
    self.isEntity= isEntity

class Dog(Animal):
  def __init__(self,isLive, isEntity, name, age, realm):
    self.isLive = isLive
    self.isEntity = isEntity
    self.name = name
    self.age = age
    self.realm = realm
    self.type = "dog"

  def speakDog(self):
    if self.isEntity and self.isLive:
      print(f"My name is {self.name}, and I am Living Entity and {self.realm}. My age is {self.age}, my type is {self.type}")

myAnimal = Dog(True, True,'Gofret', 5, 'Animal')
myAnimal.speakDog()
myAnimal.isLiving()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author:
Grimm Venom <grimmvenom@gmail.com>

Summary:
Python tool to parse sitemap.xml files and add to DB and write organized xml output
Example:  python3 ./sitemap-parse.py -f Enterprise-Prod-sitemap.xml -db Enterprise.db -table Enterprise_Prod

"""

import os, time, sys, json, ast, datetime
import requests, argparse, sqlite3
import xml.etree.ElementTree as ET
from operator import itemgetter

def log_output(output_name):
	log_dir = current_dir + "/logs"
	if not os.path.exists(log_dir):  # Check if logs directory does not exist
		os.makedirs(log_dir)  # Create logs directory
	pylog = log_dir + "/" + output_name
	# Define Standard Output
	# sys.stdout = open(pylog, 'w')
	class Tee(object):
		def __init__(self, *files):
			self.files = files

		def write(self, obj):
			for f in self.files:
				f.write(obj)
				f.flush()  # If you want the output to be visible immediately

		def flush(self):
			for f in self.files:
				f.flush()

	pyout = open(pylog, 'w')
	# original = sys.stdout
	sys.stdout = Tee(sys.stdout, pyout)

def get_arguments():
	# Define Arguments the Script will accept
	parser = argparse.ArgumentParser()
	parser.add_argument('-f', "-file", action='append', dest='files', required=True, help='Enter Input .xml file to parse and sort')
	parser.add_argument('-db', "-database", action='store', dest='database', required=True, help='Enter Database File to write information to. Typically <vendor>.db')
	parser.add_argument('-t', "-table", "-p", "-project", action='store', dest='table', required=True, help='Enter table name (<project>_<Environment>). Typically <applicationName>_<env>')
	arguments = parser.parse_args() # Parse through arguments added when the script is called

	if not arguments.database.endswith(".db"):
		arguments.database = arguments.database + ".db"

	if not os.path.exists(arguments.database):
		if os.path.exists(parent_dir + "/database/" + arguments.database.capitalize()):
			arguments.database = parent_dir + "/database/" + arguments.database
		else:
			arguments.database =  current_dir + "/database/" + arguments.database.capitalize()
			if not os.path.exists(os.path.dirname(os.path.realpath(arguments.database))):
				print("Creating Database Directory")
				os.makedirs(os.path.dirname(os.path.realpath(arguments.database)))

	if not arguments.table.endswith("_sitemap"):
		arguments.table = arguments.table + "_sitemap"
	arguments.table = arguments.table.replace('.', '_')
	return arguments

def clarify_domain(file, print_output=False):
	it = ET.iterparse(file)
	for _, el in it:
		if '}' in el.tag:
			el.tag = el.tag.split('}', 1)[1]  # strip all namespaces
	root = it.root

	# Get Domain from Sitemap.xml
	info = root.findall('.//url')[0]
	url = info.find('.//loc').text

	if not url.endswith("/"):
		url = url + "/"
	# Determine Protocol being used for URL
	if url.startswith("http://"):
		protocol = 'http'
	elif url.startswith("https://"):
		protocol = 'https'
	else:
		protocol = 'http'

	site = url.replace(protocol + "://", "") # Remove Protocol to determine domain name
	if "/" in site:
		domain = site.split("/", 1)[0] # Get Site Domain before the "/" in url
		# if site[-1] == '/': site = site[:-1]  # Remove Last character if it is a '/'
		page_path = site.split("/", 1)[-1]# Get the Pages in url after the first "/"
		if (len(page_path) <= 1) or (page_path == domain):
			page_path = "/"
			page = "/"
		else:
			page = page_path.split("/", 1)
			try:
				page.remove("")
			except:
				pass
			page = page[-1]
			page = page.replace("/", "")

	else:
		domain = site
		page_path = "/"
		page = "/"

	if not page_path.startswith("/"):
		page_path = "/" + page_path

	protocol = protocol + "://"
	site_root = protocol + domain

	if print_output == True:
		print(" ")
		print("URL: " + url)
		print("Protocol: " + protocol.strip("://"))
		print("Domain: " + domain)
		print("Page Path: " + page_path)
		print("Page: " + str(page))
		print("Site Root: " + site_root)
		print(" ")
	return domain, site_root, page_path, page

def parse_sitemap(file):
	print("Reading Sitemap from: " + file)
	it = ET.iterparse(file)
	for _, el in it:
		if '}' in el.tag:
			el.tag = el.tag.split('}', 1)[1]  # strip all namespaces
	root = it.root

	# Loop through all entries in sitemap.xml file
	for info in root.findall('.//url'): # Test limited [0:6]
		xml_url = info.find('.//loc').text
		try:
			last_mod = info.find('.//lastmod').text
		except:
			last_mod = str(date)
			pass
		try:
			if "T" in last_mod: # If loastmod == date+time
				last_mod = last_mod.split("T", 1)[0] # Strip the Time out
		except:
			pass

		#print("url: " + xml_url)
		#print("Last Modified: " + last_mod)
		#print(" ")
		entries.append([xml_url, last_mod])

	print(" ")

	sorted_entries = sorted(entries, key=itemgetter(0)) # Sort List alphabetically

	return sorted_entries

def manage_sitemap_db():
	print(" ")
	print("Checking for db: " + arguments.database)
	print("Checking Table: " + arguments.table)
	con = sqlite3.connect(arguments.database)
	with con:
		cur = con.cursor()
		cur.execute("CREATE TABLE IF NOT EXISTS " + arguments.table + "(url TEXT, last_modified TEXT, appended TEXT)")
		for index, entry in enumerate(entries):
			url = str(entry[0])
			last_mod = str(entry[1])
			appended = str(date)
			cur.execute("SELECT url,last_modified FROM " + arguments.table + " WHERE url = ?", (url,))
			data = cur.fetchone()

			if data is None:
				print(str(index) + ") - entry: " + str(entry) + " -- Not Found in DB")
				print(entries[index])
				print(str(data))
				# print('There is no url found for:  %s' % url)
				try:
					cur.execute("insert into " + arguments.table + "  values(?,?,?)", (url, last_mod, appended,))
				except:
					print("Issue Writing Entry to DB")
					pass
				print(" ")

			elif str(data[1]) != str(last_mod):
				print(str(index) + ") - entry: " + str(entry) + " -- Last Modified Dates don't match")
				print(entries[index])
				print(str(data))
				print("data[1]: " + str(data[1] + " last_mod: " + str(last_mod)))
				#print("Updating Last Modified Date")
				try:
					cur.execute("update " + arguments.table + " set last_modified=? , appended=?", (last_mod, appended))
				except:
					print("Issue Updating Entry in DB")
					pass
			else:
				print(str(index) + ") - entry: " + str(entry) + " -- Exists in DB")
				print(" ")
		print(" ")
		#con.executemany('insert into ' + table_name + '(url, last_modified) values (?, ?)', entries)
	con.commit()
	con.close()

# Global Variables
date = time.strftime("%m-%d-%y") # Date Format mm-dd-yyyy_Hour_Min
Time = time.strftime("%H_%M")
current_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
output_dir = current_dir + "/output/"

arguments = get_arguments()
log_output("Sitemap-parser-" + str(date) + "_" + str(Time))

print("Database: " + str(arguments.database))
print("Table: " + str(arguments.table))
print("Files: " + str(arguments.files))
print(" ")

if len(arguments.files) > 0:
	for file in arguments.files:
		print("Checking " + file)
		file = output_dir + file
		entries = []
		domain, site_root, page_path, page = clarify_domain(file)  # extract domain from sitemap
		entries = parse_sitemap(file)  # Sitemap extract urls and last modified
		manage_sitemap_db()  # Sitemap create DB


import functools

import librl.agent.pg, librl.agent.mdp
import librl.task
import librl.train.cc

@functools.singledispatch
def compute_meta_loss(agent, task):
    # If you introduce a new agent type, and you wish to allow this agent to be updated via
    # MAML, you must register an override for this function.
    # Must return an iterable of losses.
    raise NotImplemented(f"Meta loss computation not implemented for this agent type.")

@compute_meta_loss.register(librl.agent.mdp.RandomAgent)
def _(agent, task):
    return []

@compute_meta_loss.register(librl.agent.pg.REINFORCEAgent)
def _(agent, task):
    return (getattr(agent, 'actor_loss_mult', 1) * agent.actor_loss(task),)

@compute_meta_loss.register(librl.agent.pg.ActorCriticAgent)
def _(agent, task):
    return (agent.critic_loss(task), getattr(agent,'actor_loss_mult', 1) * agent.actor_loss(task))

@functools.singledispatch
def step_meta_optimizer(agent):
        # If you introduce a new agent type, and you wish to allow this agent to be updated via
    # MAML, you must register an override for this function.
    raise NotImplemented(f"Meta optimizer step not implemented for this agent type.")

@step_meta_optimizer.register(librl.agent.mdp.RandomAgent)
def _(agent):
    pass
@step_meta_optimizer.register(librl.agent.pg.REINFORCEAgent)
def _(agent):
    # TODO: Grab grad clip from agent's hypers.
    #torch.nn.utils.clip_grad_norm(agent.parameters(), 40)
    agent.actor_optimizer.step()
@step_meta_optimizer.register(librl.agent.pg.ActorCriticAgent)
def _(agent):
    # TODO: Grab grad clip from agent's hypers.
    #torch.nn.utils.clip_grad_norm(agent.parameters(), 40)
    agent.actor_optimizer.step()
    agent.critic_optimizer.step()

# Implement MAML algorithm for meta-RL tasks
# Assumes there is no interaction between different agents.
# If components of an agent are shared between tasks, gradient updates are no longer independent.
def maml_meta_step(task_samples, adapt_steps = 1):
    for task in task_samples: assert task.problem_type == librl.task.ProblemTypes.ContinuousControl
    # Collect all unique agents in our task list.
    agents = { (id(task.agent),task.agent) for task in task_samples}
    # Make sure we do not persist grads between training epochs.
    for _, agent in agents: agent.zero_grad()
    # Keep track of our starting parmeters.
    # Since we have potential redundant agents, only keep one copy of our params per agent.
    slow_parameters = {id_agent : agent.steal() for id_agent, agent in agents}
    # However, each task will have unique parameters after being adapted.
    size = len(task_samples)
    adapted_parameters, adapted_grads, adapted_rewards = size*[None], size*[None], size*[None]

    ####################
    # Task Adaptation  #
    ####################
    for idx, task in enumerate(task_samples):
        agent = task.agent
        agent.stuff(slow_parameters[id(agent)])
        # Perform an arbitrary number of adaptation steps
        for _ in range(adapt_steps): librl.train.cc.policy_gradient_step([task])

        # Sample a task for the meta-adaptation step and compute the loss based on agent type.
        task.sample(task)
        for loss in compute_meta_loss(agent, task): loss.backward()

        # All pytorch optimizers perform updates using grads.
        # If we copy out the grads and apply them later, pytorch won't be any wiser
        # as to how those grads got there. Use "clone" to prevent grads from being deleted.
        adapted_grads[idx] = [(p.grad.clone().detach() if p.grad != None else None)for p in agent.parameters()]
        adapted_rewards[idx] = functools.reduce(lambda x, y: x+sum(y.reward_buffer.view(-1)), task.trajectories, 0)

        # Prevent meta-grads from polluting the next task's update.
        agent.zero_grad()
        adapted_parameters[idx] = agent.steal()

    ####################
    # Meta-update step #
    ####################
    # We want to apply gradient updates to our starting weights,
    # and we want to discard any existing gradient updates
    for id_agent, agent in agents: agent.stuff(slow_parameters[id_agent]), agent.zero_grad()

    # Apply the i'th task's gradient update to the i'th task's agent.
    for idx, task in enumerate(task_samples):
        agent = task.agent
        for param, grad in zip(agent.parameters(), adapted_grads[idx]):
            # Some parts of a model may be frozen, so we can skip those params.
            if not param.requires_grad or grad is None: continue
            # If our grad object doesn't exist, we must create one in place.
            if param.grad is None: param.grad = grad
            # Otherwise accumulate grads in place.
            else: param.grad.add_(grad)

    # And apply those using our existing optimizer.
    for _, agent in agents: step_meta_optimizer(agent)


"""
:created on: 2017-08-15

:author: Marcin Muszynski
:contact: marcinowski007@gmail.com
"""

from django.shortcuts import reverse
from paranuara.tests import NoSQLTestCase

class TestAPIEndpoints(NoSQLTestCase):
    """ Class for testing 200 on list endpoints """
    def test_companies_list(self):
        url = reverse('api:company-list')
        r = self.client.get(url)
        self.assertEqual(r.status_code, 200)

    def test_employees_list(self):
        url = reverse('api:employee-list')
        r = self.client.get(url)
        self.assertEqual(r.status_code, 200)


import time
import serial

HEADER    = "\x5D"
WRITE_CMD = "\xC0"

class OscControl(object):

	def __init__(self, portName):
		self.port = serial.Serial(portName, 115200)

	# Calculate checksum for string {instr}
	# this is a very simple checksum, not a CRC or anything.
	# For the short packet sizes used here, it's sufficent.
	def __calculateChecksum(self, instr):
		cksum = 0
		for char in instr:
			cksum += ord(char)
		return chr(cksum & 0xFF)

	# Write frequency value {value} out the serial port in the proper command structure
	def __writeOscillator(self, value):

		pkt = "%s%s" % (HEADER, WRITE_CMD)
		for dummy_x in range(4):
			pkt += chr(value & 0xFF)
			value >>= 8

		cksum = self.__calculateChecksum(pkt)
		pkt += cksum
		print("Checksum", ord(cksum))
		self.port.write(pkt)
		time.sleep(0.05)
		rx = self.exhaust()
		if rx:
			print("Hardware Response: '%s'" % rx)

	# Read all data in the rx buffer. Return it as a string with leading and trailing whitespace/newlines stripped
	def exhaust(self):
		ret = ""
		while self.port.inWaiting():
			ret += self.port.read()
		return ret.strip()

	# Set oscillator frequency
	def writeOscillator(self, freq):
		print("Writing oscillator", freq)
		freq = int(freq)
		if freq < 10e6 or freq > 810e6:
			raise ValueError("Frequency %s is not valid. Valid available frequencies are 10 Mhz - 810 Mhz." % freq)

		self.__writeOscillator(freq)

	# Needs hardware support, not currently supported
	def enableOscillator(self, powState=True):
		pass

	# Convenience method
	def disableOscillator(self):
		self.enableOscillator(False)

def go():
	print("Starting")
	port = OscControl("COM29")
	# port.port.write("\x5Dasdasdasd")
	print("Port opened, written to")
	print(port.exhaust())
	time.sleep(2)
	print(port.exhaust())

	print("Writing oscillator")
	port.writeOscillator(50e6)
	print("Written")

	while 1:

		port.writeOscillator(50e6)
		time.sleep(1)
		port.writeOscillator(60e6)
		time.sleep(1)
		port.writeOscillator(70e6)
		time.sleep(1)

if __name__ == "__main__":
	go()


import datetime

import discord
from discord.ext import commands, tasks
from database import Database, RaidDatabase

class ReminderCog(commands.Cog):
    def __init__(self, bot: discord.ext.commands.Bot, database: Database):
        self.bot = bot
        self.database = database
        self.reminder.start()
        self.passed = False  # 3 cases, what if start up and already passed

    def cog_unload(self):
        self.reminder.cancel()

    @tasks.loop(seconds=30)
    async def reminder(self):
        for raid in self.database.raids.values():
            if raid.has_reminder():
                for raid_reminder in raid.reminders.values():
                    time_delta = raid_reminder.get_countdown()
                    if raid_reminder.should_remind():
                        hours = int(time_delta.seconds // 3600)
                        minutes = int((time_delta.seconds % 3600) // 60)

                        channel = self.bot.get_channel(raid_reminder.channel)

                        await channel.send(f"Raid Reminder! Time until raid: {hours} hours, "
                                           f"{minutes} minutes.")

                        raid_reminder.last_reminder = datetime.datetime.now()
                        raid_reminder.alarm = False

                    if time_delta.total_seconds() < 30 and raid_reminder.alarm:
                        channel = self.bot.get_channel(raid_reminder.channel)
                        await channel.send(f"Gamers, it's time for raid owo!")
                        raid_reminder.alarm = False

class DatabaseCog(commands.Cog):
    def __init__(self, bot: discord.ext.commands.Bot, database: Database):
        self.bot = bot
        self.database = database
        self.save_database.start()

    def cog_unload(self):
        self.save_database.cancel()

    @tasks.loop(seconds=10)
    async def save_database(self):
        self.database.save("database.temp")
        self.database.save()

cogs = [ReminderCog, DatabaseCog]


class BST:
	def __init__(self, data):
		self.data = data
		self.left = None
		self.right = None

	def add_child(self, data):
		if self.data == data:
			return
		elif data<self.data:
			if self.left:
				self.left.add_child(data)
			else:
				self.left = BST(data)
		else:
			if self.right:
				self.right.add_child(data)
			else:
				self.right = BST(data)

	def print_tree(self, li=[]):
		if self.left:
			self.left.print_tree(li)
		print(self.data)
		if self.right:
			self.right.print_tree(li)
		return li

	def search(self, val):
		if val==self.data:
			return True

		if val<self.data:
			if self.left:
				return self.left.search(val)
			else:
				return False

		if val>self.data:
			if self.right:
				return self.right.search(val)
			else:
				return False

	def min(self):
		minimum = self.data
		while self.left:
			# print(minimum)
			minimum = self.left.data
			self.left = self.left.left
		return minimum

	def minrecur(self):
		if not self.left:
			return self.data
		return self.left.minrecur()

	def max(self):
		maximum = self.data
		while self.right:
			# print(maximum)
			maximum = self.right.data
			self.right = self.right.right
		return maximum

	def maxrecur(self):
		if not self.right:
			return self.data
		return self.right.maxrecur

	def delete(self, value):
		if value<self.data:
			if self.left:
				self.left = self.left.delete(value)

		elif value>self.data:
			if self.right:
				self.right = self.right.delete(value)

		else:

			if self.left is None and self.right is None:
				return None

			if self.left is None:
				return self.right

			if self.right is None:
				return self.left

			minval = self.right.minrecur()
			self.data = minval
			self.right = self.right.delete(minval)

		return self

def build(elements):
	root = BST(elements[0])
	for x in range(1, len(elements)):
		root.add_child(elements[x])

	return root

tree = build([7, 8, 9, 10, 11, 12, 13])
print(tree.print_tree())
print(tree.min())
print(tree.max())


# -*- coding: utf-8 -*-
"""This file contains a SQLite parser."""

import logging

try:
  from pysqlite2 import dbapi2 as sqlite3
except ImportError:
  import sqlite3

from plaso.lib import errors
from plaso.parsers import plugins

class SQLitePlugin(plugins.BasePlugin):
  """A SQLite plugin for Plaso."""

  NAME = u'sqlite'
  DESCRIPTION = u'Parser for SQLite database files.'

  # Queries to be executed.
  # Should be a list of tuples with two entries, SQLCommand and callback
  # function name.
  QUERIES = []

  # List of tables that should be present in the database, for verification.
  REQUIRED_TABLES = frozenset([])

  def GetEntries(
      self, parser_mediator, cache=None, database=None, **unused_kwargs):
    """Extracts event objects from a SQLite database.

    Args:
      parser_mediator: A parser mediator object (instance of ParserMediator).
      cache: A SQLiteCache object.
      database: A database object (instance of SQLiteDatabase).
    """
    for query, callback_method in self.QUERIES:
      try:
        callback = getattr(self, callback_method, None)
        if callback is None:
          logging.warning(
              u'[{0:s}] missing callback method: {1:s} for query: {2:s}'.format(
                  self.NAME, callback_method, query))
          continue

        sql_results = database.Query(query)
        row = sql_results.fetchone()

        while row:
          callback(
              parser_mediator, row, query=query, cache=cache, database=database)

          row = sql_results.fetchone()

      except sqlite3.DatabaseError as exception:
        logging.debug(u'SQLite error occurred: {0:s}'.format(exception))

  def Process(self, parser_mediator, cache=None, database=None, **kwargs):
    """Determine if this is the right plugin for this database.

    This function takes a SQLiteDatabase object and compares the list
    of required tables against the available tables in the database.
    If all the tables defined in REQUIRED_TABLES are present in the
    database then this plugin is considered to be the correct plugin
    and the function will return back a generator that yields event
    objects.

    Args:
      parser_mediator: A parser mediator object (instance of ParserMediator).
      cache: A SQLiteCache object.
      database: A database object (instance of SQLiteDatabase).

    Raises:
      errors.WrongPlugin: If the database does not contain all the tables
      defined in the REQUIRED_TABLES set.
      ValueError: If the database attribute is not passed in.
    """
    if database is None:
      raise ValueError(u'Database is not set.')

    if not frozenset(database.tables) >= self.REQUIRED_TABLES:
      raise errors.WrongPlugin(
          u'Not the correct database tables for: {0:s}'.format(self.NAME))

    # This will raise if unhandled keyword arguments are passed.
    super(SQLitePlugin, self).Process(parser_mediator)

    self.GetEntries(parser_mediator, cache=cache, database=database)


import csv
import pandas

# How  to read a csv file
with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Columns names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works at {row[1]} department, and was born in {row[2]}')
            line_count += 1
    print(f'Processed {line_count} lines')
#
#
# ##### Reading a CSV file into a Dictionary with csv

with open('employee_birthday.txt', mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Columns names are {", ".join(row)}')
            line_count += 1

        print(f'\t{row["name"]} works at {row["department"]} department,and was born in {row["birthday month"]}')
        line_count += 1
    print(f'Processed {line_count} lines')

############## WRITING CSV FILES with csv

with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file,delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)

    employee_writer.writerow(['John Smith', 'Accounting', 'November'])
    employee_writer.writerow(['Erica Meyers', 'IT', 'March'])

with open('employee_file2.csv', mode='w') as csv_file:
    fieldnames = ['emp_name', 'dept', 'birth_month']
    writer = csv.DictWriter(csv_file,fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'emp_name': 'Oloyede Paul', 'dept': 'Business Administration', 'birth_month': 'April'})
    writer.writerow({'emp_name': 'Oloyede Silas', 'dept': 'Theatre Art', 'birth_month': 'February'})