import struct
import math

def parse_boot_block(fat_contents):
    #print(fat_contents)
    res = []
    info = dict()
    boot_sector = 0

    sector_size = struct.unpack('H', fat_contents[0x0b:0x0d])[0]
    info['sectorsize'] = sector_size

    blocks_per_cluster = fat_contents[0x0d]
    info['blocks_per_cluster'] = blocks_per_cluster

    n_reserved_blocks = struct.unpack('H', fat_contents[0x0e:0x10])[0]
    info['n_reserved_blocks'] = n_reserved_blocks

    num_of_fats = fat_contents[0x10]
    num_root_dir_entries = struct.unpack('H', fat_contents[0x11:0x13])[0]
    info['n_fats'] = num_of_fats
    info['n_dir_entries'] = num_root_dir_entries

    num_blocks_per_fat = struct.unpack('H', fat_contents[0x16:0x18])[0]
    info['blocks_per_fat'] = num_blocks_per_fat

    total_num_of_blocks = struct.unpack('I', fat_contents[0x20:0x24])[0] + struct.unpack('H', fat_contents[0x13:0x15])[0]
    info['total_blocks'] = total_num_of_blocks

    """fat0_start = boot_sector*sector_size
    fat0_end = boot_sector*sector_size + num_blocks_per_fat*sector_size
    fat1_start = fat0_end
    fat1_end = fat0_end + num_blocks_per_fat*sector_size"""

    root_dir_start = sector_size + num_of_fats * num_blocks_per_fat * sector_size
    root_dir_end = root_dir_start  + num_root_dir_entries*32
    #print('@@@@',root_dir_start, root_dir_end)

    info['root_dir_start'] = root_dir_start
    info['root_dir_end'] = root_dir_end

    cluster_range = int((total_num_of_blocks - (root_dir_end +1))/2)

    first_cluster_sector = info['n_reserved_blocks'] + info['blocks_per_fat']*info['n_fats'] + int((info['n_dir_entries']*32)/ sector_size)
    info['first_cluster_sector'] = first_cluster_sector

    return info

def as_unsigned(bs, endian='<'):
    unsigned_format = {1: 'B', 2: 'H', 4: 'L', 8: 'Q'}
    if len(bs) <= 0 or len(bs) > 8:
        raise ValueError()
    fill = '\x00'
    while len(bs) not in unsigned_format:
        bs = bs + fill
    result = struct.unpack(endian + unsigned_format[len(bs)], bs)[0]
    return result

def decode_fat_time(time_bytes, tenths=0, tz='EDT'):
    v = as_unsigned(time_bytes)
    second = int(int(0x1F & v) * 2)
    if tenths > 100:
        second += 1
    minute = (0x7E0 & v) >> 5
    hour = (0xF800 & v) >> 11
    return '{:02}:{:02}:{:02} ({})'.format(hour, minute, second, tz)

def decode_fat_day(date_bytes):
    v = as_unsigned(date_bytes)
    day = 0x1F & v
    month = (0x1E0 & v) >> 5
    year = ((0xFE00 & v) >> 9) + 1980
    return '{}-{:02}-{:02}'.format(year, month, day)

def get_dir_cluster_run(cluster_tables, sector_size, n_fats, blocks_per_fat, blocks_per_cluster, starting_cluster, first_cluster_sector, allocation_status):
    cluster_num = starting_cluster
    sectors = []
    counter = 0
    #print('starting cluster',starting_cluster, file_sectors)
    cluster_chain = dict()

    while True:
        index = (cluster_num - 2)*2
        sec1 = (cluster_num - 2) * blocks_per_cluster + first_cluster_sector
        sec2 = (cluster_num - 2) * blocks_per_cluster + first_cluster_sector + 1

        next_cluster = as_unsigned(cluster_tables[index : index + 2])
        #print('next_cluster bytes', next_cluster)
        if allocation_status == 'Allocated':
            #print('########', sec1, sec2, next_cluster)
            sectors.append(sec1)
            sectors.append(sec2)

            if next_cluster in cluster_chain:
                cluster_chain[cluster_num] = next_cluster
                cluster_num += 1

            else:
                if next_cluster == 0xffff:
                    break

                elif next_cluster == 0x0000:
                    if cluster_num not in cluster_chain:
                        cluster_chain[cluster_num] = cluster_num + 2#next_cluster

                    cluster_num += 2

                else:
                    if cluster_num not in cluster_chain:
                        cluster_chain[cluster_num] = next_cluster
                        cluster_num = next_cluster

                    else:
                        cluster_num += 1

            counter += 2

        else:
            sec1 = (cluster_num - 2) * blocks_per_cluster + first_cluster_sector
            sec2 = (cluster_num - 2) * blocks_per_cluster + first_cluster_sector + 1

            if next_cluster != 0x0000 and next_cluster != 0xffff:
                cluster_num += 1
                continue
            sectors.append(sec1)
            sectors.append(sec2)
            cluster_num += 1
            counter += 2

    res = []
    line = ''
    dir_size = sector_size*len(sectors)
    for i in range(0, len(sectors)):
        #print(sectors[i])
        if i%8 == 0:
            res.append(line+'\n')
            line = str(sectors[i])+ ' '
        else:
            line += str(sectors[i]) + ' '

    res.append(line+'\n')

    return res, dir_size

def get_cluster_run(cluster_tables, sector_size, n_fats, blocks_per_fat, blocks_per_cluster, starting_cluster, first_cluster_sector, file_sectors, allocation_status, filetype):
    cluster_num = starting_cluster
    sectors = []
    counter = 0
    #print('starting cluster',starting_cluster, file_sectors)
    cluster_chain = dict()

    while counter < file_sectors:
        index = (cluster_num - 2)*2
        sec1 = (cluster_num - 2) * blocks_per_cluster + first_cluster_sector
        sec2 = (cluster_num - 2) * blocks_per_cluster + first_cluster_sector + 1

        next_cluster = as_unsigned(cluster_tables[index : index + 2])
        #print('next_cluster bytes', next_cluster)
        if allocation_status == 'Allocated':
            sectors.append(sec1)
            sectors.append(sec2)

            if next_cluster == 0xffff:
                #print('***sec2', sec2)
                break

            else:
                cluster_num += 1

            counter += 2

        else:
            sec1 = (cluster_num - 2) * blocks_per_cluster + first_cluster_sector
            sec2 = (cluster_num - 2) * blocks_per_cluster + first_cluster_sector + 1

            if next_cluster != 0x0000 and next_cluster != 0xffff:
                cluster_num += 1
                continue
            sectors.append(sec1)
            sectors.append(sec2)
            cluster_num += 1
            counter += 2

    res = []
    line = ''
    for i in range(0, len(sectors)):
        #print(sectors[i])
        if i%8 == 0:
            res.append(line+'\n')
            line = str(sectors[i])+ ' '
        else:
            line += str(sectors[i]) + ' '

    res.append(line+'\n')

    return res

def get_direntry_data(f, metadata_address, info):
    sector_size = info['sectorsize']
    cluster_size = info['blocks_per_cluster']
    root_dir_start = info['root_dir_start']
    root_dir_end = info['root_dir_end']
    last_direntry_address = 2 + info['n_dir_entries']

    dir_info = dict()
    filetypes = dict({0x01: 'Read Only', 0x02: 'Hidden', 0x04: 'System', 0x08: 'Volume Label', 0x10: 'Directory', 0x20: 'Archive'})

    #print('metadata address', metadata_address)

    if metadata_address <= last_direntry_address:
        direntry_address = root_dir_start + (metadata_address - 3)*32
        print(direntry_address)
        direntry = f[direntry_address:direntry_address +32]

    else:
        offset = (metadata_address - 515) * 32
        #print('offset ', offset)
        direntry_address = root_dir_end + offset
        print(direntry_address, (info['n_dir_entries']*32 + root_dir_start+offset))
        direntry = f[direntry_address:direntry_address +32]

    #print(direntry[:0x0b])
    filename = ''
    if direntry[0] == 0xe5:
        dir_info['allocation_status'] = 'Not Allocated'
        filename = direntry[1:0x0b].decode('utf-8')

    else:
        dir_info['allocation_status'] = 'Allocated'
        filename = direntry[0:0x0b].decode('utf-8')

    elems = filename.split()

    if len(elems) > 1:
        filename = '.'.join(elems)
    #print(filename)
    dir_info['filename'] = 'Name: '+filename

    filetype = direntry[0x0b]
    type1 = filetype&0x0f
    type2 = filetype&0xf0
    fileattrib = ''

    if filetype == 0x0f:
        n_lfns = 0x0f&direntry[0]
        total = f[direntry_address:direntry_address +32*(n_lfns + 1)]
        lfns = f[direntry_address:direntry_address +32*n_lfns]
        direntry = f[direntry_address +32*n_lfns: direntry_address +32*n_lfns + 32]
        filename = ''

        for i in range(0, n_lfns):
            lfn = lfns[i*32:i*32 + 32]
            temp_name = lfn[1:0x0b].decode('utf-8') + lfn[0x0e:0x1a].decode('utf-8') + direntry[0x1b:].decode('utf-8')
            filename = filename + temp_name

        if direntry[0] == 0xe5:
            dir_info['allocation_status'] = 'Not Allocated'
            #filename = direntry[1:0x0b].decode('utf-8')

        else:
            dir_info['allocation_status'] = 'Allocated'
            #filename = direntry[0:0x0b].decode('utf-8')

    if filetype == 0x10:
        fileattrib = 'Directory'

    else:
        filetype_str = ''
        if type1 != 0:
            filetype_str += filetypes[type1]
        filetype_str += ', '+ filetypes[type2]
        fileattrib = 'File'
        fileattrib += ', '+filetype_str
        #if filetype_str == 'Archive':
            #fileattrib += ', '+filetype_str

    fileattrib = 'File Attributes: '+fileattrib
    dir_info['file_attrib'] = fileattrib

    created_date = decode_fat_day(direntry[0x10:0x12])
    created_time = decode_fat_time(direntry[0x0e:0x10])

    accessed_time = decode_fat_time(direntry[0x14:0x16])
    accessed_date = decode_fat_day(direntry[0x12:0x14])

    written_time = decode_fat_time(direntry[0x16:0x18])
    written_date = decode_fat_day(direntry[0x18:0x1a])

    dir_info['written'] = 'Written:\t'+written_date+' '+written_time
    dir_info['accessed'] = 'Accessed:\t'+accessed_date+' '+accessed_time
    dir_info['created'] = 'Created:\t'+created_date+' '+created_time

    starting_cluster = as_unsigned(direntry[0x1a:0x1c])
    file_size = as_unsigned(direntry[0x1c:0x20])

    file_sectors = math.ceil(file_size/sector_size)

    cluster_tables = f[sector_size : sector_size *info['blocks_per_fat']]
    #cluster_tables = f[info['first_cluster_sector']*sector_size:]
    #print('starting cluster: ',starting_cluster,'\n', 'file size: ', file_size)

    sectors = []

    if filetype == 0x10:
        sectors, dirsize = get_dir_cluster_run(cluster_tables, sector_size, info['n_fats'], info['blocks_per_fat'], info['blocks_per_cluster'], starting_cluster, info['first_cluster_sector'], dir_info['allocation_status'])
        file_size = dirsize

    else:
        sectors = get_cluster_run(cluster_tables, sector_size, info['n_fats'], info['blocks_per_fat'], info['blocks_per_cluster'], starting_cluster, info['first_cluster_sector'], file_sectors, dir_info['allocation_status'], fileattrib)

    dir_info['filesize'] = 'Size: '+str(file_size)

    #print('cluster 5 :',cluster_tables[10:12])

    return dir_info, sectors

def istat_fat16(f, address, sector_size=512, offset=0):
    fat_contents = f.read()
    fat_contents = fat_contents[offset*sector_size:]
    boot_info = parse_boot_block(fat_contents)
    sector_size = boot_info['sectorsize']
    print('\n\n\n')
    dir_res, sectors = get_direntry_data(fat_contents, address, boot_info)

    res = []

    res.append('Directory Entry: '+str(address)+'\n')
    res.append(dir_res['allocation_status']+'\n')
    res.append(dir_res['file_attrib']+'\n')
    res.append(dir_res['filesize']+'\n')
    res.append(dir_res['filename']+'\n')
    res.append('\n')
    res.append('Directory Entry Times:\n')
    res.append(dir_res['written']+'\n')
    res.append(dir_res['accessed']+'\n')
    res.append(dir_res['created']+'\n')
    res.append('\n')
    res.append('Sectors:\n')
    res += sectors
    """for line in sectors:
        print(line)"""

    return res

if __name__ == '__main__':
    # The code below just exercises the time/date decoder and need not be included
    # in your final submission!
    #
    # values below are from the directory entry in adams.dd that corresponds to the
    # creation date/time of the `IMAGES` directory in the root directory, at
    # metadata address 5; it starts at offset 0x5240 from the start of the image
    print(decode_fat_day(bytes.fromhex('E138')), decode_fat_time(bytes.fromhex('C479'), 0))


"""
문제 설명
준식이의 모엄 1
문제
준식이의 모엄 은 준식이가 2차원 N × M 격자 세상에서 떠나는 모험을 주제로 한 게임이다. 당신은 이 게임의 개발자가 되었다.

준식이는 2차원 N × M 격자 세상의 어딘가에 위치해 있다. 플레이어는 L , R , U , D 입력을 통해 준식이를 왼쪽, 오른쪽, 위, 아래 칸으로 이동시킬 수 있다. 하지만 만약 이동하려는 칸이 격자 바깥이거나, 벽인 경우 준식이는 플레이어의 입력을 무시하고 제자리에서 이동하지 않는다.

2차원 N × M 격자 세상과 플레이어의 입력이 주어질 때, 플레이어의 모든 입력이 끝난 후의 준식이의 위치는 어디일까?

입력
첫째 줄에 테스트 케이스의 개수 T가 주어진다.

각 테스트 케이스의 첫째 줄에 2차원 격자 세상의 크기 N, M (1 ≤ N, M ≤ 8) 이 주어진다. N 은 격자의 세로 길이이고, M 은 가로 길이이다.

둘째 줄부터 N 개의 줄에 2차원 N × M 격자 세상 S 가 주어진다.

S 에서 @ 는 단 한 번 등장하며, 준식이를 의미한다.

나머지 위치의 문자는 . 이거나 # 이다. . 은 빈 칸을 의미한다. 준식이는 빈 칸으로 자유롭게 이동할 수 있다. # 은 벽을 의미한다. 준식이는 벽이 있는 칸으로 이동할 수 없다.

셋째 줄에 플레이어의 입력의 길이 K (1 ≤ K ≤ 100) 이 주어진다.

넷째 줄에 플레이어의 입력 T 가 주어진다. T 는 길이가 K 인 문자열이며 L , R , U , D 만으로 구성되어 있다. 플레이어의 입력은 입력된 순서대로 주어지며, 준식이를 격자 바깥이나 벽으로 이동하게 하는 입력이 있을 수 있다.

출력
각 테스트 케이스마다 플레이어의 모든 입력이 끝난 후의 준식이의 위치를 의미하는 두 정수 R, C (1 ≤ R, C ≤ 8) 를 출력한다. R 은 격자에서 행 번호를 의미하고 C 는 열 번호를 의미한다.

 123
1...
2...
3.@.
예를 들어 위 그림에서 준식이는 (3, 2) 에 위치하고 있다.

예제 입력 1
6
5 5
@....
####.
.....
.####
.....
16
RRRRDDLLLLDDRRRR
3 4
#.##
#...
#..@
4
LLUU
3 8
.......@
###..###
........
10
LDDLLDLLDR
3 3
.#.
#@#
.#.
4
LRUD
4 5
@#.#.
.#.#.
.###.
.....
10
URRDDLDRRR
2 2
@.
..
9
RDLURRDLU
예제 출력 1
5 5
1 2
3 5
2 2
4 4
1 1
힌트
입력과 출력 스트림은 분리되어있기 때문에 입력을 받자마자 출력해도 되고, 저장해뒀다가 맨 마지막에 몰아서 출력해도 됩니다. 여러 테스트 케이스로 분리되어있는 문제는 맨 마지막에 몰아서 출력하면 출력을 확인하기 편합니다.

즉시 출력하는 예시
6
5 5
@....
####.
.....
.####
.....
16
RRRRDDLLLLDDRRRR
5 5 // 출력
3 4
#.##
#...
#..@
4
LLUU
1 2 // 출력
3 8
.......@
###..###
........
10
LDDLLDLLDR
3 5 // 출력
3 3
.#.
#@#
.#.
4
LRUD
2 2 // 출력
4 5
@#.#.
.#.#.
.###.
.....
10
URRDDLDRRR
4 4 // 출력
2 2
@.
..
9
RDLURRDLU
1 1 // 출력
몰아서 출력하는 예시
6
5 5
@....
####.
.....
.####
.....
16
RRRRDDLLLLDDRRRR
3 4
#.##
#...
#..@
4
LLUU
3 8
.......@
###..###
........
10
LDDLLDLLDR
3 3
.#.
#@#
.#.
4
LRUD
4 5
@#.#.
.#.#.
.###.
.....
10
URRDDLDRRR
2 2
@.
..
9
RDLURRDLU
5 5 // 출력
2 2 // 출력
3 5 // 출력
2 2 // 출력
4 4 // 출력
1 1 // 출력
"""
def adventure(world1, h, w, command1):
    junsik_h = -1;
    junsik_w = -1;
    for i in range(h):
        for j in range(w):
            if world1[i][j] == '@':
                junsik_h = i
                junsik_w = j
    for idx, val in enumerate(command1):
        j_h = junsik_h
        j_w = junsik_w
        if val == 'R':
            j_w += 1
        elif val == 'L':
            j_w -= 1
        elif val == 'U':
            j_h -= 1
        elif val == 'D':
            j_h += 1
        else:
            print("err")
        if j_h < 0 or j_h > h-1 or j_w < 0 or j_w > w-1:
            #print("continued", h, w, j_h, j_w)
            continue
        elif world1[j_h][j_w] != '#':
            junsik_h = j_h
            junsik_w = j_w
        #print(val, junsik_h, junsik_w)
    answer.append([junsik_h+1, junsik_w+1])

testcase = int(input().strip())
height = 0
width = 0
answer = []
for _ in range(testcase):
    height, width = (map(int, input().strip().split(' ')))
    world = []
    for _ in range(height):
        world.append(input().strip())
    command_size = int(input())
    command = input()

    adventure(world, height, width, command)

for idx in range(len(answer)):
    print(answer[idx][0], answer[idx][1])


import fileinput

lines = [line for line in fileinput.input()].join('\n')

cals = sorted((sum(map(int, items.split())) for items in lines.split("\n\n")))

# part 1
print(cals[-1])

# part 2
print(sum(cals[-3:]))


# https://lost-contact.mit.edu/afs//umich.edu/user/j/o/joaander/Public/hoomd-web/doc/create_random_polymers-example.html

# ---- create_random_polymers.py ----
from hoomd import *
# from hoomd_script import *
import math
# parameters
phi_P = 0.25
n_poly = 600
T = 1.2
polymer1 = dict(bond_len=1.2, type=['A']*6 + ['B']*7 + ['A']*6,
                bond="linear", count=n_poly)
# perform some simple math to find the length of the box
N = len(polymer1['type']) * polymer1['count']
# generate the polymer system
init.create_random_polymers(box=data.boxdim(volume=math.pi * N / (6.0 * phi_P)), polymers=[polymer1],
                            separation=dict(A=0.35, B=0.35), seed=12)
# force field setup
harmonic = bond.harmonic()
harmonic.bond_coeff.set('polymer', k=330.0, r0=0.84)
lj = pair.lj(r_cut=3.0)
lj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0)
lj.pair_coeff.set('A', 'B', epsilon=1.0, sigma=1.0)
lj.pair_coeff.set('B', 'B', epsilon=1.0, sigma=1.0)
# dump every 100,000 steps
dump.xml(filename="create_random_polymers.xml", vis=True)
dump.dcd(filename="create_random_polymers.dcd", period=100000)
# integrate NVT for a bunch of time steps
all = group.all()
integrate.mode_standard(dt=0.005)
integrate.nvt(group=all, T=1.2, tau=0.5)
run(2000)
# uncomment the next run() command if you have a few hours to spare
# running this on a GPU the resulting dump files should show the
# polymers self-assembling into the hex phase
# run(10e6)


# -*- coding:utf-8 -*-
import sqlite3
import cPickle as pickle

class User(object):
    def __init__(self, name):
        self.name = name
        self.body = [name, name]

class DbTest(object):
    def __init__(self, db_file="test.db"):
        self.__connector = sqlite3.connect(db_file)
        self.__cursor = self.__connector.cursor()
        self.create_table_if_not_exist()

    def create_table_if_not_exist(self):
        self.__cursor.execute('''CREATE TABLE IF NOT EXISTS table_users
                      (user_id text primary key, user_data blob)''')
        self.__connector.commit()

    def test_write(self, user):
        try:
            self.__cursor.execute('INSERT INTO table_users(user_id, user_data) values(?, ?)', (user.name, sqlite3.Binary(pickle.dumps(user, protocol=2))))
            self.__connector.commit()
        except Exception as ex:
            print("Exception happen when insert into table, user_str=%s" % user.name)

    def test_read(self):
        self.__cursor.execute("select user_data from table_users")
        users = self.__cursor.fetchall()
        if users:
            print("length: %d" % len(users))
            print(users[0])
            return [pickle.loads(str(user[0])) for user in users]
        else:
            return []

if __name__ == '__main__':
    dbTest = DbTest()
    dbTest.test_write(User(u'吴海峰'))
    dbTest.test_write(User(u'画画'))
    users = dbTest.test_read()
    for user in users:
        print(user.name)
        for body in user.body:
            print(body)


import fileinput
import math
import re
import time
from collections import defaultdict, namedtuple

PATTERN = [0, 1, 0, -1]

def parse(lines):
    return [int(x) for x in [line for line in lines][0]]

def build_pattern(idx, length):
    pattern = []
    for chunk in [[x] * (idx + 1) for x in PATTERN]:
        pattern += chunk
    pattern.append(pattern.pop(0))

    while len(pattern) < length:
        pattern += pattern

    return pattern

def part1(lines):
    phase = parse(lines)

    for _ in range(100):
        new_phase = []
        for i in range(len(phase)):
            pattern = build_pattern(i, len(phase))

            eq = list(zip(phase, pattern))

            new_phase.append(abs(sum([x * y for x, y in eq])) % 10)

        phase = new_phase

    return "".join(str(x) for x in phase[0:8])

def part2(lines):
    phase = parse(lines) * 10000
    offset = int("".join(map(str, phase[:7])))
    phase = phase[offset:]

    for _ in range(100):
        s = sum(phase)
        new_phase = []
        for i in range(len(phase)):
            new_phase += [((s % 10) + 10) % 10]
            s -= phase[i]
        phase = new_phase

    return "".join(str(x) for x in phase[0:8])

parts = (part1, part2)

if __name__ == "__main__":
    lines = list(fileinput.input())

    print("part 1: %s" % (part1(lines),))
    print("part 2: %s" % (part2(lines),))


import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import ResNet50
import numpy as np
import GPUtil
import time
import argparse
import sys
import warnings
warnings.filterwarnings(action='ignore')

# TO print GPU Stat
class CustomCallback(keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None):
        keys = list(logs.keys())
        print()
        GPUs = GPUtil.getGPUs()
        for GPU in GPUs:
            print()
            print("GPU ID : {}, Memory Free : {},  Memory Used : {}, Memory Temp : {}"
                  .format(GPU.id, GPU.memoryFree,GPU.memoryUsed,GPU.temperature))
            print()

def init_gpus(soft_device_placement=True, log_device_placement=False, create_virtual_devices=False, memory_limit=11):

    tf.config.set_soft_device_placement(soft_device_placement)
    tf.debugging.set_log_device_placement(log_device_placement)

    gpus = tf.config.experimental.list_physical_devices('GPU')
    if gpus:
        # If there is only one GPU, create two logical virtual devices for developing
        # on a machine with only one GPU installed
        try:
            # Create 2 virtual GPUs on each physical GPU with the given memory_limit GPU memory
            if create_virtual_devices and len(gpus) == 1:
                for gpu in gpus:
                    tf.config.experimental.set_virtual_device_configuration(
                        gpu,
                        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit*10000),
                         tf.config.experimental.VirtualDeviceConfiguration(memory_limit*10000)]
                    )
            else:
                # Currently, memory growth needs to be the same across GPUs
                for gpu in gpus:
                    tf.config.experimental.set_memory_growth(gpu, True)

        except RuntimeError as e:
            # Memory growth must be set before GPUs have been initialized
            print(e)

        # print out physical and logical GPUs
        logical_gpus = tf.config.experimental.list_logical_devices('GPU')
        print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")

    else:
        print("No visible GPU is detected...")
        print("Possibly a mismatch in CUDA version if using NVIDIA 2xxx GPU")

def main ():
    #Model Setting
    parser = argparse.ArgumentParser(description='tensorflow gpu_stress_test')
    parser.add_argument('--vram', type=int, default=24,
                        help ='vram size of each gpu (default:24)')
    parser.add_argument('--num_gpus', type=int, default=2,
                        help ='number of gpus within the machine (default:2)')
    parser.add_argument('--epochs', type=int, default=500,
                        help ='number of epoch to train(default:500)')
    parser.add_argument('--num_classes' ,type=int, default=10,
                        help='number of classification classes (default : 10)')
    args=parser.parse_args()
    init_gpus(
        log_device_placement=False,
        create_virtual_devices=False,
        memory_limit=args.vram
    )

    cifar = tf.keras.datasets.cifar10

    (x_train, y_train), (x_test, y_test) = cifar.load_data()
    x_train, x_test = x_train / 255.0, x_test / 255.0
    x_train = tf.concat([x_train, x_train, x_train, x_train, x_train], 0)
    y_train = tf.concat([y_train, y_train, y_train, y_train, y_train], 0)

    classes = args.num_classes
    batch = 512 * args.vram * args.num_gpus
    epoch = args.epochs

    train_num=0
    s_time=time.time()

    strategy = tf.distribute.MirroredStrategy() # multi gpu
    with strategy.scope():
        parallel_model = ResNet50(weights=None, input_shape=(32, 32, 3), classes=classes)
        parallel_model.compile(loss='sparse_categorical_crossentropy', optimizer=keras.optimizers.SGD(learning_rate=0.1, momentum=0.9),metrics=[keras.metrics.SparseCategoricalAccuracy()])

    test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))
    test_dataset = test_dataset.batch(batch, drop_remainder=True)

    print("======================================================================")
    print("Train Start")
    print("======================================================================")

    # Train Start
    parallel_model.fit(x_train, y_train, epochs=epoch, validation_data=test_dataset, validation_freq=1, batch_size=batch,callbacks=[CustomCallback()])
    parallel_model.evaluate(x_test, y_test, verbose=2)
    print("======================================================================")
    print("Train End")
    print("Total Elapsed Time : {}".format(time.time()-s_time))
    print("======================================================================")
    tf.keras.backend.clear_session()

if __name__ == '__main__':
    main()


# This is the file that implements a flask server to do inferences. It's the file that you will modify to
# implement the scoring for your own algorithm.

import os
import json
import torch
import flask
from torchtext import data
from torchtext import datasets

#Define the path
prefix = '/opt/ml/'
model_path = os.path.join(prefix, 'model')

#Torch use GPU if available
if torch.cuda.is_available():
    torch.cuda.set_device(0)
    device = torch.device('cuda:{}'.format(0))
else:
    device = torch.device('cpu')

# Load the model components
inputs = data.Field(lower=True, tokenize='spacy')
answers = data.Field(sequential=False)
text_fields = {'sentence1': ('premise', inputs),
             'sentence2': ('hypothesis', inputs)}
inputs.vocab = torch.load(os.path.join(model_path, 'inputs_vocab.pt'))
model = torch.load(os.path.join(model_path, 'model.pt'), map_location=device)

# The flask app for serving predictions
app = flask.Flask(__name__)
@app.route('/ping', methods=['GET'])
def ping():
    # Check if the classifier was loaded correctly
    try:
        model
        status = 200
    except:
        status = 400
    return flask.Response(response= json.dumps(' '), status=status, mimetype='application/json' )

@app.route('/invocations', methods=['POST'])
def transformation():
    # Get input JSON data and convert it to a DF
    input_json = flask.request.get_json()
    json_input = json.dumps(input_json)
    example = data.example.Example.fromJSON(json_input, text_fields)
    example_list = [example]
    # Tokenize data and predict
    if isinstance(text_fields, dict):
        fields, field_dict=[],text_fields
        for field in field_dict.values():
            if isinstance(field, list):
                fields.extend(field)
            else:
                fields.append(field)

    predict = data.dataset.Dataset(examples = example_list, fields = fields)
    predict_iter = data.iterator.Iterator(dataset = predict, batch_size = 1, device=device)
    predict_item = next(iter(predict_iter))
    model.eval()
    answer = model(predict_item)
    xmax = int(torch.max(answer, 1)[1])

    # Transform predicted labels (1, 2, and 3) to easier to understand as (Entailment, Contradiction, and Neutral)
    prediction = lambda x: 'Entailment' if x == 1 else ('Contradiction' if
                       x == 2 else 'Neutral')
    label = prediction(xmax)
    percentage = float(torch.exp(answer[0][xmax])/torch.sum(torch.exp(answer)))
    percentage = '{:.2%}'.format(percentage)

    # Transform predictions to JSON
    result = {'label': label, 'probability': percentage}
    result = json.dumps(result)
    return flask.Response(response=result, status=200, mimetype='application/json')


import math
import numpy as np
import matplotlib.pyplot as plt

a = 0.2
b = 0.2
c = 4.05
x_max = []
x_min= []
y_max = []
y_min = []
z_max = []
z_min = []
r = []

def rk4(x,y):
    k1,l1,m1 = derivative(x,y,z)

    k2,l2,m2 = derivative(x + k1*h/2, y + l1*h/2, z + m1*h/2)

    k3,l3,m3 = derivative(x + k2*h/2, y + l2*h/2, z + m2*h/2)

    k4,l4,m4 = derivative(x + k3*h, y + l3*h, z+l3*h)

    k = (h/6)*(k1 + 2*k2 + 2*k3 + k4)
    l = (h/6)*(l1 + 2*l2 + 2*l3 + l4)
    m = (h/6)*(m1 + 2*m2 + 2*m3 + m4)

    return k,l,m

def derivative(x,y,z):
  dxdt = -y - z
  dydt = x + a*y
  dzdt = b + z*(x - c)
  return dxdt,dydt,dzdt
while c<4.5:

  x = 1.0
  y = 1.0
  z = 1.0
  t = 0.0
  h = 0.01

  X,Y,Z,T = [],[],[],[]

  dxdt,dydt,dzdt = derivative(x,y,z)

  while t < 400.0:

    t = t+h
    k,l,m = rk4(x,y)
    x = x+k
    y = y+l
    z = z+m

    X.append(x),Y.append(y),Z.append(z),T.append(t)

  min_x, max_x = [],[]
  min_y, max_y = [],[]
  min_z, max_z = [],[]

  for i in range(20000,(len(X)-1)):
    if(X[i-1] > X[i] < X[i + 1]):
      min_x.append(X[i])
    if(X[i-1] < X[i] > X[i + 1]):
      max_x.append(X[i])

  x_max.append(list(set(max_x)))
  x_min.append(list(set(min_x)))

  for i in range(20000,(len(Y)-1)):
    if(Y[i-1] > Y[i] < Y[i + 1]):
      min_y.append(Y[i])
    if(Y[i-1] < Y[i] > Y[i + 1]):
      max_y.append(Y[i])

  y_max.append(list(set(max_y)))
  y_min.append(list(set(min_y)))

  for i in range(20000,(len(Z)-1)):
    if(Z[i-1] > Z[i] < Z[i + 1]):
      min_z.append(Z[i])
    if(Z[i-1] < Z[i] > Z[i + 1]):
      max_z.append(Z[i])

  z_max.append(list(set(max_z)))
  z_min.append(list(set(min_z)))

  r.append(c)
  c = c+0.0002

fig = plt.figure(dpi=100)

for i in range(len(x_max)):
  plt.scatter([r[i] for j in range(len(x_max[i]))],x_max[i],s=0.05,c='black', marker = '.')
plt.title('Rossler System for a=0.2, b=0.2')
plt.xlabel('c')
plt.ylabel('x')
fig.tight_layout()
plt.show()
fig.savefig('bif2.png')


"""

>>> somar(5, 10)
15

>>> somar(5, 15)
20

"""

'''def somar(num1, num2):
    a = num1 + num2
    return a
'''

from tkinter import *
from random import randint

jogadas = 3
player = 0
selecionar = 0
ganhou = 0

hub = '''
Numero de jogadas restante: 3
Numero = 0
voce escolheu: NENHUM
'''

def SelecionarImpar():
    global selecionar
    selecionar = 1
    atualizarHub()

def SelecionarPar():
    global selecionar
    selecionar = 2
    atualizarHub()

def atualizarHub():
    global selecionar, player, jogadas
    string = "NENHUM"
    if selecionar == 1:
        string = "IMPAR"
    elif selecionar == 2:
        string = "PAR"
    hub = '''
    Numero de jogadas restante %i
    Numero selecionado %i
    Voce escolheu %s
    ''' % (jogadas, player, string)
    label['text'] = hub

def Jogar():
    global player, jogadas, ganhou, selecionar
    if jogadas == -2:
        # resetar as jogadas
        jogadas = 3
        player = selecionar = ganhou = 0
        atualizarHub()
        start['text'] = "Start"
        show['text'] = "---"

    elif jogadas == -1:
        show['text'] = "Voce ganhou [%i/3]" % (ganhou)
        show['fg'] = "green"
        start['text'] = "Resetar"
        jogadas -= 1
    elif jogadas == 0:
        # Caso já der 3 jogadas
        start['text'] = "Resultado"
        jogadas -= 1
    else:
        caption = numero.get()
        if len(caption) == 0:
            show['fg'] = "red"
            show['text'] = "Não a nenhum valor inserido"
            return

        if (caption.isnumeric()) == False:
            show['fg'] = "red"
            show['text'] = "O valor inserido não é numerico"
            return
        player = int(numero.get())  # pegaremos o valor do Entry
        if (player > 0 and player < 11) == False:
            show['fg'] = "red"
            show['text'] = "O valor inserido não é invalido[entre 1 e 10]"
            return
        if selecionar == 0:
            show['fg'] = "red"
            show['text'] = "Voce precisa escolher impar ou par"
            return
        computador = randint(1, 10)  # Valor aleatorio do computador
        total = player + computador  # total - valor somado
        string = "IMPAR"
        if (total % 2) == 0:
            string = "PAR"
        string = "Voce escolheu {} e o computador {} , no total de {} deu {}".format(player, computador, total, string)
        show['text'] = string
        show['fg'] = "blue"
        jogadas -= 1
        if (total % 2) == (selecionar - 1):
            # Caso o jogador ganhar
            ganhou += 1
        atualizarHub()

janela = Tk()
janela.title('Exercicio nº 068')
janela['bg'] = "white"
label = Label(janela, text=hub)
label.place(x=0, y=0)

impar = Button(janela, text='Impar', width=20, command=SelecionarImpar)
impar.place(x=40, y=100)

par = Button(janela, text='Par', width=20, command=SelecionarPar)
par.place(x=230, y=100)

start = Button(janela, text='Start', width=20, command=Jogar)
start.place(x=150, y=300)

numero = Entry(janela)
numero.place(x=40, y=170)

spec = Label(janela, text="Digite um numero de 1 a 10")
spec.place(x=145, y=170)

show = Label(janela, text="---")
show.place(x=0, y=380)

janela.geometry("400x400+200+200")
janela.mainloop()


#To study the performance of the student with the ID TRL_987
import csv
import plotly.graph_objects as og
import pandas as pd

df = pd.read_csv("data.csv")
student_df = df.loc[df["student_id"] == "TRL_987"]
print(student_df.groupby("level")["attempt"].mean())

fig = og.Figure(og.Bar(
    x = student_df.groupby("level")["attempt"].mean(),
    y = ["level 1", "level 2", "level 3", "level 4"],
    orientation = "h"
))
fig.show()


import numpy as np
from pprint import pprint
from random import randint
from src.env.env import Environment, EnvStatus
from src.agent.reactive import BrooksA
from src.agent.proactive import ProactiveAgent
if __name__ == '__main__':
    n_envs = 0
    results = []
    while n_envs < 1:

        rows = randint(5, 10)
        cols = randint(5, 10)
        t = randint(rows*cols // 10, rows*cols *2)
        dirty_percent = randint(0, 50)
        blocks_percent = randint(0, 50)
        childs = randint(2, 4)

        fired_times = [0, 0]
        cleaned_times = [0, 0]
        dirty_level = [[], []]
        invalid_env = False

        for i in range(30):
            try:
                en1 = Environment(rows, cols, lambda env, pos : BrooksA(env, pos), t, blocks_percent, dirty_percent, childs)
                en2 = Environment(rows, cols, lambda env, pos : ProactiveAgent(env, pos, 100), t, blocks_percent, dirty_percent, childs)
            except AssertionError:
                invalid_env = True
                break
            envs = [en1, en2]
            for i, env in enumerate(envs):
                env.run()
                if env.result == EnvStatus.ROBOT_FIRED:
                    fired_times[i] += 1
                if env.result == EnvStatus.HOUSE_CLEANED:
                    cleaned_times[i] += 1
                dirty_level[i].append(np.mean(env.dirty_history))

        if invalid_env:
            continue

        agents_result =  [(fired_times[i], cleaned_times[i], np.mean(dirty_level[i])) for i in range(2)]
        result = ((rows, cols, t, dirty_percent, blocks_percent, childs), agents_result)
        results.append(result)

        n_envs += 1

    pprint(results)


import numpy as np
import rdkit
from rdkit import Chem
from rdkit.Chem import rdmolfiles
import os
import math

def get_xray_positions(ref_directory):
    xray_positions = []

    # assign directories

    for filename in os.listdir(ref_directory):
        f = os.path.join(ref_directory, filename)
        # checking if it is a file
        if os.path.isfile(f):
            # get mol of xray structure
            print("Getting PDB: ", f)
            xray_mol = rdmolfiles.MolFromPDBFile(
                f,
                sanitize=True,
                removeHs=False,
                proximityBonding=False,
            )

    # get 3Dpoints of atoms in xray structure, store in xray_positions
    for i, atom in enumerate(xray_mol.GetAtoms()):
        positions = xray_mol.GetConformer().GetAtomPosition(i)
        xray_positions.append(positions)
    print("XRAY positions appended")
    return xray_positions

def compute_geom_distance(centroid_1, point_2):

    return np.sqrt(
        ((point_2.x) - (centroid_1.x)) ** 2
        + ((point_2.y) - (centroid_1.y)) ** 2
        + ((point_2.z) - (centroid_1.z)) ** 2
    )

def total_entropy(N_total, dict_total_entropy):
    result = 0

    for key, value in dict_total_entropy.items():
        result += (int(key) / (N_total)) * float(value)

    return result

def calculate_entropy_channel(N_w, X, O):
    x_i = X / N_w
    o_i = O / N_w

    try:
        H_w = -((x_i) * math.log2(x_i) + (o_i) * math.log2(o_i))
        return H_w
    except ValueError:
        if x_i == 0:
            H_w = -((o_i) * math.log2(o_i))
            return H_w

        elif o_i == 0:
            H_w = -((x_i) * math.log2(x_i))
            return H_w
        else:
            return 0


# setup.py
'''
Setup tools
'''
import re
import subprocess
from setuptools import setup, find_packages

NAME = 'pydroneapi'
VERSION = '0.1.2'
LICENSE = 'MIT'
AUTHOR = 'Jelili Adebello'
AUTHOR_EMAIL = 'jeliliadebello@gmail.com'
DESCRIPTION = 'Helper scripts to manage Drone API operations'
URL = 'https://github.com/bellyjay1005/pydroneci'
DOWNLOAD_URL = 'https://github.com/bellyjay1005/pydroneci/archive/refs/tags/v0.1.0.tar.gz'

REQUIRES = [
    'boto3',
    'requests',
]

REQUIRES_TEST = [
    'PyYAML>=5.3.1',
    'pylint>=2.5.0',
    'pytest>=5.4.1',
    'pytest-cov>=2.8.1',
    'bandit>=1.6.2',
    'safety>=1.10.3',
    'requests_mock',
    'setuptools>=67.8.0'
]

LONG_DESCRIPTION = 'A DRONE CI - Python helper scripts to manage API interactions and operations.'

CLASSIFIERS = [
    'Development Status :: 3 - Alpha',
    'Intended Audience :: Developers',
    'Topic :: Software Development :: Build Tools',
    'License :: OSI Approved :: MIT License',
    'Programming Language :: Python :: 3',
    'Operating System :: OS Independent',
]

with open('README.md', 'r') as fh:
    LONG_DESCRIPTION = fh.read()

def has_ssh() -> bool:
    '''
    Check that the user has ssh access to github.com
    First it will verify if ssh is installed in $PATH
    then check if we can authenticate to github.com
    over ssh. Returns false if either of these are untrue
    '''
    result = None
    which_ssh = subprocess.run(['which', 'ssh'], check=False)
    if which_ssh.returncode == 0:
        result = subprocess.Popen(['ssh', '-Tq', 'git@github.com', '&>', '/dev/null'])
        result.communicate()
    if not result or result.returncode == 255:
        return False
    return True

def flip_ssh(requires: list) -> list:
    '''
    Attempt to authenticate with ssh to github.com
    If permission is denied then flip the ssh dependencies
    to https dependencies automatically.
    '''
    # Not authenticated via ssh. Change ssh to https dependencies
    if not has_ssh():
        requires = list(map(
            lambda x: re.sub(r'ssh://git@', 'https://', x), requires
        ))
    return requires

setup(
    name=NAME,
    version=VERSION,
    license=LICENSE,
    author=AUTHOR,
    author_email=AUTHOR_EMAIL,
    description=DESCRIPTION,
    download_url=DOWNLOAD_URL,
    long_description=LONG_DESCRIPTION,
    classifiers=CLASSIFIERS,
    long_description_content_type="text/markdown",
    url=URL,
    packages=find_packages(exclude=("tests", "tests.*")),
    install_requires=flip_ssh(REQUIRES),
    extras_require={
        'dev': flip_ssh(REQUIRES_TEST),
    },
    include_package_data=True,
    python_requires='>=3.6'
)


# edit distance
# minimum number of operations to convert word1 to word2
# allowed operations:
# insert a character
# delete a character
# replace a character

# recursive solution
def minDistance(word1, word2, i, j):
    if i < 0:
        return j+1
    if j < 0:
        return i+1

    if word1[i] == word2[j]:
        return minDistance(word1, word2, i-1, j-1)
    insert = minDistance(word1, word2, i, j-1)
    delete = minDistance(word1, word2, i-1, j)
    replace = minDistance(word1, word2, i-1, j-1)
    return 1 + min(insert, delete, replace)

# memoization
def minDistanceMem(word1, word2, i, j, dp):
    if i < 0:
        return j+1
    if j < 0:
        return i+1
    if dp[i][j] != -1:
        return dp[i][j]

    if word1[i] == word2[j]:
        dp[i][j] = minDistanceMem(word1, word2, i-1, j-1, dp)
    else:
        insert = minDistanceMem(word1, word2, i, j-1, dp)
        delete = minDistanceMem(word1, word2, i-1, j, dp)
        replace = minDistanceMem(word1, word2, i-1, j-1, dp)
        dp[i][j] = 1 + min(insert, delete, replace)
    return dp[i][j]

# tabulation
def minDistanceTab(word1, word2):
    n = len(word1)
    m = len(word2)
    dp = [[0 for i in range(m+1)] for j in range(n+1)]

    for i in range(n+1):
        dp[i][0] = i
    for j in range(m+1):
        dp[0][j] = j

    for i in range(1, n+1):
        for j in range(1, m+1):
            if word1[i-1] == word2[j-1]:
                dp[i][j] = dp[i-1][j-1]
            else:
                insert = dp[i][j-1]
                delete = dp[i-1][j]
                replace = dp[i-1][j-1]
                dp[i][j] = 1 + min(insert, delete, replace)

    return dp[n][m]

# space optimization
def minDistanceOpt(word1, word2):
    n = len(word1)
    m = len(word2)
    dp = [0 for i in range(m+1)]
    curr = [0 for i in range(m+1)]

    for i in range(m+1):
        dp[i] = i

    for i in range(1, n+1):
        curr[0] = i
        for j in range(1, m+1):
            if word1[i-1] == word2[j-1]:
                curr[j] = dp[j-1]
            else:
                insert = curr[j-1]
                delete = dp[j]
                replace = dp[j-1]
                curr[j] = 1 + min(insert, delete, replace)
        dp = curr.copy()

    return dp[m]

s1 = "horse"
s2 = "ros"
print(minDistance(s1, s2, len(s1)-1, len(s2)-1))
dp = [[-1 for i in range(len(s2))] for j in range(len(s1))]
print(minDistanceMem(s1, s2, len(s1)-1, len(s2)-1, dp))
print(minDistanceTab(s1, s2))
print(minDistanceOpt(s1, s2))


import airflow
from airflow import models
from airflow.operators import bash_operator
from airflow.contrib.operators.gcs_to_bq import GoogleCloudStorageToBigQueryOperator

args = {
    'owner': 'Anand Raghunathan',
    'start_date': airflow.utils.dates.days_ago(2)
}

dag = models.DAG(
    dag_id='direct_load_gcs_to_bigquery', default_args=args, schedule_interval=None)

#create_dataset = bash_operator.BashOperator(
#    task_id='create_dataset',
#    bash_command='bq mk gcs_to_bq_dataset',
#    dag=dag)

gcs_sensor = GoogleCloudStorageObjectSensor(
    task_id='sensor_for-gcs',
    bucket=models.Variable.get('input_bucket_name'),
    #object='file-name-prefix' + date + '.gz',
    object='usa_names.csv',
    #google_cloud_conn_id='google-cloud-storage-default',
    dag=dag)

# [START gcs_to_bq]
load_csv = GoogleCloudStorageToBigQueryOperator(
    task_id = 'load_csv_on_gcs_to_bq',
    bucket = models.Variable.get('input_bucket_name'),
    source_objects = ['usa_names.csv'],
    destination_project_dataset_table='dataset.usa_names',
    #schema_objects=models.Variable.get('schema_fullpath')
    schema_fields=[
        {'name': 'state', 'type': 'STRING', 'mode': 'NULLABLE'},
        {'name': 'gender', 'type': 'STRING', 'mode': 'NULLABLE'},
        {'name': 'year', 'type': 'STRING', 'mode': 'NULLABLE'},
        {'name': 'name', 'type': 'STRING', 'mode': 'NULLABLE'},
        {'name': 'number', 'type': 'STRING', 'mode': 'NULLABLE'},
        {'name': 'created_date', 'type': 'STRING', 'mode': 'NULLABLE'},
    ],
    write_disposition='WRITE_TRUNCATE',
    dag=dag)
# [END gcs_to_bq]

load_csv.set_upstream(gcs_sensor)

#delete_dataset = bash_operator.BashOperator(
#    task_id='delete_dataset',
#    bash_command='bq rm -rf gcs_to_bq_dataset',
#    dag=dag)

#create_test_dataset >> load_csv #>> delete_test_dataset
load_csv


from subprocess import Popen, PIPE, STDOUT
from random import randint
import binascii
def startZplet(jardir, gamedir):
    if(gamedir != ''):
        p = Popen(['java', '-jar', jardir, 'ieeecig.advent.IOAgent', gamedir], stdin=PIPE, stdout=PIPE)
    else:
        p = Popen(['java', '-jar', jardir, 'ieeecig.advent.IOAgent'], stdin=PIPE, stdout=PIPE)
    return (readNarrative(p),p)

def postCommand(p, command):
    print("Response: " + command)
    p.stdin.write(bytes(command + "\n", "ascii"))
    p.stdin.flush()
    return readNarrative(p)

def readNarrative(p):
    narrative=""
    cont = True
    while cont:
        for line in p.stdout:
            if(line.decode("utf-8").startswith("BREAK-NARRATIVE")):
                print("BREAK")
                cont = False
                break
            narrative = narrative + line.decode("utf-8") + "\n"
    return narrative

def action(narrative):
    print("Narrative: " + narrative)
    commands = ["n", "s", "e", "w", "verbose", "yes", "no", "IEEECIG-ADVENT-QUIT-COMMAND", "IEEECIG-ADVENT-RESTART-COMMAND", "IEEECIG-ADVENT-SOFT-RESTART-COMMAND"]
    command = commands[randint(0,len(commands)-1)]
    if(len(command)%2==1):
        command = command + " "
    return command

print("Booting Z Machine...")
ret = startZplet('../Example Project/lib3rd/ieee-cig-advent-1.5.jar','../resources/monkey-and-bananas-v1.z8')
narrative = ret[0]
p = ret[1]
print("Z Machine Launched")
while True:
    command = action(narrative)
    narrative = postCommand(p, command)

Python 3.5 - Example Project/ZpletIOAgent.py


from conans import ConanFile, ConfigureEnvironment
import os, codecs, re
from conans.tools import download, untargz, cpu_count, os_info

class LibxsltConan(ConanFile):
    name = "libxslt"
    version = "1.1.29"
    url = "http://github.com/vitallium/conan-libxslt"
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [True, False]}
    default_options = "shared=False"
    src_dir = "libxslt-%s" % version
    license = "https://git.gnome.org/browse/libxslt/tree/Copyright"
    requires = "libxml2/2.9.4@vitallium/testing"

    def source(self):
        tar_name = "libxslt-%s.tar.gz" % self.version
        url = "http://xmlsoft.org/sources/" + tar_name
        download(url, tar_name)
        untargz(tar_name)
        os.unlink(tar_name)

    def configure(self):
        if self.settings.compiler == "Visual Studio":
            if self.options.shared and "MT" in str(self.settings.compiler.runtime):
                self.options.shared = False
            self.configure_options = "iconv=no xslt_debug=no debugger=no"
        else:
            self.configure_options = " \
                --without-python \
                --without-crypto \
                --without-debugger \
                --without-plugins \
                "

            if self.options.shared:
                self.configure_options += " --disable-static --enable-shared"
            else:
                self.configure_options += " --enable-static --disable-shared"

    def build(self):
        if self.settings.compiler == "Visual Studio":
            self.build_windows()
        else:
            self.build_with_configure()

    def build_windows(self):
        include_paths = ";".join(self.deps_cpp_info.include_paths)
        libs_paths = ";".join(self.deps_cpp_info.lib_paths)
        icu_libs = self.deps_cpp_info["icu"].libs
        icu_libs.append("wsock32")

        # add icu libs
        makefile_win_path = os.path.join(self.src_dir, "win32", "Makefile.msvc")
        encoding = self.detect_by_bom(makefile_win_path, "utf-8")
        patched_content = self.load(makefile_win_path, encoding)
        patched_content = re.sub("wsock32.lib", " ".join("%s.lib"%i for i in icu_libs), patched_content)
        self.save(makefile_win_path, patched_content)

        self.run('cd %s\win32 && cscript configure.js cruntime=/%s include=\"%s\" lib=\"%s" %s' % (
            self.src_dir,
            self.settings.compiler.runtime,
            include_paths,
            libs_paths,
            self.configure_options,
            ))
        self.run("cd %s\\win32 && nmake /f Makefile.msvc" % self.src_dir)

    def normalize_prefix_path(self, p):
        if os_info.is_windows:
            return p.replace('\\', '/')
        else:
            return p

    def build_with_configure(self):
        env = ConfigureEnvironment(self.deps_cpp_info, self.settings)
        command_env = env.command_line_env
        xml_config = self.normalize_prefix_path(self.deps_cpp_info["libxml2"].rootpath) + "/bin/xml2-config"

        if os_info.is_windows:
            command_env += " &&"
            command_env += ' set "XML_CONFIG=%s" &&' % xml_config
        else:
            command_env += ' XML_CONFIG="%s"' % xml_config

        self.run("%s sh %s/configure --prefix=%s %s" % (
            command_env,
            self.src_dir,
            self.normalize_prefix_path(self.package_folder),
            self.configure_options
            ))
        self.run("%s make -j %s" % (command_env, cpu_count()))
        self.run("%s make install" % command_env)

    def package(self):
        if self.settings.os != "Windows":
            return

        include_path = os.path.join(self.src_dir, "libxslt")
        self.copy("*.h", "include/libxslt", src=include_path, keep_path=True)

        if self.settings.os == "Windows":
            include_path = os.path.join(self.src_dir, "libexslt")
            self.copy("*.h", "include/libexslt", src=include_path, keep_path=True)

        self.copy(pattern="*.dll", dst="bin", src=self.src_dir, keep_path=False)
        self.copy(pattern="*.lib", dst="lib", src=self.src_dir, keep_path=False)

    def package_info(self):
        self.cpp_info.libs = ["libxslt"]

    # from https://github.com/SteffenL/conan-wxwidgets-custom/blob/master/conanfile.py#L260
    def load(self, path, encoding=None):
        encoding = detect_by_bom(path, "utf-8") if encoding is None else encoding
        with codecs.open(path, "rb", encoding=encoding) as f:
            return f.read()

    def save(self, path, content, encoding=None):
        with codecs.open(path, "wb", encoding=encoding) as f:
            f.write(content)

    # Ref.: http://stackoverflow.com/a/24370596
    def detect_by_bom(self,path,default):
        with open(path, 'rb') as f:
            raw = f.read(4)    #will read less if the file is smaller
        for enc,boms in \
                ('utf-8-sig',(codecs.BOM_UTF8,)),\
                ('utf-16',(codecs.BOM_UTF16_LE,codecs.BOM_UTF16_BE)),\
                ('utf-32',(codecs.BOM_UTF32_LE,codecs.BOM_UTF32_BE)):
            if any(raw.startswith(bom) for bom in boms): return enc
        return default


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

# == IMPORTATIONS == #

try:
    #- Librairies
    import tkinter as tk

except Exception as e:
    raise e

# == LOGIC PART == #

class Menu:

    def __init__(self, _language, _theme, _options_window, _about_page, _alert):
        '''
            initialisation des objets herites de <root>
        '''
        self.language = _language
        self.theme = _theme

        self.alert = _alert

        #- views
        self.options_window = _options_window
        self.about_window = _about_page

    def stop_program(self):
        '''
            ferme la fenetre et arrete le programme
        '''
        self.place.quit()

    def show_options_window(self):
        '''
            affiche la page des options
        '''
        self.options_window.initialize_window(self.place)

    def show_about_page(self):
        self.about_window.initialize_window()

    def show_help_pages(self):
        self.alert.create_classic_alert('link')

    def create_content(self, place):
        self.place = place
        '''
            creation du conteneur menu
        '''
        self.menu_bar = tk.Menu()

        '''
            creation des composants du menu
        '''
        #- Les composants directs (affiches constament)
        self.menu1 = tk.Menu(self.menu_bar, tearoff=0)
        self.menu2 = tk.Menu(self.menu_bar, tearoff=0)
        self.menu3 = tk.Menu(self.menu_bar, tearoff=0)

        #- Les composants indirects (affiches lorsque clique)
        self.menu1.add_command(label=self.language.get_text("options"), command=self.show_options_window)
        self.menu_bar.add_cascade(label=self.language.get_text("settings"), menu=self.menu1)

        self.menu2.add_command(label=self.language.get_text('about'), command=self.show_about_page)
        self.menu2.add_command(label=self.language.get_text('documentation'), command=self.show_help_pages)
        self.menu_bar.add_cascade(label=self.language.get_text('help'), menu=self.menu2)

        self.menu3.add_separator()
        self.menu3.add_command(label=self.language.get_text("quit"), command=self.stop_program)
        self.menu_bar.add_cascade(label=self.language.get_text('quit'), menu=self.menu3)

        return self.menu_bar


import math

class Node:
    def __init__(self, isLeaf, label, threshold):
        self.label = label
        self.threshold = threshold
        self.isLeaf = isLeaf
        self.children = []

class C45:
    """Decision Tree Classifier using C4.5 algorithm."""

    def __init__(self):
        self.data = []
        self.classes = []
        self.numAttributes = -1
        self.attrValues = {}
        self.attributes = []
        self.tree = None

    def preprocessData(self):
        for index, row in enumerate(self.data):
            for attr_index in range(self.numAttributes):
                if(not self.isAttrDiscrete(self.attributes[attr_index])):
                    self.data[index][attr_index] = float(
                        self.data[index][attr_index])

    def log(self, x):
        if x == 0:
            return 0
        else:
            return math.log(x, 2)

    def getMajClass(self, curData):
        freq = [0]*len(self.classes)
        for row in curData:
            index = self.classes.index(row[-1])
            freq[index] += 1
        maxInd = freq.index(max(freq))
        return self.classes[maxInd]

    def allSameClass(self, data):
        for row in data:
            if row[-1] != data[0][-1]:
                return False
        return data[0][-1]

    def isAttrDiscrete(self, attribute):
        if attribute not in self.attributes:
            raise ValueError("Attribute not listed")
        elif len(self.attrValues[attribute]) == 1 and self.attrValues[attribute][0] == "continuous":
            return False
        else:
            return True

    def entropy(self, dataSet):
        S = len(dataSet)
        if S == 0:
            return 0
        num_classes = [0 for i in self.classes]
        for row in dataSet:
            classIndex = list(self.classes).index(row[-1])
            num_classes[classIndex] += 1
        num_classes = [x/S for x in num_classes]
        ent = 0
        for num in num_classes:
            ent += num*self.log(num)
        return ent*-1

    def gain(self, unionSet, subsets):
        # input : data and disjoint subsets of it
        S = len(unionSet)
        weights = [len(subset)/S for subset in subsets]
        impurityAfterSplit = 0
        for i in range(len(subsets)):
            impurityAfterSplit += weights[i]*self.entropy(subsets[i])

        totalGain = self.entropy(unionSet) - impurityAfterSplit
        return totalGain

    def split_info(self, unionSet, subsets):
        ans = 0
        S = len(unionSet)
        probs = [len(subset)/S for subset in subsets]
        for p in probs:
            ans += p * self.log(p)
        return ans*-1

    def gain_ratio(self, unionSet, subsets):
        return self.gain(unionSet, subsets)/self.split_info(unionSet, subsets)

    def fit(self, X, y, classes, attrValues):
        self.classes = classes
        self.attrValues = attrValues
        self.numAttributes = len(self.attrValues.keys())
        self.attributes = list(self.attrValues.keys())
        self.data = []
        for (idx, row) in enumerate(X):
            new_row = list(row) + [y[idx]]
            self.data.append(new_row)
        self.preprocessData()
        self.tree = self.recursiveGenerateTree(self.data, self.attributes)

    def recursiveGenerateTree(self, curData, curAttributes):
        allSame = self.allSameClass(curData)

        if len(curData) == 0:
            # Fail
            return Node(True, "Fail", None)
        elif allSame is not False:
            # return a node with that class
            return Node(True, allSame, None)
        elif len(curAttributes) == 0:
            # return a node with the majority class
            majClass = self.getMajClass(curData)
            return Node(True, majClass, None)
        else:
            (best, best_threshold, splitted) = self.splitAttribute(
                curData, curAttributes)
            remainingAttributes = curAttributes[:]
            remainingAttributes.remove(best)
            node = Node(False, best, best_threshold)
            node.children = [self.recursiveGenerateTree(
                subset, remainingAttributes) for subset in splitted]
            return node

    def splitAttribute(self, curData, curAttributes):
        splitted = []
        maxEnt = -1*float("inf")
        best_attribute = -1

        # None for discrete attributes, threshold value for continuous attributes
        best_threshold = None
        for attribute in curAttributes:
            indexOfAttribute = self.attributes.index(attribute)
            if self.isAttrDiscrete(attribute):
                # split curData into n-subsets, where n is the number of
                # different values of attribute i. Choose the attribute with
                # the max gain
                valuesForAttribute = self.attrValues[attribute]
                subsets = [[] for a in valuesForAttribute]

                for row in curData:
                    for index in range(len(valuesForAttribute)):
                        if row[-1] == valuesForAttribute[index]:
                            subsets[index].append(row)
                            break

                e = self.gain(curData, subsets)
                if e > maxEnt:
                    maxEnt = e
                    splitted = subsets
                    best_attribute = attribute
                    best_threshold = None
            else:
                # Sort the data according to the column. Then try all possible adjacent pairs.
                # Choose the one that yields maximum gain.
                curData.sort(key=lambda x: x[indexOfAttribute])
                for j in range(0, len(curData) - 1):
                    if curData[j][indexOfAttribute] != curData[j+1][indexOfAttribute]:
                        threshold = (curData[j][indexOfAttribute] +
                                     curData[j+1][indexOfAttribute]) / 2
                        less = []
                        greater = []
                        for row in curData:
                            if(row[indexOfAttribute] > threshold):
                                greater.append(row)
                            else:
                                less.append(row)
                        e = self.gain(curData, [less, greater])
                        if e >= maxEnt:
                            splitted = [less, greater]
                            maxEnt = e
                            best_attribute = attribute
                            best_threshold = threshold
        return (best_attribute, best_threshold, splitted)

    def predict(self, X):
        y_pred = [self._walk_down(self.tree, sample) for sample in X]
        return y_pred

    def _walk_down(self, node, sample):
        if node.isLeaf:
            return node.label

        feature_name = node.label
        feature_id = self.attributes.index(feature_name)
        feature_value = sample[feature_id]

        if node.threshold is None:
            feature_value_id = self.attrValues[feature_name].tolist().index(
                feature_value)
            return self._walk_down(node.children[feature_value_id], sample)
        else:
            if(float(feature_value) < node.threshold):
                return self._walk_down(node.children[0], sample)
            else:
                return self._walk_down(node.children[1], sample)

    def printTree(self):
        self.printNode(self.tree)

    def printNode(self, node, indent=""):
        if not node.isLeaf:
            if node.threshold is None:
                # discrete
                for index, child in enumerate(node.children):
                    if child.isLeaf:
                        print(indent + node.label + " = " +
                              self.attributes[index] + " : " + child.label)
                    else:
                        print(indent + node.label + " = " +
                              self.attributes[index] + " : ")
                        self.printNode(child, indent + "	")
            else:
                # numerical
                leftChild = node.children[0]
                rightChild = node.children[1]
                if leftChild.isLeaf:
                    print(indent + node.label + " <= " +
                          str(node.threshold) + " : " + leftChild.label)
                else:
                    print(indent + node.label + " <= " +
                          str(node.threshold)+" : ")
                    self.printNode(leftChild, indent + "	")

                if rightChild.isLeaf:
                    print(indent + node.label + " > " +
                          str(node.threshold) + " : " + rightChild.label)
                else:
                    print(indent + node.label + " > " +
                          str(node.threshold) + " : ")
                    self.printNode(rightChild, indent + "	")


# -*- coding: utf-8 -*-
"""
Created on Wed Jun 22 13:27:49 2016

@author: PRANAV
"""

from bs4 import BeautifulSoup as soup
import urllib.request
raw=urllib.request.urlopen('http://finance.yahoo.com/q?s=AAPL').read()
raw=soup(raw)
gsoup1=raw
fi=gsoup1.find_all(class_="yfnc_tabledata1")
print(fi[0])
print(fi[7])
print(fi[8])
print(fi[11])
my=(str(fi[0]))
my=my.split('>')[1]
print(my.split('<')[0],'was the stock price of apple yesterday')


from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
from imutils.video import VideoStream
import numpy as np
import cv2

vs = VideoStream(src=0).start()
frame = vs.read()
h, w = frame.shape[:2]

face_cascade = cv2.CascadeClassifier("./haarcascade_frontalface_default.xml")

def detect_and_predict_mask(frame, maskNet):

    faces = []
    locs = []
    preds = []

    face_rects = face_cascade.detectMultiScale(frame)

    for (x, y, wf, hf) in face_rects:
        (startX, startY, endX, endY) = (x, y, x + wf, y + hf)
        # ensure the bounding boxes fall within the dimensions of
        # the frame
        (startX, startY) = (max(0, startX), max(0, startY))
        (endX, endY) = (min(w - 1, endX), min(h - 1, endY))
        print(startX, startY, endX, endY)
        # extract the face ROI, convert it from BGR to RGB channel
        # ordering, resize it to 224x224, and preprocess it
        face = frame[startY:endY, startX:endX]
        face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
        # cv2.imshow('face',face)
        face = cv2.resize(face, (224, 224))
        face = img_to_array(face)
        face = preprocess_input(face)

        # add the face and bounding boxes to their respective
        # lists
        faces.append(face)
        locs.append((startX, startY, endX, endY))

    # only make a predictions if at least one face was detected
    if len(faces) > 0:
        # for faster inference we'll make batch predictions on *all*
        # faces at the same time rather than one-by-one predictions
        # in the above `for` loop
        faces = np.array(faces, dtype="float32")
        preds = maskNet.predict(faces, batch_size=32)

    # return a 2-tuple of the face locations and their corresponding
    # locations
    return (locs, preds)

# load the face mask detector model from disk
maskNet = load_model("mask_detector.model")
while True:
    # grab the frame from the threaded video stream and resize it
    # to have a maximum width of 400 pixels
    frame = vs.read()

    # detect faces in the frame and determine if they are wearing a
    # face mask or not
    (locs, preds) = detect_and_predict_mask(frame, maskNet)

    # loop over the detected face locations and their corresponding
    # locations
    for (box, pred) in zip(locs, preds):
        # unpack the bounding box and predictions
        (startX, startY, endX, endY) = box
        (mask, withoutMask) = pred

        # determine the class label and color we'll use to draw
        # the bounding box and text
        label = "Mask" if mask > withoutMask else "No Mask"
        color = (0, 255, 0) if label == "Mask" else (0, 0, 255)

        # include the probability in the label
        label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)

        # display the label and bounding box rectangle on the output
        # frame
        cv2.putText(
            frame,
            label,
            (startX, startY - 10),
            cv2.FONT_HERSHEY_SIMPLEX,
            0.45,
            color,
            2,
        )
        cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)
        detectColor(
            frame,
            np.int32(startX + (endX - startX) / 2),
            np.int32(endY + (endY - startY) / 2),
            color,
        )

    # show the output frame
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break

# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()


import time
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

class HomePageParser():
    def __init__(self, driver, source, destination, date):
        self.driver = driver
        self.source = source
        self.destination = destination
        self.date = date

    def parseAndAutomate(self):
        isCloseBannerSuccessful = self.__closeBanners()
        isInputBoxFillingSuccessful = self.__fillInputBoxes()
        isSubmitSuccessful = False
        if isInputBoxFillingSuccessful:
            isSubmitSuccessful = self.__submit()

        if isCloseBannerSuccessful and isInputBoxFillingSuccessful and isSubmitSuccessful:
            print("Homepage parsed and automated successfully")
            return True
        else:
            print("Some error occurred while working on homepage")
            return False

    def __closeBanners(self):
        driver = self.driver
        try:
            # close popup message
            WebDriverWait(driver, 10).until(EC.visibility_of_any_elements_located((webdriver.common.by.By.CLASS_NAME, "btn")))
            okayButton = driver.find_elements(webdriver.common.by.By.CLASS_NAME, "btn")[0]
            okayButton.click()
            time.sleep(2)
            # close side banner
            WebDriverWait(driver, 10).until(EC.visibility_of_any_elements_located((webdriver.common.by.By.ID, "disha-banner-close")))
            sideBanner = driver.find_element(webdriver.common.by.By.ID, "disha-banner-close")
            sideBanner.click()
            time.sleep(2)
            # close login banner
            # WebDriverWait(driver, 5).until(EC.visibility_of_any_elements_located((webdriver.common.by.By.CLASS_NAME, "fa.fa-window-close.pull-right.loginCloseBtn.ng-tns-c19-17")))
            # loginBanner = driver.find_element(webdriver.common.by.By.CLASS_NAME, "fa.fa-window-close.pull-right.loginCloseBtn.ng-tns-c19-17")
            # loginBanner.click()
            print("All banners closed")
            return True
        except Exception as e:
            print("Problem occurred while closing banners")
            return False

    def __fillInputBoxes(self):
        driver = self.driver
        try:
            # find input elements from the page
            fromInput = None
            dateInput = None
            toInput = None
            for inputElement in driver.find_elements(webdriver.common.by.By.TAG_NAME, "input"):
                if inputElement.get_attribute("class") == "ng-tns-c57-8 ui-inputtext ui-widget ui-state-default ui-corner-all ui-autocomplete-input ng-star-inserted":
                    fromInput = inputElement
                elif inputElement.get_attribute("class") == "ng-tns-c58-10 ui-inputtext ui-widget ui-state-default ui-corner-all ng-star-inserted":
                    dateInput = inputElement
                elif inputElement.get_attribute("class") == "ng-tns-c57-9 ui-inputtext ui-widget ui-state-default ui-corner-all ui-autocomplete-input ng-star-inserted":
                    toInput = inputElement

            # fill station data of journey starting station
            fromInput.send_keys(self.source)
            for listItem in driver.find_elements(webdriver.common.by.By.CLASS_NAME, "ng-star-inserted"):
                try:
                    if len(listItem.text) > 0:
                        garbageList = listItem.text.split("\n")
                        for text in garbageList:
                            if "PNBE" in text:
                                fromInput.clear()
                                fromInput.send_keys(text)
                                listItem.click()
                                break
                        break
                except:
                    pass
            time.sleep(2)

            # fill station data of journey destination station
            toInput.send_keys(self.destination)
            for listItem in driver.find_elements(webdriver.common.by.By.CLASS_NAME, "ng-star-inserted"):
                try:
                    if len(listItem.text) > 0:
                        garbageList = listItem.text.split("\n")
                        for text in garbageList:
                            if "NDLS" in text:
                                toInput.clear()
                                toInput.send_keys(text)
                                listItem.click()
                                break
                        break
                except:
                    pass
            time.sleep(2)

            # fill date of journey
            dateInput.send_keys("29/29")
            dateInput.clear()
            dateInput.send_keys(self.date)
            time.sleep(2)

            print("All input boxes filled")
            return True
        except Exception as e:
            print("Problem occurred while feeding data to input elements")
            return False

    def __submit(self):
        driver = self.driver
        try:
            # click the send button
            sendButton = None
            buttons_list = driver.find_elements(webdriver.common.by.By.TAG_NAME, "button")
            for button in buttons_list:
                if button.text == "Search":
                    sendButton = button
                    break

            WebDriverWait(driver, 10).until(EC.element_to_be_clickable((sendButton)))
            sendButton.click()
            time.sleep(3)

            print("Data submitted")
            return True
        except Exception as e:
            print(e.values)
            print("Problem occurred while submitting data")
            return False

if __name__ == "__main__":
    print("Go to /Users/ashutoshkumar/python directory and then run \"python3 selenium_scrapper.py\" ")


from selenium.webdriver.common.by import By
from selenium.webdriver import ChromeOptions, Chrome
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
import random
import pandas as pd

class Job_craw():
    def __init__(self, job_title, job_location):

        self.job_title = job_title
        self.job_location = job_location
        columns = ["title","date","company","company_link","location","type-salary","description"]
        self.df = pd.DataFrame(columns=columns)
        # self.df = pd.read_csv("job.csv")
        service = Service(executable_path='chromedriver.exe')
        options = ChromeOptions()
        options.add_experimental_option("detach", True)
        options.add_argument("--disable-extensions")
        # options.add_argument("--headless")
        options.add_argument("--incognito")
        options.add_argument("--window-size=1920x1080")

        try:
            self.browser = Chrome(service=service, options=options)
        except Exception as e:
            print(f"An error occurred: {e}")

    def close_popup(self):
        try:
            popup = self.browser.find_element(By.ID, "mosaic-desktopserpjapopup")
            if popup.is_displayed():
                close_button = self.browser.find_element(By.CLASS_NAME, "css-yi9ndv.e8ju0x51")
                close_button.click()
        except Exception as e:
            print(f"An error occurred while trying to close the popup: {e}")

    def Start_craw(self):

        print("Starting")
        n = 0
        self.browser.get("https://jobs.vn.indeed.com/jobs?q={}&l={}".format(self.job_title, self.job_location))

        wait = WebDriverWait(self.browser, 100)

        while True:
            sleep(random.randint(1,3))
            try:
                cards = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'job_seen_beacon')))
                date = self.browser.find_elements(By.CLASS_NAME, 'date')
                print(len(cards))
                for i,card in enumerate(cards):
                    cards[i].click()
                    title = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'jobsearch-JobInfoHeader-title')))[0].text
                    print(title)
                    try:
                        company = self.browser.find_element(By.CLASS_NAME, 'css-1cjkto6')
                        # print(company.text)
                        try:
                            company_link = company.find_element(By.TAG_NAME, 'a').get_attribute('href')
                            # print(company_link)

                        except: company_link = None
                    except: company=None

                    try:
                        location = self.browser.find_element(By.CLASS_NAME, 'css-ks9svk').text
                    except:
                        try:
                            location = self.browser.find_element(By.CLASS_NAME, 'css-9yl11a').text
                        except:
                            try:
                                location = self.browser.find_element(By.CLASS_NAME, 'css-6z8o9s').text
                            except: location = None
                    # print(location)

                    try:
                        type = self.browser.find_element(By.CLASS_NAME, 'css-k5flys').text
                    except:
                        type = None
                    description = self.browser.find_element(By.ID, 'jobDescriptionText').text
                    # print(description)
                    sleep(random.randint(1,5))

                    data = [title, date[i].text, company.text, company_link, location, type, description]
                    new_row = pd.DataFrame([data], columns=self.df.columns)
                    self.df = pd.concat([self.df, new_row], ignore_index=True)
                try:
                    next_button = self.browser.find_element(By.XPATH, '//a[@aria-label="Next Page"]')
                    next_button.click()
                except Exception:
                    self.browser.quit()
                    break
            except:
                self.close_popup()
        print("================================")
        print("Save results")

        self.df.to_csv("job_{}_{}.csv".format(self.job_title, self.job_location))

        return

if __name__ == "__main__":
    job_title = "Your Job Title"
    job_location = "Your Location"
    job_crawler = Job_craw(job_title, job_location)
    job_crawler.Start_craw()


# test_interface.py

import PySimpleGUI as sg
import os.path

file_list_column = [
    [
        sg.Text("Image Folder"),
        sg.In(size=(25,1), enable_events=True, key="-FOLDER-"), #Input avec les events enabled et la key pour s'y référer par la suite
        sg.FolderBrowse(), #Bouton de browsing
    ],
    [
        sg.Listbox(
            values=[], enable_events=True, size=(40,20), key="-FILE LIST-"  #Pas encore de valeurs présentes
        )
    ],
]

image_viewer_column = [
    [sg.Text("Choose an image from the list on the left:")],
    [sg.Text(size=(40,1), key="-TOUT-")],
    [sg.Image(key="-IMAGE-")],
]

layout = [
    [
        sg.Column(file_list_column),
        sg.VSeparator(), #Séparer les deux colonnes
        sg.Column(image_viewer_column),
    ]
]

#Pour ajouter un thème pour changer les couleurs de base
#sg.theme("Theme name")

#Pour voir le preview de tous les thèmes
#sg.theme_previewer()

#SimpleGUI window, first arg = title name, second arg = layout created
window = sg.Window("Image Viewer", layout)

while True:
    event, values = window.read()
    if event == "Exit" or event == sg.WIN_CLOSED:
        break
    if event == "-FOLDER-": #if key of the event = -FOLDER-
        folder = values["-FOLDER-"] #Retourne le path de l'input avec la key -FOLDER-
        print(type(folder))
        try:
            file_list = os.listdir(folder)
        except:
            file_list = []

        fnames = [
            f
            for f in file_list
            if os.path.isfile(os.path.join(folder, f))
            and f.lower().endswith((".png", ".gif"))
        ]
        window["-FILE LIST-"].update(fnames)
    elif event == "-FILE LIST-":
        try:
            filename = os.path.join(
                values["-FOLDER-"], values["-FILE LIST-"][0]
            )
            window["-TOUT-"].update(filename)
            window["-IMAGE-"].update(filename=filename) #Display l'image avec le filename mentionné
        except:
            pass

window.close()


from django.shortcuts import get_object_or_404, render, redirect
from .models import Google, Write, Category
from django.core.paginator import Paginator
from django.http import HttpResponseRedirect
from django.urls import reverse
import random
import json
# Create your views here.
def index(request):

    all_boards = Google.objects.all()
    paginator = Paginator(all_boards, 9)
    page = int(request.GET.get('page', 1))
    board_list = paginator.get_page(page)
    # context = {
    #     'destinations' : destinations
    # }
    return render(request, 'main/index.html', {'title':'Board List', 'board_list':board_list})

def search(request):
    search_list = Google.objects.all()
    q = request.POST.get('q', '')

    if q:
        search_list = search_list.filter(name__icontains=q)
        return render(request, 'main/search.html', {'search_list' : search_list, 'q' : q})
    else:
        return render(request, 'main/search.html')

def result_full(request):
    result_full_list = Google.objects.all()
    paginator = Paginator(result_full_list, 9)
    page = int(request.GET.get('page', 1))
    result_full_list = paginator.get_page(page)
    return render(request, 'main/result_full.html', {'result_full_list':result_full_list})

def result_in(request):
    result_in_list = Google.objects.filter(inout='in')
    paginator = Paginator(result_in_list, 9)
    page = int(request.GET.get('page', 1))
    result_in_list = paginator.get_page(page)
    return render(request, 'main/result_in.html', {'result_in_list':result_in_list})

def result_out(request):
    result_out_list = Google.objects.filter(inout='out')
    paginator = Paginator(result_out_list, 9)
    page = int(request.GET.get('page', 1))
    result_out_list = paginator.get_page(page)
    return render(request, 'main/result_out.html', {'result_out_list':result_out_list})

def result_free(request):
    result_free_list = Google.objects.filter(charge='free')
    paginator = Paginator(result_free_list, 9)
    page = int(request.GET.get('page', 1))
    result_free_list = paginator.get_page(page)
    return render(request, 'main/result_free.html', {'result_free_list':result_free_list})

def result_charge(request):
    result_charge_list = Google.objects.filter(charge='charge')
    paginator = Paginator(result_charge_list, 9)
    page = int(request.GET.get('page', 1))
    result_charge_list = paginator.get_page(page)
    return render(request, 'main/result_charge.html', {'result_charge_list':result_charge_list})

# 테마파크
def result_theme_park(request):
    result_theme_park_list = Google.objects.filter(theme='theme park')
    paginator = Paginator(result_theme_park_list, 9)
    page = int(request.GET.get('page', 1))
    result_theme_park_list = paginator.get_page(page)
    return render(request, 'main/result_theme_park.html', {'result_theme_park_list':result_theme_park_list})

# 빌딩 & 타워
def result_building_tower(request):
    result_building_tower_list = Google.objects.filter(theme='building') | Google.objects.filter(theme='tower')
    paginator = Paginator(result_building_tower_list, 9)
    page = int(request.GET.get('page', 1))
    result_building_tower_list = paginator.get_page(page)
    return render(request, 'main/result_building_tower.html', {'result_building_tower_list':result_building_tower_list})

# 산
def result_mountain(request):
    result_mountain_list = Google.objects.filter(theme='mountain')
    paginator = Paginator(result_mountain_list, 9)
    page = int(request.GET.get('page', 1))
    result_mountain_list = paginator.get_page(page)
    return render(request, 'main/result_mountain.html', {'result_mountain_list':result_mountain_list})

# 역사 유적지
def result_historical_site(request):
    result_historical_site_list = Google.objects.filter(theme='historical site')
    paginator = Paginator(result_historical_site_list, 9)
    page = int(request.GET.get('page', 1))
    result_historical_site_list = paginator.get_page(page)
    return render(request, 'main/result_historical_site.html', {'result_historical_site_list':result_historical_site_list})

# 공원
def result_park(request):
    result_park_list = Google.objects.filter(theme='park')
    paginator = Paginator(result_park_list, 9)
    page = int(request.GET.get('page', 1))
    result_park_list = paginator.get_page(page)
    return render(request, 'main/result_park.html', {'result_park_list':result_park_list})

# 쇼핑
def result_shopping(request):
    result_shopping_list = Google.objects.filter(theme='shopping')
    paginator = Paginator(result_shopping_list, 9)
    page = int(request.GET.get('page', 1))
    result_shopping_list = paginator.get_page(page)
    return render(request, 'main/result_shopping.html', {'result_shopping_list':result_shopping_list})

def list(request):
    return render(request, 'main/list.html')

def details(request, pk):
    destination = Google.objects.get(pk=pk)
    context = {
        'destination':destination,
    }
    print(context)
    return render(request, 'main/details.html', context)

def write(request):
    if request.method == 'POST':
        data = {
            'name':request.POST.get('name'),
            'contents' : request.POST.get('contents'),
        }
        destination = Write.objects.create(**data)

        return redirect(f'/details/{destination.pk}')
    context = {
            'locations' : Write.google,
        }
    return render(request, 'main/write.html', context)

# def result_in(request):
#     store_list_in = []
#     for store in Google.objects.all():
#         if request['inout'] == 'in':
#             continue
#         store_list_in.append(store)
#     if len(store_list_in) == 0:
#         for store in Google.objects.all():
#             if request['inout'] == 'in':
#                 continue

#     return render(request, 'main/result_in.html', {'store_list_in':store_list_in})

# def get_in(info_dict):
#     store_list_in = []
#     for store in Google.objects.all():
#         if info_dict['inout'] == 'in':
#             store_list_in.append(store)
#     if len(store_list_in) == 0:
#         for store in Google.objects.all():
#             if info_dict['inout'] == 'in':
#                 continue
#     return store_list_in

# def result_in(request):
#     # try:
#     #     inout = request.GET['inout']
#     #     charge = request.GET['charge']
#     #     info_dict = {'inout':inout, 'charge':charge}
#     #     store_in = get_in(info_dict)

#     # except (KeyError):
#     #     print("ERROR")

#     inout = request.GET['inout']
#     charge = request.GET['charge']
#     info_dict = {'inout':inout, 'charge':charge}
#     store_in = get_in(info_dict)
#     # else:
#     #     return HttpResponseRedirect(reverse('result_in', args=(store_in.name,)))

#     return render(request, 'main/result_in.html', {'store_in':store_in})

# def vote_in(request):
#     try:
#         inout = request.GET['inout']
#         charge = request.GET['charge']
#         info_dict = {'inout': inout, 'charge': charge}
#         store = get_store_in(info_dict)
#     except (KeyError):
#         print("ERROR")
#     else:
#         return HttpResponseRedirect(reverse('result_in', args=(store.name,)))

#     return render(request, 'result_in.html')

# def result(request, store_name):
#     try:
#         store = get_object_or_404(Google, pk=store_name)
#     except (KeyError):
#         print('ERROR')
#         return render(request, 'result.html')
#     else:
#         return render(request, 'result.html', {'store': store})

def result(request):

    destination_list = []

    for destination in Google.objects.all():
        destination_list.append(destination)

    # restaurant_answer_list = filter(restaurant_list)
    # cafe_answer_list = filter(cafe_list)

    # 이거는 랜덤이라 무조건 넣어야됨
    destination_answer = destination_list[random.randrange(0, len(destination_list))]
    #destination_answer = destination_list
    # for restaurant in Write.objects.all():
    #     if str(restaurant.category) == '카페':
    #         continue
    #     if str(restaurant.google) != 'destination_answer':
    #         continue
    #     restaurant_list.append(restaurant)

    # for cafe in Write.objects.all():
    #     if str(cafe.category) != '식당':
    #         continue
    #     if str(cafe.google) != 'destination_answer':
    #         continue
    #     cafe_list.append(cafe)
    #     print(cafe_list)

    # restaurant_answer = restaurant_list
    # cafe_answer = cafe_list
    # restaurant_answer = restaurant_list[random.randrange(0, len(restaurant_list))]
    # cafe_answer = cafe_list[random.randrange(0, len(cafe_list))]

    # if str(cafe_list.google) == str(destination_answer.name):
    #     cafe_answer_list = cafe_list
    # cafe_answer = cafe_answer_list [random.randrange(0, len(cafe_answer_list))]

    # if str(restaurant_list.google) == str(destination_answer.name):
    #     restaurant_answer_list = restaurant_list
    # restaurant_answer = restaurant_answer_list[random.randrange(0, len(restaurant_answer_list))]

    return render(request, 'main/result.html',
     {'destination_answer' : destination_answer})

# def filter(info_dict):
#     for destination in Google.objects.all():
#         if info_dict['google'] == destination.name:
#             return info_dict


import os

#central function and initiator
def __init__():

    with open ("counter.txt") as f:
        count = int(f.read())
        print(f"first open is {count}")
        f.close()

    cleanUp(count)

    newCount = writeFile(count)
    print (f"new count written is {newCount}")

#function used to take arguement of count, add 1 and rewrite to file
#used for the function of indexing and aiding in cleaning up past automatic posts
def writeFile(count):
    with open ("counter.txt", "w") as f:
        newCount=str(count+1)
        f.write(newCount)

        return newCount

def cleanUp(count: int):
    try:

        currentPic = "picture"+str(count)+".png"
        print(currentPic)

        location = "/Users/jxck/Desktop/computer shit/ongoing/ainsta/topost"

        path = os.path.join(location, currentPic)
        os.remove(path)

    except:

        print("error in cleanUp function was handled, proceed with caution")
        pass

#POST FILE (GENERIC) ////////////////////////////
__init__()


""" Test the KSFunction component. """
import unittest

import numpy as np

import openmdao.api as om
from openmdao.test_suite.components.simple_comps import DoubleArrayComp
from openmdao.test_suite.test_examples.beam_optimization.multipoint_beam_stress import MultipointBeamGroup
from openmdao.utils.assert_utils import assert_rel_error, assert_warning

class TestKSFunction(unittest.TestCase):

    def test_basic_ks(self):
        prob = om.Problem()
        model = prob.model

        model.add_subsystem('px', om.IndepVarComp(name="x", val=np.ones((2, ))))
        model.add_subsystem('comp', DoubleArrayComp())
        model.add_subsystem('ks', om.KSComp(width=2))
        model.connect('px.x', 'comp.x1')
        model.connect('comp.y2', 'ks.g')

        model.add_design_var('px.x')
        model.add_objective('comp.y1')
        model.add_constraint('ks.KS', upper=0.0)

        prob.setup()
        prob.run_driver()

        assert_rel_error(self, max(prob['comp.y2']), prob['ks.KS'][0])

    def test_vectorized(self):
        prob = om.Problem()
        model = prob.model

        x = np.zeros((3, 5))
        x[0, :] = np.array([3.0, 5.0, 11.0, 13.0, 17.0])
        x[1, :] = np.array([13.0, 11.0, 5.0, 17.0, 3.0])*2
        x[2, :] = np.array([11.0, 3.0, 17.0, 5.0, 13.0])*3

        model.add_subsystem('px', om.IndepVarComp(name="x", val=x))
        model.add_subsystem('ks', om.KSComp(width=5, vec_size=3))
        model.connect('px.x', 'ks.g')

        model.add_design_var('px.x')
        model.add_constraint('ks.KS', upper=0.0)

        prob.setup()
        prob.run_driver()

        assert_rel_error(self, prob['ks.KS'][0], 17.0)
        assert_rel_error(self, prob['ks.KS'][1], 34.0)
        assert_rel_error(self, prob['ks.KS'][2], 51.0)

        partials = prob.check_partials(includes=['ks'], out_stream=None)

        for (of, wrt) in partials['ks']:
            assert_rel_error(self, partials['ks'][of, wrt]['abs error'][0], 0.0, 1e-6)

    def test_partials_no_compute(self):
        prob = om.Problem()

        model = prob.model

        model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0])))

        ks_comp = model.add_subsystem('ks', om.KSComp(width=2))

        model.connect('px.x', 'ks.g')

        prob.setup()
        prob.run_driver()

        # compute partials with the current model inputs
        inputs = { 'g': prob['ks.g'] }
        partials = {}

        ks_comp.compute_partials(inputs, partials)
        assert_rel_error(self, partials[('KS', 'g')], np.array([1., 0.]), 1e-6)

        # swap inputs and call compute partials again, without calling compute
        inputs['g'][0][0] = 4
        inputs['g'][0][1] = 5

        ks_comp.compute_partials(inputs, partials)
        assert_rel_error(self, partials[('KS', 'g')], np.array([0., 1.]), 1e-6)

    def test_beam_stress(self):
        E = 1.
        L = 1.
        b = 0.1
        volume = 0.01
        max_bending = 100.0

        num_cp = 5
        num_elements = 25
        num_load_cases = 2

        prob = om.Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume, max_bending = max_bending,
                                                    num_elements=num_elements, num_cp=num_cp,
                                                    num_load_cases=num_load_cases))

        prob.driver = om.ScipyOptimizeDriver()
        prob.driver.options['optimizer'] = 'SLSQP'
        prob.driver.options['tol'] = 1e-9
        prob.driver.options['disp'] = False

        prob.setup(mode='rev')

        prob.run_driver()

        stress0 = prob['parallel.sub_0.stress_comp.stress_0']
        stress1 = prob['parallel.sub_0.stress_comp.stress_1']

        # Test that the the maximum constraint prior to aggregation is close to "active".
        assert_rel_error(self, max(stress0), 100.0, tolerance=5e-2)
        assert_rel_error(self, max(stress1), 100.0, tolerance=5e-2)

        # Test that no original constraint is violated.
        self.assertTrue(np.all(stress0 < 100.0))
        self.assertTrue(np.all(stress1 < 100.0))

    def test_upper(self):

        prob = om.Problem()
        model = prob.model

        model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0])))
        model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, )), y=np.zeros((2, ))))
        model.add_subsystem('ks', om.KSComp(width=2))

        model.connect('px.x', 'comp.x')
        model.connect('comp.y', 'ks.g')

        model.ks.options['upper'] = 16.0
        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['ks.KS'][0], -1.0)

    def test_lower_flag(self):

        prob = om.Problem()
        model = prob.model

        model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0])))
        model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, )), y=np.zeros((2, ))))
        model.add_subsystem('ks', om.KSComp(width=2))

        model.connect('px.x', 'comp.x')
        model.connect('comp.y', 'ks.g')

        model.ks.options['lower_flag'] = True
        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['ks.KS'][0], -12.0)

class TestKSFunctionFeatures(unittest.TestCase):

    def test_basic(self):
        import numpy as np

        import openmdao.api as om

        prob = om.Problem()
        model = prob.model

        model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0])))
        model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, )),
                                                y=np.zeros((2, ))))
        model.add_subsystem('ks', om.KSComp(width=2))

        model.connect('px.x', 'comp.x')
        model.connect('comp.y', 'ks.g')

        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['ks.KS'][0], 15.0)

    def test_vectorized(self):
        import numpy as np

        import openmdao.api as om

        prob = om.Problem()
        model = prob.model

        model.add_subsystem('px', om.IndepVarComp('x', val=np.array([[5.0, 4.0], [10.0, 8.0]])))
        model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, 2)),
                                                y=np.zeros((2, 2))))
        model.add_subsystem('ks', om.KSComp(width=2, vec_size=2))

        model.connect('px.x', 'comp.x')
        model.connect('comp.y', 'ks.g')

        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['ks.KS'][0], 15.0)
        assert_rel_error(self, prob['ks.KS'][1], 30.0)

    def test_upper(self):
        import numpy as np

        import openmdao.api as om

        prob = om.Problem()
        model = prob.model

        model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0])))
        model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, )),
                                                y=np.zeros((2, ))))
        model.add_subsystem('ks', om.KSComp(width=2))

        model.connect('px.x', 'comp.x')
        model.connect('comp.y', 'ks.g')

        model.ks.options['upper'] = 16.0
        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['ks.KS'][0], -1.0)

    def test_lower_flag(self):
        import numpy as np

        import openmdao.api as om

        prob = om.Problem()
        model = prob.model

        model.add_subsystem('px', om.IndepVarComp('x', val=np.array([5.0, 4.0])))
        model.add_subsystem('comp', om.ExecComp('y = 3.0*x', x=np.zeros((2, )),
                                                y=np.zeros((2, ))))
        model.add_subsystem('ks', om.KSComp(width=2))

        model.connect('px.x', 'comp.x')
        model.connect('comp.y', 'ks.g')

        model.ks.options['lower_flag'] = True
        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['ks.KS'][0], -12.0)

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


print('''Дано целое число n. Сколько цифр в числе n?''')

n = int(input("Введите целое число n: "))

n = abs(n)
kolDigits = 0

if n == 0:
    kolDigits += 1

while n > 0:
    n //= 10
    kolDigits += 1

print(f"Ответ: {kolDigits}")


"""Host common and generic functions.

Host all the common and generic functions that are used throughout
the project.

"""

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from logging import getLogger
from subprocess import (PIPE, Popen)
from ConfigParser import ConfigParser
from wifiphisher.common.constants import DN

# pylint: disable=C0103
logger = getLogger(__name__)

def execute_commands(commands):
    # type: (List[str]) -> None
    """Execute each command and log any errors."""
    for command in commands:
        _, error = Popen(command.split(), stderr=PIPE, stdout=DN).communicate()
        if error:
            logger.error(
                "{command} has failed with the following error:\n{error}".
                format(command=command, error=error))

def config_section_map(config_file, section):
    """Map the values of a config file to a dictionary."""
    config = ConfigParser()
    config.read(config_file)
    dict1 = {}

    if section not in config.sections():
        return dict1

    options = config.options(section)
    for option in options:
        try:
            dict1[option] = config.get(section, option)
        except KeyError:
            dict1[option] = None
    return dict1


'''Crea una aplicación que permita adivinar un número.
En primer lugar la aplicación solicita un número entero por teclado.
A continuación va pidiendo números y va respondiendo si
el número a adivinar es mayor o menor que el introducido.
El programa termina cuando se acierta el número.'''

a=int(input('Ingrese un número entero: '))
def adivi():
    b=int(input('Adivine el número: '))
    if b==a:
        print('Correcto')
    elif b>a:
        print('Prediccion incorrecta el número es mayor, vuelva a intentarlo ')
        return adivi()
    else:
        print('Prediccion incorrecta el número es menor, vuelva a intentarlo ')
        return adivi()
adivi()


import turtle
turtle.shape('turtle')

def triangle():
    for i in range(3):
        turtle.forward(50)
        turtle.right(360/3)

def square():
    for i in range(4):
        turtle.forward(50)
        turtle.right(360/4)

def pentagon():
    for i in range(5):
        turtle.forward(50)
        turtle.right(360/5)

answer = input('pick a shape.. triangle, square or pentagon')
if answer ==('triangle'):
    triangle()

elif answer == ('square'):
    square()

elif answer == ('pentagon'):
    pentagon()

else:
    print ('wrong input')