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