from django import forms
from ..contrib.sysdate import dateFromLocal

class DateBigInput(forms.DateInput):
    def value_from_datadict(self, data, files, name):
        valData = super().value_from_datadict(data, files, name)
        return dateFromLocal(valData)

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context['widget']['attrs']['data-provide'] = 'datepicker'
        context['widget']['attrs']['data-date-language'] = 'th-th'
        # context['widget']['attrs']['data-date-startdate'] = '-10d'
        # context['widget']['attrs']['data-date-enddate'] = '+10d'
        context['widget']['attrs']['class'] = 'form-control'
        return context

class NumberBigInput(forms.TextInput):
    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context['widget']['attrs']['data-inputmask-alias'] = 'currency'
        context['widget']['attrs']['class'] = 'form-control'
        return context

class TextBigInput(forms.TextInput):
    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context['widget']['attrs']['class'] = 'form-control'
        return context

class DecimalBigInput(forms.TextInput):
    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context['widget']['attrs']['data-inputmask-alias'] = 'currency'
        context['widget']['attrs']['class'] = 'form-control'
        return context

class IntegerBigInput(forms.TextInput):
    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context['widget']['attrs']['data-inputmask-alias'] = 'integer'
        context['widget']['attrs']['class'] = 'form-control'
        return context

# class ChoiceBigSelect(forms.Select):
#     def get_context(self, name, value, attrs):
#         context = super().get_context(name, value, attrs)
#         context['widget']['attrs']['class'] = 'form-control'
#         return context

class FormMixinBig:
    use_required_attribute = False
    readonly = []
    field_require = []
    currency = []
    # selectChoice = []

    def form_init(self):
        self.__WidgetBase()
        self.__FieldBase()

    def __FieldBase(self):
        for field in iter(self.fields):
            self.fields[field].required = False
            fieldType = self.fields[field].widget.__class__.__name__
            if fieldType not in ['Select', 'Select2','HiddenInput']:
                clsAttr = self.fields[field].widget.attrs.get('class','')
                if clsAttr.find('form-control') < 0 :
                    self.fields[field].widget.attrs['class'] = '{} form-control'.format(clsAttr)

            if fieldType in ['DateInput', 'DateTimeInput']:
                self.fields[field].widget = DateBigInput()
            if field in self.currency:
                self.fields[field].widget = NumberBigInput()

            if field in self.readonly or self.readonly == 'all':
                self.fields[field].widget.attrs['readonly'] = True
                if fieldType in ['DateInput', 'DateTimeInput']:
                    self.fields[field].widget.attrs['disabled'] = True

            if field in self.field_require or self.field_require == 'all':
                self.fields[field].required = True
                # if self.fields[field].label and not self.fields[field].label[0:1] == '*':
                #     self.fields[field].label = '*{}'.format(self.fields[field].lable)

    def __WidgetBase(self):
        if not hasattr(self,'Meta') : return
        if not hasattr(self.Meta, 'widgets'): return
        for widget in self.Meta.widgets:
            fieldType = self.Meta.widgets[widget].__class__.__name__
            if fieldType not in ['Select', 'Select2','HiddenInput']:
                clsAttr = self.Meta.widgets[widget].attrs.get('class', '')
                if clsAttr.find('form-control') < 0:
                    self.Meta.widgets[widget].attrs['class'] = '{} form-control'.format(clsAttr)

class BaseEditModelForm(forms.ModelForm,FormMixinBig):
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.form_init()

    def clean(self):
        super().clean()
        for f in self.cleaned_data:
            if not self.cleaned_data[f] and not self.cleaned_data[f] == 0:
                self.cleaned_data[f] = None

class BaseEditForm(forms.Form,FormMixinBig):
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.form_init()


from fastapi import FastAPI, Path

from typing import Optional
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    color: Optional[str] = None

inventory = {
    1: {
        'name': 'Milk',
        'price': 3.99,
        'color': 'white'
    }
}

app = FastAPI()

@app.get('/')
async def home():
    return [1,'a','3']#{"Welcome": "Home Python"}

@app.get("/items/{item_id}")
async def get_item(item_id:int = Path(None, description="This is item get method")):
    return inventory[item_id]

@app.post('/create-items/{item_id}')
async def create_item(item_id:int, item: Item):
    if item_id in inventory:
        return "Item already exists"
    else:
        inventory[item_id] = item
        return inventory[item_id]


class TrieNode:
    def __init__(self):
        self.is_end = False
        self.count = 0
        self.children = {}

class Solution:

    def __init__(self):
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        current = self.root
        for char in word:
            if char not in current.children:
                current.children[char] = TrieNode()

            current = current.children[char]
            current.count += 1

        current.is_end = True

    def score(self, word:str) -> int:

        current = self.root
        count = 0
        for char in word:

            current = current.children[char]
            count += current.count
        return count

    def sumPrefixScores(self, words: List[str]) -> List[int]:
        ans = [0] * len(words)
        for i in words:
            self.insert(i)

        for i in range(len(words)):
            word = words[i]
            # print(self.score(word))
            ans[i] += self.score(word)

        return ans


import logging
from random import randint
from time import sleep
from typing import List
import pandas as pd
import requests  # type: ignore

from models.auction import Lot, Lots
from models.item import Item, Items
from models.media import Media, Medias
from scrape.item_scraper import ItemScraper
from scrape.lot_scraper import LotScraper
from scrape.media_scraper import MediaScraper
from utils.aws import S3Connector

logger = logging.getLogger(__name__)

class AuctionScraper:
    def __init__(self, access_token: str, bucket: str):
        self.access_token = access_token
        self.s3_connector = S3Connector(bucket)

    def crawl(self, sample: int = 0):
        lots_scraper = LotScraper(self.access_token)
        lots: Lots = lots_scraper.crawl()

        if lots:
            df = pd.DataFrame.from_records(lots.dict()["lots"])
            path = self.s3_connector.create_parquet_path("lots")
            self.s3_connector.write_parquet(df, path)
            logger.info(f"Wrote to {path}")

        logger.info(f"{len(lots.lots)} lots crawled..")

        self.item_ids = list({lot.item.id for lot in lots.lots})
        logger.info(f"{len(self.item_ids)} item ids found..")

        scraped_item_ids: List[int] = self._read_item_ids()
        print(f"Previous {len(scraped_item_ids)} item ids found")
        item_ids = [
            item_id for item_id in self.item_ids if item_id not in scraped_item_ids
        ]
        if sample > 0:
            sample_item_ids = []
            for _ in range(sample):
                rand_item_id = randint(0, len(item_ids) - 1)
                sample_item_ids.append(rand_item_id)
            item_ids = sample_item_ids

        logger.info(f"{len(item_ids)} item ids found. Crawling items..")
        print(f"{len(item_ids)} item ids found")

        item_scraper = ItemScraper(self.access_token)
        media_scraper = MediaScraper(self.access_token)

        handled_items: List[Item] = []
        handled_media: List[Media] = []
        try:
            logger.info(f"Crawling {len(item_ids)}")
            for i, item_id in enumerate(item_ids):
                item: Item = item_scraper.crawl(item_id)
                sleep(1)
                if item:
                    handled_items.append(item)
                media: Media = media_scraper.crawl(item_id)
                sleep(1)
                if media:
                    handled_media.append(media)
                scraped_item_ids.append(item_id)
                logger.info(f"Item {i+1}/{len(item_ids)} crawled.")
                print(f"Item {i+1}/{len(item_ids)} crawled.")

                # write intermediate hanlded item_ids to s3 in case of failure
                if (i + 1) % 100 == 0:
                    self._store(
                        items=handled_items,
                        media=handled_media,
                        item_ids=scraped_item_ids,
                    )

            # write the final results
            self._store(
                items=handled_items,
                media=handled_media,
                item_ids=scraped_item_ids,
            )
        except Exception as e:
            logger.error(e)
            logger.info("Storing processed item_ids.")

    def _store(self, items: list[Item], media: list[Media], item_ids: list[int]):
        items_ = Items(items=items)
        df_items = pd.DataFrame.from_records(items_.dict()["items"])
        self._write_to_s3(df_items, "items")
        medias_ = Medias(media=media)
        df_media = pd.DataFrame.from_records(medias_.dict()["media"])
        self._write_to_s3(df_media, "media")
        self._write_item_ids(item_ids)

        # clear handled items
        items = []
        media = []

    def random_lots(self, lots: List[Lot], size: int = 1) -> Lots:
        sample_lots: List[Lot] = []
        for _ in range(size):
            random_lot: Lot = lots[randint(0, len(lots))]
            sample_lots.append(random_lot)

        return sample_lots

    def _write_to_s3(self, df: pd.DataFrame, name: str):
        path = self.s3_connector.create_parquet_path(name)
        self.s3_connector.write_parquet(df, path)
        logger.info(f"Wrote to {path}")

    def _read_item_ids(self) -> List[int]:
        df = self.s3_connector.read_csv("item_ids.csv")
        return list(df["id"].values)

    def _write_item_ids(self, item_ids: List[int]) -> pd.DataFrame:
        df = pd.DataFrame(item_ids, columns=["id"])
        self.s3_connector.write_csv(df, "item_ids.csv")


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

# # Computer Science Refresher Project 1
#
# ## Description
#
# The problem given was the following : we want to set up an indoor location system, like an indoor GPS. In this project we will focus on computing the error of detection of the position of a moving object. Thus, we have the trajectory that the object is supposed to follow and the one that the location system says it has followed. The goal is to compute the error of detected trajectory. The given result should be the ratio between the area between the two trajectories, and the length of the theoretical path.
#
# ## Solution:
# _Divide and Conquer !_
# Divide the problem when:
# - change of segment in the theoretical trajectory
# - intersection of the theoretical and experimental trajectories
# - reach a _vertex_ in the experimental trajectory
#
# How to calculate the error:
#
# __The total area between the two paths is the sum of the areas of the "trapeziums" formed by two points on the theoretical trajectory and two points of the experimental trajectory.__
# When two points from the experimental and theoretical trajectories are equal, the area is a triangle.
#
# ## Note on data structure :
# The data structure chosen by the group to model a test case is the following :
#
# A sequence of ints, only separated by commas, without any bracket, representing the abscissas of the theoretical path
# A sequence of ints, only separated by commas, without any bracket, representing the ordinates of the theoretical path
# A sequence of ints, only separated by commas, without any bracket, representing the abscissas of the experimental path
# A sequence of ints, only separated by commas, without any bracket, representing the ordinates of the experimental path
# The result expected.
# The error tolerated.
#
# However, ours is :
# Each path is a list of tuples, each tuple representing the coordinates of a point. This explains the function oracle_parser in test.ipynb and test.py.

# In[1]:

#imports

import numpy as np
import numpy.linalg as lin

# In[2]:

def trajectory_error(coord_th,coord_exp):
    """
    Compute the error between the theoretical and the experimental trajectories,
    in the format decided, that is, the area between the two paths divided by
    the length of the theoretical path.
    arg1 coord_th : a list of tuples (x,y). The path which should be followed.
    arg2 coord_exp: a list of tuples (x,y). The points received from the "indoors-gps"
    return: error, the total area difference betweeen the theoretical trajectory
    and the experimental one, divided by the length of coord_th.
    """
    # initialize values:
    area = 0 # the total area between the theoretical and experimental paths
    distance = path_length(coord_th) # total theoretical path length
    j = 0 # iterator over the experimental path
    i = 0 # iterator over the theoretical path

    # start iterations:
    while (i+1 < len(coord_th) and j+1 < len(coord_exp)):
        # we work on a subsegment [coord_th[i], coord_th[i+1]]
        # search for an intersection:
        intersect_point = intersection(coord_th[i], coord_th[i+1], coord_exp[j], coord_exp[j+1])
        # compute orthogonal projections:
        ort_proj1 =  ortogonal_projection(coord_th[i], coord_th[i+1], coord_exp[j])
        ort_proj2 =  ortogonal_projection(coord_th[i], coord_th[i+1], coord_exp[j+1])

        if intersect_point:

            if intersect_point == coord_th[i+1] == coord_exp[j]:
                # we're outside of the subsegment
                i += 1 # advance along the theoretical path

            elif point_belongs_to_segment(coord_th[i], coord_th[i+1], ort_proj1)\
            and point_belongs_to_segment(coord_th[i], coord_th[i+1], ort_proj2):
                # Before the intersection:
                # the points form the right triangle -> coord_exp[j], its projection, intersection
                base = seg_length(ort_proj1, intersect_point)
                height =  seg_length(coord_exp[j], ort_proj1)
                area += area_right_triangle(base, height)

                # After the intersection:
                # the points form the right triangle -> intersect_point, coord_exp[j+1], its projection
                base = seg_length(intersect_point, ort_proj2)
                height =  seg_length(coord_exp[j+1], ort_proj2)
                area += area_right_triangle(base, height)

                j += 1 # advance along the experimental path

            else:
                # Before the intersection:
                # the points form the right triangle -> coord_exp[j], its projection, intersection
                base = seg_length(coord_exp[j], intersect_point)
                height =  seg_length(coord_th[i],\
                                     ortogonal_projection(coord_exp[j], intersect_point, coord_th[i]))
                area += area_right_triangle(base, height)

                # After the intersection:
                # the points form the right triangle -> intersect_point, coord_exp[j+1], its projection
                base = seg_length(intersect_point, coord_exp[j+1])
                height =  seg_length(coord_th[i+1],\
                                     ortogonal_projection(coord_exp[j+1], intersect_point, coord_th[i+1]))
                area += area_right_triangle(base, height)

                j += 1 # advance along the experimental path

        elif point_belongs_to_segment(coord_th[i], coord_th[i+1], ort_proj1)\
        and point_belongs_to_segment(coord_th[i], coord_th[i+1], ort_proj2):

            area += compute_area(ort_proj1, ort_proj2, coord_exp[j], coord_exp[j+1])
            j += 1 # advance along the experimental path

        else:
            # we're outside of the subsegment
            i += 1 # advance along the theoretical path

        ## TODO check for backtracking:

        # a) if ort1 or ort2 in in segment [ coord_th[i] , prevOrt1 ] or [ coord_th[i] , prevOrt2 ]

        # b) identify the area to remove

    return area / distance

def seg_length(x_1,x_2):
    """
    Compute the length of a segment.
    arg1 x_1 : A tuple, the coordinates of the first point of the segment
    arg2 x_2 : A tuple, the coordinates of the second point of the segment
    return : A float, the length of the segment made up by x_1 and x_2
    """
    return(np.sqrt((x_1[0]-x_2[0])**2 + (x_1[1]-x_2[1])**2))

def path_length(path):
    """
    Compute the length of a path.
    arg1 path : A table of tuples, each tuple representing the coordinates of a point of the path.
    return : leng. A float,
    """
    assert len(path) > 1
    leng = 0
    for i in range(len(path)-1):
        leng += seg_length(path[i],path[i+1])
    return(leng)

def point_belongs_to_segment(x_1, x_2, y):
    """
    Check if a point belongs to a segment.

    arg1,2 x_i: A tuple, the coordinates of a point on the theoretical trajectory
    arg3 y: A tuple, the coordinates of a point on the experimental trajectory
    return: A boolean, True if y belongs to the segment [x_1,x_2]. False otherwise.
    """
    # A necessary condition is that x_1, x_2 and y are aligned.
    # Otherwise y can't be in the segment.
    # compute the cross product of the points : if it is 0, it means they are not aligned.
    # Given the calculation performed, if the result is a float we consider that
    # if it is smaller than 10**(-10), it is zero up to machine error.
    cross_product = (y[1] - x_1[1]) * (x_2[0] - x_1[0]) - (y[0] - x_1[0]) * (x_2[1] - x_1[1])
    if (isinstance(cross_product, int) and abs(cross_product) != 0)\
    or (isinstance(cross_product,float) and abs(cross_product) > 0.0000000001):
        return False

    # Now, the case when the points are aligned : we compute the dot product
    # between (y-x_1) and (x_2-x1).
    dot_product = (y[0] - x_1[0])*(x_2[0] - x_1[0]) + (y[1] - x_1[1])*(x_2[1] - x_1[1])
    if dot_product < 0:
        # Then y is beyond x_1, not between the two points.
        return False

    squared_segment_length = seg_length(x_1,x_2)**2
    if dot_product > squared_segment_length:
        # Then y is beyond x_2, not between the two points.
        return False

    return True

def intersection(x_1, x_2, y_1, y_2):
    """
    Compute the intersection of two segments, if any.
    arg1,2 x_i: A tuple, the coordinates of a point on the theoretical trajectory
    arg3,4 y_i: A tuple, the coordinates of a point on the experimental trajectory
    return: intersect. A tuple, the coordinates of the intersection.
    Remark : if the intersection is not in the two segments, return None.
    """

    # First case : the two lines are vertical
    if (x_1[0] == x_2[0] and y_1[0] == y_2[0]) :
        intersect = None

    # Second case : only the first line is vertical
    elif x_1[0] == x_2[0] :
        a = (y_1[1]-y_2[1])/(y_1[0]-y_2[0])
        b = y_2[1] - a * y_2[0]
        intersect = (x_1[0],a*x_1[0] + b)

    # Third case : only the second line is vertical
    elif y_1[0]  == y_2[0] :
        a = (x_1[1]-x_2[1])/(x_1[0]-x_2[0])
        b = x_2[1] - a * x_2[0]
        intersect = (y_1[0],a*y_1[0] + b)

    # Last case : general case
    else :
        a_x = (x_1[1] - x_2[1])/(x_1[0] - x_2[0])
        b_x = x_1[1] - a_x * x_1[0]
        a_y = (y_1[1] - y_2[1])/(y_1[0] - y_2[0])
        b_y = y_1[1] - a_y * y_1[0]

        if a_x == a_y :
            # Case where the lines are parallel
            intersect = None

        else :
            #The equations are
            #y = a_x*x + b_x
            #y = a_y*x + b_y
            # The solution is the inverted matrix
            intersect = ( (b_y-b_x)/(a_x-a_y),\
                          (b_y * a_x - b_x * a_y)/(a_x - a_y) )
    # If a point is found, check if it belongs to the segments
    # and not only to the lines.
    if intersect:
        if not point_belongs_to_segment(x_1, x_2, intersect) and not point_belongs_to_segment(y_1, y_2, intersect):
            intersect = None

    return intersect

def ortogonal_projection(x_1, x_2, y):
    """
    Compute the orthogonal projection of y on the line made up of the points x_1 and x_2.

    arg1,2 x_i: A tuple, the coordinates of a point on the theoretical trajectory
    arg3 y: A tuple, the coordinates of a point on the experimental trajectory
    return: new_point. A tuple, the coordinates of the orthogonal projection on y on the segment [x_1,x_2]
    """

    if point_belongs_to_segment(x_1, x_2, y): # y already belongs to the segment [x_1, x_2]
        new_point = y

    # Now we want to find the equation of the line containing x_1 and x_2.
    # We have to tackle the case of the vertical line first, because then
    # we can't find a slope. Then we can tackle the other case,
    # with a slope and intercept.

    elif x_1[0] == x_2[0] :
        # First case : the line containing x_1 and x_2 is vertical
        new_point = (x_1[0],y[1])

    else :
    # Second case : the line containing x_1 and x_2 is not vertical,
    # so we look for its slope and intercept.
        a = (x_2[1]-x_1[1])/(x_2[0]-x_1[0])
        b = x_1[1] - a * x_1[0]
        # Now we know the line containing x_1 and x_2 has the equation y = a * x + b
        # So a normal vector to this line is (a,-1)
        # This vector is directing the normal line passing by the point y and its equation is - x - a * y + c = 0 :
        # let's find c!
        c = y[0] + a*y[1]
        # Now the intersection point is the point (x,y) which verifies :
        # a*x - y = -b
        # -x - a*y = -c
        # We find it by inverting the matrix.
        mat = np.array([[a,-1],[-1,-a]])
        point = np.dot(lin.inv(mat), np.array([-b,-c]))
        new_point = (point[0],point[1])

    return new_point

def area_right_triangle(base, height):
    """
    Compute the area of a right triangle.

    arg1: base. A numeral, the length of the basis of the triangle
    arg2: height. A numeral, the length of the basis of the triangle
    return: the area of the rectangle
    """
    return np.abs((base * height) / 2)

def compute_area(x_1, x_2, y_1, y_2):
    """
    Compute the area of the quadrilateral formed by the four given points.
    To compute it, it splits the quadrilateral into two triangles, with (x_1,y_2)
    as splitting line. Thus, be careful of not giving these two points as successive
    points, otherwise the computed area may be different from what you expect.

    arg1,2 x_i: A tuple, the coordinates of a point on the theoretical trajectory
    arg3,4 y_i: A tuple, the coordinates of a point on the experimental trajectory
    return: area. An int, the area of the figure formed by the 4 points
    """
    area = 0

    # Let's split into two triangles, on either side of (x_1,y_2)

    # first triangle:
    base = seg_length(x_1, y_2)
    height = seg_length(x_2, ortogonal_projection(x_1, y_2, x_2))
    area += area_right_triangle(base, height)

    # second triangle:
    base = seg_length(x_1, y_2)
    height =  seg_length(y_1, ortogonal_projection(x_1, y_2, y_1))
    area += area_right_triangle(base, height)

    return area


from unittest import TestCase
from reverse_linked_list_ii import *

class TestSolution(TestCase):
    def test_reverse_between(self):
        ln1 = list_to_node([1, 2, 3, 4, 5])
        ln2 = list_to_node([3, 5])

        inputs = ((ln1, 2, 4), (ln2, 1, 1))
        outs = ([1, 4, 3, 2, 5], [3, 5])
        for inp, out in zip(inputs, outs):
            result = Solution().reverseBetween(*inp)
            self.assertEqual(out, node_to_list(result))


import numpy as np
import csv
import os
import cv2
import matplotlib.pyplot as plt
from xml.etree import ElementTree as ET
import argparse

parser = argparse.ArgumentParser(description='compare mediapipe and kinect skeleton data', epilog = 'Enjoy the program! :)')

parser.add_argument('--inputfile', default =r'/datasets_nas/elma1294/example_tape/dominikw_front_0/e4sm_tape-2021-08-18_14-07-44.211275_skeletons.shuttleFront.csv',
                     help = 'The address of the input csv file')
parser.add_argument('--sample_image', default = r'/datasets_nas/elma1294/example_tape/dominikw_front_0/e4sm_tape-2021-08-18_14-07-44.211275_png.shuttleFront/shuttleFront_Kinect_ColorImage1629288474191866000.jpg',
                   help = 'sample image to get the width and height of the image')
parser.add_argument('--output_directory', default=r'/datasets_nas/elma1294/results' , help = 'The address of the results')
arguments = parser.parse_args()

path = arguments.inputfile
file_path = arguments.sample_image
output_directory = arguments.output_directory

output_kineckt = os.path.join(output_directory, 'results3Dto2Dnew.csv')

def _parse_camera_parameter(camera_name: str):

    assert camera_name in ['shuttleFront', 'shuttleSide', 'spike']

    # parse serialized kinect azure calibration
    root = ET.parse(f'intrinsics/{camera_name}.xml').getroot()
    root = root.find('KinectAzureCalibration')

    # get color intrinsics as cx, cy, fx, fy
    color_params = root.find('color_camera_calibration')

    # intrsinics
    intrinsics = color_params.find('intrinsics').find('parameters').findall('item')

    cx = float(intrinsics[0].text)
    cy = float(intrinsics[1].text)
    fx = float(intrinsics[2].text)
    fy = float(intrinsics[3].text)

    # get transformation from depth frame to color frame
    # the kinect sdk defines the local transformation tree as
    # mount frame -> depth_frame -> color_frame
    # so we can just parse the extrinsics from color camera which represents
    # the transformation depth_frame -> color_frame
    extrinsics = color_params.find('extrinsics')

    # NOTE: rotation matrix is serialized as simple vector
    rotation = extrinsics.find('rotation').findall('item')
    translation = extrinsics.find('translation').findall('item')

    rotation_vec = np.zeros(9)
    for i, el in enumerate(rotation):
        rotation_vec[i] = el.text

    translation_vec = np.zeros(3)
    for i, el in enumerate(translation):
        translation_vec[i] = el.text

    # translation is given in mm
    # as we work in m we convert
    translation_vec *= 0.001

    transform = np.eye(4)
    transform[:3, :3] = rotation_vec.reshape(3, 3)
    transform[:3, 3] = translation_vec

    return [cx, cy, fx, fy], transform

def convert_3d_to_2d_position(x,y,z, transform, camera_parameter, width, height):
    ''' with Intrinsic Parameter i defined Camera Matrix to get the 2D Position'''

    xc = float(x)
    yc = float(y)
    zc = float(z)
    xc, yc, zc = np.dot(transform, np.array([xc, yc, zc, 1]))[:3]

    #shutlefront
    cx, cy, fx, fy = camera_parameter

    if len(x) < 1 or len(y) < 1 or len(z) <1:
        return 0,0
    k = np.array([[fx,0,cx],[0,fy,cy],[0,0,1]])
    one = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0]])
    camera_matrix = np.array([[xc],[yc],[zc],[1]])
    m1 = np.dot(k,one)
    output_matrix = np.dot(m1,camera_matrix)
    u_array = (output_matrix[0]/output_matrix[2])/width
    v_array= (output_matrix[1]/output_matrix[2])/height
    u = u_array[0].astype(float)
    v = v_array[0].astype(float)
    return u,v

def _plot_sample(joint_dict, img):
    joints = np.zeros(((len(joint_dict) -1) // 2, 2))
    for ei, joint in enumerate(list(joint_dict.values())[1:]):
        joints[ei // 2, ei % 2] = joint
    plt.imshow(img)
    joints *= img.shape[:2][::-1]
    plt.scatter(joints[:, 0], joints[:, 1], s=10, c='r')
    plt.show()
    # plt.savefig('test.png')

list_of_results = []
camera_params, transform = _parse_camera_parameter('shuttleFront')
img = cv2.imread(file_path, cv2.IMREAD_COLOR)
width = img.shape[1]
height = img.shape[0]

with open(path) as f:
    ''' read the csv file and convert the 3D Position to 2D Position and save it in a new csv file'''
    rows = [{k: v for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True)]
    for row in rows:
        mDict = {}
        mDict['timestamp'] = row['timestamp']
        for x_header in row.keys():
            if '.x' in x_header:
                y_header = x_header.replace('.x','.y')
                z_header = x_header.replace('.x','.z')
                x_value = row[x_header]
                y_value = row[y_header]
                z_value = row[z_header]
                u,v= convert_3d_to_2d_position(x_value,y_value,z_value, transform, camera_params, width, height)
                mDict[x_header] = u
                mDict[y_header] = v
        list_of_results.append(mDict)

_plot_sample(mDict, img)

with open(output_kineckt, 'w', encoding='UTF8', newline='') as f2:
    writer = csv.DictWriter(f2, mDict.keys())
    writer.writeheader()
    writer.writerows(list_of_results)


# Example: echo server, using StreamServer

import logging
import argparse

from gruvi import get_hub, util
from gruvi.stream import StreamServer

logging.basicConfig()

parser = argparse.ArgumentParser()
parser.add_argument('port', type=int)
args = parser.parse_args()

def echo_handler(stream, protocol, client):
    peer = client.getpeername()
    print('Connection from {0}'.format(util.saddr(peer)))
    while True:
        buf = stream.read(4096)
        if not buf:
            break
        stream.write(buf)
    print('Connection closed')

server = StreamServer(echo_handler)
server.listen(('0.0.0.0', args.port))

hub = get_hub()
hub.switch(interrupt=True)


import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader

import torchvision as tv

from time import time
from src.model.madry_model import WideResNet
from src.attack import FastGradientSignUntargeted
from src.utils import makedirs, create_logger, tensor2cuda, numpy2cuda, evaluate, save_model

from src.argument import parser, print_args

class Trainer():
    def __init__(self, args, logger, attack):
        self.args = args
        self.logger = logger
        self.attack = attack

    def standard_train(self, model, tr_loader, va_loader=None):
        self.train(model, tr_loader, va_loader, False)

    def adversarial_train(self, model, tr_loader, va_loader=None):
        self.train(model, tr_loader, va_loader, True)

    def train(self, model, tr_loader, va_loader=None, adv_train=False):
        args = self.args
        logger = self.logger

        opt = torch.optim.SGD(model.parameters(), args.learning_rate,
                              weight_decay=args.weight_decay,
                              momentum=args.momentum)
        scheduler = torch.optim.lr_scheduler.MultiStepLR(opt,
                                                         milestones=[40000, 60000],
                                                         gamma=0.1)
        _iter = 0

        begin_time = time()

        for epoch in range(1, args.max_epoch+1):
            for data, label in tr_loader:
                data, label = tensor2cuda(data), tensor2cuda(label)

                if adv_train:
                    # When training, the adversarial example is created from a random
                    # close point to the original data point. If in evaluation mode,
                    # just start from the original data point.
                    adv_data = self.attack.perturb(data, label, 'mean', True)
                    output = model(adv_data, _eval=False)
                else:
                    output = model(data, _eval=False)

                loss = F.cross_entropy(output, label)

                opt.zero_grad()
                loss.backward()
                opt.step()

                if _iter % args.n_eval_step == 0:
                    t1 = time()

                    if adv_train:
                        with torch.no_grad():
                            stand_output = model(data, _eval=True)
                        pred = torch.max(stand_output, dim=1)[1]

                        # print(pred)
                        std_acc = evaluate(pred.cpu().numpy(), label.cpu().numpy()) * 100

                        pred = torch.max(output, dim=1)[1]
                        # print(pred)
                        adv_acc = evaluate(pred.cpu().numpy(), label.cpu().numpy()) * 100

                    else:

                        adv_data = self.attack.perturb(data, label, 'mean', False)

                        with torch.no_grad():
                            adv_output = model(adv_data, _eval=True)
                        pred = torch.max(adv_output, dim=1)[1]
                        # print(label)
                        # print(pred)
                        adv_acc = evaluate(pred.cpu().numpy(), label.cpu().numpy()) * 100

                        pred = torch.max(output, dim=1)[1]
                        # print(pred)
                        std_acc = evaluate(pred.cpu().numpy(), label.cpu().numpy()) * 100

                    t2 = time()

                    logger.info(f'epoch: {epoch}, iter: {_iter}, lr={opt.param_groups[0]["lr"]}, '
                                f'spent {time()-begin_time:.2f} s, tr_loss: {loss.item():.3f}')

                    logger.info(f'standard acc: {std_acc:.3f}%, robustness acc: {adv_acc:.3f}%')

                    # begin_time = time()

                    # if va_loader is not None:
                    #     va_acc, va_adv_acc = self.test(model, va_loader, True)
                    #     va_acc, va_adv_acc = va_acc * 100.0, va_adv_acc * 100.0

                    #     logger.info('\n' + '='*30 + ' evaluation ' + '='*30)
                    #     logger.info('test acc: %.3f %%, test adv acc: %.3f %%, spent: %.3f' % (
                    #         va_acc, va_adv_acc, time() - begin_time))
                    #     logger.info('='*28 + ' end of evaluation ' + '='*28 + '\n')

                    begin_time = time()

                if _iter % args.n_store_image_step == 0:
                    tv.utils.save_image(torch.cat([data.cpu(), adv_data.cpu()], dim=0),
                                        os.path.join(args.log_folder, f'images_{_iter}.jpg'),
                                        nrow=16)

                if _iter % args.n_checkpoint_step == 0:
                    file_name = os.path.join(args.model_folder, f'checkpoint_{_iter}.pth')
                    save_model(model, file_name)

                _iter += 1
                # scheduler depends on training interation
                scheduler.step()

            if va_loader is not None:
                t1 = time()
                va_acc, va_adv_acc = self.test(model, va_loader, True, False)
                va_acc, va_adv_acc = va_acc * 100.0, va_adv_acc * 100.0

                t2 = time()
                logger.info('\n'+'='*20 +f' evaluation at epoch: {epoch} iteration: {_iter} ' \
                    +'='*20)
                logger.info(f'test acc: {va_acc:.3f}%, test adv acc: {va_adv_acc:.3f}%, spent: {t2-t1:.3f} s')
                logger.info('='*28+' end of evaluation '+'='*28+'\n')

    def test(self, model, loader, adv_test=False, use_pseudo_label=False):
        # adv_test is False, return adv_acc as -1

        total_acc = 0.0
        num = 0
        total_adv_acc = 0.0

        with torch.no_grad():
            for data, label in loader:
                data, label = tensor2cuda(data), tensor2cuda(label)

                output = model(data, _eval=True)

                pred = torch.max(output, dim=1)[1]
                te_acc = evaluate(pred.cpu().numpy(), label.cpu().numpy(), 'sum')

                total_acc += te_acc
                num += output.shape[0]

                if adv_test:
                    # use predicted label as target label
                    with torch.enable_grad():
                        adv_data = self.attack.perturb(data,
                                                       pred if use_pseudo_label else label,
                                                       'mean',
                                                       False)

                    adv_output = model(adv_data, _eval=True)

                    adv_pred = torch.max(adv_output, dim=1)[1]
                    adv_acc = evaluate(adv_pred.cpu().numpy(), label.cpu().numpy(), 'sum')
                    total_adv_acc += adv_acc
                else:
                    total_adv_acc = -num

        return total_acc / num , total_adv_acc / num

def main(args):

    save_folder = '%s_%s' % (args.dataset, args.affix)

    log_folder = os.path.join(args.log_root, save_folder)
    model_folder = os.path.join(args.model_root, save_folder)

    makedirs(log_folder)
    makedirs(model_folder)

    setattr(args, 'log_folder', log_folder)
    setattr(args, 'model_folder', model_folder)

    logger = create_logger(log_folder, args.todo, 'info')

    print_args(args, logger)

    model = WideResNet(depth=34, num_classes=10, widen_factor=10, dropRate=0.0)

    attack = FastGradientSignUntargeted(model,
                                        args.epsilon,
                                        args.alpha,
                                        min_val=0,
                                        max_val=1,
                                        max_iters=args.k,
                                        _type=args.perturbation_type)

    if torch.cuda.is_available():
        model.cuda()

    trainer = Trainer(args, logger, attack)

    if args.todo == 'train':
        transform_train = tv.transforms.Compose([
                tv.transforms.RandomCrop(32, padding=4, fill=0, padding_mode='constant'),
                tv.transforms.RandomHorizontalFlip(),
                tv.transforms.ToTensor(),
            ])
        tr_dataset = tv.datasets.CIFAR10(args.data_root,
                                       train=True,
                                       transform=transform_train,
                                       download=True)

        tr_loader = DataLoader(tr_dataset, batch_size=args.batch_size, shuffle=True, num_workers=4)

        # evaluation during training
        te_dataset = tv.datasets.CIFAR10(args.data_root,
                                       train=False,
                                       transform=tv.transforms.ToTensor(),
                                       download=True)

        te_loader = DataLoader(te_dataset, batch_size=args.batch_size, shuffle=False, num_workers=4)

        trainer.train(model, tr_loader, te_loader, args.adv_train)
    elif args.todo == 'test':
        te_dataset = tv.datasets.CIFAR10(args.data_root,
                                       train=False,
                                       transform=tv.transforms.ToTensor(),
                                       download=True)

        te_loader = DataLoader(te_dataset, batch_size=args.batch_size, shuffle=False, num_workers=4)

        checkpoint = torch.load(args.load_checkpoint)
        model.load_state_dict(checkpoint)

        std_acc, adv_acc = trainer.test(model, te_loader, adv_test=True, use_pseudo_label=False)

        print(f"std acc: {std_acc * 100:.3f}%, adv_acc: {adv_acc * 100:.3f}%")

    else:
        raise NotImplementedError

if __name__ == '__main__':
    args = parser()

    os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu

    main(args)


import nltk

def nouns_transform(sentence):
    tokenized = nltk.word_tokenize(sentence)

    def is_noun (pos):
        return pos[:2] == 'NN'
    return [word for (word, pos) in nltk.pos_tag(tokenized) if is_noun(pos)]

def render_template(template_name='html pages/home.html', context={}):
    html_str = ""
    with open(template_name, 'r') as f:
        html_str = f.read()
        html_str = html_str.format(**context)
    return html_str

def main(environ, start_response):
    query = environ.get("QUERY_STRING")
    path = environ.get("PATH_INFO")

    if len(query) > len("text="):
       sentence = query[5:].replace("+"," ").replace("%27","'")
       nouns = nouns_transform(sentence)
       data = render_template(template_name='html pages/nouns.html', context={"nouns_key": nouns})

    elif path == "/":
        data = render_template()
    else:
        data = render_template(template_name='html pages/404.html')

    data = data.encode("utf-8")
    start_response(
        f"200 OK", [
            ("Content-Type", "text/html"),
            ("Content-Length", str(len(data)))
        ]
    )
    return iter([data])


# task 2.1
import numpy as np

# 1.Write a NumPy program to convert a list of numeric values into a one-dimensional NumPy array.

l = [6.3, -3.45, 10542, 39.3]
arr = np.array(l)
print(arr)

# 2.Write a NumPy program to create a NumPy array with values ranging from 2 to 10.

arr = np.arange(2, 11)
print(arr)

# 3.Write a NumPy program to create a null vector of size 10 and update sixth to eight values to 11.

arr = np.zeros(10)
for i in range(6, 9):
    arr[i] = 11
print(arr)

# 4.Write a NumPy program to test whether each element of a 1-D array is also present in a second array.

arr1 = np.array([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])

arr2 = [2, 3, 5, 7, 11, 17, 19, 23, 29, 31, 37]

print(np.in1d(arr1, arr2))


#aoc20150101

import pathlib
import sys

def parse(path):
  return list(pathlib.Path(path).read_text())

def solve(puzzleInput):
  finalFloor = 0

  for datum in puzzleInput:
    if datum == '(':
      finalFloor += 1
    else:
      finalFloor -= 1

  return finalFloor

if __name__ == "__main__":
  for path in sys.argv[1:]:
    puzzleInput = parse(path)
    print(puzzleInput, solve(puzzleInput))


import os
import time
from dotenv import dotenv_values
from selenium import webdriver
from selenium.webdriver import Chrome
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from utilities.commons.exceptions import DriverSetupFailedException
from utilities.commons.context import Context
from utilities.scripts.script_executor import ScriptExecutor
import requests
from requests.exceptions import ConnectionError

def _get_env_values() -> dict:
    config = dotenv_values(".env")
    return {**config} if config else None

def _load_init_configs(context):
    env_values = _get_env_values()
    context: Context = context
    if env_values is not None:
        context.WEB_URL = env_values.get("WEB_URL")
        context.API_URL = env_values.get("API_URL")
    else:
        raise Exception(f"Env file/values are missing")

def _get_service() -> Service:
    try:
        service = Service(executable_path=ChromeDriverManager(path=os.path.dirname(__file__)).install())
    except DriverSetupFailedException:
        raise DriverSetupFailedException(msg="Failed to install driver or create service")
    return service

def _get_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("no-sandbox")
    options.add_argument("--verbose")
    options.add_argument("--disable-gpu")
    options.add_argument("--disable-web-security")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--ignore-certificate-errors")
    options.add_argument("--allow-insecure-localhost")
    return options

def _get_local_webdriver():
    service: Service = _get_service()
    try:
        browser = Chrome(service=service, \
                         options=_get_chrome_options())
    except DriverSetupFailedException:
        raise DriverSetupFailedException(msg="Failed to initialize driver")
    return browser

def _build_selenium_remote_base_url(host):
    if host is None or len(host) > 1:
        return f"http://{host}:4444/"
    else:
        raise ValueError("host cannot be None or empty, please provide host")

def _get_remote_selenium_url(hosts: list) -> str:
    if len(hosts) < 1:
        raise ValueError("Please enter host(s) as list, at least one host is expected")
    retry = True
    max_retries = 5
    retry_attempt = 0
    while retry:
        retry_attempt += 1
        for host in hosts:
            try:
                selenium_remote_url = _build_selenium_remote_base_url(host)
                status_code = requests.get(selenium_remote_url).status_code
                if status_code == 200:
                    retry = False
                    return selenium_remote_url + "wd/hub"
                else:
                    print(f"request to {selenium_remote_url} failed due to status code: {status_code} ")
                    retry = False
            except ConnectionError:
                print(f"{selenium_remote_url} is not reachable \n")
                if hosts.index(host) + 1 < len(hosts):
                    print(f"now trying to reach selenium at:{_build_selenium_remote_base_url(hosts[hosts.index(host) + 1])}")
                if retry_attempt >= max_retries:
                    retry = False
                time.sleep(5)
        print(f"*** retry attempt:{retry_attempt} ***\n")

def _get_webdriver_from_remote():
    remote_selenium_url = _get_remote_selenium_url(hosts=["selenium", "localhost"])
    return webdriver.Remote(command_executor=remote_selenium_url, \
                            options=_get_chrome_options())

def before_scenario(context, scenario):
    _load_init_configs(context)
    context.browser = _get_local_webdriver() \
        if os.environ.get("RUN_ENV") == "local" \
        else _get_webdriver_from_remote()

def after_scenario(context, scenario):
    context.browser.quit()

def after_all(context):
    ScriptExecutor.delete_temp_files()

'''
#other available hooks

def before_step(context, step):
    pass

def after_step(context, step):
    pass

def before_feature(context, feature):
    pass

def after_feature(context, feature):
    pass

def before_tag(context, tag):
    pass

def after_tag(context, tag):
    pass

def before_all(context):
    pass

def after_all(context):
    pass
'''


#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
	from the month of edge deletion, find the SR before, at the time and after
"""
from collections import defaultdict
import codecs
import os
import json
import numpy as np

IN_DIR = "../../../DATA/General/MO_MENT_networks"
os.chdir(IN_DIR)

F_IN = "mention_edges_monthly_SR"
F_OUT = "mention_network_dir_w"

MONTHS =  ["5", "6", "7", "8", "9", "10", "11"]

def read_in_monthly_mentions(MO):
	monthly_ment = defaultdict(dict)
	f_in = str(MO) + "mention_edges_monthly_SR"
	f = open(f_in, 'r')
	for line in f:
		(u1, u2, SR, w1, w2) = line.split()
		userA = int(u1)
		userB = int(u2)
		w1 = int(w1)
		w2 = int(w2)
		if w1 > 0:
			monthly_ment[(u1, u2)] = w1
		if w2 > 0:
			monthly_ment[(u2, u1)] = w2
	f.close()
	return monthly_ment

def save_monthly_network_dir_w(MO):
	monthly_ment = read_in_monthly_mentions(MO)
	f_out = str(MO) + "mention_edgelist_dir_w"
	f = open(f_out, 'w')
	for el in monthly_ment:
		userA = el[0]
		userB = el[1]
		w = monthly_ment[el]
		f.write(str(userA) + '\t' + str(userB) + '\t' + str(w) + '\n')
	f.close()

for MO in MONTHS:
	save_monthly_network_dir_w(MO)


from match.models import Match

# Yes, I'm aware this isn't really the best way of doing this.
class Gateway:
    def update_match(self, id, payload):
        try:
            match = Match.objects.get(pk=id)
            match_fields = [f.name for f in Match._meta._get_fields()]
            for field, value in payload.items():
                if field in match_fields:
                    setattr(match, field, value)
            match.save()
            return True
        except Exception as ex:
            print(ex)
            return False


print('-=' * 30)
print('Lojas JOÃO')
print('-=' * 30)
preço = float(input('Preço das compras: '))
print('''FORMAS DE PAGAMENTO
[1] à vista dinheiro/cheque 10% de desconto
[2] à visto no cartão 5% de desconto
[3] em até 2x no cartão é o preço normal
[4] 3x ou mais no cartão: 20% de juros''')
print('-=' * 30)
opção = int(input('Digite a opção de pagamento: '))
if opção == 1:
    total = preço - (preço * 10) / 100
    print(f'sua compra no valor de {preço} terá desconto de 10% e ficara no valor de {total}')
elif opção == 2:
    total = preço - (preço * 5) / 100
    print(f'sua compra no valor de {preço} terá desconto de 5% e ficara no valor de {total}')
elif opção == 3:
    total = preço
    print(f'sua compra ficara no valor normal de {total}')
else:
    total = preço + (preço * 20) / 100
    print(f'sua compra no valor de {preço} divido em 3x ou mais terá acrescimo de 20% de juros e ficara {total}')


import io
import json
import sys

INDENT = 4 * " "
DEFAULT_NEWRESPARAM = "res"

def toCppType(t):
    if isinstance(t, list):
        if len(t) == 2:
            return "{}<{}>".format(t[0], t[1])
        elif len(t) == 3:
            return "{}<{}<{}>>".format(t[0], t[1], t[2])
        else:
            raise RuntimeError("unexpected nesting level of template types: {}".format(t))
    else:
        return t

def generateKernelInstantiation(kernelTemplateInfo, templateValues, opCodes, outFile, API):
    # Extract some information.
    opName = kernelTemplateInfo["opName"]
    returnType = kernelTemplateInfo["returnType"]
    templateParams = kernelTemplateInfo["templateParams"]
    runtimeParams = kernelTemplateInfo["runtimeParams"]
    opCodeAsTemplateParam = False
    if "opCodeAsTemplateParam" in kernelTemplateInfo:
        opCodeAsTemplateParam = True if kernelTemplateInfo["opCodeAsTemplateParam"] == 1 else False

    if len(templateParams) != len(templateValues):
        raise RuntimeError(
            f"kernel \"{opName}\" has {len(templateParams)} template parameters, but "
            f"{len(templateValues)} template values are supplied in an instantiation"
        )

    if opCodes is not None:
        # We assume that the op-code is the first run-time parameter.
        opCodeType = runtimeParams[0]["type"]
        runtimeParams = runtimeParams[1:]
    else:
        opCodeType = None

    # Create mapping from original template argument names to assigned C++
    # types.
    templateArgToCppType = {tp["name"]: toCppType(tv) for tp, tv in zip(templateParams, templateValues)}

    # ToDo: commented by mdokter - maybe remove. I think this would be too verbose
    # Comments indicating values assigned to original template arguments.
    # for tp in templateParams:
    #     outStr = INDENT + "// {} = {}\n".format(tp["name"], templateArgToCppType[tp["name"]])
    #     outFile.write(outStr)

    # The function wrapping the generated kernel instantiation always has
    # the return type void. If the considered kernel returns a scalar value,
    # we prepend an additional run-time parameter.
    extendedRuntimeParams = [
        {"name": DEFAULT_NEWRESPARAM, "type": "{} *".format(returnType), "isOutput": True}
    ] if (returnType != "void") else []
    # Add all run-time parameters of the kernel. We need to copy, because
    # we apply string replacements to the types.
    extendedRuntimeParams.extend([rp.copy() for rp in runtimeParams])
    # Replace occurences of original template arguments by their assigned
    # types.
    for rp in extendedRuntimeParams:
        for tpIdx, tp in enumerate(templateParams):
            if isinstance(templateValues[tpIdx], list):
                rp["type"] = rp["type"].replace("typename {}::VT".format(tp["name"]), templateValues[tpIdx][1])
            rp["type"] = rp["type"].replace(tp["name"], templateArgToCppType[tp["name"]])
        if rp["type"].endswith("*&"):
            rp["type"] = rp["type"][:-2] + "**"
            rp["isOutput"] = True
        if rp["type"].endswith("&"):
            rp["type"] = rp["type"][:-1]
            rp["isOutput"] = True
        elif "isOutput" not in rp:
            rp["isOutput"] = False

    isCreateDaphneContext = opName == "createDaphneContext"

    # typesForName = "__".join([("{}_{}".format(tv[0], tv[1]) if isinstance(tv, list) else tv) for tv in templateValues])
    typesForName = "__".join([
        rp["type"]
            [((rp["type"].rfind("::") + 2) if "::" in rp["type"] else 0):]
            .replace("const ", "")
            .replace(" **", "" if rp["isOutput"] else "_variadic")
            .replace(" *", "_variadic" if "isVariadic" in rp and rp["isVariadic"] else "")
            .replace("& ", "")
            .replace("<", "_").replace(">", "")
        for rp in extendedRuntimeParams
    ])
    if typesForName != "":
        typesForName = "__" + typesForName
    params = ", ".join(
        ["{} {}".format(rtp["type"], rtp["name"]) for rtp in extendedRuntimeParams] +
        ([] if isCreateDaphneContext else ["DCTX(ctx)"])
    )

    def generateFunction(opCode):
        # Obtain the name of the function to be generated from the opName by
        # removing suffices "Sca"/"Mat"/"Obj" (they are not required here), and
        # potentially by inserting the opCode into the name.
        if API != "CPP":
            funcName = API + "_" + opName
        else:
            funcName = "_" + opName
        while funcName[-3:] in ["Sca", "Mat", "Obj"]:
            funcName = funcName[:-3]
        funcName = funcName.replace("::", "_")

        if opCode is not None:
            opCodeWord = opCodeType[:-len("OpCode")]
            funcName = funcName.replace(opCodeWord, opCode[0].upper() + opCode[1:].lower())
            funcName = funcName.replace(opCodeWord.lower(), opCode.lower())

        # Signature of the function wrapping the kernel instantiation.
        outFile.write(INDENT + "void {}{}({}) {{\n".format(
            funcName,
            typesForName,
            # Run-time parameters, possibly including DaphneContext:
            params
        ))

        # List of parameters for the call.
        if opCode is None or opCodeAsTemplateParam:
            callParams = []
        else:
            callParams = ["{}::{}".format(opCodeType, opCode)]

        callParams.extend([
            # Dereference double pointer for output parameters.
            "{}{}".format("*" if (rp["type"].endswith("**") and rp["isOutput"]) else "", rp["name"])
            for rp in extendedRuntimeParams[(0 if returnType == "void" else 1):]
        ])

        # List of template parameters for the call.
        callTemplateParams = [toCppType(tv) for tv in templateValues]
        if opCodeAsTemplateParam and opCode is not None:
            opCodeWord = opCodeType[:-len("OpCode")]
            callTemplateParams = ["{}::{}".format(opCodeWord if API == "CPP" else API + "::" + opCodeWord, opCode)] + callTemplateParams

        # Body of that function: delegate to the kernel instantiation.
        outFile.write(2 * INDENT)
        if returnType != "void":
            outFile.write("*{} = ".format(DEFAULT_NEWRESPARAM))

        kernelCallString = "{}{}::apply({});\n" if opCodeAsTemplateParam else "{}{}({});\n"

        outFile.write(kernelCallString.format(
            opName if API == "CPP" else (API + "::" + opName),
            # Template parameters, if the kernel is a template:
            "<{}>".format(", ".join(callTemplateParams)) if len(templateValues) else "",
            # Run-time parameters, possibly including DaphneContext:
            ", ".join(callParams + ([] if isCreateDaphneContext else ["ctx"])),
        ))
        outFile.write(INDENT + "}\n")

    # Generate the function(s).
    if opCodes is None:
        generateFunction(None)
    else:
        for opCode in opCodes:
            generateFunction(opCode)
    # outFile.write(INDENT + "\n")

def printHelp():
    print("Usage: python3 {} INPUT_SPEC_FILE OUTPUT_CPP_FILE API".format(sys.argv[0]))
    print(__doc__)

if __name__ == "__main__":
    if len(sys.argv) == 2 and (sys.argv[1] == "-h" or sys.argv[1] == "--help"):
        printHelp()
        sys.exit(0)
    elif len(sys.argv) != 4:
        print("Wrong number of arguments.")
        print()
        printHelp()
        sys.exit(1)
    # Parse arguments.
    inFilePath = sys.argv[1]
    outFilePath = sys.argv[2]
    API = sys.argv[3]
    ops_inst_str = ""
    header_str = ""

    # Load the specification (which kernel template shall be instantiated
    # with which template arguments) from a JSON-file.
    with open(inFilePath, "r") as inFile:
        kernelsInfo = json.load(inFile)

        for kernelInfo in kernelsInfo:
            kernelTemplateInfo = kernelInfo["kernelTemplate"]
            if "api" in kernelInfo:
                for api in kernelInfo["api"]:
                    for name in api["name"]:
                        # print("Processing API: " + name)
                        # print("  OpName: " + kernelTemplateInfo["opName"])
                        # print("  Instantiations: " + str(api["instantiations"]))
                        # if "opCodes" in api:
                        #     print("  opCodes: " + str(api["opCodes"]))
                        if name == API:
                            # Comment reporting the kernel name.
                            ops_inst_str += INDENT + "// {}\n".format("-" * 76)
                            ops_inst_str += INDENT + "// {}\n".format(kernelTemplateInfo["opName"])
                            ops_inst_str += INDENT + "// {}\n".format("-" * 76)

                            # Include for the required header.
                            if API != "CPP":
                                header_str = header_str + "#include <runtime/local/kernels/{}/{}>\n".format(API, kernelTemplateInfo["header"])
                            else:
                                header_str = header_str + "#include <runtime/local/kernels/{}>\n".format(kernelTemplateInfo["header"])

                            outBuf = io.StringIO()
                            for instantiation in api["instantiations"]:
                                generateKernelInstantiation(kernelTemplateInfo, instantiation,
                                                            api.get("opCodes", None), outBuf, API)
                            ops_inst_str += outBuf.getvalue()
            else:
                if API == "CPP":
                    # Comment reporting the kernel name.
                    ops_inst_str += INDENT + "// {}\n".format("-" * 76)
                    ops_inst_str += INDENT + "// {}\n".format(kernelTemplateInfo["opName"])
                    ops_inst_str += INDENT + "// {}\n".format("-" * 76)

                    # Include for the required header.
                    header_str = header_str + "#include <runtime/local/kernels/{}>\n".format(kernelTemplateInfo["header"])
                    # One function per instantiation of the kernel.
                    opCodes = kernelInfo.get("opCodes", None)
                    outBuf = io.StringIO()
                    for instantiation in kernelInfo["instantiations"]:
                        generateKernelInstantiation(kernelTemplateInfo, instantiation, opCodes, outBuf, API)
                    ops_inst_str += outBuf.getvalue()

    with open(outFilePath, "w") as outFile:
        outFile.write("// This file was generated by {}. Don't edit manually!\n\n".format(sys.argv[0]))
        outFile.write("#include <runtime/local/context/DaphneContext.h>\n")
        outFile.write(header_str)
        outFile.write("\nextern \"C\" {\n")
        outFile.write(ops_inst_str)
        outFile.write("}\n")


n = int(input())

for i in range(1, n + 1):
    #각 자릿수 합 구하기
    a = sum(map(int, str(i)))
    num = i + a
    if num == n:
        print(i)
        break
    if n == i:
        print(0)


from math import pi, cos, sin
import numpy

# Return a list of points representing a circle with radius R, centered at origin and on xz plane.
# With DIVISION points.
# The first point is at (0, 0, R) and go counter-clockwise.
def getCircle(r, division=1800):
    p = []
    step = 2 * pi / division
    for i in xrange(division):
        p.append([r * sin(i * step), 0.0, r * cos(i * step)])
    return p

def getThing(r1, r2, r3, division=1800):
    p = []
    step = 2 * pi / division
    for i in xrange(division):
        p.append([r1 * sin(i * step) + 40, 0, r3 * cos(i * step)])
    return p

def getShape(r, x_factor, z_factor, division=1800):
    p = []
    step = 2 * pi / division
    for i in xrange(division):
        x = r * sin(i * step)
        z = r * cos(i * step)
        y = x * x_factor + (z - r) * z_factor
        p.append([x, y, z])
    return p

def writeToFile(filename, points):
    f = open(filename, "w")
    for x, y, z in points:
        f.write("%f %f %f\n" % (x, y, z))
    f.close()

c = numpy.array([0., 0., 0.]);
def getCircle(u, v, r, c, division=3600):
    p = []
    step = 2 * pi / division
    for i in xrange(division):
        p.append(c + r * cos(i * step) * u + r * sin(i * step) * v)
    return p

t = 0.
u = numpy.array([0., -sin(t), cos(t)])
v = numpy.array([1., 0., 0.])
r = 50.
#exp_c = numpy.array([0., -20 * sin(t), 15 + 20 * cos(t)])
exp_c = numpy.array([0., 0., 60])
c = exp_c - r * u

p = getThing(40,0,20)
writeToFile("config/ellipse.path", p)


from collections import Iterable
l = isinstance('abc',Iterable)
print(l)

L=list(range(1,11))
print(L)

L2 = [x * x for x in range(1,20)]
print(L2)

L3 = [m + n for m in 'abc' for n in 'hkl']
print(L3)

import os
L4 = [d for d in os.listdir('.')]
print('all dir',L4)

L5 = ['Hello','World',18,'Apple',None]
L6 = [s.lower() for s in L5 if isinstance(s,str)]
print(L6)

L7 = ['Hello','World',18,'Apple',None]
L8 = [s.lower() if isinstance(s,str) else s for s in L7]
print(L8)


instructions = []
with open('input.txt', 'r') as f:
    for line in f.readlines():
        instruction, value = line.strip().split(' ')
        value = int(value[1:]) if value.startswith('+') else int(value)
        instructions.append((instruction, value))

acc = 0
i = 0
mem = set()
while True:
    instruction, value = instructions[i]
    print(f"{i}. {instruction} {value}")
    if i in mem:
        raise ValueError(f"Instruction {i} is about to be executed twice. Acc: {acc}")
    mem.add(i)
    if instruction == 'acc':
        acc += value
        i += 1
    elif instruction == 'jmp':
        i += value
    elif instruction == 'nop':
        i += 1


"""
Snapping
"""

def snap_points_to_near_line(lineShp, pointShp, epsg, workGrass,
                             outPoints, location='overlap_pnts', api='grass',
                             movesShp=None):
    """
    Move points to overlap near line

    API's Available:
    * grass;
    * saga.
    """

    if api == 'grass':
        """
        Uses GRASS GIS to find near lines.
        """

        import os;          import numpy
        from geopandas      import GeoDataFrame
        from glass.pys.oss  import fprop
        from glass.wenv.grs import run_grass
        from glass.rd.shp   import shp_to_obj
        from glass.wt.shp   import df_to_shp

        # Create GRASS GIS Location
        grassBase = run_grass(workGrass, location=location, srs=epsg)

        import grass.script as grass
        import grass.script.setup as gsetup
        gsetup.init(grassBase, workGrass, location, 'PERMANENT')

        # Import some GRASS GIS tools
        from glass.gp.prox      import grs_near as near
        from glass.tbl.attr  import geomattr_to_db
        from glass.it.shp import shp_to_grs, grs_to_shp

        # Import data into GRASS GIS
        grsLines = shp_to_grs(
            lineShp, fprop(lineShp, 'fn', forceLower=True)
        )

        grsPoint = shp_to_grs(
            pointShp, fprop(pointShp, 'fn', forceLower=True)
        )

        # Get distance from points to near line
        near(grsPoint, grsLines, nearCatCol="tocat", nearDistCol="todistance")

        # Get coord of start/end points of polylines
        geomattr_to_db(grsLines, ['sta_pnt_x', 'sta_pnt_y'], 'start', 'line')
        geomattr_to_db(grsLines, ['end_pnt_x', 'end_pnt_y'],   'end', 'line')

        # Export data from GRASS GIS
        ogrPoint = grs_to_shp(grsPoint, os.path.join(
            workGrass, grsPoint + '.shp', 'point', asMultiPart=True
        ))

        ogrLine = grs_to_shp(grsLines, os.path.join(
            workGrass, grsLines + '.shp', 'point', asMultiPart=True
        ))

        # Points to GeoDataFrame
        pntDf = shp_to_obj(ogrPoint)
        # Lines to GeoDataFrame
        lnhDf = shp_to_obj(ogrLine)

        # Erase unecessary fields
        pntDf.drop(["todistance"], axis=1, inplace=True)
        lnhDf.drop([c for c in lnhDf.columns.values if c != 'geometry' and
                    c != 'cat' and c != 'sta_pnt_x' and c != 'sta_pnt_y' and
                    c != 'end_pnt_x' and c != 'end_pnt_y'],
                    axis=1, inplace=True)

        # Join Geometries - Table with Point Geometry and Geometry of the
        # nearest line
        resultDf = pntDf.merge(
            lnhDf, how='inner', left_on='tocat', right_on='cat')

        # Move points
        resultDf['geometry'] = [geoms[0].interpolate(
            geoms[0].project(geoms[1])
        ) for geoms in zip(resultDf.geometry_y, resultDf.geometry_x)]

        resultDf.drop(["geometry_x", "geometry_y", "cat_x", "cat_y"],
                      axis=1, inplace=True)

        resultDf = GeoDataFrame(
            resultDf, crs={"init" : 'epsg:{}'.format(epsg)}, geometry="geometry"
        )

        # Check if points are equal to any start/end points
        resultDf["x"] = resultDf.geometry.x
        resultDf["y"] = resultDf.geometry.y

        resultDf["check"] = numpy.where(
            (resultDf["x"] == resultDf["sta_pnt_x"]) & (resultDf["y"] == resultDf["sta_pnt_y"]),
            1, 0
        )

        resultDf["check"] = numpy.where(
            (resultDf["x"] == resultDf["end_pnt_x"]) & (resultDf["y"] == resultDf["end_pnt_y"]),
            1, 0
        )

        # To file
        df_to_shp(resultDf, outPoints)

    elif api == 'saga':
        """
        Snap Points to Lines using SAGA GIS
        """

        from glass.pys  import execmd

        mv="" if not movesShp else f" -MOVES {movesShp}"

        cmd = (
            f"saga_cmd shapes_points 19 -INPUT {pointShp} "
            f"-SNAP {lineShp} "
            f"-OUTPUT {outPoints}{mv}"
        )

        outcmd = execmd(cmd)

    else:
        raise ValueError(f"{api} is not available!")

    return outPoints


from ..shared.list_arithmatic import add
from ..shared.digits import to_digits
from itertools import permutations
from ..shared.solver import Solver

def digit_sum(n:int)->int:
    return add(to_digits(n))

def digit_sums(biggest: int):
    pool = list(range(0,biggest))
    for a, b in permutations(pool,2):
        power = a**b
        yield a, b, power, digit_sum(power)

def _solve(print=print):
    biggest = max(digit_sums(100), key=lambda x: x[3])
    print(f"{biggest[0]}**{biggest[1]}=={biggest[2]}")
    print(f"Digit sum: {biggest[3]}")
    return True

description = '''A googol (10**100) is a massive number: one followed by one-hundred zeros; 100**100 is almost
unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.

Considering natural numbers of the form, a**b, where a, b < 100, what is the maximum digital sum?
'''

solver = Solver(56,
                'Powerful digit sum',
                description,
                _solve
                )


from collective.honeypot import _
from collective.honeypot.config import ACCEPTED_LOG_LEVEL
from collective.honeypot.config import DISALLOW_ALL_POSTS
from collective.honeypot.config import EXTRA_PROTECTED_ACTIONS
from collective.honeypot.config import HONEYPOT_FIELD
from collective.honeypot.config import IGNORED_FORM_FIELDS
from collective.honeypot.config import SPAMMER_LOG_LEVEL
from collective.honeypot.config import WHITELISTED_ACTIONS
from collective.honeypot.config import WHITELISTED_START
from copy import deepcopy
from zExceptions import Forbidden
from zope.globalrequest import getRequest
from zope.i18n import translate

try:
    from plone.restapi.deserializer import json_body
except ImportError:
    json_body = None

import logging
import six

logger = logging.getLogger("collective.honeypot")

def found_honeypot(form, required):
    """Did a spammer find a honeypot?

    We have two requirements:

    1. The honeypot field MUST be there if required is True.
    2. The honeypot field MUST be empty.

    Return True when one of these requirements is not met.
    """
    if not HONEYPOT_FIELD:
        # Apparently the user is only interested in logging the
        # requests, not in stopping spammers.
        return False
    if required and HONEYPOT_FIELD not in form:
        # Spammer did not submit required field.
        return "misses required field"
    value = form.get(HONEYPOT_FIELD)
    if not value:
        # All tests are clear.
        return False
    # Spammer submitted forbidden field with non-empty value.
    # But: we could have made a mistake and put in the honeypot
    # field twice, which means it gets submitted as a list.
    if isinstance(value, list):
        value = "".join(value)
        if not value:
            # All clear
            return False
    return "has forbidden field"

def deny(msg=None):
    # Deny access.
    if msg is None:
        msg = translate(
            _(
                "post_denied_label",
                default="Posting denied due to possible spamming. "
                "Please contact us if we are wrong.",
            ),
            context=getRequest(),
        )
    raise Forbidden(msg)

def whitelisted(action):
    if action in WHITELISTED_ACTIONS:
        return True
    # Check action start strings.
    for white in WHITELISTED_START:
        if action.startswith(white):
            return True
    return False

def get_form(request):
    form = getattr(request, "form", {})
    if (
        not form
        and getattr(request, "CONTENT_TYPE", "") == "application/json"
        and json_body
    ):
        # restapi post
        form = json_body(request)
    if not form and isinstance(request, dict):
        form = request

    # We may need to make a copy of the form.  This may be expensive
    # in memory, so we make sure to do this only once when needed.
    copied = False
    for field in IGNORED_FORM_FIELDS:
        if field not in form:
            continue
        if not copied:
            form = deepcopy(form)
            copied = True
        form.pop(field)
    # Remove all password fields.
    for field in form:
        if "password" not in field:
            continue
        if not copied:
            form = deepcopy(form)
            copied = True
        form.pop(field)
    return form

def get_small_form(form):
    # Avoid printing large textareas or complete file uploads.
    small_form = {}
    for key, value in form.items():
        if not isinstance(value, six.string_types):
            small_form[key] = value
            continue
        if len(value) > 250:
            small_form[key] = value[:250] + "..."

    return small_form

def check_post(request):
    """Log a POST request.

    And possibly forbid access.

    Could be useful in case of a spam attack.
    """
    if request.get("REQUEST_METHOD", "").upper() != "POST":
        return
    if DISALLOW_ALL_POSTS:
        logger.warn("All posts are disallowed.")
        # block the request:
        deny(msg="All posts are disallowed.")
    ip = request.get("HTTP_X_FORWARDED_FOR") or request.get("REMOTE_ADDR", "unknown")
    referer = request.get("HTTP_REFERER", "")
    url = request.get("ACTUAL_URL", "")

    action = url.split("/")[-1]  # last part of url
    action = action.lstrip("@")

    if whitelisted(action):
        logger.debug("Action whitelisted: %s.", action)
        return
    form = get_form(request)
    if action in EXTRA_PROTECTED_ACTIONS:
        result = found_honeypot(form, required=True)
    else:
        result = found_honeypot(form, required=False)
    logger.debug("Checking honeypot fields for action %s. Result: %s.", action, result)
    if not result:
        try:
            form = get_small_form(form)
        except Exception:
            # Do not crash just because we want to log something.
            pass
        logger.log(
            ACCEPTED_LOG_LEVEL,
            "ACCEPTED POST from ip %s, url %r, referer %r, with form " "%r",
            ip,
            url,
            referer,
            form,
        )
        return
    logger.log(
        SPAMMER_LOG_LEVEL,
        "SPAMMER caught in honeypot: %s.  ip %s, url %r",
        result,
        ip,
        url,
    )
    # block the request:
    deny()


# coding=utf-8

def isNum(n:str)-> int:
    sum = 0
    for i in n:
        sum += int(i)**3
    return sum == int(n)

def main():
    n = input()
    if(isNum(n)):
        print("YES")
    else:
        print("NO")

main()


import numpy as np
def update_varSum(idx_new, series, win_size, prevVal=None):
    """
    Returns the power sum average based on the blog post from
    Subliminal Messages.  Use the power sum average to help derive the running
    variance.
    sources: http://subluminal.wordpress.com/2008/07/31/running-standard-deviations/

    Keyword arguments:
    idx_new     --  current index or location of the value in the series
    series  --  list or tuple of data to average
    win_size  -- number of values to include in average
    pval    --  previous powersumavg (n - 1) of the series.
    """

    if win_size < 1:
        raise ValueError("period must be 1 or greater")

    if idx_new < 0:
        idx_new = 0

    if prevVal == None:
        if idx_new > 0:
            raise ValueError("pval of None invalid when bar > 0")

        prevVal = 0.0

    newVal = float(series[idx_new])

    if idx_new < win_size:
        result = prevVal + (newVal * newVal - prevVal) / (idx_new + 1.0)

    else:
        oldVal = float(series[idx_new - win_size])
        result = prevVal + (((newVal * newVal) - (oldVal * oldVal)) / win_size)

    return result

def varSum_to_var(idx_new, series, win_size, mean_current, varSum):
    """
    Returns the running variance based on a given time period.
    sources: http://subluminal.wordpress.com/2008/07/31/running-standard-deviations/

    Keyword arguments:
    idx_new     --  current index or location of the value in the series
    series  --  list or tuple of data to average
    mean_current    --  current average of the given period
    varSum -- current powersumavg of the given period
    """
    if win_size < 1:
        raise ValueError("period must be 1 or greater")

    if idx_new <= 0:
        return 0.0

    if mean_current == None:
        raise ValueError("asma of None invalid when bar > 0")

    if varSum == None:
        raise ValueError("powsumavg of None invalid when bar > 0")

    windowsize = idx_new + 1.0
    if windowsize >= win_size:
        windowsize = win_size

    return (varSum * windowsize - windowsize * mean_current * mean_current) / windowsize

def running_mean(idx_new, series, mean_old):
    """
    Returns the cumulative or unweighted simple moving average.
    Avoids sum of series per call.

    Keyword arguments:
    idx_new     --  current index or location of the value in the series
    series  --  list or tuple of data to average
    mean_old  --  previous average (n - 1) of the series.
    """

    if idx_new <= 0:
        return series[0]

    return mean_old + ((series[idx_new] - mean_old) / (idx_new + 1.0))

def update_mean(idx_new, series, win_size, mean_old):
    """
    Returns the running simple moving average - avoids sum of series per call.

    Keyword arguments:
    idx_new     --  current index or location of the value in the series
    series  --  list or tuple of data to average
    win_size  --  number of values to include in average
    mean_old  --  previous simple moving average (n - 1) of the series
    """

    if win_size < 1:
        raise ValueError("period must be 1 or greater")

    if idx_new <= 0:
        return series[0]

    elif idx_new < win_size:
        return running_mean(idx_new, series, mean_old)

    return mean_old + ((series[idx_new] - series[idx_new - win_size]) / float(win_size))


import numpy
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure

img_path = '/home/moby/PycharmProjects/datasets_processing/figures/'
plt.rcParams.update({

    'font.family': 'serif',
    'font.sans-serif': ['Times'],
    'text.latex.preamble':
        r'\usepackage[T2A]{fontenc}'
        r'\usepackage[utf8]{inputenc}'
})
classes = [
    'Normal (Без спец. техники)',
    'Muting (Пиццикато)',
    'Vibrato (Вибрато)',
    'Pull-off (Нисх. легато)',
    'Hammer-on (Восх. легато)',
    'Sliding (Глиссандо)',
    'Bending (Бенд)'
]
vals = np.array([
    2009,
    385,
    637,
    525,
    581,
    1162,
    1281
])

def absolute_value(val):
    a = numpy.round(val / 100. * vals.sum(), 0)
    return int(a)

fig1, ax1 = plt.subplots(figsize=(9, 5))
ax1.pie(vals, labels=classes, autopct=absolute_value,
        shadow=False, startangle=90,
        textprops={'fontsize': 15}
        )
# ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle
# fig1.set_size_inches(18.5, 10.5)
# plt.tight_layout()
plt.savefig(img_path + "gpt_pie" + '.pdf')
plt.show()


from __future__ import absolute_import

import logging
import tempfile
import unittest

from apache_beam.examples.cookbook import group_with_coder
from apache_beam.testing.util import open_shards

# Patch group_with_coder.PlayerCoder.decode(). To test that the PlayerCoder was
# used, we do not strip the prepended 'x:' string when decoding a Player object.
group_with_coder.PlayerCoder.decode = lambda self, s: group_with_coder.Player(  # type: ignore[assignment]
    s.decode('utf-8'))

class GroupWithCoderTest(unittest.TestCase):

  SAMPLE_RECORDS = [
      'joe,10',
      'fred,3',
      'mary,7',
      'joe,20',
      'fred,6',
      'ann,5',
      'joe,30',
      'ann,10',
      'mary,1'
  ]

  def create_temp_file(self, records):
    with tempfile.NamedTemporaryFile(delete=False) as f:
      for record in records:
        f.write(b'%s\n' % record.encode('utf-8'))
      return f.name

  def test_basics_with_type_check(self):
    # Run the workflow with pipeline_type_check option. This will make sure
    # the typehints associated with all transforms will have non-default values
    # and therefore any custom coders will be used. In our case we want to make
    # sure the coder for the Player class will be used.
    temp_path = self.create_temp_file(self.SAMPLE_RECORDS)
    group_with_coder.run(
        ['--input=%s*' % temp_path, '--output=%s.result' % temp_path],
        save_main_session=False)
    # Parse result file and compare.
    results = []
    with open_shards(temp_path + '.result-*-of-*') as result_file:
      for line in result_file:
        name, points = line.split(',')
        results.append((name, int(points)))
      logging.info('result: %s', results)
    self.assertEqual(
        sorted(results),
        sorted([('x:ann', 15), ('x:fred', 9), ('x:joe', 60), ('x:mary', 8)]))

  def test_basics_without_type_check(self):
    # Run the workflow without pipeline_type_check option. This will make sure
    # the typehints associated with all transforms will have default values and
    # therefore any custom coders will not be used. The default coder (pickler)
    # will be used instead.
    temp_path = self.create_temp_file(self.SAMPLE_RECORDS)
    group_with_coder.run([
        '--no_pipeline_type_check',
        '--input=%s*' % temp_path,
        '--output=%s.result' % temp_path
    ],
                         save_main_session=False)
    # Parse result file and compare.
    results = []
    with open_shards(temp_path + '.result-*-of-*') as result_file:
      for line in result_file:
        name, points = line.split(',')
        results.append((name, int(points)))
      logging.info('result: %s', results)
    self.assertEqual(
        sorted(results),
        sorted([('ann', 15), ('fred', 9), ('joe', 60), ('mary', 8)]))

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)
  unittest.main()


from utilities import util

import binascii
import RSA as rsa

# Challenge 40

def broadcast_attack(c1, c2, c3, p1, p2, p3):
  _, n1 = p1
  _, n2 = p2
  _, n3 = p3

  c1 = int(binascii.hexlify(c1), 16)
  c2 = int(binascii.hexlify(c2), 16)
  c3 = int(binascii.hexlify(c3), 16)

  x1 = c1 * n2 * n3 * util.modinv(n2 * n3, n1)
  x2 = c2 * n3 * n1 * util.modinv(n3 * n1, n2)
  x3 = c3 * n1 * n2 * util.modinv(n1 * n2, n3)

  m_cubed = (x1 + x2 + x3) % (n1 * n2 * n3)
  m = util.iroot(3, m_cubed)
  return util.int_to_bytes(m)

if __name__ == '__main__':
  p1, _ = rsa.generate_keys(e = 3)
  p2, _ = rsa.generate_keys(e = 3)
  p3, _ = rsa.generate_keys(e = 3)

  m = b'rsa br0adca5t att4ck'

  c1 = rsa.encrypt(m, p1)
  c2 = rsa.encrypt(m, p2)
  c3 = rsa.encrypt(m, p3)

  assert broadcast_attack(c1, c2, c3, p1, p2, p3) == m
  print('Successfully determined plaintext')


import time
import random
import lxc
import code
import string
from multiprocessing.pool import ThreadPool
import os
from os.path import join, isfile, exists
import json

LXC_BASE = "tmpl_apach"
MOUNTPOINT = "files"
LXC_IP = "10.10.13.7"

##### GRADER FUNCTIONS
import http.client
ip1 = '127.0.0.1'
ip2 = LXC_IP

def DisableSSLv3():
    import socket, ssl, pprint
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # disable sslv3 and sslv2
    ssl_sock = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, do_handshake_on_connect=False)
    try:
        ssl_sock.connect(('localhost', 443))
        ssl_sock.do_handshake()
        return False
    except:
        ssl_sock.close()
        # enable tlsv1
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ssl_sock = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1, do_handshake_on_connect=False)
        try:
            ssl_sock.connect(('localhost', 443))
            ssl_sock.do_handshake()
            return True
        except:
            return False

def RestrictWeakSSLCiphers():
    import socket, ssl, pprint
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # disable sslv3 and sslv2
    ciphers = "EXP:NULL:ADH:LOW:MD5:RC4"
    ssl_sock = ssl.wrap_socket(s, do_handshake_on_connect=False, ciphers=ciphers)
    try:
        ssl_sock.connect(('localhost', 443))
        ssl_sock.do_handshake()
        return False
    except:
        ssl_sock.close()
        # enable tlsv1
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ssl_sock = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1, do_handshake_on_connect=False)
        try:
            ssl_sock.connect(('localhost', 443))
            ssl_sock.do_handshake()
            return True
        except:
            return False

def SetServerTokenToProd():
    try:
        ret = True
        conn = http.client.HTTPConnection("localhost")
        conn.request("GET","/")
        res = conn.getresponse()
        headers = res.getheaders()
        for header in headers:
            if(header[0].lower() == 'server' and (header[1].find('Ubuntu') != -1)):
                ret = False
    except:
        return False
    return ret

def SetServerSignatureToOff():
    try:
        ret = True
        conn = http.client.HTTPConnection("localhost")
        conn.request("GET","/")
        res = conn.getresponse()
        body = res.read()
        if(body.find('Apache') != -1):
                ret = False
    except:
        return False
    return ret

def DirectoryListing():
    try:
        ret = True
        conn = http.client.HTTPConnection("localhost")
        conn.request("GET","/DirectoryListing/")
        res = conn.getresponse()
        if(res.status == 200):
                return False

    except:
        return False
    return ret

##### END OF GRADER FUNCTIONS

def filter_submition(submition):
    for root, subdirs, files in os.walk(submition):
        for filename in files:
            if not (filename.endswith(".conf") or filename.endswith(".load") or  filename =="envvars" or  filename=="magic"):
                os.remove(join(root,filename))
                print("deleted",join(root,filename))

def run_test_body():
    # apache test syntax
    import subprocess
    cmd = "apachectl configtest"
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    res =str(p.stdout.read())
    retval = p.wait()
    if retval != 0:
       return {"stat":10,"msg":"`apachectl configtest` failed.",'data': {'stdio':res,'retval':retval}}  # stat: 10 cmd error
    print("ctl passed")
    # apache restart
    cmd = "service apache2 restart"
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    res =str(p.stdout.read())
    retval = p.wait()
    if retval != 0:
       return {"stat":10,"msg":"`service apache2 restart` failed.",'data': {'stdio':res,'retval':retval}}
    print("restart passed")
    # evals
    funcs = [
             ('DisableSSLv3', 20), \
             ('RestrictWeakSSLCiphers', 20), \
             ('SetServerTokenToProd', 20), \
             ('SetServerSignatureToOff', 20), \
             ('DirectoryListing', 20)]
    score = 0
    result = []
    max = 0
    for func in funcs:
        res = (func, False)
        max += func[1]
        if(globals()[func[0]]()):
            res = (func, True)
            score += func[1]
        result.append(res)
    if max == score:
        return {"stat":1,"msg":"VeryWell!",'data': {'stdio':'','retval':'','score':score,'result':result}}    # completely done
    else:
        return {"stat":2,"msg":"Try Harder.",'data': {'stdio':'','retval':'','score':score,'result':result}} # partially done

def run_test():
    #global ip2
    #ip2 = argz[0]
    res = run_test_body()
    with open("/files/result.txt","w") as f:
    #with open("/root/result.txt","w") as f:
          f.write(json.dumps(res))
    return 10

def thread_worker(child):
    child.start()
    child.wait("RUNNING", 15)
    if not child.running:
        return {"stat":0,"msg":"child cannot start.",'data': None}
    #child.attach_wait(lxc.attach_run_command, ["service", "networking", "restart"])
    #if not child.get_ips(timeout=15):
    #    return {"stat":0,"msg":"failed to get ip address of container",'data': None}
    #ip2 = child.get_ips()[0]

    child.attach_wait(lxc.attach_run_command, ["rm","-rf","/etc/apache2/conf-available*"])
    child.attach_wait(lxc.attach_run_command, ["rm","-rf","/etc/apache2/conf-enabled/*"])
    child.attach_wait(lxc.attach_run_command, ["rm","-rf","/etc/apache2/mods-available/*"])
    child.attach_wait(lxc.attach_run_command, ["rm","-rf","/etc/apache2/mods-enabled/*"])
    child.attach_wait(lxc.attach_run_command, ["rm","-rf","/etc/apache2/sites-available/*"])
    child.attach_wait(lxc.attach_run_command, ["rm","-rf","/etc/apache2/sites-enabled/*"])
    child.attach_wait(lxc.attach_run_command, ["cp","-r","/files/etc","/"])
    time.sleep(0.3)
    res = child.attach_wait(run_test)
    if(res >= 256):
       res = res / 256
    if(res == 10):
       child_root_fs = child.get_config_item('lxc.rootfs').split(':')[-1]
       return {"stat":200,"msg":"extract info file",'data': {'file':join(child_root_fs,"root","result.txt")}}
    else:
       return {"stat":0,"msg":"Illegal state",'data': None}

def grade(folder,pid,file,submition):
  try:
    filter_submition(submition)
    base = lxc.Container(LXC_BASE)
    if not base.defined:
        print("Base is not defined.")
        return {"stat":0,"msg":"خطای سرور",'data': None}
    if base.running:
        print("Base container is running")
        return {"stat":0,"msg":"خطای سرور",'data': None}
    c_name = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(16))
    child = lxc.Container(c_name)
    if not child.defined:
      try:
        child = base.clone(c_name, bdevtype="overlayfs",
              flags=lxc.LXC_CLONE_SNAPSHOT)
        child.append_config_item("lxc.mount.entry", submition +" "+ MOUNTPOINT + " none bind 0 0")
        #child.append_config_item("lxc.mount.entry", submition +"/etc/apache2 etc/apache2 none bind 0 0")
        child.save_config()
        pool = ThreadPool(processes=1)
        async_result = pool.apply_async(thread_worker, (child,))
        result = async_result.get(timeout=60)
        child.stop()
        if(result["stat"]==200):
           with open(join(submition,"result.txt")) as f:
           #with open(result["data"]["file"]) as f:

               jsonstr =f.read()
               jsonstr = json.loads(jsonstr)
               result = jsonstr
               if result["stat"] == 1:
                    import hashlib
                    #team_folder = hashlib.md5(("6a204bd89f3c8348afd5c77c717a097a"+team).encode('utf-8')).hexdigest()
                    #flag = "infosec-" + hashlib.md5((folder + "infosec-3f51f45f424a61516b5cc8b6663d919c").encode('utf-8')).hexdigest()
                    flag = "infosec-3f51f45f424a61516b5cc8b6663d919c"
                    result["data"]["flag"] = flag
        #child.destroy()
        return result
      except Exception as inst:
        import traceback
        e = traceback.format_exc()
        return {"stat":0,"msg":"failed due exception",'data': {'exp': inst,'stack':e}}
      finally:
        #print(c_name)
        if child.running:#pass
           child.stop()
        child.destroy()
    else:
        return {"stat":0,"msg":"duplicate Name " + c_name,'data': None}
  except Exception as inst:
        return {"stat":0,"msg":"failed due exception",'data': {'exp': inst,'stack':e}}


from SortAlgs import *
import matplotlib.pyplot as plt
import plotly.express as px
import timeit
import random
import numpy as np

N = 10000
X = [random.randint(0, N) for _ in range(N)]

naive_time = timeit.timeit("naive_sort(X, X)", globals=globals(), number=1)
merge_time = timeit.timeit("merge_sort(X, X)", globals=globals(), number=1)
count_time = timeit.timeit("count_sort(X, X)", globals=globals(), number=1)

naive_complexity = lambda n: naive_time/10000**2             * n**2
merge_complexity = lambda n: merge_time/10000/np.log2(10000) * n*np.log2(n)
count_complexity = lambda n: count_time/10000                * n

n = np.logspace(1, 10, 10000)
fig = px.line(x=n, y=naive_complexity(n)/3600/24/365.25, labels={"x": "n", "y": "time [years]"}, title="Naive sort")
fig.add_scatter(x=n, y=merge_complexity(n)/3600/24/365.25, name="Merge sort")
fig.add_scatter(x=n, y=count_complexity(n)/3600/24/365.25, name="Count sort")
fig.update_xaxes(type="log")
fig.update_yaxes(type="log")
fig.update_layout(yaxis=dict(exponentformat="power"), xaxis=dict(exponentformat="power"))
fig.show()


# 3
# 5 1 5
N = int(input())
nums = input().strip().split(' ')
for i in range(len(nums)):
    nums[i] = int(nums[i])
def cal(nums):
    nums.sort()
    mid = len(nums)//2
    less, great = nums[:mid],nums[mid:]
    return 2*(sum(great)-sum(less))-great[0]-(great[1] if len(nums) & 1 else -less[-1])
print(cal(nums))


import sys
import os
import subprocess
import graphviz_gen

from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QPlainTextEdit, QVBoxLayout
from PySide6.QtCore import QFile, QThread, Slot, Qt
from PySide6.QtUiTools import QUiLoader
from PySide6.QtSvgWidgets import QSvgWidget

class Base(QWidget):
    def __init__(self):
        super(Base, self).__init__()
        self.load_ui()
        # self.thread = Worker()
        self.domain_in = self.ui.findChild(QLineEdit, "domain_in")
        self.text_box = self.ui.findChild(QPlainTextEdit, "log_out")
        self.btn = self.ui.findChild(QPushButton, 'rs_button')
        self.graph_btn = self.ui.findChild(QPushButton, 'graph_btn')

    def load_ui(self):
        loader = QUiLoader()
        path = os.path.join(os.path.dirname(__file__), "form.ui")
        ui_file = QFile(path)
        ui_file.open(QFile.ReadOnly)
        self.ui = loader.load(ui_file, self)
        ui_file.close()

class GraphWindow(QWidget):
    def __init__(self, path):
        super().__init__()
        layout = QVBoxLayout()
        self.svg_wid = QSvgWidget(self)
        self.svg_wid.load(path)
#        self.svg_wid.show()
        layout.addWidget(self.svg_wid)
        self.setLayout(layout)

class Implement(Base):
    def __init__(self):
        super().__init__()
        self.w = None
        print(self.text_box)
        self.btn.clicked.connect(self.run_script)
        self.graph_btn.clicked.connect(self.graph_disp)

    @Slot()
    def run_script(self):
        text_value = self.domain_in.text()
        print(type(text_value))
        out_file = open("output", 'w')
        script_path = "{insert your path here for the bash script }"
        rc = subprocess.run(
            [script_path, text_value],
            stdout=out_file,
            stderr=subprocess.PIPE
        )
        out_file.close()
        self.show_output_box()

    @Slot()
    def show_output_box(self):
        out_file = open("output").read()
        print(out_file)
        self.text_box.clear()
        self.text_box.insertPlainText(out_file)

    def graph_disp(self):
        graphviz_gen.gengraph(self.domain_in.text())
#        if self.w is None:
        print(self.domain_in.text())
        self.w = GraphWindow("final_graph"+self.domain_in.text()+".svg")
        self.w.show()

if __name__ == "__main__":
    app = QApplication([])
    widget = Implement()
    widget.show()
#    widget.show_ui_object()
    sys.exit(app.exec_())


from django.urls import path

from . import views
from django.urls import include, path, re_path

# /playlist
# /user/<id>

urlpatterns = [
    path('index/', views.index, name='index'), # page
    re_path('^index/registration/', views.registration),
    path('login/', views.login), # page
    path('logout/', views.logout),
    path('user/playlist', views.userlist), # page userId=1&playlistId=2
    path('userlist/track/', views.addTrack), #page
    re_path('^userlist/track/add/', views.addTrack),
    re_path('^userlists/delete/', views.userlists),  # page -_-
    re_path('^userlists/create/add/', views.addPlaylist),
    re_path('^userlists/create/', views.addPlaylist),
    path('user/playlist/modify/', views.modify_pl),
    path('user/playlist/modify/add/', views.modify_pl),
    path('user/playlist/modify/put/', views.mod_put),
    path('user/playlist/modify/put/put/', views.mod_put)
]


import pandas as pd
import pickle

# leemos el archivo con las respuestas a la encuesta Origen Destino
# este archivo es muy grande para github. No lo subí
encuesta = pd.read_csv("C:/Users/Edgar Trejo/Desktop/tviaje.csv")
# obtenemos las respuestas para viajes que son de la cdmx, del edomex y hgo
# la pregunta 'p5_7_7' tiene el código del estado de origen
encuesta = encuesta[encuesta["p5_7_7"].isin([9, 15, 13])]
# queremos los datos del municipio de origen: p5_7_6, estado de origen: p5_7_7, distrito de origen: dto_origen
# municipio de destino: p5_12_6, estado de destino: p5_12_7, distrito de destino: dto_dest
encuesta = encuesta[["p5_7_6", "p5_7_7", "dto_origen", "p5_12_6", "p5_12_7", "dto_dest"]]
# cambiamos los nombres para que esté más cool. Nos da más info que solo el código de la pregunta
encuesta = encuesta.rename(columns = {"p5_7_6":"mun_origen", "p5_7_7":"est_origen", "p5_12_6":"mun_dest",
                                                 "p5_12_7":"est_dest"})

# hacemos un multi index
encuesta.set_index(['dto_origen', 'est_origen', 'mun_origen'], inplace = True)
# con esto ya podemos mapear
distritos = {}
cve_est = lambda x: "0"*(2-len(str(x))) + str(x)
cve_mun = lambda x: "0"*(3-len(str(x))) + str(x)
for i in encuesta.index:
    # i es una tupla: la primer entrada es el distrito, la segunda el estado y el tercero el municipio
    if i[0] not in distritos and i[2] < 130: # números grandes en mun significan otra cosa
        distritos[i[0]] = cve_est(i[1]) + cve_mun(i[2])
# guardamos el diccionario en un archivo binario
with open('data/cleandata/ZMVM/distritos_a_cve_umun.pkl', 'wb') as handle:
    pickle.dump(distritos, handle, protocol=pickle.HIGHEST_PROTOCOL)

Modeling COVID-19 Spreading in the ZMVM/data/src/datos_geo/distritos_a_mun.py


# gunicorn/django  服务监听地址、端口
bind = '0.0.0.0:8210'

# gunicorn worker 进程个数，建议为： CPU核心个数 * 2 + 1
workers = 3

# gunicorn worker 类型， 使用异步的event类型IO效率比较高
worker_class = "gevent"

# 日志文件路径
errorlog = "./log/error.log"
accesslog = './log/access.log' #正常时的log路径
loglevel = "info"

import os
import sys

cwd = os.getcwd()
sys.path.append(cwd)


import os, sys

ruta = __file__
for i in range(2):
    ruta = os.path.dirname(ruta)  #subir dos niveles en carpetas, es decir sube hasta imp

print("Ruta:", ruta)
sys.path.append(ruta)

#import a.x as x

def y1():
    print("y1")

def y2():
    print("y2")
    x.x1()

if __name__ == "__main__":  #con esta condición no se importa lo que esté debajo de if __name__
    import a.x as x
    print("este print no se ejecuta")
    y2()


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: anzhang28@163.com
# FileName: qsbk.py
# function: search story from qiushibaike
# date: 2017/01/09

import re
import basictest

class Qsbk(basictest.StaticPage):
    def getBriefContent(self):
        pginfo = self.getOnelineContent(self.getPageInfo().read())
        sc_re = re.compile('

.*?
(.*?)
.*?' +
                           '
.*?
(.*?).*?(.*?)' +
                           '
.*?(\d+)' +
                           '.*?(\d+)')
        sc = sc_re.findall(pginfo)
        return sc

    def getNoImgContent(self):
        nic = []
        sc = self.getBriefContent()
        for s in sc:
            if len(s[2]) == 0:
                nic.append(s)
        return nic

    def startPrintRocorder(self):
        sc = []
        pg = 1
        bsurl = self.url
        while pg:
            self.url = bsurl + str(pg)
            print('loading story form {0} ......'.format(self.url))
            sc += self.getNoImgContent()
            for s in sc:
                flag = raw_input("press any key to continue except Q/q to quit\n")
                if flag == 'q' or flag == 'Q':
                    break
                else:
                    print('author:{0}\n{1}\nAN: {2} QN:{3}'
                          .format(s[0], re.sub('(
)', '\n', s[1]), s[3], s[4]))
            nextpg = raw_input('Press Y/y to continue scanning next page')
            if nextpg == 'y' or nextpg == 'Y':
                sc = []
                pg += 1
            else:
                break

if __name__ == '__main__':
    qsbk = Qsbk('https://www.qiushibaike.com/hot/page/')
    qsbk.startPrintRocorder()