import numpy as np

class LinearModel:
    def __init__(self, A=np.array([]), B=np.array([]), C=np.array([]), minmax="MAX"):
        self.A = A
        self.B = B
        self.C = C
        self.minmax = minmax
        self.optimized = False
        self.feasible = True
        self.tableau = np.array([])
        self.basicVariableNo = self.A.shape[0]
        self.solnVarNo = self.C.size
        self.basicVars = np.ones(self.basicVariableNo) * self.basicVariableNo
        self.optimizedValue = 0
        self.optimizedVars = np.zeros(self.basicVariableNo)

    def setA(self, A):
        self.A = A

    def setB(self, B):
        self.B = B

    def setC(self, C):
        self.C = C
        self.basicVariableNo = self.C.size

    def createTableau(self):
        if self.A.size == 0 or self.B.size == 0 or self.C.size == 0:
            print("The constraints are not defined")
            exit()

        self.tableau = np.vstack((self.A, -self.C))
        self.tableau = np.hstack((self.tableau, np.identity(self.tableau.shape[0])))
        self.tableau = np.hstack((self.tableau, np.atleast_2d(np.append(self.B, 0)).T))

    def pivotCol(self):
        if not self.optimized:
            self.objRow = self.tableau[-1]
            self.pcol = min(np.where(self.objRow == min(self.objRow))[0])

    def pivotElement(self):
        nonneg = [i for i in range(self.B.size) if self.tableau[i, self.pcol] > 0]
        if nonneg == []:
            self.feasible = False
            print("The solution is not feasible")

        else:
            division = [self.tableau[i][-1]/self.tableau[i][self.pcol] for i in nonneg]
            self.prow = nonneg[division.index(min(division))]
            self.pelem = self.tableau[self.prow][self.pcol]

    def simplex(self):
        if self.feasible:
            self.basicVars[self.prow] = self.pcol

            self.tableau[self.prow] /= self.pelem
            for i in range(self.tableau.shape[0]):
                if i != self.prow:
                    self.tableau[i] = self.tableau[i] - self.tableau[self.prow] * self.tableau[i][self.pcol]

    def checkOptimized(self):
        if self.feasible:
            self.optimized = True
            for x in self.tableau[-1][:-1]:
                if x < 0:
                    self.optimized = False

    def optimize(self):
        self.createTableau()
        self.checkOptimized()
        while self.feasible and not self.optimized:
            self.pivotCol()
            self.pivotElement()
            self.simplex()
            self.checkOptimized()

    def optimalSoln(self):
        if self.optimized:
            sol = np.zeros(self.solnVarNo)
            for i in range(self.solnVarNo):
                if i in self.basicVars:
                    sol[i] = self.tableau[np.where(self.basicVars == i)[0], -1]
            return sol
        return "The value is not optimized yet you fool"

    def optimalVal(self):
        if self.optimized:
            return self.tableau[-1, -1]


import re

from spiderfoot import SpiderFootEvent, SpiderFootPlugin

class sfp_company(SpiderFootPlugin):

    meta = {
        'name': "Company Name Extractor",
        'summary': "Identify company names in any obtained data.",
        'flags': [],
        'useCases': ["Footprint", "Investigate", "Passive"],
        'categories': ["Content Analysis"]
    }

    opts = {
        'filterjscss': True
    }

    optdescs = {
        'filterjscss': "Filter out company names that originated from CSS/JS content. Enabling this avoids detection of popular Javascript and web framework author company names."
    }

    def setup(self, sfc, userOpts=dict()):
        self.sf = sfc

        for opt in list(userOpts.keys()):
            self.opts[opt] = userOpts[opt]

    # What events is this module interested in for input
    def watchedEvents(self):
        return ["TARGET_WEB_CONTENT", "SSL_CERTIFICATE_ISSUED",
                "DOMAIN_WHOIS", "NETBLOCK_WHOIS",
                "AFFILIATE_DOMAIN_WHOIS", "AFFILIATE_WEB_CONTENT"]

    # What events this module produces
    def producedEvents(self):
        return ["COMPANY_NAME", "AFFILIATE_COMPANY_NAME"]

    # Handle events sent to this module
    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data

        # Various ways to identify companies in text
        # Support up to three word company names with each starting with
        # a capital letter, allowing for hyphens brackets and numbers within.
        pattern_prefix = r"(?=[,;:\'\">\(= ]|^)\s?([A-Z0-9\(\)][A-Za-z0-9\-&,\.][^ \"\';:><]*)?\s?([A-Z0-9\(\)][A-Za-z0-9\-&,\.]?[^ \"\';:><]*|[Aa]nd)?\s?([A-Z0-9\(\)][A-Za-z0-9\-&,\.]?[^ \"\';:><]*)?\s+"
        pattern_match_re = [
            'LLC', r'L\.L\.C\.?', 'AG', r'A\.G\.?', 'GmbH', r'Pty\.?\s+Ltd\.?',
            r'Ltd\.?', r'Pte\.?', r'Inc\.?', r'INC\.?', 'Incorporated', 'Foundation',
            r'Corp\.?', 'Corporation', 'SA', r'S\.A\.?', 'SIA', 'BV', r'B\.V\.?',
            'NV', r'N\.V\.?', 'PLC', 'Limited', r'Pvt\.?\s+Ltd\.?', 'SARL']
        pattern_match = [
            'LLC', 'L.L.C', 'AG', 'A.G', 'GmbH', 'Pty',
            'Ltd', 'Pte', 'Inc', 'INC', 'Foundation',
            'Corp', 'SA', 'S.A', 'SIA', 'BV', 'B.V',
            'NV', 'N.V', 'PLC', 'Limited', 'Pvt.', 'SARL']

        pattern_suffix = r"(?=[ \.,:<\)\'\"]|[$\n\r])"

        # Filter out anything from the company name which matches the below
        filterpatterns = [
            "Copyright",
            r"\d{4}"  # To catch years
        ]

        # Don't re-parse company names
        if eventName in ["COMPANY_NAME", "AFFILIATE_COMPANY_NAME"]:
            return

        if eventName == "TARGET_WEB_CONTENT":
            url = event.actualSource
            if self.opts['filterjscss'] and (".js" in url or ".css" in url):
                self.debug("Ignoring web content from CSS/JS.")
                return

        self.debug(f"Received event, {eventName}, from {srcModuleName} ({len(eventData)} bytes)")

        # Strip out everything before the O=
        try:
            if eventName == "SSL_CERTIFICATE_ISSUED":
                eventData = eventData.split("O=")[1]
        except Exception:
            self.debug("Couldn't strip out 'O=' from certificate issuer, proceeding anyway...")

        # Find chunks of text containing what might be a company name first.
        # This is to avoid running very expensive regexps on large chunks of
        # data.
        chunks = list()
        for pat in pattern_match:
            start = 0
            m = eventData.find(pat, start)
            while m > 0:
                start = m - 50
                if start < 0:
                    start = 0
                end = m + 10
                if end >= len(eventData):
                    end = len(eventData) - 1
                chunks.append(eventData[start:end])
                offset = m + len(pat)
                m = eventData.find(pat, offset)

        myres = list()
        for chunk in chunks:
            for pat in pattern_match_re:
                matches = re.findall(pattern_prefix + "(" + pat + ")" + pattern_suffix, chunk, re.MULTILINE | re.DOTALL)
                for match in matches:
                    matched = 0
                    for m in match:
                        if len(m) > 0:
                            matched += 1
                    if matched <= 1:
                        continue

                    fullcompany = ""
                    for m in match:
                        flt = False
                        for f in filterpatterns:
                            if re.match(f, m):
                                flt = True
                        if not flt:
                            fullcompany += m + " "

                    fullcompany = re.sub(r"\s+", " ", fullcompany.strip())

                    self.info("Found company name: " + fullcompany)

                    if fullcompany in myres:
                        self.debug("Already found from this source.")
                        continue

                    myres.append(fullcompany)

                    if "AFFILIATE_" in eventName:
                        etype = "AFFILIATE_COMPANY_NAME"
                    else:
                        etype = "COMPANY_NAME"

                    evt = SpiderFootEvent(etype, fullcompany, self.__name__, event)
                    if event.moduleDataSource:
                        evt.moduleDataSource = event.moduleDataSource
                    else:
                        evt.moduleDataSource = "Unknown"
                    self.notifyListeners(evt)

# End of sfp_company class


import esper
import pygame
from code.settings import *
from code.timer import *
from code.components.deck import *
from code.components.map import *
from code.components.sprite import *
from code.components.ui import *
from code.systems.animation import *
from code.systems.input import *
from code.systems.rendering import *
from code.systems.timer import *

# -------------------------------------------------------------------------------------------------

def create_grid(world, grid_width, grid_height):

	# Entity
	tilemap = world.create_entity()

	# Components
	offset_x = DECK_WIDTH * TILE_SIZE
	offset_y = 0
	tilemap_data = PipeMap( width = grid_width,
							height = grid_height,
							offset_x = offset_x,
							offset_y = offset_y,
							tileset = PIPES )

	# Assign components to entity
	world.add_component( tilemap, tilemap_data )

	# Build map structure
	quantity_in = random.randint(1, 4)
	quantity_out = random.randint(3, 5)

	allowed_pipes_up = [ PIPE_VERTICAL, PIPE_VERTICAL, PIPE_VERTICAL, PIPE_T_LEFT, PIPE_T_RIGHT, PIPE_BENT_LEFT_UP, PIPE_BENT_LEFT_UP ]
	allowed_pipes_down = [ PIPE_VERTICAL, PIPE_VERTICAL, PIPE_VERTICAL, PIPE_T_LEFT, PIPE_T_RIGHT, PIPE_BENT_LEFT_DOWN, PIPE_BENT_LEFT_DOWN ]

	for i in range(quantity_in):
		choice = random.randint(1, 8)
		while tilemap_data.level[0][choice] != "-1":
			choice = random.randint(1, 8)
		tilemap_data.level[0][choice] = PIPE_INPUT
		tilemap_data.level[1][choice] = random.choice(allowed_pipes_up)
		tilemap_data.inputs.append((0,choice))

	for i in range(quantity_out):
		choice = random.randint(1, 8)
		while tilemap_data.level[0][choice] != "-1":
			choice = random.randint(1, 8)
		tilemap_data.level[grid_height - 1][choice] = PIPE_OUTPUT
		tilemap_data.level[grid_height - 2][choice] = random.choice(allowed_pipes_down)
		tilemap_data.outputs.append((grid_height - 1,choice))

	# Create components for the base map
	for row in range(grid_height):
		for col in range(grid_width):

			# Empty cells
			if tilemap_data.level[row][col] == "-1": continue

			# Entity
			entity = world.create_entity()

			# Components
			spawn_point = (
				col * TILE_SIZE + TILE_SIZE//2 + tilemap_data.offset_x,
				row * TILE_SIZE + TILE_SIZE//2 + tilemap_data.offset_y
			)

			# Assign components to entity
			world.add_component(
				entity,
				Pipe(
					file_name=PIPES[tilemap_data.level[row][col]]["sprite"],
					spawn_point=spawn_point,
					pipe_id=PIPES[tilemap_data.level[row][col]]["id"],
					left=PIPES[tilemap_data.level[row][col]]["left"],
					right=PIPES[tilemap_data.level[row][col]]["right"],
					up=PIPES[tilemap_data.level[row][col]]["up"],
					down=PIPES[tilemap_data.level[row][col]]["down"],
					fixed=PIPES[tilemap_data.level[row][col]]["fixed"]
				)
			)

def create_deck(world, font, deck_width, deck_height):

	# Entities
	deck = world.create_entity()
	left_button = world.create_entity()
	right_button = world.create_entity()

	# Deck
	deck_component = Deck( width=deck_width, height=deck_height, offset_x=0, offset_y=0 )
	deck_component.reset(world)
	world.add_component( deck, deck_component )

	# First button
	text = "Draw"
	text_surface = font.render( text, True, (255, 255, 255) )
	text_size = font.size(text)
	text_rect = text_surface.get_rect( center = ( 	deck_component.offset_x + deck_component.padding_outer + TILE_SIZE//2,
													deck_component.offset_y + deck_component.padding_outer + TILE_SIZE//2 ) )
	image = UiButtonStates( normal_image_filename = SPRITE_BUTTON_NORMAL,
							pressed_image_filename = SPRITE_BUTTON_PRESSED,
							hovering_image_filename = SPRITE_BUTTON_HOVERING )
	image.rect.center = text_rect.center
	world.add_component( left_button, image )
	world.add_component( left_button, UiText( text=text, surface=text_surface, rect=text_rect, size=32 ) )
	world.add_component( left_button, UiItem( rect=image.rect, callback=lambda: deck_component.draw(world) ) )

	# Second button
	text = "Boh?"
	text_surface = font.render( text, True, (255, 255, 255) )
	text_size = font.size(text)
	text_rect = text_surface.get_rect( center = ( 	(deck_component.offset_x + deck_component.padding_outer + TILE_SIZE//2) + deck_component.padding_inner + TILE_SIZE,
													deck_component.offset_y + deck_component.padding_outer + TILE_SIZE//2 ) )
	image = UiButtonStates( normal_image_filename = SPRITE_BUTTON_NORMAL,
							pressed_image_filename = SPRITE_BUTTON_PRESSED,
							hovering_image_filename = SPRITE_BUTTON_HOVERING )
	image.rect.center = text_rect.center
	world.add_component( right_button, image )
	world.add_component( right_button, UiText( text=text, surface=text_surface, rect=text_rect, size=32 ) )

# -------------------------------------------------------------------------------------------------

def load(file_name):
	world = esper.World()

	# Active display reference
	screen 		= pygame.display.get_surface()
	screen_size = screen.get_size()

	# Pygame font object
	font = pygame.font.SysFont(None, 24)

	# Create game area grid
	create_grid(world, GRID_WIDTH, GRID_HEIGHT)

	# Create side deck interface
	create_deck(world, font, DECK_WIDTH, DECK_HEIGHT)

	# Entities
	cursor = world.create_entity()
	timer = world.create_entity()

	# Components
	world.add_component( cursor, Cursor( scale_size=(24, 24) ) )
	world.add_component( timer, Timer( 10000 ) )

	# Systems
	world.add_processor( TimerController( scene_name=file_name, timer_entity=timer ) )
	world.add_processor( MouseInputHandler( scene_name=file_name, cursor_entity=cursor ) )
	world.add_processor( AnimationController() )
	world.add_processor( Rendering( scene_name=file_name, world_width=screen_size[0], world_height=screen_size[1] ) )

	return world


from django.urls import reverse
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
# tasks = []
# it will use client side validation, server will no nothing about this, this thing is solely done webpage itself.
class NewTaskForm(forms.Form):
    task = forms.CharField(label="Add New Task")
    priority = forms.IntegerField(label="Priority", min_value=1, max_value=5)

def index(request):
    if "tasks" not in request.session:
        print("if k andar")
        request.session["tasks"] = []
    print("if k bahar")
    return render(request, 'task/index.html', {
        "tasks": request.session["tasks"] # to return from existing session
        # "tasks": tasks [if we want to return global variable (here it's tasks list)]
    })

def add(request):
    if request.method == "POST":
        # creting a form variable by taking all of the data and filling all of the data
        # and filling it into this NewTaskForm, which will contain now all of the data the
        # user submitted
        form = NewTaskForm(request.POST) # request.post contains all of the data that the user submitted when they submitted the form.
        if form.is_valid():
            task = form.cleaned_data["task"]  # this will give me access to all of the data the user submitted.
                                              # and I want to get what task they submitted, bcz we had a variable
                                              # called task inside of NewTaskForm, so add ["task"] to form.clean-data.

            # tasks.append(task)  # to add task [if list is defined in global variable]

            request.session["tasks"] += [task]  # we have append the task to the already store tasks list

            return HttpResponseRedirect(reverse('task:index')) # to redirect to the task page on adding task.

        # if not valid show the error to the user
        else:
            return render(request, "task/add.html", {
                "form": form
                })

    # if empty submission redirect to the empty form
    return render(request, "task/add.html", {
        "form": NewTaskForm(),
    })


#!/usr/bin/python3

import socket
import os

port = 12345
connected = True

s = socket.socket()
s.bind(('', port))
try:
	while True:
		s.listen(5)
		c, addr = s.accept()
		print("Socket Up and running with a connection from ",addr)
		while connected:
			rcvdData = c.recv(1024).decode()
			if rcvdData=="bye":
				connected=False
				break
			else:
				print("Command: "+rcvdData)

				os.system(rcvdData+' > tmp')
				sendData = open('tmp','r').read()
				os.remove('tmp')
				print(sendData)

				c.send(sendData.encode())
		connected=True
except:
	c.close()


from re import S
import requests
import time
from bs4 import BeautifulSoup

#using https://www.islamicfinder.org/widgets/#prayertimeswidget
Prayer_time_based_on_country_URL = 'https://www.islamicfinder.org/prayer-widget/248946/shafi/4/0/18.5/19.0'

while True:
    html_request = requests.get(Prayer_time_based_on_country_URL)
    soup = BeautifulSoup(html_request.text, 'html.parser')

    Fajr = soup.find_all(text="Fajr")
    Fajr = Fajr[0].parent.text.split("\n")[1].split()[0].split(":")
    Fajr = int(Fajr[0])*60 + int(Fajr[1])

    Sunrise = soup.find_all(text="Sunrise  ")
    Sunrise = Sunrise[0].parent.text.split("\n")[1].split()[0].split(":")
    Sunrise = int(Sunrise[0])*60 + int(Sunrise[1])

    Dhuhr = soup.find_all(text="Dhuhr")
    Dhuhr = Dhuhr[0].parent.text.split("\n")[1].split()[0].split(":")
    if(Dhuhr[1] == "PM"):
        Dhuhr = int((Dhuhr[0])+12)*60 + int(Dhuhr[1])
    else:
        Dhuhr = int(Dhuhr[0])*60 + int(Dhuhr[1])

    Asr = soup.find_all(text="Asr")
    Asr = Asr[0].parent.text.split("\n")[1].split()[0].split(":")
    Asr = (int(Asr[0])+12)*60 + int(Asr[1])

    Maghrib = soup.find_all(text="Maghrib")
    Maghrib = Maghrib[0].parent.text.split("\n")[1].split()[0].split(":")
    Maghrib = (int(Maghrib[0])+12)*60 + int(Maghrib[1])

    Isha = soup.find_all(text="Isha")
    Isha = Isha[0].parent.text.split("\n")[1].split()[0].split(":")
    Isha = (int(Isha[0])+12)*60 + int(Isha[1])

    F = 1
    S = 1
    D = 1
    A = 1
    Ma = 1
    I = 1

    while F:
        now = time.gmtime()
        H = (now[3] + 3)%24
        M = now[4]
        if H*60 + M >= Fajr:
            F = 0
            break
        print("{Fajr:{}".format(Fajr -(H*60 + M)))
        time.sleep(30)

    while S:
        now = time.gmtime()
        H = (now[3] + 3)%24
        M = now[4]
        if H*60 + M >= Sunrise:
            S = 0
            break
        print("Sunrise:{}".format(Sunrise -(H*60 + M)))
        time.sleep(30)

    while D:
        now = time.gmtime()
        H = (now[3] + 3)%24
        M = now[4]
        if H*60 + M >= Dhuhr:
            D = 0
            break
        print("Dhuhr:{}".format(Dhuhr -(H*60 + M)))
        time.sleep(30)

    while A:
        now = time.gmtime()
        H = (now[3] + 3)%24
        M = now[4]
        if H*60 + M >= Asr:
            A = 0
            break
        print("Asr:{}".format(Asr -(H*60 + M)))
        time.sleep(30)

    while Ma:
        now = time.gmtime()
        H = (now[3] + 3)%24
        M = now[4]
        if H*60 + M >= Maghrib:
            Ma = 0
            break
        print("Maghrib:{}".format(Maghrib -(H*60 + M)))
        time.sleep(30)

    while I:
        now = time.gmtime()
        H = (now[3] + 3)%24
        M = now[4]
        if H*60 + M >= Isha:
            I = 0
            break
        print("Isha:{}".format(Isha -(H*60 + M)))
        time.sleep(30)

    F = 1
    S = 1
    D = 1
    A = 1
    Ma = 1
    I = 1


import re
from abc import ABC, abstractclassmethod, abstractmethod
from dataclasses import dataclass

import numpy as np
import requests
from at2p_app.domain.common.error import WeatherError
from at2p_app.domain.entities.place import Place
from at2p_app.domain.value_objects.temperature import Temperature
from at2p_app.domain.value_objects.weather import Weather
from bs4 import BeautifulSoup
from django.core.exceptions import ValidationError

class WeatherSource(ABC):

    _place: Place

    @abstractclassmethod
    def new(self):
        pass

    def _validate(cls):
        pass

    @abstractmethod
    def get(self):
        pass

@dataclass
class WeatherScraper(WeatherSource):

    _place: Place
    _url_prefix: str = "https://www.timeanddate.com/weather/@z-"

    @classmethod
    def new(cls, place: Place):
        cls._validate(place)
        return cls(place)

    @classmethod
    def _validate(cls, place: Place):
        cls._check_place(place)
        return

    @classmethod
    def _check_place(cls, place: Place):
        if not isinstance(place, Place):
            return WeatherError

    def get(self):
        avg = self.historic_temp()
        high, low = self.forecast_high_low()
        weather_report = Weather.new(self._place.id, high, low, avg)
        return weather_report

    def historic_temp(self) -> Temperature:
        url = self.weather_url("historic")
        soup = self.get_soup(url)
        row = soup.find("tr", {"class": "sep-t"})
        cells = row.find_all("td")
        historic_temp = int(re.findall(r"\d+", cells[0].text)[0])
        return Temperature.new(historic_temp)

    def forecast_high_low(self) -> Temperature:
        url = self.weather_url("ext")
        soup = self.get_soup(url)
        forecast_table = soup.find("table", id="wt-ext")
        table_body = forecast_table.find("tbody")
        rows = table_body.find_all("tr")
        data = []
        for row in rows:
            cells = row.find_all("td")
            temps = re.findall(r"\d+", cells[1].text)
            data.append(list((int(temps[0]), int(temps[1]))))
        data_t = np.transpose(data)
        high = np.max(data_t[0])
        low = np.min(data_t[1])
        return Temperature.new(int(high)), Temperature.new(int(low))

    def get_soup(self, url) -> BeautifulSoup:
        page = requests.get(url)
        soup = BeautifulSoup(page.content, "lxml")
        head_tag = soup.head
        title = head_tag.title
        if "Unknown address" in title.contents[0]:
            raise ValidationError("Scraping error: address not found.")
        return soup

    def weather_url(self, type_postfix: str):
        country = self._place.country.code
        zip_code = self._place.zip_code.zip
        return f"{self._url_prefix}{country.lower()}-{zip_code}/{type_postfix}"


import unittest
import requests
from pyapp import data_collection
from pyapp import data_obj

class TestDatapublish(unittest.TestCase):
    def setUp(self):
        # creating fake data
        node = data_obj.Node()
        node.course_name = 'test_course'
        node.node_label = 'test_node_name'
        node.gpu_type = '1080ti'
        node.gpu_used =1
        node.gpu_total=2
        self.data = {'test_node':node}
        # function to be tested
        self.data_publish = data_collection.data_publish

    def test_hello_world(self):
        # start the server
        data_collection.start_server(9000)
        gpu_metric = data_collection.create_guage()
        # create the metric
        self.data_publish(nodes=self.data,gpu_metric=gpu_metric)
        # use http get method to read data
        r =requests.get('http://127.0.0.1:9000')
        # check the return data
        assert r.status_code == 200
        assert 'dsmlp_gpu{course="test_course",hostname="test_node_name",status="total",type="1080ti"} 2.0' in r.text
        assert 'dsmlp_gpu{course="test_course",hostname="test_node_name",status="reserved",type="1080ti"} 1.0' in r.text
        assert 'dsmlp_gpu{course="test_course",hostname="test_node_name",status="available",type="1080ti"} 1.0' in r.text


import xml.etree.ElementTree as ET

#returns all text over nodes
def getDocFullText(r,flag,depth,isLast,text):
    # Condition when node is None
    if r == None:
        return

    # Condition when the current
    # node is the root node
    if depth == 0:
        if(r.text != "" and r.text != None and r.text!=" "):
            text.append(r.text)

    # Condition when the node is
    # the last node of
    # the exploring depth
    elif isLast:
        if(r.text != "" and r.text != None and r.text!=" "):
            text.append(r.text)

        # No more childrens turn it
        # to the non-exploring depth
        flag[depth] = False
    else:
        if(r.text != "" and r.text != None and r.text!=" "):
            text.append(r.text)

    it = 0
    for i in r:  #was r.root but here r is an iterable array containing its children
        it+=1

        # Recursive call for the
        # children nodes
        getDocFullText(i, flag, depth + 1, it == (len(r) - 1),text)  #was r.root but here r is an iterable array containing its children
    flag[depth] = True


import ipdb
import sys, os.path, ast
import inspect, typing, pybx
import dataclasses, enum

class ModuleDef:
    def __init__(self, name):
        self.name = name
        self.interfaces = []
        self.structs = {} # struct name -> struct def
        self.enums = []
        self.struct_order = [] # struct names

    def dump(self):
        print("interfaces:", [x.name for x in self.interfaces])
        print("structs:", [x.name for x in self.structs.values()])
        print("struct_order:", self.struct_order)
        print("enums:", [x.name for x in self.enums])

        for d in self.interfaces:
            d.dump()
        for s in self.structs.values():
            s.dump()
        for e in self.enums:
            e.dump()

class InterfaceDef:
    def __init__(self, def_type):
        self.def_type = def_type
        self.name = self.def_type.__name__
        self.methods = []

    def dump(self):
        print(f"interface {self.def_type}")
        for m in self.methods:
            m.dump()

fundamental_types = {str: 'string', int: 'int', float: 'double', bool: 'bool'}
class Type:
    def __init__(self, py_type):
        self.py_type = py_type

    def __repr__(self):
        ret = "Type " + repr(self.py_type)
        return ret

    def is_none(self):
        return self.py_type == type(None)

    def is_vector_type(self):
        return hasattr(self.py_type, '_name') and self.py_type._name == 'List'

    def is_rop_type(self):
        return hasattr(self.py_type, '_name') and self.py_type._name == 'object'

    def is_struct(self):
        return dataclasses.is_dataclass(self.py_type)

    def is_enum(self):
        return inspect.isclass(self.py_type) and issubclass(self.py_type, enum.Enum)

    def get_py_code_name(self):
        t = self.py_type
        if t == type(None):
            ret = "type(None)"
        elif inspect.isclass(t):
            ret = f"{t.__module__}.{t.__name__}"
        elif hasattr(t, '__origin__'):
            #ipdb.set_trace()
            args_s = ",".join([f"{c.__module__}.{c.__name__}" for c in t.__args__])
            ret = f"{t.__module__}.{t._name}[{args_s}]"
            #ipdb.set_trace()
        else:
            raise Exception(f"can't get py_code_name for type {self.py_type}")
        return ret

    def get_cpp_code_name(self):
        t = self.py_type
        if self.is_none():
            ret = "void"
        elif self.is_struct():
            ret = f"{t.__module__}::{t.__name__}"
        elif self.is_vector_type():
            value_type = self.py_type.__args__[0]
            value_type_cpp_code_name = Type(value_type).get_cpp_code_name()
            ret = f"vector<{value_type_cpp_code_name}>"
        elif self.is_rop_type():
            i_t = t.__args__[0]
            ret = f"{i_t.__module__}::{i_t.__name__}_rop"
        elif self.is_enum():
            ret = f"{t.__module__}::{t.__name__}"
        elif self.py_type in fundamental_types:
            ret = fundamental_types[self.py_type]
        else:
            raise Exception(f"can't get cpp_code_name for type {self.py_type}")
        return ret

    def get_js_code_name(self):
        t = self.py_type
        if self.is_none():
            ret = "null"
        elif self.is_struct():
            ret = f"new {t.__name__}()"
        elif self.is_vector_type():
            ret = "[]";
        elif self.is_rop_type():
            i_t = t.__args__[0]
            ret = f"new {i_t.__name__}_rop()"
        elif self.is_enum():
            ret = f"{t.__module__}::{t.__name__}"
        elif self.py_type in fundamental_types:
            ret = "null"
        else:
            raise Exception(f"can't get cpp_code_name for type {self.py_type}")
        return ret

class InterfaceMethodDef:
    def __init__(self, interface_def, method_name, type_hints, sig):
        self.interface_def = interface_def
        self.name = method_name
        self.type_hints = type_hints
        self.sig = sig

    def get_method_args(self):
        return [x for x in self.sig.parameters if x != 'self']

    def get_method_typed_args(self):
        return [f"{x[1]} {x[0]}" for x in zip(self.get_method_args(), self.get_method_arg_types())]

    def get_method_arg_types(self):
        args = self.get_method_args()
        return [Type(self.type_hints[x]) for x in args]

    def get_method_return_type(self):
        return Type(self.type_hints['return'])

    def dump(self):
        print(f" method {self.name}")
        m_args = self.get_method_args()
        m_arg_types = self.get_method_arg_types()
        m_ret_type = self.get_method_return_type()
        print(f"  arguments: {m_args}")
        print(f"  argument types: {m_arg_types}")
        print(f"  return type: {m_ret_type}")

class StructDef:
    def __init__(self, def_type):
        self.def_type = def_type
        self.name = self.def_type.__name__
        self.fields = [] # List[StructMemberDef]

    def dump(self):
        print(f"struct {self.def_type}")
        for m in self.fields:
            m.dump()

class StructMemberDef:
    def __init__(self, struct_def, field, field_type):
        self.struct_def = struct_def
        self.field = field
        self.field_type = Type(field_type)

    def get_member_name(self):
        return self.field.name

    def get_member_type(self):
        return self.field_type

    def dump(self):
        m_name = self.get_member_name()
        m_type = self.get_member_type()
        print(f" member: {m_name}")
        print(f" member type: {m_type}")

class EnumDef:
    def __init__(self, enum_def):
        self.def_type = enum_def
        self.name = enum_def.__name__
        self.members = []
        self.member_values = []
        #ipdb.set_trace()
        for n, m in enum_def.__members__.items():
            self.members.append(n)
            self.member_values.append(m.value)

    def dump(self):
        print(f"enum {self.def_type}")
        for m, m_v in zip(self.members, self.member_values):
            print(f" enum member {m} {m_v}")

def parse_pybx_interface(interface_class):
    #ipdb.set_trace()
    print("parse_pybx_interface: ", interface_class.__name__)
    interface_def = InterfaceDef(interface_class)
    methods = inspect.getmembers(interface_class, predicate=inspect.isfunction)
    for m_name, m_func in methods:
        th = typing.get_type_hints(m_func)
        sig = inspect.signature(m_func)
        m_def = InterfaceMethodDef(interface_def, m_name, th, sig)
        interface_def.methods.append(m_def)
    return interface_def

def parse_pybx_struct(struct):
    struct_def = StructDef(struct)
    #ipdb.set_trace()
    dataclass_th = typing.get_type_hints(struct)
    for f in dataclasses.fields(struct):
        f_type = dataclass_th[f.name]
        f_def = StructMemberDef(struct_def, f, f_type)
        struct_def.fields.append(f_def)
    return struct_def

def parse_pybx_enum(enum_def):
    enumdef_def = EnumDef(enum_def)
    return enumdef_def

def parse_module(mod):
    #ipdb.set_trace()
    if not inspect.ismodule(mod):
        raise Exception("mod expected to be Module")

    mod_def = ModuleDef(mod.__name__)
    for mod_el_name in dir(mod):
        mod_el = getattr(mod, mod_el_name)
        if inspect.isclass(mod_el) and issubclass(mod_el, pybx.interface):
            mod_def.interfaces.append(parse_pybx_interface(mod_el))
        elif dataclasses.is_dataclass(mod_el):
            struct_def = parse_pybx_struct(mod_el)
            mod_def.structs[struct_def.name] = struct_def
        elif inspect.isclass(mod_el) and issubclass(mod_el, enum.Enum):
            mod_def.enums.append(parse_pybx_enum(mod_el))

    return mod_def

def find_declaration_order(mod_def, mod_fn):
    source_code = "\n".join(open(mod_fn).readlines())
    pt = ast.parse(source_code)
    #ipdb.set_trace()
    for node in ast.iter_child_nodes(pt):
        #print(pt)
        if isinstance(node, ast.ClassDef):
            if len(node.decorator_list) > 0 and node.decorator_list[0].attr == 'dataclass':
                # we got pybx struct
                mod_def.struct_order.append(node.name)


def words_sorting(*args):
    my_dictionary = {}
    output = []
    total_sum = 0

    for word in args:
        sum_counter = 0
        for letter in word:
            sum_counter += ord(letter)
        my_dictionary[word] = sum_counter

    for value in my_dictionary.values():
        total_sum += value

    if total_sum % 2 == 0:
        sort_result = dict(sorted(my_dictionary.items(), key=lambda x: x[0]))
        for k, v in sort_result.items():
            output.append(f"{k} - {v}")
    else:
        sort_result = dict(sorted(my_dictionary.items(), key=lambda x: -x[1]))
        for k, v in sort_result.items():
            output.append(f"{k} - {v}")

    return '\n'.join(output)

10.Exam Preparation/10.Exam 14 April 2022/03.Words Sorting.py


# Given a list which describes operators executing environment (run on some device),
# then we can use relay.transform.MergeCompilerRegions to annotate the whole model,
# then do the partition by transform.PartitionGraph

import tvm
from tvm import relay
from tvm.relay.op.annotation import compiler_begin, compiler_end
from tvm.relay.testing import run_opt_pass
from tvm.relay.expr_functor import ExprMutator
from tvm.relay import transform
from tvm.relay.expr import Call

def origin():
    data = relay.var("data", shape=(10, 10))
    O_1 = relay.abs(data)
    O_2 = relay.nn.relu(O_1)
    X = relay.tanh(O_1)
    O_3 = relay.add(O_2, X)
    diamond = relay.Function([data], O_3)
    return diamond

def diamond_graph_fanouts():
    data = relay.var("data", shape=(10, 10))
    cb_1 = compiler_begin(data, "test")
    O_1 = relay.abs(cb_1)
    ce_1 = compiler_end(O_1, "test")
    ce_2 = compiler_end(O_1, "test")
    cb_2 = compiler_begin(ce_1, "test")
    cb_3 = compiler_begin(ce_2, "default")
    O_2 = relay.nn.relu(cb_2)
    ce_3 = compiler_end(O_2, "test")

    X = relay.tanh(cb_3)
    ce_4 = compiler_end(X, "default")

    cb_4 = compiler_begin(ce_3, "test")
    cb_5 = compiler_begin(ce_4, "test")
    O_3 = relay.add(cb_4, cb_5)
    ce_5 = compiler_end(O_3, "test")

    diamond = relay.Function([data], ce_5)
    return diamond

def expected():
    data = relay.var("data", shape=(10, 10))
    cb_1 = compiler_begin(data, "test")
    O_1 = relay.abs(cb_1)
    ce_2 = compiler_end(O_1, "test")
    O_2 = relay.nn.relu(O_1)
    ce_3 = compiler_end(O_2, "test")

    cb_3 = compiler_begin(ce_2, "default")
    X = relay.tanh(cb_3)
    ce_4 = compiler_end(X, "default")

    cb_4 = compiler_begin(ce_3, "test")
    cb_5 = compiler_begin(ce_4, "test")
    O_3 = relay.add(cb_4, cb_5)
    ce_5 = compiler_end(O_3, "test")

    func = relay.Function([data], ce_5)
    return func

class ScheduleConv2d(ExprMutator):
    def __init__(self, compiler):
        self.compiler = compiler
        super().__init__()

    def visit_call(self, expr):
        new_args = []
        new_fn = self.visit(expr.op)
        if expr.op != tvm.relay.op.get("tanh"):
            for arg in expr.args:
                if isinstance(arg, Call):
                    if arg.op != tvm.relay.op.get("tanh"):
                        arg = compiler_end(self.visit(arg), self.compiler)
                    else:
                        arg = compiler_end(self.visit(arg), "default")
                arg = compiler_begin(arg, self.compiler)
                new_args.append(arg)
        else:
            for arg in expr.args:
                if isinstance(arg, Call):
                    if arg.op != tvm.relay.op.get("tanh"):
                        arg = compiler_end(self.visit(arg), self.compiler)
                    else:
                        arg = compiler_end(self.visit(arg), "default")
                arg = compiler_begin(arg, "default")
                new_args.append(arg)
        return Call(new_fn, new_args, expr.attrs, expr.type_args, expr.span)

def annotate(sched, fn):
    new_fn = sched.visit(fn)
    new_params = [x for x in new_fn.params]
    # add compiler_end for the last operator in fn
    if (new_fn.body.op != tvm.relay.op.get("tanh")):
        new_body = compiler_end(new_fn.body, sched.compiler)
    else:
        new_body = compiler_end(new_fn.body, "default")
    return relay.Function(list(new_params), new_body, new_fn.ret_type, new_fn.type_params, new_fn.attrs)

func = origin()
sched = ScheduleConv2d("test")
func = annotate(sched, func)
diamond = diamond_graph_fanouts()
# print(func)
# print(diamond)
assert tvm.ir.structural_equal(func, diamond)
func = run_opt_pass(func, relay.transform.MergeCompilerRegions())
mod = tvm.IRModule.from_expr(func)
mod = transform.PartitionGraph()(mod)
print(mod.astext(show_meta_data=False))


from rsf.proj import *

Flow('spike0',None,'spike n1=256 k1=128 d1=50 label1= unit1= | bandpass fhi=0.002')
Flow('spike',None,'spike n1=256 k1=128 d1=50 label1= unit1= | ricker1 freq=0.1')
Flow('zero','spike','math output=0')

v = 1000.0
dt = 0.01
twopi = 6.28318530718

# Constant-velocity wave propagation
####################################

prev = 'zero'
curr = 'spike'

# Time steps
steps = ['spike']
for it in range(500):
    next = 'step%d' % it

    Flow(next,[curr,prev],
         '''
         fft1 |
         math output="2*(cos(abs(%g*x1)*%g)-1)*input" |
         fft1 inv=y |
         add scale=1,-1,2 ${SOURCES[1]} ${SOURCES[0]}
         ''' % (twopi,v*dt))

    steps.append(next)

    prev = curr
    curr = next

Flow('wave',steps,'cat axis=2 ${SOURCES[1:%d]}' % len(steps))
Result('wave','grey title=Wave transp=n')

prev = 'zero'
curr = 'spike'

# Time steps
steps = ['spike']
for it in range(500):
    next = 'astep%d' % it

    Flow(next,[curr,prev],
         '''
         fft1 |
         math output="2*cos(abs(%g*x1)*%g)*input" |
         fft1 inv=y |
         add scale=1,-1 ${SOURCES[1]}
         ''' % (twopi,v*dt))

    steps.append(next)

    prev = curr
    curr = next

Flow('wave1',steps,'cat axis=2 ${SOURCES[1:%d]}' % len(steps))
Result('wave1','grey title=Wave transp=n')

# Constant-velocity wave propagation (cosine FT)
################################################

prev = 'zero'
curr = 'spike'

# Time steps
steps = ['spike']
for it in range(500):
    next = 'cstep%d' % it

    Flow(next,[curr,prev],
         '''
         cosft sign1=1 |
         math output="2*cos(abs(%g*x1)*%g)*input" |
         cosft sign1=-1 |
         add scale=1,-1 ${SOURCES[1]}
         ''' % (twopi,v*dt))

    steps.append(next)

    prev = curr
    curr = next

Flow('cwave',steps,'cat axis=2 ${SOURCES[1:%d]}' % len(steps))
Result('cwave','grey title="Wave (Cosine FT)" transp=n')

# Fourier transform back and forth
##################################

Flow('rand',None,'spike n1=256 d1=5 | noise seed=2009 var=0.1')

# FFT forward

Flow('fft','rand','fft1')

# Slow inverse FT

Flow('fourier','fft',
     '''
     spray axis=2 n=256 d=5 o=0 |
     math output="exp(%g*I*x1*x2)/128"
     ''' % twopi)

Flow('fourier0','fourier','window n1=1 squeeze=n | scale dscale=0.5')
Flow('fouriern','fourier','window n1=1 f1=-1 squeeze=n | scale dscale=0.5')
Flow('fourierm','fourier','window n1=127 f1=1')

Flow('fourier2','fourier0 fourierm fouriern','cat axis=1 ${SOURCES[1:3]}')

Flow('ift','fft fourier2','cmatmult mat=${SOURCES[1]} | real')

Flow('dif','ift rand','add scale=1,-1 ${SOURCES[1]}')

Result('ift','ift rand','cat axis=2 ${SOURCES[1]} | graph wanttitle=n')

# Variable-velocity wave propagation
####################################

Flow('vel','spike','math output=1000+0.1*x1')
Result('vel','graph title=Velocity')

Flow('cvel','spike','pad end1=1 | math output=1000+0.1*x1')

# propagator matrix
Flow('prop','vel',
     '''
     spray axis=1 n=129 d=0.000078125 o=0 |
     math output="2*(cos(abs(%g*x1)*input*%g)-1)"
     ''' % (twopi,dt))

# propagator matrix - cosine FT
Flow('cprop','cvel',
     '''
     spray axis=1 n=257 d=0.0000390625 o=0 |
     math output="2*(cos(abs(%g*x1)*input*%g)-1)"
     ''' % (twopi,dt))

# propagator matrix - large dt
Flow('prop1','vel',
     '''
     spray axis=1 n=129 d=0.000078125 o=0 |
     math output="2*(cos(abs(%g*x1)*input*%g)-1)"
     ''' % (twopi,20*dt))

Flow('prop2','prop fourier2','rtoc | mul ${SOURCES[1]}')
Flow('prop10','prop1 fourier2','rtoc | mul ${SOURCES[1]}')
Flow('propo2','propo fourier2','rtoc | mul ${SOURCES[1]}')

Result('prop','grey title="Propagator Matrix" color=j bias=-1 scalebar=y label1=Wavenumber unit1=1/m label2=Distance unit2=m')

# propagator matrix (without -1)
Flow('propo','vel',
     '''
     spray axis=1 n=129 d=0.000078125 o=0 |
     math output="2*cos(abs(%g*x1)*input*%g)"
     ''' % (twopi,dt))

Result('propo','grey title="Propagator Matrix" color=j scalebar=y label1=Wavenumber unit1=1/m label2=Distance unit2=m')

# Lowrank decomposition
#######################

targets = ','.join(map(lambda x: '\'${TARGETS[%d]}\'' % x, range(6)))

Flow('prod left2 right2','prop',
     'lrmatrix seed=2010 left=${TARGETS[1]} right=${TARGETS[2]}')

Result('prod','grey title="Lowrank Propagator Matrix" color=j bias=-1 scalebar=y label1=Wavenumber unit1=1/m label2=Distance unit2=m')
Result('proderr','prod prop',
       '''
       add scale=1,-1 ${SOURCES[1]} |
       grey title="Lowrank Approximation Error" color=j scalebar=y label1=Wavenumber unit1=1/m label2=Distance unit2=m
       ''')

# Exact matrix multiplication
Flow('wave2','spike prop2','fftwave1 prop=${SOURCES[1]} nt=500 dt=%g' % dt)
Result('wave2','window max2=3 | grey title="Wave" transp=n clip=0.5 label1=Distance unit1=m')

# Propagating a spike
Flow('wave0','spike0 prop2','fftwave1 prop=${SOURCES[1]} nt=500 dt=%g' % dt)
Result('wave0','window max2=3 | grey title="Wave" transp=n clip=0.5 label1=Distance unit1=m')

# Lowrank propagation
Flow('awave2','spike left2 right2',
     'fftwave1 prop=${SOURCES[1]} right=${SOURCES[2]} nt=500 dt=%g' % dt)
Result('awave2',
       '''
       window max2=3 |
       grey title="Lowrank Wave" transp=n clip=0.5 label1=Distance unit1=m
       ''')

Result('waverr','awave2 wave2',
       '''
       add scale=1,-1 ${SOURCES[1]} | window max2=3 |
       grey title="Lowrank Wave Error (x 10)" transp=n clip=0.05 label1=Distance unit1=m
       ''')

End()


import csv

names = []

with open('./csv/names.csv', newline='\n') as f:
  reader = csv.reader(f, delimiter=',')

  i = 1
  for row in reader:
    names.append((i, row[0], row[1]))
    i += 1

with open('./csv/customer.csv', 'w', newline='\n') as f:
  writer = csv.writer(f, delimiter=',')
  for row in names:
    writer.writerow(row)


from os import path, listdir, pardir
from pathlib import Path

def table_of_contents():
    content = ""
    for dir in [p for p in listdir() if path.isdir(p) and not p.startswith(".")]:
        content += f"- [{dir}]({dir})\n"
        for file in [dir+"/"+p for p in listdir(dir) if p.endswith(".c")]:
            pdf = dir+"/"+Path(file).stem+".pdf"
            label = " ".join([a.capitalize() for a in Path(file).stem.replace("_"," ").split(" ")])
            content += f"    - **{label}** [[Code]({file})] [[Description]({pdf})]\n"
    return content

open("README.md","w",encoding="UTF-8").write(f"""
# Curriculum Challenges

This repository contains codefiles and challenge descriptions to all challenges in RobotC Virtual Worlds Curriculum.

## Challenges

{table_of_contents()}

## Code description

**For all code files applies that**:
- At the top there is defined robot to use to succesfully complete this challenge, so check it before challenge start to have correct robot in usage
- All constants are defined via C-keyword `#define` at the top
- I am trying to write code as efficient as possible

""".strip())


class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        map = {}
        res = []
        for i in range(len(nums)):
            map[target - nums[i]] = i

        for i in range(len(nums)):
            if nums[i] in map:
                if map[nums[i]] != i:
                    res.append(map[nums[i]])
                    res.append(i)
                    break

        return res


import logging

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from uvicorn import run

from config import Config

logger = logging.getLogger(__name__)

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.middleware("http")
async def add_config_middleware(request: Request, call_next):
    """ Добавляет config в request,
     Доставать так:
      config: Config = request.state.config
    """
    request.state.config = Config()
    return await call_next(request)

def run_fastapi():
    run(app, host="0.0.0.0", port=5000)


from tgbot.commands.UserAccess import UserAccess
from tgbot.commands.base import BaseCommand

class SetMaxWarns(BaseCommand):
    command_names = ['setmaxwarns']
    access_level = UserAccess.CHAT_SUDO

    def __init__(self, event, parsed):
        super().__init__(event, parsed, SetMaxWarns.access_level)

    async def process(self):
        await self.fetch_data()

        if not (await self.can_process()):
            return

        try:
            max_warns = int(self.parsed.pop(1))
        except:
            await self.reply_incorrect_input()
            return

        if max_warns is None or max_warns < 0:
            max_warns = 0

        if max_warns == self.channel['max_warns']:
            await self.reply_fail(self.get_translation('CMD_MAX_WARNS_EXISTS').format(mw=max_warns))
            return

        await self.db.updateSubchatMaxWarns(self.channel['tg_chat_id'], max_warns)
        await self.reply_success(self.get_translation('CMD_MAX_WARNS_CHANGED').format(mw=max_warns))


from collections import deque

def solution(r, o):
    N = len(r)
    M = len(r[0])
    l = deque([r[i][0] for i in range(N)])
    m = deque([deque(r[i][1:M - 1]) for i in range(N)])
    rt = deque([r[i][M - 1] for i in range(N)])

    for op in o:
        if op == 'ShiftRow':
            l.appendleft(l.pop())
            m.appendleft(m.pop())
            rt.appendleft(rt.pop())
        else:
            m[0].appendleft(l.popleft())
            rt.appendleft(m[0].pop())
            m[N - 1].append(rt.pop())
            l.append(m[N - 1].popleft())
    a = []
    for i in range(N):
        a.append([l[i]] + list(m[i]) + [rt[i]])
    return a

프로그래머스/lv4/118670. 행렬과 연산/행렬과 연산.py


# -*- coding: utf-8 -*-

__author__ = 'nothi'

from os.path import join
from tornado.web import RequestHandler
from web.service.book_service import BookService
from web.service.comment_service import CommentService
from web.settings import *

class BookDetailController(RequestHandler):
    def initialize(self):
        self.service = BookService()
        self.comment_service = CommentService()

    @staticmethod
    def get_platfrom_name(platform):
        platfom_name = {
            0:"当当网",
            1:"京东商城",
            2:"亚马逊"
        }
        return platfom_name[platform]

    def get(self, isbn):
        result = self.service.query_by_isbn(isbn)

        if  result:
            for goods_info in result.goods_list:
                goods_info.platform = self.get_platfrom_name(goods_info.platform)
            comments = self.comment_service.get_comment(isbn)
            self.render(os.path.join(template_dir, "bookdetail.html"), book=result,comments=comments)
        else:
            self.render(os.path.join(template_dir, "notfind.html"), sentence="哈哈，书没找到")

    def post(self, isbn):
        self.get()


from turtle import *

# Clase 7 - Turtle II

speed(0)

def izquierda():
    left(15)

def derecha():
    right(15)

def saltar(x,y):
    penup()
    goto(x,y)
    pendown()

lims = 330
def limites():
    x = xcor()
    y = ycor()
    if x < -lims:
        saltar(lims, y)
    if x > lims:
        saltar(-lims, y)
    if y < -lims:
        saltar(x, lims)
    if y > lims:
        saltar(x, -lims)

onkey(izquierda, 'a')
onkey(derecha, 'd')

listen()

# Game loop
while True:
    forward(10)
    limites()


#%% EDA ### EDA 할 때는 대표발의 테이터로 다시하기 -> 생략 문제를 최대한 단순하게 가져가자.
with open(r'C:\Github\Project_Social_Bigdata_Assignment\Data\raw2.pickle', 'rb') as f:
    raw2 = pickle.load(f)

# 국회의원 사전 만드는 함수.

# 원내 7당체재 기준, 바른미래당 창당. 최근 1년 동안 법안을 가장 많이/적게 만든 의원
color_dict = {'더불어민주당':'blue','자유한국당':'red','바른미래당':'skyblue','민주평화당':'green','정의당':'yellow','무소속':'gray','대한애국당':'darkblue','민중당':'orange'}
EDA1 = pd.DataFrame({'hanja':tmpmem,'party':tmppar,'hangle':hangle})

cnt = EDA1.hanja.value_counts()[0:30]

plt.figure(figsize=(10, 10))
height = cnt.values
bars = list(map(lambda x:mem_dict[x][0],cnt.index))
y_pos = np.flip(np.arange(len(bars)))
color = list(map(lambda x:color_dict[x],list(map(lambda x:mem_dict[x][1],cnt.index))))

plt.barh(y_pos, height,color = color) ; plt.yticks(y_pos, bars)
plt.title('발의법안 수 상위 의원')
plt.show()

cnt = EDA1.hanja.value_counts()[-31:-1]

plt.figure(figsize=(10, 10))
height = cnt.values
bars = list(map(lambda x:mem_dict[x][0],cnt.index))
y_pos = np.arange(len(bars))
color = list(map(lambda x:color_dict[x],list(map(lambda x:mem_dict[x][1],cnt.index))))

plt.barh(y_pos, height,color = color) ; plt.yticks(y_pos, bars)
plt.axvline(x= mean_cnt, color = 'red', ls = 'dotted')
plt.title('발의법안 수 하위 의원')
plt.show()

# 최근 6개월 1인당 법안 발의 수 가장 높은/낮은 정당.
cnt = EDA1.party.value_counts()

tmp = EDA1.groupby(['hanja','party']).count().index.get_level_values(1)
tmp = list(tmp)
b = pd.Series(tmp).value_counts()
b.values.sum()

height = cnt.values
bars = cnt.index
color = list(map(lambda x:color_dict[x],bars))
y_pos = np.flip(np.arange(len(bars)))

plt.barh(y_pos, height,color = color) ; plt.yticks(y_pos, bars)
plt.axvline(x=np.mean(height), color = 'red', ls = 'dotted')
plt.title('정당별 총 발의 법안 수')
plt.show()

mean_cnt = np.mean(height/b)
plt.barh(y_pos, height/b ,color = color) ; plt.yticks(y_pos, bars)
plt.axvline(x= mean_cnt, color = 'red', ls = 'dotted')
plt.title('정당별 1 인당 발의 법안 수')
plt.show()

# 법률안 발의 빈도의 시계열 추이. (일주일 간격.)

EDA3 = raw2['date'].to_frame()
EDA3.set_index('date', inplace=True)
EDA3['count'] = 1
EDA3 = EDA3.resample('30D', how='sum')

y = EDA3['count'][:-1]
x = EDA3.index[:-1]
plt.plot(x,y)

# 별차이가 없다...


from random import randint
from time import sleep
from art import *
from Score import *

def check_result():
    print("Let's see if you were right", end="")
    for i in range(3):
        sleep(1)
        print(".", end="")
    print()

def compare_results(lucky_number, secret_number, difficulty, name):
    if lucky_number == secret_number:
        print("\033[1m***YOU WIN***\033[0m")
        add_score(name, points_of_winning(difficulty))
        sleep(1)
    else:
        print("\033[1mYOU LOSE!\033[0m")
        sleep(1)

def if_one(difficulty):
    if difficulty != 1:
        return difficulty
    else:
        return difficulty + 1

def generate_number(difficulty):
    num = randint(1, difficulty)
    return num

def get_guess_from_user(difficulty):
    lucky_num = 0
    status = 0
    while lucky_num < 1 or lucky_num > difficulty:
        if status != 0: print(f"Only numbers 1-{difficulty} can be selected")
        try:
            lucky_num = int(input(f"Choose your lucky number between 1 to {difficulty}: "))
        except ValueError:
            pass
        status = 1
    return lucky_num

def play_again():
    again = input("Another game? (y/n): ").lower()
    while again not in ["y", "n"]:
        print("Choose y or n only!")
        again = input("Another game? (y/n): ").lower()
    return again

def play1(name, difficulty):
    again = "y"
    while again == "y":
        difficulty = if_one(difficulty)
        lucky_number = get_guess_from_user(difficulty)
        secret_number = generate_number(difficulty)
        check_result()
        compare_results(lucky_number, secret_number, difficulty, name)
        print(f"Your number is: {lucky_number}\nThe winning number is: {secret_number}\n")
        again = play_again()
    else:
        print("GOODBYE\n")
        sleep(1)


'''
Given a signed 32-bit integer x, return x with its digits reversed.
If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1],
then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

Constraints:

-231 <= x <= 231 - 1
'''

def reverse(x):
    num = 0
    signed = False

    # Check if a number is signed(negative) and convert it to a positive number
    if x < 0:
        x = x * -1
        signed = True

    while x:
        # Get the last digit in x
        value = x % 10
        # Floor division by 10 to get remove the last digit from x
        x = x // 10
        # Add value to the end of num
        num = (num * 10) + value

    if signed:
        return num * -1
    else:
        return num

def main():
    print(reverse(123))

if __name__ == '__main__':
    main()


import json
import os
import subprocess
import multiprocessing
from datetime import datetime
from multiprocessing import Manager
from typing import Dict, Tuple
import logging

def send_disc(packet, nc_command):
    echo_command = "echo " + "\"" + packet + "\"" + " | " + nc_command
    os.system(echo_command)

def send_resp(packet, nc_cmd):
    echo_cmd = "echo " + "\"" + packet + "\"" + " | " + nc_cmd
    os.system(echo_cmd)

def listen(nc_command):
    os.system(nc_command)

def get_name_and_ip(response_str) -> Tuple[str, str]:
    start = response_str.find("NAME") + 6
    finish = response_str.find("MY_IP") - 2
    name = response_str[start:finish]
    start = response_str.find("MY_IP") + 7
    finish = response_str.find("TYPE") - 2
    ip = response_str[start:finish]
    return name, ip

def get_response(resp_dict, user_dict):
    port: str = "12345"
    resp_packet = str(json.dumps(resp_dict))
    while True:
        server = subprocess.run(["nc", "-l", port], stdout=subprocess.PIPE)
        response_str = str(server.stdout)
        if response_str != "":
            user_name, user_ip = get_name_and_ip(response_str)
            nc_command: str = "nc -vn -w 1 " + user_ip + " " + port
            initial_type = response_str.find("TYPE") + 6
            if user_ip not in list(user_dict.values()):
                user_dict[user_name] = user_ip
                print(user_name + " is added to your address list!")
                print("Address list: " + str(user_dict.keys()))
                print("Select a user name from the address list: ")
                if response_str[initial_type:initial_type + 1] == "D":
                    p_response = multiprocessing.Process(target=send_resp, args=(resp_packet, nc_command,))
                    p_response.start()
            elif response_str[initial_type: initial_type + 1] == "M" and user_ip in list(user_dict.values()):
                with open('chat_history.txt', "a") as f:
                    initial_m = response_str.find("PAYLOAD") + 9
                    last_m = response_str.rfind("}")
                    recv_msg = response_str[initial_m:last_m]
                    f.write("FROM {0} to {1}: \"{2}\" at {3}\n".format(user_name, resp_dict["NAME"], recv_msg,
                                                                       datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            elif response_str[initial_type: initial_type + 1] == "M" and user_ip not in list(user_dict.values()):
                print("{0} is not in the address list. The message is hidden from the user!".format(user_ip))
            else:
                logging.error("Something wrong happened!")

def discover_ip(disc_dict):
    common_ip: str = disc_dict["MY_IP"][:-3]
    my_ip = int(disc_dict["MY_IP"][-3:])
    port: str = "12345"
    packet = str(json.dumps(disc_dict))
    for i in range(254, 255):
        if i != my_ip:
            nc_command: str = "nc -vn -w 1 " + common_ip + str(i) + " " + port
            p1 = multiprocessing.Process(target=send_disc, args=(packet, nc_command,))
            p1.start()

def create_jsons() -> Tuple[Dict[str, str], Dict[str, str], Dict[str, str]]:
    name = os.popen("whoami").read()[:-1]
    my_ip = os.popen("ipconfig getifaddr en0").read()[:-1]
    discover_dict = {
        "NAME": name,
        "MY_IP": my_ip,
        "TYPE": "DISCOVER",
        "PAYLOAD": ""
    }
    respond_dict = {
        "NAME": name,
        "MY_IP": my_ip,
        "TYPE": "RESPOND",
        "PAYLOAD": ""
    }
    message_dict = {
        "NAME": name,
        "MY_IP": my_ip,
        "TYPE": "MESSAGE",
        "PAYLOAD": ""
    }
    return discover_dict, respond_dict, message_dict

def simulation(disc_json, resp_json, user_dict):
    p_discover = multiprocessing.Process(target=discover_ip, args=(disc_json,))
    p_discover.start()

    while True:
        p2 = multiprocessing.Process(target=get_response, args=(resp_json, user_dict,))
        p2.start()
        p2.join()
        print(1)

if __name__ == '__main__':
    if os.path.exists("chat_history.txt"):
        os.remove("chat_history.txt")

    print("Welcome to BuChat!")
    disc_json, resp_json, msg_json = create_jsons()
    manager = Manager()
    user_dict = manager.dict()
    p_simulate = multiprocessing.Process(target=simulation, args=(disc_json, resp_json, user_dict,))
    p_simulate.start()
    while True:
        print("Address list: " + str(user_dict.keys()))
        user_name = input("Select a user name from the address list: \n")
        if user_name in user_dict.keys():
            message_to_sent = input("USERNAME FOUND!\nWrite your message to {0}: ".format(user_name))
            msg_json["PAYLOAD"] = message_to_sent
            msg_packet = str(json.dumps(msg_json))
            common_ip: str = msg_json["MY_IP"][:-3]
            port = "12345"
            nc_command: str = "nc -vn -w 1 " + user_dict[user_name] + " " + port
            echo_command = "echo " + "\"" + msg_packet + "\"" + " | " + nc_command
            os.system(echo_command)
            with open('chat_history.txt', "a+") as f:
                f.write("FROM {0} to {1}: \"{2}\" at {3}\n".format(msg_json["NAME"], user_name, message_to_sent,
                                                                   datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
        else:
            logging.info("{0} is not in the user dict! IP NOT FOUND!".format(user_name))

bogazici/CMPE487 | Applied Computer Networks/NetcatChat/chat.py


import pandas as panda
from openpyxl import Workbook
from openpyxl.drawing.image import Image
import os
import shutil
import os.path
import openpyxl
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
import tkinter as tk
from tkinter import filedialog

"""This program is to pull certain  photos from a selected pool according to excel sheet.
Photos will be copied to a directory of your choice, and will be seperated to different
folders with sheet names."""

print(" "* 2700)
print("Welcome to PhotoCarry")
print("This program is written for the purpose of copying photos")
print("from a pool to a directory according to an excelfile")
print("You will be asked to choose the pool directory  first and then")
print("the excel file. Lastly the location of the new directory.")
print(" "* 900)
#input('Press any key to continue')

root = tk.Tk()
root.withdraw()

#Pop-up that asks from where the  photos are taken
pool_path = filedialog.askdirectory(title="Choose the location of the photo pool")

#pop-up that asks where the excel file is.
file_path = filedialog.askopenfilename(title="Choose the excel file")
print(file_path)

#Pop-up that asks Where it will be stored
directory_path = filedialog.askdirectory(title="Choose the directory where the photos will be copied to")

file = panda.ExcelFile(file_path)
sheets = file.sheet_names

wb = load_workbook(file_path)

#iterating through the sheets
for sheet in sheets:
    page=file.parse(sheet)
    lenght, widht = page.shape
    print("The lenght of this sheet is :"+ str(lenght))
    ws = wb[sheet]
    path = os.path.join(directory_path, sheet)

    #if a folder with sheet's name exist it will fo nothing, else it will create a new one.
    if sheet in os.listdir(directory_path):
        continue
    else:
        os.mkdir(path)
        print("Directory '%s' created" %sheet)

    store_folder = directory_path+"/"+sheet
    for i in range(0, lenght):
        photo_check = page['Inv. No.'][i]

        #checking if there is a match
        #The algorithm for searching the filename is created according the need of the developer.
         #example of a filename for this algorithm is "ARK_123_4567.jpg" and we want to match with "4567".
        for filename in os.listdir(pool_path):

            #If your photo's name and the cell have the same name simply delete the codes until two lines above the Eureka part.
            first_line=0

            for k in range(0,len(filename)):
                if filename[k] == "_":
                    if first_line==0:
                        first_line=1
                    else:
                        second_line=0
                        for j in range(0,len(filename)):
                            if filename[j] == "_" or filename[j]== ".":
                                if second_line ==0 or second_line == 1:
                                    second_line = second_line + 1

                                elif second_line ==2:
                                    shm_number = "SHM "+ filename[k+1:j]

                                    #This means that the photo's name is the same with the cell.
                                    if shm_number == photo_check:
                                        print("Eureka!!")
                                        shutil.copy(pool_path+"/"+filename, store_folder)


import string
import math

tmp = string.digits+string.ascii_lowercase

def convert(n, k):
    q, r = divmod(n, k)
    if q == 0:
        return tmp[r]
    else :
        return convert(q, k) + tmp[r]

def is_prime_number(x):
    for i in range(2, int(math.sqrt(x)) + 1):
        if x % i == 0:
            return False

    return True

def solution(n, k):
    answer = 0
    k_num = convert(n, k)

    num_list = [ int(i) for i in k_num.split('0') if i and i > "1"]

    for num in num_list:
        if is_prime_number(num):
            answer += 1

    return answer

print(solution(437674, 3))
print(solution(110011, 10))
print(solution(3, 3))


"""HTTP request and response models for /health endpoints."""
import typing
from pydantic import BaseModel, Field
from opentrons_shared_data.deck.dev_types import RobotModel
from robot_server.service.json_api import BaseResponseBody

class HealthLinks(BaseModel):
    """Useful server links."""

    apiLog: str = Field(
        ...,
        description="The path to the API logs endpoint",
    )
    serialLog: str = Field(
        ...,
        description="The path to the motor control serial communication logs endpoint",
    )
    serverLog: str = Field(
        ...,
        description="The path to the HTTP server logs endpoint",
    )
    oddLog: typing.Optional[str] = Field(
        None,
        description="The path to the ODD app logs endpoint",
    )
    apiSpec: str = Field(
        ...,
        description="The path to the OpenAPI specification of the server",
    )
    systemTime: str = Field(
        ...,
        description="The path to the system time endpoints",
    )

class Health(BaseResponseBody):
    """Information about the server and system."""

    name: str = Field(
        ...,
        description="The robot's name. In most cases the same as its "
        "mDNS advertisement domain name, but this can get out "
        "of sync. Mostly useful for user-facing titles.",
    )
    robot_model: RobotModel = Field(
        ...,
        description="Which model of Opentrons robot this is",
    )
    api_version: str = Field(
        ...,
        description="The API server's software version",
    )
    fw_version: str = Field(
        ...,
        description="The motor controller's firmware version. Doesn't "
        "follow a pattern; suitable only for display or exact matching.",
    )
    board_revision: str = Field(
        ...,
        description="The hardware revision of the OT-2's central routing board.",
    )
    logs: typing.List[str] = Field(
        ...,
        description="List of paths at which to find log endpoints",
    )
    system_version: str = Field(
        ...,
        description="The robot's operating system version.",
    )
    maximum_protocol_api_version: typing.List[int] = Field(
        ...,
        description="The system's maximum supported Protocol API version, "
        "in the format `[major_version, minor_version]`",
        min_items=2,
        max_items=2,
    )
    minimum_protocol_api_version: typing.List[int] = Field(
        ...,
        description="The system's minimum supported Protocol API version, "
        "in the format `[major_version, minor_version]`",
        min_items=2,
        max_items=2,
    )
    robot_serial: typing.Optional[str] = Field(
        default=None,
        description="The robot serial number. Should be used if present; if not present, use result of /server/update/health.",
    )
    links: HealthLinks

    class Config:
        """Health response model schema configuration."""

        schema_extra = {
            "example": {
                "name": "OT2CEP20190604A02",
                "api_version": "3.15.2",
                "fw_version": "v2.15.0",
                "board_revision": "2.1",
                "logs": ["/logs/serial.log", "/logs/api.log"],
                "system_version": "1.2.1",
                "maximum_protocol_api_version": [2, 8],
                "minimum_protocol_api_version": [2, 0],
                "links": {
                    "apiLog": "/logs/api.log",
                    "serialLog": "/logs/serial.log",
                    "apiSpec": "/openapi.json",
                    "systemTime": "/system/time",
                },
                "robot_serial": None,
            }
        }


import site
import sys
import os
from backend import install as backend_install
from setuptools import setup

'''Setuptools installer. This script will be called by pip when:
- We want to create a distributable (sdist) tar.gz
- We want to build the C extension (build and build_ext)
- We want to install PyCOMPSs (install)

It can be invoked to do these functionalities with
python setup.py (install|sdist|build)
'''

bindings_location = os.path.join('COMPSs', 'Bindings')
venv = False

def get_virtual_env_target_path():
    '''Get the target path within a virtual environment
    :return: target path
    '''
    from distutils.sysconfig import get_python_lib
    return os.path.join(get_python_lib(), 'pycompss')

def get_root_target_path():
    '''Get the target path for root installations
    :return: target path
    '''
    return os.path.join(site.getsitepackages()[0], 'pycompss')

def get_user_target_path():
    '''Get the target path for user installation
    :return: target path
    '''
    return os.path.join(site.getusersitepackages(), 'pycompss')

if 'VIRTUAL_ENV' in os.environ:
    # We are within a virtual environment
    # This is more legit than within the exception
    venv = True
    target_path = get_virtual_env_target_path()
    print('Installing within virtual environment in: ' + str(target_path))
else:
    try:
        if os.getuid() == 0:
            # Installing as root
            target_path = get_root_target_path()
            print('Installing as root in: ' + str(target_path))
        else:
            # Installing as user
            target_path = get_user_target_path()
            print('Installing as user in: ' + str(target_path))
    except AttributeError:
        # This exception can be raised within virtual environments due to a bug
        # with the site module.
        venv = True
        target_path = get_virtual_env_target_path()
        print('Installing within virtual environment in: ' + str(target_path))

def check_system():
    '''Check that we have a proper python version and a proper OS (i.e: not windows)
    Also, check that we have JAVA_HOME defined.
    This does NOT intend to perform an exhaustive system check, and it is neither
    the role nor in the scope of a distutils installer
    '''
    # check Python version
    assert sys.version_info[:2] >= (3, 6), 'COMPSs does not support Python version %s, only Python >= 3.6.x is supported.'%sys.version

    # check os version not Windows
    assert not sys.platform == "win32", "COMPSs does not support Windows"
    assert not sys.platform == "cygwin", "COMPSs does not support Windows/Cygwin"
    assert not sys.platform == "msys", "COMPSs does not support Windows/MSYS2"

    # check we have JAVA_HOME defined
    assert 'JAVA_HOME' in os.environ, 'JAVA_HOME is not defined'

'''Pre-install operation: download and install COMPSs
This will try to stop the installation if some error is
found during this part. However, some sub-scripts do not
propagate the errors they find, so there is not absolute
guarantee that this script will lead to a perfect, clean
installation.
'''
messages = []
if 'install' in sys.argv or 'bdist_wheel' in sys.argv:
    check_system()
    messages = backend_install(target_path, venv)

'''Setup function.
'''
setup(name='pycompss',
    version=open('VERSION.txt').read().rstrip(),
    description='Python Binding for COMP Superscalar Runtime',
    long_description=open('README.rst').read(),
    long_description_content_type='text/x-rst',
    author='The COMPSs team',
    author_email='support-compss@bsc.es',
    maintainer='The COMPSs team',
    maintainer_email='support-compss@bsc.es',
    url='http://compss.bsc.es',
    classifiers=['Development Status :: 5 - Production/Stable',
                'Environment :: Console',
                'Intended Audience :: Developers',
                'Intended Audience :: Science/Research',
                'License :: OSI Approved :: Apache Software License',
                'Operating System :: POSIX :: Linux',
                'Operating System :: Unix',
                'Programming Language :: C',
                'Programming Language :: C++',
                'Programming Language :: Java',
                'Programming Language :: Python :: 3.6',
                'Programming Language :: Python :: 3.7',
                'Programming Language :: Python :: 3.8',
                'Programming Language :: Python :: 3.9',
                'Programming Language :: Python :: 3.10',
                'Topic :: Software Development',
                'Topic :: Scientific/Engineering',
                'Topic :: System :: Distributed Computing',
                'Topic :: Utilities'],
    install_requires=['setuptools'],
    license='Apache 2.0',
    platforms=['Linux']
)

'''Show final messages
'''
for message in messages:
    print(message)


# -*- coding: utf-8 -*-
import sys
import xml.etree.ElementTree as ET

from lib import SuggestionCompleter, SuggestionNetworkModel

from PyQt5.QtCore import Qt, QUrl, QUrlQuery
from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
from PyQt5.QtWidgets import QApplication, QLineEdit

class SearchSuggestionModel(SuggestionNetworkModel):
    def create_request(self, text):
        url = QUrl("http://toolbarqueries.google.com/complete/search")
        query = QUrlQuery()
        query.addQueryItem("q", text)
        query.addQueryItem("output", "toolbar")
        query.addQueryItem("hl", "en")
        url.setQuery(query)
        request = QNetworkRequest(url)
        return request

    def process_reply(self, reply):
        results = []
        error_string = ""
        if reply.error() == QNetworkReply.NoError:
            content = reply.readAll().data()
            suggestions = ET.fromstring(content)
            for data in suggestions.iter("suggestion"):
                results.append(data.attrib["data"])
        elif reply.error() != QNetworkReply.OperationCanceledError:
            error_string = reply.errorString()
        return results, error_string

def main():
    app = QApplication(sys.argv)

    searchbar = QLineEdit()
    completer = SuggestionCompleter(caseSensitivity=Qt.CaseInsensitive)
    model = SearchSuggestionModel()
    completer.setModel(model)
    searchbar.setCompleter(completer)
    searchbar.resize(640, 60)
    searchbar.show()

    ret = app.exec_()
    sys.exit(ret)

if __name__ == "__main__":
    main()


import cv2
from matplotlib import pyplot as plt

# Download files from https://drive.google.com/file/d/1XdZLvORnCnfpyBYflh15I58VQrQdVlUe/view?usp=sharing

h_skin_hist = 0
h_nonskin_hist = 0
s_skin_hist = 0
s_nonskin_hist = 0
for im_id in range(1, 4):
    print(im_id)
    im = cv2.imread("SkinDetection\SkinTrain" + str(im_id) + ".jpg")
    mask = cv2.imread("SkinDetection\SkinTrain" + str(im_id) + "_mask.jpg", 0)
    im_hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
    h_skin_hist = h_skin_hist + cv2.calcHist([im_hsv], [0], mask, [256], [0, 256])
    h_nonskin_hist = h_nonskin_hist + cv2.calcHist([im_hsv], [0], 255 - mask, [256], [0, 256])
    s_skin_hist = s_skin_hist + cv2.calcHist([im_hsv], [1], mask, [256], [0, 256])
    s_nonskin_hist = s_nonskin_hist + cv2.calcHist([im_hsv], [1], 255 - mask, [256], [0, 256])

h_skin_prob = h_skin_hist / sum(h_skin_hist) # P(h|skin)
h_nonskin_prob = h_nonskin_hist / sum(h_nonskin_hist) # P(h|non-skin)
s_skin_prob = s_skin_hist / sum(s_skin_hist) # P(s|skin)
s_nonskin_prob = s_nonskin_hist / sum(s_nonskin_hist) # P(s|non-skin)

plt.plot(h_skin_prob, 'r', label = 'P(h|skin)')
plt.plot(h_nonskin_prob, 'b', label = 'P(h|non-skin)')
plt.legend()
plt.figure()
plt.plot(s_skin_prob, 'r', label = 'P(s|skin)')
plt.plot(s_nonskin_prob, 'b', label = 'P(s|non-skin)')
plt.show()


#! /usr/bin/python2
# -*- coding: utf-8; -*-
#
# (c) 2013 booya (http://booya.at)
#
# This file is part of the OpenGlider project.
#
# OpenGlider is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# OpenGlider is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OpenGlider.  If not, see <http://www.gnu.org/licenses/>.
import logging
import numpy as np
import logging

from openglider.lines import line_types
from openglider.lines.functions import proj_force, proj_to_surface
from openglider.utils.cache import cached_property, CachedObject
from openglider.vector import PolyLine
from openglider.vector.functions import norm, normalize
from openglider.mesh import Mesh, Vertex, Polygon

logger = logging.getLogger(__name__)

class SagMatrix():
    def __init__(self, number_of_lines):
        size = number_of_lines * 2
        self.matrix = np.zeros([size, size])
        self.rhs = np.zeros(size)
        self.solution = np.zeros(size)

    def __str__(self):
        return str(self.matrix) + "\n" + str(self.rhs)

    def insert_type_0_lower(self, line):
        """
        fixed lower node
        """
        i = line.number
        self.matrix[2 * i + 1, 2 * i + 1] = 1.

    def insert_type_1_lower(self, line, lower_line):
        """
        free lower node
        """
        i = line.number
        j = lower_line.number
        self.matrix[2 * i + 1, 2 * i + 1] = 1.
        self.matrix[2 * i + 1, 2 * j + 1] = -1.
        self.matrix[2 * i + 1, 2 * j] = -lower_line.length_projected
        self.rhs[2 * i + 1] = -lower_line.ortho_pressure * \
            lower_line.length_projected ** 2 / lower_line.force_projected / 2

    def insert_type_1_upper(self, line, upper_lines):
        """
        free upper node
        """
        i = line.number
        self.matrix[2 * i, 2 * i] = 1
        infl_list = []
        vec = line.diff_vector_projected
        for u in upper_lines:
            infl = u.force_projected * np.dot(vec, u.diff_vector_projected)
            infl_list.append(infl)
        sum_infl = sum(infl_list)
        for k in range(len(upper_lines)):
            j = upper_lines[k].number
            self.matrix[2 * i, 2 * j] = -(infl_list[k] / sum_infl)
        self.rhs[2 * i] = line.ortho_pressure * \
            line.length_projected / line.force_projected

    def insert_type_2_upper(self, line):
        """
        Fixed upper node
        """
        i = line.number
        self.matrix[2 * line.number, 2 * line.number] = line.length_projected
        self.matrix[2 * line.number, 2 * line.number + 1] = 1.
        self.rhs[2 * i] = line.ortho_pressure * \
            line.length_projected ** 2 / line.force_projected / 2

    def solve_system(self):
        self.solution = np.linalg.solve(self.matrix, self.rhs)

    def get_sag_parameters(self, line_nr):
        return [
            self.solution[line_nr * 2],
            self.solution[line_nr * 2 + 1]]

class Line(CachedObject):
    rho_air = 1.2

    def __init__(self, lower_node, upper_node, v_inf,
                 line_type=line_types.LineType.get('default'), target_length=None, number=None, name=None, color=""):
        """
        Line Class
        """
        self.number = number
        self.type = line_type  # type of line

        self._color = None
        self.color = color

        self.lower_node = lower_node
        self.upper_node = upper_node

        self.target_length = target_length
        self.init_length = target_length

        self.force = None

        self.sag_par_1 = None
        self.sag_par_2 = None

        self.name = name or "line_name_not_set"

        self.lineset = None      # the parent have to be set after initialization

    @property
    def color(self):
        return self._color or "default"

    @color.setter
    def color(self, color):
        if color in self.type.colors:
            self._color = color

    @property
    def has_geo(self):
        """
        true if upper and lower nodes of the line were already computed
        """
        #the node vectors can be None or numpy.arrays. So we have to check for both types
        try:
            return all(list(self.lower_node.vec) +
                       list(self.upper_node.vec))
        except TypeError:
            # one of the nodes vec is None
            return False

    @property
    def v_inf_0(self):
        return normalize(self.v_inf)

    @property
    def v_inf(self):
        return self.lineset.v_inf

    #@cached_property('lower_node.vec', 'upper_node.vec')
    @property
    def diff_vector(self):
        """
        Line Direction vector (normalized)
        :return:
        """
        return normalize(self.upper_node.vec - self.lower_node.vec)

    #@cached_property('lower_node.vec', 'upper_node.vec')
    @property
    def diff_vector_projected(self):
        return normalize(self.upper_node.vec_proj - self.lower_node.vec_proj)

    @cached_property('lower_node.vec', 'upper_node.vec', 'v_inf')
    def length_projected(self):
        return norm(self.lower_node.vec_proj - self.upper_node.vec_proj)

    @property
    def length_no_sag(self):
        return norm(self.upper_node.vec - self.lower_node.vec)

    @cached_property('lower_node.vec', 'upper_node.vec', 'v_inf', 'sag_par_1', 'sag_par_2')
    def length_with_sag(self):
        if self.sag_par_1 is None or self.sag_par_2 is None:
            raise ValueError('Sag not yet calculated!')

        return PolyLine(self.get_line_points(numpoints=100)).get_length()

    def get_stretched_length(self, pre_load=50, sag=True):
        """
        Get the total line-length for production using a given stretch
        length = len_0 * (1 + stretch*force)
        """
        if sag:
            l_0 = self.length_with_sag
        else:
            l_0 = self.length_no_sag
        factor = self.type.get_stretch_factor(pre_load) / self.type.get_stretch_factor(self.force)
        return l_0 * factor

    #@cached_property('v_inf', 'type.cw', 'type.thickness')
    @property
    def ortho_pressure(self):
        """
        drag per meter (projected)
        :return: 1/2 * cw * d * v^2
        """
        return 1 / 2 * self.type.cw * self.type.thickness * self.rho_air * norm(self.v_inf) ** 2

    @cached_property('lower_node.vec', 'upper_node.vec', 'v_inf')
    def drag_total(self):
        """
        Get total drag of line
        :return: 1/2 * cw * A * v^2
        """
        return self.ortho_pressure * self.length_projected

    def get_weight(self):
        if self.type.weight is None:
            logger.warning("predicting weight of linetype {self.type.name} by line-thickness.")
            logger.warning("Please enter line_weight in openglider/lines/line_types")
            weight = self.type.predict_weight()
        else:
            weight = self.type.weight
        try:
            return weight * self.length_with_sag
        except ValueError:
            # computing weight without sag
            return weight * self.length_no_sag

    @cached_property('force', 'lower_node.vec', 'upper_node.vec')
    def force_projected(self):
        return self.force * self.length_projected / self.length_no_sag

    def get_line_points(self, sag=True, numpoints=10):
        """
        Return points of the line
        """
        if self.sag_par_1 is None or self.sag_par_2 is None:
            sag=False
        return np.array([self.get_line_point(i / (numpoints - 1), sag=sag) for i in range(numpoints)])

    def get_line_point(self, x, sag=True):
        """pos(x) [x,y,z], x: [0,1]"""
        if sag:
            return (self.lower_node.vec * (1. - x) + self.upper_node.vec * x +
                    self.get_sag(x) * self.v_inf_0)
        else:
            return self.lower_node.vec * (1. - x) + self.upper_node.vec * x

    def get_sag(self, x):
        """sag u(x) [m], x: [0,1]"""
        xi = x * self.length_projected
        u = (- xi ** 2 / 2 * self.ortho_pressure /
             self.force_projected + xi *
             self.sag_par_1 + self.sag_par_2)
        return u

    def get_mesh(self, numpoints):
        line_points = [Vertex(*point) for point in self.get_line_points(numpoints=numpoints)]
        boundary = {"lines": []}
        if self.lower_node.type == 0:
            boundary["lower_attachment_points"] = [line_points[0]]
        else:
            boundary["lines"].append(line_points[0])
        if self.upper_node.type == 2:
            boundary["attachment_points"] = [line_points[-1]]
        else:
            boundary["lines"].append(line_points[-1])

        if numpoints == 2:
            stretch_factor = 1 + self.force / self.type.get_spring_constant()
            attributes = {
                "name": self.name,
                "l_12": self.length_no_sag / stretch_factor,
                "e_module": self.type.get_spring_constant()
            }
            line_poly = {"lines": [Polygon(line_points, attributes=attributes)]}
        else:
            line_poly = {"lines": [Polygon(line_points[i:i + 2]) for i in range(len(line_points) - 1)]}

        return Mesh(line_poly, boundary)

    @property
    def _get_projected_par(self):
        c1_n = np.dot(self.lower_node.get_diff(), self.v_inf_0)
        c2_n = np.dot(self.upper_node.get_diff(), self.v_inf_0)
        return [c1_n + self.sag_par_1, c2_n / self.length_projected + self.sag_par_2]

    def __json__(self):
        return{
            'number': self.number,
            'lower_node': self.lower_node,
            'upper_node': self.upper_node,
            'v_inf': None,               # remove this!
            'line_type': self.type.name,
            'target_length': self.target_length,
            'name': self.name
        }

    @classmethod
    def __from_json__(cls, number, lower_node, upper_node, v_inf, line_type, target_length, name):
        return cls(lower_node,
                   upper_node,
                   v_inf,
                   line_types.LineType.get(line_type),
                   target_length,
                   number,
                   name)

    def get_connected_ribs(self, glider):
        '''
        return the connected ribs
        '''
        lineset = glider.lineset
        att_pnts = lineset.get_upper_influence_nodes(self)
        return set([att_pnt.rib for att_pnt in att_pnts])

    def get_rib_normal(self, glider):
        '''
        return the rib normal of the connected rib(s)
        '''
        ribs = self.get_connected_ribs(glider)
        result = np.array([0., 0., 0.])
        for rib in ribs:
            result += rib.normalized_normale
        return result / np.linalg.norm(result)

    def rib_line_norm(self, glider):
        '''
        returns the squared norm of the cross-product of
        the line direction and the normal-direction of
        the connected rib(s)
        '''
        return self.diff_vector.dot(self.get_rib_normal(glider))

    def get_correction_influence(self, residual_force):
        '''
        returns an influence factor [force / length] which is a proposal for
        the correction of a residual force if the line is moved in the direction
        of the residual force
        '''
        diff = self.diff_vector
        l = np.linalg.norm(diff)
        r = np.linalg.norm(residual_force)
        normed_residual_force = residual_force / r
        normed_diff_vector = diff / l
        f = 1. - normed_residual_force @ normed_diff_vector   # 1 if normal, 0 if parallel
        return f * self.force / l

class Node(object):
    def __init__(self, node_type, position_vector=None, attachment_point=None, name=None):
        self.type = node_type  # lower, middle, top (0, 1, 2)
        if position_vector is not None:
            position_vector = np.array(position_vector)
        self.vec = position_vector

        self.vec_proj = None  # pos_proj
        self.force = np.array([None, None, None])  # top-node force
        self.attachment_point = attachment_point
        self.name = name or "name_not_set"

    def calc_force_infl(self, vec):
        v = np.array(vec)
        direction = self.vec - v
        if self.type == 2:
            force = proj_force(self.force, direction)
        else:
            force = self.force @ direction / np.linalg.norm(direction)
        if force is None:
            logging.warn("projected force for line {} is None, direction: {}, force: {}".format(
                self.name, direction, self.force))
            force = 0.00001
        return normalize(direction) * force

    def get_position(self):
        pass

    def calc_proj_vec(self, v_inf):
        self.vec_proj = proj_to_surface(self.vec, v_inf)
        return proj_to_surface(self.vec, v_inf)

    def get_diff(self):
        return self.vec - self.vec_proj

    def is_upper(self):
        return self.type == 2

    def __json__(self):
        return{
            'node_type': self.type,
            'position_vector': list(self.vec),
            "name": self.name
        }

    def copy(self):
        return self.__class__(self.type, self.vec, self.attachment_point, self.name)

    def __repr__(self):
        return super().__repr__() + f" of type: {self.type}"


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('tasting', '0006_tastingcategory_singulartitle'),
    ]

    operations = [
        migrations.AddField(
            model_name='whisky',
            name='degAlcool',
            field=models.IntegerField(default=0),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='wine',
            name='degAlcool',
            field=models.IntegerField(default=0),
            preserve_default=True,
        ),
    ]


class Solution:
    def largestMerge(self, word1: str, word2: str) -> str:
        i, j = 0, 0
        result = ''

        while i < len(word1) and j < len(word2):
            if word1[i:] > word2[j:]:
                result+=word1[i]
                i += 1
            else:
                result+=word2[j]
                j += 1

        result += word1[i:] + word2[j:]
        return result


import re, collections
from matplotlib import pyplot as plt

def get_vocab(filename):
    """
    :param filename: 文件地址，需要切好词，空格隔开
    :return: dic ：{ 'str str .. </w>' : 频率int  }
    """
    vocab = collections.defaultdict(int)
    class_num_list = []
    with open(filename, 'r', encoding='utf-8') as fhand:
        for line in fhand:
            words = line.strip().split()
            for word in words:
                vocab[' '.join(list(word)) + ' </w>'] += 1
    return vocab, class_num_list

def get_stats(vocab):
    pairs = collections.defaultdict(int)
    for word, freq in vocab.items():  # 遍历每个单词中的 pair
        symbols = word.split()
        for i in range(len(symbols) - 1):
            pairs[symbols[i], symbols[i + 1]] += freq
    return pairs

def merge_vocab(pair, v_in):
    """
    :param pair:
    :param v_in: 将 v_in 中的所有 pair 全部拼接
    :return:
    """
    v_out = {}
    bigram = re.escape(' '.join(pair))
    p = re.compile(r'(?<!\S)' + bigram + r'(?!\S)')
    for word in v_in:
        w_out = p.sub(''.join(pair), word)
        v_out[w_out] = v_in[word]
    return v_out

def get_tokens(vocab):
    """ 得到 字符频率字典 """
    tokens = collections.defaultdict(int)
    for word, freq in vocab.items():
        word_tokens = word.split()  # [ 'str', 'str', ... ]
        for token in word_tokens:  # 遍历 str，放入tokens字典中
            tokens[token] += freq
    return tokens

def save_keys(tokens, path):
    with open(path, "w", encoding='utf-8') as f:
        for i in tokens.keys():
            f.write(i + "\n")

def save_items(tokens, path):
    with open(path, "w", encoding='utf-8') as f:
        for i, j in tokens:
            f.write(i + ' ' + j + "\n")

if __name__ == "__main__":
    """
    # 目的是压缩词表，所以设置目标 size
    """
    original_path = "../DC_train.src.txt"  # 目标文本 使用 src 模拟
    output_tgt_path = "BPE_DC_train.tgt.txt"  # 处理后文本
    output_token_path = "DC_vocab.txt"  # 处理后的词表
    # 两个东西共同设置迭代次数
    min_vocab_size = -1  # 默认可以设置为 -1
    merge_num = 400  # 默认可以设置为 999999999999

    vocab = get_vocab(original_path)  # word频率表
    # if len(vocab) > min_vocab_size:
    #     print("The word size is {}, bigger than min_vocab_size {},"
    #           " Please try bigger min_vocab_size !!!".format(len(vocab), min_vocab_size))
    #     exit()

    print('==========')
    print('Tokens Before BPE')
    tokens = get_tokens(vocab)  # token频率表 （统计用，训练用不到）理想情况下先增大再减小，再增大，再减小到和vocab大小一致。
    print('Tokens: {}'.format(tokens))
    print('Number of tokens: {}'.format(len(tokens)))
    print('==========')
    token_num = []
    for i in range(merge_num):
        if len(tokens) <= min_vocab_size:
            break
        pairs = get_stats(vocab)  # token pair频率表 （训练用，不会保存）
        if not pairs:  # 全为整词（len(symbols)-1==0）
            break
        best = max(pairs, key=pairs.get)  # 找最高频 pair
        # 更新 vocab 和 token 频率表
        vocab = merge_vocab(best, vocab)  # 融合 word词频表 中pair
        # print('Best pair: {}'.format(best))
        tokens = get_tokens(vocab)  # 重新得到 token词频表
        # print('Tokens: {}'.format(tokens))
        # print('Number of tokens: {}'.format(len(tokens)))
        # print('==========')
        token_num.append(len(tokens))

    print("Finally, Number of tokens: {}".format(len(tokens)))

    plt.plot(range(len(token_num)), token_num)
    plt.show()

    save_keys(tokens, output_token_path)
    save_keys(vocab, output_tgt_path)


import sys, os, io, atexit

input = lambda: sys.stdin.readline().rstrip('\r\n')
stdout = io.BytesIO()
sys.stdout.write = lambda s: stdout.write(s.encode("ascii"))
atexit.register(lambda: os.write(1, stdout.getvalue()))

# 221001 17404 rgb거리 2

# 정답코드

N = int(input())

rgb = [list(map(int, input().split())) for _ in range(N)]

ans = sys.maxsize
for i in range(3):
    dp = [[0, 0, 0] for _ in range(N)]
    dp[0] = [sys.maxsize] * 3
    dp[0][i] = rgb[0][i]

    for j in range(1, N):
        dp[j][0] = rgb[j][0] + min(dp[j - 1][1], dp[j - 1][2])
        dp[j][1] = rgb[j][1] + min(dp[j - 1][0], dp[j - 1][2])
        dp[j][2] = rgb[j][2] + min(dp[j - 1][0], dp[j - 1][1])

    for k in range(3):
        if i == k:
            continue
        ans = min(ans, dp[-1][k])

print(ans)


#!/usr/bin/python3

""" Export all photos to specified directory using album names as folders
    If file has been edited, also export the edited version,
    otherwise, export the original version
    This will result in duplicate photos if photo is in more than album """

import os.path
import pathlib
import sys

import click
from pathvalidate import is_valid_filepath, sanitize_filepath

import osxphotos

@click.command()
@click.argument("export_path", type=click.Path(exists=True))
@click.option(
    "--default-album",
    help="Default folder for photos with no album. Defaults to 'unfiled'",
    default="unfiled",
)
@click.option(
    "--library-path",
    help="Path to Photos library, default to last used library",
    default=None,
)
def export(export_path, default_album, library_path):
    export_path = os.path.expanduser(export_path)
    library_path = os.path.expanduser(library_path) if library_path else None

    photosdb = osxphotos.PhotosDB()

    photos = photosdb.photos(albums=["TEST"])

    for p in photos:
        if not p.ismissing:
            for [TEST] in albums:
                click.echo(f"exporting {p.filename} in album {album}")

                # make sure no invalid characters in destination path (could be in album name)
                album_name = sanitize_filepath(album, platform="auto")

                # create destination folder, if necessary, based on album name
                dest_dir = os.path.join(export_path, album_name)

                # verify path is a valid path
                if not is_valid_filepath(dest_dir, platform="auto"):
                    sys.exit(f"Invalid filepath {dest_dir}")

                # create destination dir if needed
                if not os.path.isdir(dest_dir):
                    os.makedirs(dest_dir)

                # export the photo
                if p.hasadjustments:
                    # export edited version
                    exported = p.export(dest_dir, edited=True)
                    edited_name = pathlib.Path(p.path_edited).name
                    click.echo(f"Exported {edited_name} to {exported}")
                # export unedited version
                exported = p.export(dest_dir)
                click.echo(f"Exported {p.filename} to {exported}")
        else:
            click.echo(f"Skipping missing photo: {p.filename}")

if __name__ == "__main__":
    export()


#------------------------------------------------------------------------------------------------------------------------------------------------------------
# WIECLAW Manon
# TP IA
# 31.03.2023
#Script permettant de générer un exécutable à partir d'un modèle de régression linéaire.
#------------------------------------------------------------------------------------------------------------------------------------------------------------

import joblib
import numpy as np
import os

model= joblib.load('regressionlinear.joblib')
is_lr = type(model)
print ("is lr : ", is_lr)

features = [194.4, 2, 1]
n_param = len(features)

def get_coef(model):
    coef = [model.intercept_] + [coef for coef in model.coef_]
    print ("coefficient :", coef)
    return (coef)

def generate_c_function(model):
    coef = get_coef(model)
    s1 = f"""
        #include <stdio.h>
        #include <stdlib.h>

        float linear_regression_prediction (float* features, int n_parameters){{
            float result = {coef[0]};
    """

    for i in range (n_param):

        s1 += f" result += features[{i}] * {coef[i+1]};"

    s1 += f"\nreturn result; }}"

    s1+= f"""
        \tint main() {{
            float features [{n_param}] = {{{','.join(str(feature) for feature in features)}}};
            int n_parameters  = sizeof(features)/sizeof(float);
            float pred = linear_regression_prediction (features, n_parameters);
            printf("Prix estime : %f", pred);
            return 0;
        }}

    """
    if os.path.isfile('linear_regression_prediction.c'):
        os.remove('linear_regression_prediction.c')
    f = open('linear_regression_prediction.c', 'w')
    f.write(s1)
    f.close()

generate_c_function(model)

pred = model.predict(np.array(features).reshape(1, -1))
print("\n prix prédit en py :" + str(pred))